From fe333e188a93c46ff7c7bf118ca90da49c06609d Mon Sep 17 00:00:00 2001 From: "Wladimir J. van der Laan" Date: Thu, 5 Oct 2017 18:07:34 +0200 Subject: [PATCH] Merge #10440: [tests] Add libFuzzer support f3ba869 [tests] Add libFuzzer support. (practicalswift) Pull request description: Add `libFuzzer` support. As discussed in [issue #10364](https://github.com/bitcoin/bitcoin/issues/10364#issuecomment-300000902). See http://llvm.org/docs/LibFuzzer.html#fuzzer-usage for usage instructions. Tree-SHA512: 32562a3a43eb07e79989d55eeb0bfe94e2cff060da8ff0cb50c2f838ef19f2fd583a3dc89074a6442bd3e395185d309371325ed9a0ef50065431d5ea7f099772 --- src/test/test_dash_fuzzy.cpp | 50 ++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/src/test/test_dash_fuzzy.cpp b/src/test/test_dash_fuzzy.cpp index ed99ae27bf..ae72e0054e 100644 --- a/src/test/test_dash_fuzzy.cpp +++ b/src/test/test_dash_fuzzy.cpp @@ -51,8 +51,8 @@ enum TEST_ID { TEST_ID_END }; -bool read_stdin(std::vector &data) { - char buffer[1024]; +bool read_stdin(std::vector &data) { + uint8_t buffer[1024]; ssize_t length=0; while((length = read(STDIN_FILENO, buffer, 1024)) > 0) { data.insert(data.end(), buffer, buffer+length); @@ -62,11 +62,7 @@ bool read_stdin(std::vector &data) { return length==0; } -int do_fuzz() -{ - std::vector buffer; - if (!read_stdin(buffer)) return 0; - +int test_one_input(std::vector buffer) { if (buffer.size() < sizeof(uint32_t)) return 0; uint32_t test_id = 0xffffffff; @@ -278,9 +274,32 @@ int do_fuzz() return 0; } +static std::unique_ptr globalVerifyHandle; +void initialize() { + globalVerifyHandle = std::unique_ptr(new ECCVerifyHandle()); +} + +// This function is used by libFuzzer +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + test_one_input(std::vector(data, data + size)); + return 0; +} + +// This function is used by libFuzzer +extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { + initialize(); + return 0; +} + +// Disabled under WIN32 due to clash with Cygwin's WinMain. +#ifndef WIN32 +// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides +// the main(...) function. +__attribute__((weak)) +#endif int main(int argc, char **argv) { - ECCVerifyHandle globalVerifyHandle; + initialize(); #ifdef __AFL_INIT // Enable AFL deferred forkserver mode. Requires compilation using // afl-clang-fast++. See fuzzing.md for details. @@ -290,11 +309,20 @@ int main(int argc, char **argv) #ifdef __AFL_LOOP // Enable AFL persistent mode. Requires compilation using afl-clang-fast++. // See fuzzing.md for details. + int ret = 0; while (__AFL_LOOP(1000)) { - do_fuzz(); + std::vector buffer; + if (!read_stdin(buffer)) { + continue; + } + ret = test_one_input(buffer); } - return 0; + return ret; #else - return do_fuzz(); + std::vector buffer; + if (!read_stdin(buffer)) { + return 0; + } + return test_one_input(buffer); #endif }