1 #include <stdarg.h>
2 #include <stddef.h>
3 #include <setjmp.h>
4 #include <assert.h>
5 #include <cmocka.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 /* cmocka < 1.0 didn't support these features we need */
9 #ifndef assert_ptr_equal
10 #define assert_ptr_equal(a, b) \
11     _assert_int_equal(cast_ptr_to_largest_integral_type(a), \
12                       cast_ptr_to_largest_integral_type(b), \
13                       __FILE__, __LINE__)
14 #define CMUnitTest UnitTest
15 #define cmocka_unit_test unit_test
16 #define cmocka_run_group_tests(t, setup, teardown) run_tests(t)
17 #endif
18 
19 
20 extern void mock_assert(const int result, const char* const expression,
21                         const char * const file, const int line);
22 #undef assert
23 #define assert(expression) \
24     mock_assert((int)(expression), #expression, __FILE__, __LINE__);
25 
26 #include "afl-fuzz.h"
27 
28 /* remap exit -> assert, then use cmocka's mock_assert
29     (compile with `--wrap=exit`) */
30 extern void exit(int status);
31 extern void __real_exit(int status);
32 //void __wrap_exit(int status);
__wrap_exit(int status)33 void __wrap_exit(int status) {
34     (void)status;
35     assert(0);
36 }
37 
38 /* ignore all printfs */
39 #undef printf
40 extern int printf(const char *format, ...);
41 extern int __real_printf(const char *format, ...);
42 int __wrap_printf(const char *format, ...);
__wrap_printf(const char * format,...)43 int __wrap_printf(const char *format, ...) {
44     (void)format;
45     return 1;
46 }
47 
48 /* Rand with 0 seed would broke in the past */
test_rand_0(void ** state)49 static void test_rand_0(void **state) {
50     (void)state;
51 
52     afl_state_t afl = {0};
53     rand_set_seed(&afl, 0);
54 
55     /* give this one chance to retry */
56     assert_int_not_equal(
57         (rand_next(&afl) != rand_next(&afl)
58             || rand_next(&afl) != rand_next(&afl))
59             , 0);
60 
61 }
62 
test_rand_below(void ** state)63 static void test_rand_below(void **state) {
64     (void)state;
65 
66     afl_state_t afl = {0};
67     rand_set_seed(&afl, 1337);
68 
69     afl.fsrv.dev_urandom_fd = open("/dev/urandom", O_RDONLY);
70 
71     assert(!(rand_below(&afl, 9000) > 9000));
72     assert_int_equal(rand_below(&afl, 1), 0);
73 
74 }
75 
main(int argc,char ** argv)76 int main(int argc, char **argv) {
77     (void)argc;
78     (void)argv;
79 
80     const struct CMUnitTest tests[] = {
81         cmocka_unit_test(test_rand_0),
82         cmocka_unit_test(test_rand_below)
83     };
84 
85     //return cmocka_run_group_tests (tests, setup, teardown);
86     __real_exit( cmocka_run_group_tests (tests, NULL, NULL) );
87 
88     // fake return for dumb compilers
89     return 0;
90 }
91