summaryrefslogtreecommitdiffstats
path: root/regressions/ck_ec/validate/fuzz_harness.h
blob: 8ba6ebe61bbbdfe638ce511c2182bc9bb5072a70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#ifndef FUZZ_HARNESS_H
#define FUZZ_HARNESS_H
#include <assert.h>
#include <ck_stddef.h>
#include <ck_string.h>
#include <stdio.h>
#include <unistd.h>

#if defined(USE_LIBFUZZER)
#define TEST(function, examples)					\
	void LLVMFuzzerInitialize(int *argcp, char ***argvp);		\
	int LLVMFuzzerTestOneInput(const void *data, size_t n);		\
									\
	void LLVMFuzzerInitialize(int *argcp, char ***argvp)		\
	{								\
		static char size[128];					\
		static char *argv[1024];				\
		int argc = *argcp;					\
									\
		assert(argc < 1023);					\
									\
		int r = snprintf(size, sizeof(size),			\
				 "-max_len=%zu", sizeof(examples[0]));	\
		assert((size_t)r < sizeof(size));			\
									\
		memcpy(argv, *argvp, argc * sizeof(argv[0]));		\
		argv[argc++] = size;					\
									\
		*argcp = argc;						\
		*argvp = argv;						\
									\
		for (size_t i = 0;					\
		     i < sizeof(examples) / sizeof(examples[0]);	\
		     i++) {						\
			assert(function(&examples[i]) == 0);		\
		}							\
									\
		return;							\
	}								\
									\
	int LLVMFuzzerTestOneInput(const void *data, size_t n)		\
	{								\
		char buf[sizeof(examples[0])];				\
									\
		memset(buf, 0, sizeof(buf));				\
		if (n < sizeof(buf)) {					\
			memcpy(buf, data, n);				\
		} else {						\
			memcpy(buf, data, sizeof(buf));			\
		}							\
									\
		assert(function((const void *)buf) == 0);		\
		return 0;						\
	}
#elif defined(USE_AFL)
#define TEST(function, examples)					\
	int main(int argc, char **argv)					\
	{								\
		char buf[sizeof(examples[0])];				\
									\
		(void)argc;						\
		(void)argv;						\
		for (size_t i = 0;					\
		     i < sizeof(examples) / sizeof(examples[0]);	\
		     i++) {						\
			assert(function(&examples[i]) == 0);		\
		}							\
									\
									\
		while (__AFL_LOOP(10000)) {				\
			memset(buf, 0, sizeof(buf));			\
			read(0, buf, sizeof(buf));			\
									\
			assert(function((const void *)buf) == 0);	\
		}							\
									\
		return 0;						\
	}
#else
#define TEST(function, examples)					\
	int main(int argc, char **argv)					\
	{								\
		(void)argc;						\
		(void)argv;						\
									\
		for (size_t i = 0;					\
		     i < sizeof(examples) / sizeof(examples[0]);	\
		     i++) {						\
			assert(function(&examples[i]) == 0);		\
		}							\
									\
		return 0;						\
	}
#endif
#endif /* !FUZZ_HARNESS_H */