Skip to content

Commit 08d8ebe

Browse files
practicalswiftfurszy
authored andcommitted
[tests] Add libFuzzer support.
See http://llvm.org/docs/LibFuzzer.html#fuzzer-usage for usage instructions.
1 parent 84f72da commit 08d8ebe

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
@@ -47,8 +47,8 @@ enum TEST_ID {
4747
TEST_ID_END
4848
};
4949

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

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

6864
uint32_t test_id = 0xffffffff;
@@ -254,9 +250,32 @@ int do_fuzz()
254250
return 0;
255251
}
256252

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

0 commit comments

Comments
 (0)