Move the libfuzzer linkopts to the stub cc_library, such that only the top-level fuzz test is instrumented. (#89)
* Move the libfuzzer linkopts to the stub cc_library, such that only the top-level fuzz test is instrumented.
Without this change, any other binary that may be built on the transitive dependency chain will also get linked with libFuzzer, resulting in a linker error (duplicate main functions).
* Fix libFuzzer's copts.
* Fix typo in stub output.
diff --git a/fuzzing/engines/BUILD b/fuzzing/engines/BUILD
index 1d5a08e..73da50d 100644
--- a/fuzzing/engines/BUILD
+++ b/fuzzing/engines/BUILD
@@ -29,6 +29,11 @@
cc_library(
name = "libfuzzer_stub",
srcs = ["libfuzzer_stub.cc"],
+ linkopts = [
+ # We add the linker options to the library, so only the fuzz test binary
+ # is linked with libfuzzer.
+ "-fsanitize=fuzzer",
+ ],
)
# Honggfuzz specification.
diff --git a/fuzzing/engines/libfuzzer_stub.cc b/fuzzing/engines/libfuzzer_stub.cc
index 0807fc1..6d999ef 100644
--- a/fuzzing/engines/libfuzzer_stub.cc
+++ b/fuzzing/engines/libfuzzer_stub.cc
@@ -12,5 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// TODO(sbucur): Implement here weak main() function that prints an error
-// signaling that the real libFuzzer engine was not linked correctly.
+#include <cstdio>
+#include <cstdlib>
+
+extern "C" int main(int argc, char** argv) __attribute__((weak));
+
+int main(int argc, char** argv) {
+ fprintf(stderr, "*** ERROR *** This is a stub *** ERROR ***\n");
+ fprintf(stderr,
+ " * You have attempted to build a libFuzzer fuzz test, but did not "
+ "link in the fuzzing engine.\n");
+ fprintf(stderr, " * Use the '-fsanitize=fuzzer' linker option instead.\n");
+ abort();
+}
diff --git a/fuzzing/instrum_opts.bzl b/fuzzing/instrum_opts.bzl
index df7c0b6..f6fb4d6 100644
--- a/fuzzing/instrum_opts.bzl
+++ b/fuzzing/instrum_opts.bzl
@@ -51,15 +51,13 @@
# Base instrumentation applied to all fuzz test executables.
base_opts = instrumentation_opts(
copts = ["-DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION"],
- linkopts = [],
)
# Engine-specific instrumentation.
fuzzing_engine_opts = {
"none": instrumentation_opts(),
"libfuzzer": instrumentation_opts(
- copts = ["-fsanitize=fuzzer"],
- linkopts = ["-fsanitize=fuzzer"],
+ copts = ["-fsanitize=fuzzer-no-link"],
),
# Reflects the set of options at
# https://github.com/google/honggfuzz/blob/master/hfuzz_cc/hfuzz-cc.c