Skip to content

Commit f3ba869

Browse files
[tests] Add libFuzzer support.
See http://llvm.org/docs/LibFuzzer.html#fuzzer-usage for usage instructions.
1 parent 217b416 commit f3ba869

File tree

1 file changed

+39
-11
lines changed

1 file changed

+39
-11
lines changed

src/test/test_bitcoin_fuzzy.cpp

Lines changed: 39 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ enum TEST_ID {
4848
TEST_ID_END
4949
};
5050

51-
bool read_stdin(std::vector<char> &data) {
52-
char buffer[1024];
51+
bool read_stdin(std::vector<uint8_t> &data) {
52+
uint8_t buffer[1024];
5353
ssize_t length=0;
5454
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
5555
data.insert(data.end(), buffer, buffer+length);
@@ -59,11 +59,7 @@ bool read_stdin(std::vector<char> &data) {
5959
return length==0;
6060
}
6161

62-
int do_fuzz()
63-
{
64-
std::vector<char> buffer;
65-
if (!read_stdin(buffer)) return 0;
66-
62+
int test_one_input(std::vector<uint8_t> buffer) {
6763
if (buffer.size() < sizeof(uint32_t)) return 0;
6864

6965
uint32_t test_id = 0xffffffff;
@@ -255,9 +251,32 @@ int do_fuzz()
255251
return 0;
256252
}
257253

254+
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
255+
void initialize() {
256+
globalVerifyHandle = std::unique_ptr<ECCVerifyHandle>(new ECCVerifyHandle());
257+
}
258+
259+
// This function is used by libFuzzer
260+
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
261+
test_one_input(std::vector<uint8_t>(data, data + size));
262+
return 0;
263+
}
264+
265+
// This function is used by libFuzzer
266+
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
267+
initialize();
268+
return 0;
269+
}
270+
271+
// Disabled under WIN32 due to clash with Cygwin's WinMain.
272+
#ifndef WIN32
273+
// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides
274+
// the main(...) function.
275+
__attribute__((weak))
276+
#endif
258277
int main(int argc, char **argv)
259278
{
260-
ECCVerifyHandle globalVerifyHandle;
279+
initialize();
261280
#ifdef __AFL_INIT
262281
// Enable AFL deferred forkserver mode. Requires compilation using
263282
// afl-clang-fast++. See fuzzing.md for details.
@@ -267,11 +286,20 @@ int main(int argc, char **argv)
267286
#ifdef __AFL_LOOP
268287
// Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
269288
// See fuzzing.md for details.
289+
int ret = 0;
270290
while (__AFL_LOOP(1000)) {
271-
do_fuzz();
291+
std::vector<uint8_t> buffer;
292+
if (!read_stdin(buffer)) {
293+
continue;
294+
}
295+
ret = test_one_input(buffer);
272296
}
273-
return 0;
297+
return ret;
274298
#else
275-
return do_fuzz();
299+
std::vector<uint8_t> buffer;
300+
if (!read_stdin(buffer)) {
301+
return 0;
302+
}
303+
return test_one_input(buffer);
276304
#endif
277305
}

0 commit comments

Comments
 (0)