[tests] Add libFuzzer support.

See http://llvm.org/docs/LibFuzzer.html#fuzzer-usage for usage instructions.
This commit is contained in:
practicalswift 2017-05-22 13:55:42 +02:00
parent 217b416c72
commit f3ba869734

View file

@ -48,8 +48,8 @@ enum TEST_ID {
TEST_ID_END
};
bool read_stdin(std::vector<char> &data) {
char buffer[1024];
bool read_stdin(std::vector<uint8_t> &data) {
uint8_t buffer[1024];
ssize_t length=0;
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer+length);
@ -59,11 +59,7 @@ bool read_stdin(std::vector<char> &data) {
return length==0;
}
int do_fuzz()
{
std::vector<char> buffer;
if (!read_stdin(buffer)) return 0;
int test_one_input(std::vector<uint8_t> buffer) {
if (buffer.size() < sizeof(uint32_t)) return 0;
uint32_t test_id = 0xffffffff;
@ -255,9 +251,32 @@ int do_fuzz()
return 0;
}
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
void initialize() {
globalVerifyHandle = std::unique_ptr<ECCVerifyHandle>(new ECCVerifyHandle());
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
test_one_input(std::vector<uint8_t>(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.
@ -267,11 +286,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<uint8_t> buffer;
if (!read_stdin(buffer)) {
continue;
}
return 0;
ret = test_one_input(buffer);
}
return ret;
#else
return do_fuzz();
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
return 0;
}
return test_one_input(buffer);
#endif
}