xref: /aosp_15_r20/external/AFLplusplus/utils/aflpp_driver/aflpp_driver.c (revision 08b48e0b10e97b33e7b60c5b6e2243bd915777f2)
1 //
2 // afl_driver.cpp - a glue between AFL++ and LLVMFuzzerTestOneInput harnesses
3 //
4 
5 /*
6 
7  This file allows to fuzz libFuzzer-style target functions
8  (LLVMFuzzerTestOneInput) with AFL++ using persistent in-memory fuzzing.
9 
10 Usage:
11 
12 # Example target:
13 $ cat << EOF > test_fuzzer.cc
14 #include <stddef.h>
15 #include <stdint.h>
16 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
17 
18   if (size > 0 && data[0] == 'H')
19     if (size > 1 && data[1] == 'I')
20        if (size > 2 && data[2] == '!')
21        __builtin_trap();
22   return 0;
23 
24 }
25 
26 EOF
27 
28 # Build your target with afl-cc -fsanitize=fuzzer
29 $ afl-c++ -fsanitize=fuzzer -o test_fuzzer test_fuzzer.cc
30 # Run AFL:
31 $ mkdir -p in ; echo z > in/foo;
32 $ afl-fuzz -i in -o out -- ./test_fuzzer
33 
34 */
35 
36 #ifdef __cplusplus
37 extern "C" {
38 
39 #endif
40 
41 #include <assert.h>
42 #include <errno.h>
43 #include <stdarg.h>
44 #include <stdbool.h>
45 #include <stdint.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include <limits.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <sys/mman.h>
55 #ifndef __HAIKU__
56   #include <sys/syscall.h>
57 #endif
58 
59 #include "config.h"
60 #include "types.h"
61 #include "cmplog.h"
62 
63 #ifdef _DEBUG
64   #include "hash.h"
65 #endif
66 
67 // AFL++ shared memory fuzz cases
68 int                   __afl_sharedmem_fuzzing = 1;
69 extern unsigned int  *__afl_fuzz_len;
70 extern unsigned char *__afl_fuzz_ptr;
71 
72 // AFL++ coverage map
73 extern unsigned char *__afl_area_ptr;
74 extern unsigned int   __afl_map_size;
75 
76 // libFuzzer interface is thin, so we don't include any libFuzzer headers.
77 /* Using the weak attributed on LLVMFuzzerTestOneInput() breaks oss-fuzz but
78    on the other hand this is what Google needs to make LLVMFuzzerRunDriver()
79    work. Choose your poison Google! */
80 /*__attribute__((weak))*/ int LLVMFuzzerTestOneInput(const uint8_t *Data,
81                                                      size_t         Size);
82 __attribute__((weak)) int     LLVMFuzzerInitialize(int *argc, char ***argv);
83 __attribute__((weak)) int     LLVMFuzzerRunDriver(
84         int *argc, char ***argv, int (*callback)(const uint8_t *data, size_t size));
85 
86 // Default nop ASan hooks for manual poisoning when not linking the ASan
87 // runtime
88 // https://github.com/google/sanitizers/wiki/AddressSanitizerManualPoisoning
__asan_poison_memory_region(void const volatile * addr,size_t size)89 __attribute__((weak)) void __asan_poison_memory_region(
90     void const volatile *addr, size_t size) {
91 
92   (void)addr;
93   (void)size;
94 
95 }
96 
__asan_unpoison_memory_region(void const volatile * addr,size_t size)97 __attribute__((weak)) void __asan_unpoison_memory_region(
98     void const volatile *addr, size_t size) {
99 
100   (void)addr;
101   (void)size;
102 
103 }
104 
105 __attribute__((weak)) void *__asan_region_is_poisoned(void *beg, size_t size);
106 
107 // Notify AFL about persistent mode.
108 static volatile char AFL_PERSISTENT[] = "##SIG_AFL_PERSISTENT##";
109 int                  __afl_persistent_loop(unsigned int);
110 
111 // Notify AFL about deferred forkserver.
112 static volatile char AFL_DEFER_FORKSVR[] = "##SIG_AFL_DEFER_FORKSRV##";
113 void                 __afl_manual_init();
114 
115 // Use this optionally defined function to output sanitizer messages even if
116 // user asks to close stderr.
117 __attribute__((weak)) void __sanitizer_set_report_fd(void *);
118 
119 // Keep track of where stderr content is being written to, so that
120 // dup_and_close_stderr can use the correct one.
121 static FILE *output_file;
122 
123 // Experimental feature to use afl_driver without AFL's deferred mode.
124 // Needs to run before __afl_auto_init.
__decide_deferred_forkserver(void)125 __attribute__((constructor(0))) static void __decide_deferred_forkserver(void) {
126 
127   if (getenv("AFL_DRIVER_DONT_DEFER")) {
128 
129     if (unsetenv("__AFL_DEFER_FORKSRV")) {
130 
131       perror("Failed to unset __AFL_DEFER_FORKSRV");
132       abort();
133 
134     }
135 
136   }
137 
138 }
139 
140 // If the user asks us to duplicate stderr, then do it.
maybe_duplicate_stderr()141 static void maybe_duplicate_stderr() {
142 
143   char *stderr_duplicate_filename =
144       getenv("AFL_DRIVER_STDERR_DUPLICATE_FILENAME");
145 
146   if (!stderr_duplicate_filename) return;
147 
148   FILE *stderr_duplicate_stream =
149       freopen(stderr_duplicate_filename, "a+", stderr);
150 
151   if (!stderr_duplicate_stream) {
152 
153     fprintf(
154         stderr,
155         "Failed to duplicate stderr to AFL_DRIVER_STDERR_DUPLICATE_FILENAME");
156     abort();
157 
158   }
159 
160   output_file = stderr_duplicate_stream;
161 
162 }
163 
164 // Most of these I/O functions were inspired by/copied from libFuzzer's code.
discard_output(int fd)165 static void discard_output(int fd) {
166 
167   FILE *temp = fopen("/dev/null", "w");
168   if (!temp) abort();
169   dup2(fileno(temp), fd);
170   fclose(temp);
171 
172 }
173 
close_stdout()174 static void close_stdout() {
175 
176   discard_output(STDOUT_FILENO);
177 
178 }
179 
180 // Prevent the targeted code from writing to "stderr" but allow sanitizers and
181 // this driver to do so.
dup_and_close_stderr()182 static void dup_and_close_stderr() {
183 
184   int output_fileno = fileno(output_file);
185   int output_fd = dup(output_fileno);
186   if (output_fd <= 0) abort();
187   FILE *new_output_file = fdopen(output_fd, "w");
188   if (!new_output_file) abort();
189   if (!__sanitizer_set_report_fd) return;
190   __sanitizer_set_report_fd((void *)(long int)output_fd);
191   discard_output(output_fileno);
192 
193 }
194 
195 // Close stdout and/or stderr if user asks for it.
maybe_close_fd_mask()196 static void maybe_close_fd_mask() {
197 
198   char *fd_mask_str = getenv("AFL_DRIVER_CLOSE_FD_MASK");
199   if (!fd_mask_str) return;
200   int fd_mask = atoi(fd_mask_str);
201   if (fd_mask & 2) dup_and_close_stderr();
202   if (fd_mask & 1) close_stdout();
203 
204 }
205 
206 // Define LLVMFuzzerMutate to avoid link failures for targets that use it
207 // with libFuzzer's LLVMFuzzerCustomMutator.
LLVMFuzzerMutate(uint8_t * Data,size_t Size,size_t MaxSize)208 __attribute__((weak)) size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size,
209                                               size_t MaxSize) {
210 
211   // assert(false && "LLVMFuzzerMutate should not be called from afl_driver");
212   return 0;
213 
214 }
215 
216 // Execute any files provided as parameters.
ExecuteFilesOnyByOne(int argc,char ** argv,int (* callback)(const uint8_t * data,size_t size))217 static int ExecuteFilesOnyByOne(int argc, char **argv,
218                                 int (*callback)(const uint8_t *data,
219                                                 size_t         size)) {
220 
221   unsigned char *buf = (unsigned char *)malloc(MAX_FILE);
222 
223   __asan_poison_memory_region(buf, MAX_FILE);
224   ssize_t prev_length = 0;
225 
226   for (int i = 1; i < argc; i++) {
227 
228     int fd = 0;
229 
230     if (strcmp(argv[i], "-") != 0) { fd = open(argv[i], O_RDONLY); }
231 
232     if (fd == -1) { continue; }
233 
234 #ifndef __HAIKU__
235     ssize_t length = syscall(SYS_read, fd, buf, MAX_FILE);
236 #else
237     ssize_t length = _kern_read(fd, buf, MAX_FILE);
238 #endif  // HAIKU
239 
240     if (length > 0) {
241 
242       if (length < prev_length) {
243 
244         __asan_poison_memory_region(buf + length, prev_length - length);
245 
246       } else {
247 
248         __asan_unpoison_memory_region(buf + prev_length, length - prev_length);
249 
250       }
251 
252       prev_length = length;
253 
254       printf("Reading %zu bytes from %s\n", length, argv[i]);
255       callback(buf, length);
256       printf("Execution successful.\n");
257 
258     }
259 
260     if (fd > 0) { close(fd); }
261 
262   }
263 
264   free(buf);
265   return 0;
266 
267 }
268 
main(int argc,char ** argv)269 __attribute__((weak)) int main(int argc, char **argv) {
270 
271   // Enable if LLVMFuzzerTestOneInput() has the weak attribute
272   /*
273     if (!LLVMFuzzerTestOneInput) {
274 
275       fprintf(stderr, "Error: function LLVMFuzzerTestOneInput() not found!\n");
276       abort();
277 
278     }
279 
280   */
281 
282   if (argc < 2 || strncmp(argv[1], "-h", 2) == 0 ||
283       strcmp(argv[1], "--help") == 0) {
284 
285     printf(
286         "============================== INFO ================================\n"
287         "This binary is built for afl++.\n"
288         "To run the target function on individual input(s) execute:\n"
289         "  %s INPUT_FILE1 [INPUT_FILE2 ... ]\n"
290         "To fuzz with afl-fuzz execute:\n"
291         "  afl-fuzz [afl-flags] -- %s [-N]\n"
292         "afl-fuzz will run N iterations before re-spawning the process "
293         "(default: "
294         "INT_MAX)\n"
295         "You can also use AFL_FUZZER_LOOPCOUNT to set N\n"
296         "For stdin input processing, pass '-' as single command line option.\n"
297         "For file input processing, pass '@@' as single command line option.\n"
298         "To use with afl-cmin or afl-cmin.bash pass '-' as single command line "
299         "option\n"
300         "===================================================================\n",
301         argv[0], argv[0]);
302     if (argc == 2 &&
303         (strncmp(argv[1], "-h", 2) == 0 || strcmp(argv[1], "--help") == 0)) {
304 
305       exit(0);
306 
307     }
308 
309   }
310 
311   return LLVMFuzzerRunDriver(&argc, &argv, LLVMFuzzerTestOneInput);
312 
313 }
314 
LLVMFuzzerRunDriver(int * argcp,char *** argvp,int (* callback)(const uint8_t * data,size_t size))315 __attribute__((weak)) int LLVMFuzzerRunDriver(
316     int *argcp, char ***argvp,
317     int (*callback)(const uint8_t *data, size_t size)) {
318 
319   int    argc = *argcp;
320   char **argv = *argvp;
321 
322   if (getenv("AFL_GDB")) {
323 
324     char cmd[64];
325     snprintf(cmd, sizeof(cmd), "cat /proc/%d/maps", getpid());
326     system(cmd);
327     fprintf(stderr, "DEBUG: aflpp_driver pid is %d\n", getpid());
328     sleep(1);
329 
330   }
331 
332   bool in_afl = !(!getenv(SHM_FUZZ_ENV_VAR) || !getenv(SHM_ENV_VAR) ||
333                   fcntl(FORKSRV_FD, F_GETFD) == -1 ||
334                   fcntl(FORKSRV_FD + 1, F_GETFD) == -1);
335 
336   if (!in_afl) { __afl_sharedmem_fuzzing = 0; }
337 
338   output_file = stderr;
339   maybe_duplicate_stderr();
340   maybe_close_fd_mask();
341   if (LLVMFuzzerInitialize) {
342 
343     fprintf(stderr, "Running LLVMFuzzerInitialize ...\n");
344     LLVMFuzzerInitialize(&argc, &argv);
345     fprintf(stderr, "continue...\n");
346 
347   }
348 
349   // Do any other expensive one-time initialization here.
350 
351   uint8_t dummy_input[64] = {0};
352   memcpy(dummy_input, (void *)AFL_PERSISTENT, sizeof(AFL_PERSISTENT));
353   memcpy(dummy_input + 32, (void *)AFL_DEFER_FORKSVR,
354          sizeof(AFL_DEFER_FORKSVR));
355 
356   int N = INT_MAX;
357 
358   if (!in_afl && argc == 2 && !strcmp(argv[1], "-")) {
359 
360     __afl_manual_init();
361     return ExecuteFilesOnyByOne(argc, argv, callback);
362 
363   } else if (argc == 2 && argv[1][0] == '-' && argv[1][1]) {
364 
365     N = atoi(argv[1] + 1);
366 
367   } else if (argc == 2 && argv[1][0] != '-' && (N = atoi(argv[1])) > 0) {
368 
369     printf("WARNING: using the deprecated call style `%s %d`\n", argv[0], N);
370 
371   } else if (!in_afl && argc > 1 && argv[1][0] != '-') {
372 
373     if (argc == 2) { __afl_manual_init(); }
374 
375     return ExecuteFilesOnyByOne(argc, argv, callback);
376 
377   } else {
378 
379     N = INT_MAX;
380 
381   }
382 
383   if (getenv("AFL_FUZZER_LOOPCOUNT")) {
384 
385     N = atoi(getenv("AFL_FUZZER_LOOPCOUNT"));
386 
387   }
388 
389   assert(N > 0);
390 
391   __afl_manual_init();
392 
393   // Call LLVMFuzzerTestOneInput here so that coverage caused by initialization
394   // on the first execution of LLVMFuzzerTestOneInput is ignored.
395   callback(dummy_input, 4);
396 
397   __asan_poison_memory_region(__afl_fuzz_ptr, MAX_FILE);
398   size_t prev_length = 0;
399 
400   // for speed only insert asan functions if the target is linked with asan
401   if (__asan_region_is_poisoned) {
402 
403     while (__afl_persistent_loop(N)) {
404 
405       size_t length = *__afl_fuzz_len;
406 
407       if (likely(length)) {
408 
409         if (length < prev_length) {
410 
411           __asan_poison_memory_region(__afl_fuzz_ptr + length,
412                                       prev_length - length);
413 
414         } else if (length > prev_length) {
415 
416           __asan_unpoison_memory_region(__afl_fuzz_ptr + prev_length,
417                                         length - prev_length);
418 
419         }
420 
421         prev_length = length;
422 
423         if (unlikely(callback(__afl_fuzz_ptr, length) == -1)) {
424 
425           memset(__afl_area_ptr, 0, __afl_map_size);
426           __afl_area_ptr[0] = 1;
427 
428         }
429 
430       }
431 
432     }
433 
434   } else {
435 
436     while (__afl_persistent_loop(N)) {
437 
438       callback(__afl_fuzz_ptr, *__afl_fuzz_len);
439 
440     }
441 
442   }
443 
444   return 0;
445 
446 }
447 
448 #ifdef __cplusplus
449 
450 }
451 
452 #endif
453 
454