xref: /aosp_15_r20/external/AFLplusplus/include/afl-fuzz.h (revision 08b48e0b10e97b33e7b60c5b6e2243bd915777f2)
1 /*
2    american fuzzy lop++ - fuzzer header
3    ------------------------------------
4 
5    Originally written by Michal Zalewski
6 
7    Now maintained by Marc Heuse <[email protected]>,
8                      Heiko Eißfeldt <[email protected]>,
9                      Andrea Fioraldi <[email protected]>,
10                      Dominik Maier <[email protected]>
11 
12    Copyright 2016, 2017 Google Inc. All rights reserved.
13    Copyright 2019-2024 AFLplusplus Project. All rights reserved.
14 
15    Licensed under the Apache License, Version 2.0 (the "License");
16    you may not use this file except in compliance with the License.
17    You may obtain a copy of the License at:
18 
19      https://www.apache.org/licenses/LICENSE-2.0
20 
21    This is the real deal: the program takes an instrumented binary and
22    attempts a variety of basic fuzzing tricks, paying close attention to
23    how they affect the execution path.
24 
25  */
26 
27 #ifndef _AFL_FUZZ_H
28 #define _AFL_FUZZ_H
29 
30 #define AFL_MAIN
31 #define MESSAGES_TO_STDOUT
32 
33 #ifndef _GNU_SOURCE
34   #define _GNU_SOURCE
35 #endif
36 #ifndef _FILE_OFFSET_BITS
37   #define _FILE_OFFSET_BITS 64
38 #endif
39 
40 #include "config.h"
41 #include "types.h"
42 #include "debug.h"
43 #include "alloc-inl.h"
44 #include "hash.h"
45 #include "sharedmem.h"
46 #include "forkserver.h"
47 #include "common.h"
48 
49 #include <stdio.h>
50 #include <unistd.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <time.h>
54 #include <errno.h>
55 #include <signal.h>
56 #include <dirent.h>
57 #include <ctype.h>
58 #include <fcntl.h>
59 #include <termios.h>
60 #include <dlfcn.h>
61 #include <sched.h>
62 
63 #include <netdb.h>
64 #include <netinet/in.h>
65 
66 #include <sys/wait.h>
67 #include <sys/time.h>
68 #ifndef USEMMAP
69   #include <sys/shm.h>
70 #endif
71 #include <sys/stat.h>
72 #include <sys/types.h>
73 #include <sys/resource.h>
74 #include <sys/mman.h>
75 #include <sys/ioctl.h>
76 #include <sys/file.h>
77 #include <sys/types.h>
78 
79 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
80     defined(__NetBSD__) || defined(__DragonFly__)
81   #include <sys/sysctl.h>
82 #endif                           /* __APPLE__ || __FreeBSD__ || __OpenBSD__ */
83 
84 #if defined(__HAIKU__)
85   #include <kernel/OS.h>
86   #include <kernel/scheduler.h>
87 #endif
88 
89 /* For systems that have sched_setaffinity; right now just Linux, but one
90    can hope... */
91 
92 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
93     defined(__DragonFly__) || defined(__sun)
94   #define HAVE_AFFINITY 1
95   #if defined(__FreeBSD__) || defined(__DragonFly__)
96     #include <sys/param.h>
97     #if defined(__FreeBSD__)
98       #include <sys/cpuset.h>
99     #endif
100     #include <sys/user.h>
101     #include <pthread.h>
102     #include <pthread_np.h>
103     #define cpu_set_t cpuset_t
104   #elif defined(__NetBSD__)
105     #include <pthread.h>
106   #elif defined(__sun)
107     #include <sys/types.h>
108     #include <kstat.h>
109     #include <sys/sysinfo.h>
110     #include <sys/pset.h>
111     #include <strings.h>
112   #endif
113 #endif                                                         /* __linux__ */
114 
115 #ifdef __APPLE__
116   #include <TargetConditionals.h>
117 #endif
118 
119 #undef LIST_FOREACH                                 /* clashes with FreeBSD */
120 #include "list.h"
121 #ifndef SIMPLE_FILES
122   #define CASE_PREFIX "id:"
123 #else
124   #define CASE_PREFIX "id_"
125 #endif                                                    /* ^!SIMPLE_FILES */
126 
127 #define STAGE_BUF_SIZE (64)  /* usable size for stage name buf in afl_state */
128 
129 // Little helper to access the ptr to afl->##name_buf - for use in afl_realloc.
130 #define AFL_BUF_PARAM(name) ((void **)&afl->name##_buf)
131 
132 #ifdef WORD_SIZE_64
133   #define AFL_RAND_RETURN u64
134 #else
135   #define AFL_RAND_RETURN u32
136 #endif
137 
138 extern s8  interesting_8[INTERESTING_8_LEN];
139 extern s16 interesting_16[INTERESTING_8_LEN + INTERESTING_16_LEN];
140 extern s32
141     interesting_32[INTERESTING_8_LEN + INTERESTING_16_LEN + INTERESTING_32_LEN];
142 
143 struct tainted {
144 
145   u32             pos;
146   u32             len;
147   struct tainted *next;
148   struct tainted *prev;
149 
150 };
151 
152 struct inf_profile {
153 
154   u32 inf_skipped_bytes;               /* Inference Stage Profiling         */
155   u64 inf_execs_cost, inf_time_cost;
156 
157 };
158 
159 /* ToDo: add cmplog profile as well */
160 struct havoc_profile {
161 
162   u32 queued_det_stage,                 /* Det/Havoc Stage Profiling        */
163       queued_havoc_stage, total_queued_det, edge_det_stage, edge_havoc_stage,
164       total_det_edge;
165 
166   u64 det_stage_time, havoc_stage_time, total_det_time;
167 
168 };
169 
170 struct skipdet_entry {
171 
172   u8  continue_inf, done_eff;
173   u32 undet_bits, quick_eff_bytes;
174 
175   u8 *skip_eff_map,                     /* we'v finish the eff_map          */
176       *done_inf_map;                    /* some bytes are not done yet      */
177 
178 };
179 
180 struct skipdet_global {
181 
182   u8 use_skip_havoc;
183 
184   u32 undet_bits_threshold;
185 
186   u64 last_cov_undet;
187 
188   u8 *virgin_det_bits;                  /* global fuzzed bits               */
189 
190   struct inf_profile *inf_prof;
191 
192 };
193 
194 struct queue_entry {
195 
196   u8 *fname;                            /* File name for the test case      */
197   u32 len;                              /* Input length                     */
198   u32 id;                               /* entry number in queue_buf        */
199 
200   u8 colorized,                         /* Do not run redqueen stage again  */
201       cal_failed;                       /* Calibration failed?              */
202 
203   bool trim_done,                       /* Trimmed?                         */
204       was_fuzzed,                       /* historical, but needed for MOpt  */
205       passed_det,                       /* Deterministic stages passed?     */
206       has_new_cov,                      /* Triggers new coverage?           */
207       var_behavior,                     /* Variable behavior?               */
208       favored,                          /* Currently favored?               */
209       fs_redundant,                     /* Marked as redundant in the fs?   */
210       is_ascii,                         /* Is the input just ascii text?    */
211       disabled;                         /* Is disabled from fuzz selection  */
212 
213   u32 bitmap_size,                      /* Number of bits set in bitmap     */
214 #ifdef INTROSPECTION
215       stats_selected,                   /* stats: how often selected        */
216       stats_skipped,                    /* stats: how often skipped         */
217       stats_finds,                      /* stats: # of saved finds          */
218       stats_crashes,                    /* stats: # of saved crashes        */
219       stats_tmouts,                     /* stats: # of saved timeouts       */
220 #endif
221       fuzz_level,                       /* Number of fuzzing iterations     */
222       n_fuzz_entry;                     /* offset in n_fuzz                 */
223 
224   u64 exec_us,                          /* Execution time (us)              */
225       handicap,                         /* Number of queue cycles behind    */
226       depth,                            /* Path depth                       */
227       exec_cksum,                       /* Checksum of the execution trace  */
228       custom,                           /* Marker for custom mutators       */
229       stats_mutated;                    /* stats: # of mutations performed  */
230 
231   u8 *trace_mini;                       /* Trace bytes, if kept             */
232   u32 tc_ref;                           /* Trace bytes ref count            */
233 
234 #ifdef INTROSPECTION
235   u32 bitsmap_size;
236 #endif
237 
238   double perf_score,                    /* performance score                */
239       weight;
240 
241   u8 *testcase_buf;                     /* The testcase buffer, if loaded.  */
242 
243   u8             *cmplog_colorinput;    /* the result buf of colorization   */
244   struct tainted *taint;                /* Taint information from CmpLog    */
245 
246   struct queue_entry *mother;           /* queue entry this based on        */
247 
248   struct skipdet_entry *skipdet_e;
249 
250 };
251 
252 struct extra_data {
253 
254   u8 *data;                             /* Dictionary token data            */
255   u32 len;                              /* Dictionary token length          */
256   u32 hit_cnt;                          /* Use count in the corpus          */
257 
258 };
259 
260 struct auto_extra_data {
261 
262   u8  data[MAX_AUTO_EXTRA];             /* Dictionary token data            */
263   u32 len;                              /* Dictionary token length          */
264   u32 hit_cnt;                          /* Use count in the corpus          */
265 
266 };
267 
268 /* Fuzzing stages */
269 
270 enum {
271 
272   /* 00 */ STAGE_FLIP1,
273   /* 01 */ STAGE_FLIP2,
274   /* 02 */ STAGE_FLIP4,
275   /* 03 */ STAGE_FLIP8,
276   /* 04 */ STAGE_FLIP16,
277   /* 05 */ STAGE_FLIP32,
278   /* 06 */ STAGE_ARITH8,
279   /* 07 */ STAGE_ARITH16,
280   /* 08 */ STAGE_ARITH32,
281   /* 09 */ STAGE_INTEREST8,
282   /* 10 */ STAGE_INTEREST16,
283   /* 11 */ STAGE_INTEREST32,
284   /* 12 */ STAGE_EXTRAS_UO,
285   /* 13 */ STAGE_EXTRAS_UI,
286   /* 14 */ STAGE_EXTRAS_AO,
287   /* 15 */ STAGE_EXTRAS_AI,
288   /* 16 */ STAGE_HAVOC,
289   /* 17 */ STAGE_SPLICE,
290   /* 18 */ STAGE_PYTHON,
291   /* 19 */ STAGE_CUSTOM_MUTATOR,
292   /* 20 */ STAGE_COLORIZATION,
293   /* 21 */ STAGE_ITS,
294   /* 22 */ STAGE_INF,
295   /* 23 */ STAGE_QUICK,
296 
297   STAGE_NUM_MAX
298 
299 };
300 
301 /* Stage value types */
302 
303 enum {
304 
305   /* 00 */ STAGE_VAL_NONE,
306   /* 01 */ STAGE_VAL_LE,
307   /* 02 */ STAGE_VAL_BE
308 
309 };
310 
311 #define operator_num 19
312 #define swarm_num 5
313 #define period_core 500000
314 
315 #define RAND_C (rand() % 1000 * 0.001)
316 #define v_max 1
317 #define v_min 0.05
318 #define limit_time_bound 1.1
319 #define SPLICE_CYCLES_puppet_up 25
320 #define SPLICE_CYCLES_puppet_low 5
321 #define STAGE_RANDOMBYTE 12
322 #define STAGE_DELETEBYTE 13
323 #define STAGE_Clone75 14
324 #define STAGE_OverWrite75 15
325 #define STAGE_OverWriteExtra 16
326 #define STAGE_InsertExtra 17
327 #define STAGE_Splice 18
328 #define period_pilot 50000
329 
330 enum {
331 
332   /* 00 */ EXPLORE, /* AFL default, Exploration-based constant schedule */
333   /* 01 */ MMOPT,   /* Modified MOPT schedule           */
334   /* 02 */ EXPLOIT, /* AFL's exploitation-based const.  */
335   /* 03 */ FAST,    /* Exponential schedule             */
336   /* 04 */ COE,     /* Cut-Off Exponential schedule     */
337   /* 05 */ LIN,     /* Linear schedule                  */
338   /* 06 */ QUAD,    /* Quadratic schedule               */
339   /* 07 */ RARE,    /* Rare edges                       */
340   /* 08 */ SEEK,    /* EXPLORE that ignores timings     */
341 
342   POWER_SCHEDULES_NUM
343 
344 };
345 
346 /* Python stuff */
347 #ifdef USE_PYTHON
348 
349   // because Python sets stuff it should not ...
350   #ifdef _POSIX_C_SOURCE
351     #define _SAVE_POSIX_C_SOURCE _POSIX_C_SOURCE
352     #undef _POSIX_C_SOURCE
353   #endif
354   #ifdef _XOPEN_SOURCE
355     #define _SAVE_XOPEN_SOURCE _XOPEN_SOURCE
356     #undef _XOPEN_SOURCE
357   #endif
358 
359   #include <Python.h>
360 
361   #ifdef _SAVE_POSIX_C_SOURCE
362     #ifdef _POSIX_C_SOURCE
363       #undef _POSIX_C_SOURCE
364     #endif
365     #define _POSIX_C_SOURCE _SAVE_POSIX_C_SOURCE
366   #endif
367   #ifdef _SAVE_XOPEN_SOURCE
368     #ifdef _XOPEN_SOURCE
369       #undef _XOPEN_SOURCE
370     #endif
371     #define _XOPEN_SOURCE _SAVE_XOPEN_SOURCE
372   #endif
373 
374 enum {
375 
376   /* 00 */ PY_FUNC_INIT,
377   /* 01 */ PY_FUNC_DEINIT,
378   /* FROM HERE ON BELOW ALL ARE OPTIONAL */
379   /* 02 */ PY_OPTIONAL = 2,
380   /* 02 */ PY_FUNC_FUZZ = 2,
381   /* 03 */ PY_FUNC_FUZZ_COUNT,
382   /* 04 */ PY_FUNC_POST_PROCESS,
383   /* 05 */ PY_FUNC_INIT_TRIM,
384   /* 06 */ PY_FUNC_POST_TRIM,
385   /* 07 */ PY_FUNC_TRIM,
386   /* 08 */ PY_FUNC_HAVOC_MUTATION,
387   /* 09 */ PY_FUNC_HAVOC_MUTATION_PROBABILITY,
388   /* 10 */ PY_FUNC_QUEUE_GET,
389   /* 11 */ PY_FUNC_QUEUE_NEW_ENTRY,
390   /* 12 */ PY_FUNC_INTROSPECTION,
391   /* 13 */ PY_FUNC_DESCRIBE,
392   /* 14 */ PY_FUNC_FUZZ_SEND,
393   /* 15 */ PY_FUNC_SPLICE_OPTOUT,
394   /* 16 */ PY_FUNC_POST_RUN,
395   PY_FUNC_COUNT
396 
397 };
398 
399 typedef struct py_mutator {
400 
401   PyObject *py_module;
402   PyObject *py_functions[PY_FUNC_COUNT];
403   void     *afl_state;
404   void     *py_data;
405 
406   u8    *fuzz_buf;
407   size_t fuzz_size;
408 
409   Py_buffer post_process_buf;
410 
411   u8    *trim_buf;
412   size_t trim_size;
413 
414   u8    *havoc_buf;
415   size_t havoc_size;
416 
417 } py_mutator_t;
418 
419 #endif
420 
421 typedef struct MOpt_globals {
422 
423   u64  *finds;
424   u64  *finds_v2;
425   u64  *cycles;
426   u64  *cycles_v2;
427   u64  *cycles_v3;
428   u32   is_pilot_mode;
429   u64  *pTime;
430   u64   period;
431   char *havoc_stagename;
432   char *splice_stageformat;
433   char *havoc_stagenameshort;
434   char *splice_stagenameshort;
435 
436 } MOpt_globals_t;
437 
438 extern char *power_names[POWER_SCHEDULES_NUM];
439 
440 typedef struct afl_env_vars {
441 
442   u8 afl_skip_cpufreq, afl_exit_when_done, afl_no_affinity, afl_skip_bin_check,
443       afl_dumb_forksrv, afl_import_first, afl_custom_mutator_only, afl_no_ui,
444       afl_force_ui, afl_i_dont_care_about_missing_crashes, afl_bench_just_one,
445       afl_bench_until_crash, afl_debug_child, afl_autoresume, afl_cal_fast,
446       afl_cycle_schedules, afl_expand_havoc, afl_statsd, afl_cmplog_only_new,
447       afl_exit_on_seed_issues, afl_try_affinity, afl_ignore_problems,
448       afl_keep_timeouts, afl_no_crash_readme, afl_ignore_timeouts,
449       afl_no_startup_calibration, afl_no_warn_instability,
450       afl_post_process_keep_original, afl_crashing_seeds_as_new_crash,
451       afl_final_sync, afl_ignore_seed_problems;
452 
453   u8 *afl_tmpdir, *afl_custom_mutator_library, *afl_python_module, *afl_path,
454       *afl_hang_tmout, *afl_forksrv_init_tmout, *afl_preload,
455       *afl_max_det_extras, *afl_statsd_host, *afl_statsd_port,
456       *afl_crash_exitcode, *afl_statsd_tags_flavor, *afl_testcache_size,
457       *afl_testcache_entries, *afl_child_kill_signal, *afl_fsrv_kill_signal,
458       *afl_target_env, *afl_persistent_record, *afl_exit_on_time;
459 
460   s32 afl_pizza_mode;
461 
462 } afl_env_vars_t;
463 
464 struct afl_pass_stat {
465 
466   u8 total;
467   u8 faileds;
468 
469 };
470 
471 struct foreign_sync {
472 
473   u8    *dir;
474   time_t mtime;
475 
476 };
477 
478 typedef struct afl_state {
479 
480   /* Position of this state in the global states list */
481   u32 _id;
482 
483   afl_forkserver_t fsrv;
484   sharedmem_t      shm;
485   sharedmem_t     *shm_fuzz;
486   afl_env_vars_t   afl_env;
487 
488   char **argv;                                            /* argv if needed */
489 
490   /* MOpt:
491     Lots of globals, but mostly for the status UI and other things where it
492     really makes no sense to haul them around as function parameters. */
493   u64 orig_hit_cnt_puppet, last_limit_time_start, tmp_pilot_time,
494       total_pacemaker_time, total_puppet_find, temp_puppet_find, most_time_key,
495       most_time, most_execs_key, most_execs, old_hit_count, force_ui_update,
496       prev_run_time;
497 
498   MOpt_globals_t mopt_globals_core, mopt_globals_pilot;
499 
500   s32 limit_time_puppet, SPLICE_CYCLES_puppet, limit_time_sig, key_puppet,
501       key_module;
502 
503   double w_init, w_end, w_now;
504 
505   s32 g_now;
506   s32 g_max;
507 
508   u64 tmp_core_time;
509   s32 swarm_now;
510 
511   double x_now[swarm_num][operator_num], L_best[swarm_num][operator_num],
512       eff_best[swarm_num][operator_num], G_best[operator_num],
513       v_now[swarm_num][operator_num], probability_now[swarm_num][operator_num],
514       swarm_fitness[swarm_num];
515 
516   u64 stage_finds_puppet[swarm_num][operator_num], /* Patterns found per
517                                                             fuzz stage    */
518       stage_finds_puppet_v2[swarm_num][operator_num],
519       stage_cycles_puppet_v2[swarm_num][operator_num],
520       stage_cycles_puppet_v3[swarm_num][operator_num],
521       stage_cycles_puppet[swarm_num][operator_num],
522       operator_finds_puppet[operator_num],
523       core_operator_finds_puppet[operator_num],
524       core_operator_finds_puppet_v2[operator_num],
525       core_operator_cycles_puppet[operator_num],
526       core_operator_cycles_puppet_v2[operator_num],
527       core_operator_cycles_puppet_v3[operator_num]; /* Execs per fuzz stage */
528 
529   double period_pilot_tmp;
530   s32    key_lv;
531 
532   u8 *in_dir,                           /* Input directory with test cases  */
533       *out_dir,                         /* Working & output directory       */
534       *tmp_dir,                         /* Temporary directory for input    */
535       *sync_dir,                        /* Synchronization directory        */
536       *sync_id,                         /* Fuzzer ID                        */
537       *power_name,                      /* Power schedule name              */
538       *use_banner,                      /* Display banner                   */
539       *in_bitmap,                       /* Input bitmap                     */
540       *file_extension,                  /* File extension                   */
541       *orig_cmdline,                    /* Original command line            */
542       *infoexec;                       /* Command to execute on a new crash */
543 
544   u32 hang_tmout,                       /* Timeout used for hang det (ms)   */
545       stats_update_freq;                /* Stats update frequency (execs)   */
546 
547   u8 havoc_stack_pow2,                  /* HAVOC_STACK_POW2                 */
548       no_unlink,                        /* do not unlink cur_input          */
549       debug,                            /* Debug mode                       */
550       custom_only,                      /* Custom mutator only mode         */
551       custom_splice_optout,             /* Custom mutator no splice buffer  */
552       is_main_node,                     /* if this is the main node         */
553       is_secondary_node,                /* if this is a secondary instance  */
554       pizza_is_served,                  /* pizza mode                       */
555       input_mode,                       /* target wants text inputs         */
556       fuzz_mode,          /* coverage/exploration or crash/exploitation mode */
557       schedule,                         /* Power schedule (default: EXPLORE)*/
558       havoc_max_mult,                   /* havoc multiplier                 */
559       skip_deterministic,               /* Skip deterministic stages?       */
560       use_splicing,                     /* Recombine input files?           */
561       non_instrumented_mode,            /* Run in non-instrumented mode?    */
562       score_changed,                    /* Scoring for favorites changed?   */
563       resuming_fuzz,                    /* Resuming an older fuzzing job?   */
564       timeout_given,                    /* Specific timeout given?          */
565       not_on_tty,                       /* stdout is not a tty              */
566       term_too_small,                   /* terminal dimensions too small    */
567       no_forkserver,                    /* Disable forkserver?              */
568       crash_mode,                       /* Crash mode! Yeah!                */
569       in_place_resume,                  /* Attempt in-place resume?         */
570       autoresume,                       /* Resume if afl->out_dir exists?   */
571       auto_changed,                     /* Auto-generated tokens changed?   */
572       no_cpu_meter_red,                 /* Feng shui on the status screen   */
573       no_arith,                         /* Skip most arithmetic ops         */
574       shuffle_queue,                    /* Shuffle input queue?             */
575       bitmap_changed,                   /* Time to update bitmap?           */
576       unicorn_mode,                     /* Running in Unicorn mode?         */
577       use_wine,                         /* Use WINE with QEMU mode          */
578       skip_requested,                   /* Skip request, via SIGUSR1        */
579       run_over10m,                      /* Run time over 10 minutes?        */
580       persistent_mode,                  /* Running in persistent mode?      */
581       deferred_mode,                    /* Deferred forkserver mode?        */
582       fixed_seed,                       /* do not reseed                    */
583       fast_cal,                         /* Try to calibrate faster?         */
584       disable_trim,                     /* Never trim in fuzz_one           */
585       shmem_testcase_mode,              /* If sharedmem testcases are used  */
586       expand_havoc,                /* perform expensive havoc after no find */
587       cycle_schedules,                  /* cycle power schedules?           */
588       old_seed_selection,               /* use vanilla afl seed selection   */
589       reinit_table;                     /* reinit the queue weight table    */
590 
591   u8 *virgin_bits,                      /* Regions yet untouched by fuzzing */
592       *virgin_tmout,                    /* Bits we haven't seen in tmouts   */
593       *virgin_crash;                    /* Bits we haven't seen in crashes  */
594 
595   double *alias_probability;            /* alias weighted probabilities     */
596   u32    *alias_table;                /* alias weighted random lookup table */
597   u32     active_items;                 /* enabled entries in the queue     */
598 
599   u8 *var_bytes;                        /* Bytes that appear to be variable */
600 
601 #define N_FUZZ_SIZE (1 << 21)
602   u32 *n_fuzz;
603 
604   volatile u8 stop_soon,                /* Ctrl-C pressed?                  */
605       clear_screen;                     /* Window resized?                  */
606 
607   u32 queued_items,                     /* Total number of queued testcases */
608       queued_variable,                  /* Testcases with variable behavior */
609       queued_at_start,                  /* Total number of initial inputs   */
610       queued_discovered,                /* Items discovered during this run */
611       queued_imported,                  /* Items imported via -S            */
612       queued_favored,                   /* Paths deemed favorable           */
613       queued_with_cov,                  /* Paths with new coverage bytes    */
614       pending_not_fuzzed,               /* Queued but not done yet          */
615       pending_favored,                  /* Pending favored paths            */
616       cur_skipped_items,                /* Abandoned inputs in cur cycle    */
617       cur_depth,                        /* Current path depth               */
618       max_depth,                        /* Max path depth                   */
619       useless_at_start,                 /* Number of useless starting paths */
620       var_byte_count,                   /* Bitmap bytes with var behavior   */
621       current_entry,                    /* Current queue entry ID           */
622       havoc_div,                        /* Cycle count divisor for havoc    */
623       max_det_extras;                   /* deterministic extra count (dicts)*/
624 
625   u64 total_crashes,                    /* Total number of crashes          */
626       saved_crashes,                    /* Crashes with unique signatures   */
627       total_tmouts,                     /* Total number of timeouts         */
628       saved_tmouts,                     /* Timeouts with unique signatures  */
629       saved_hangs,                      /* Hangs with unique signatures     */
630       last_crash_execs,                 /* Exec counter at last crash       */
631       queue_cycle,                      /* Queue round counter              */
632       cycles_wo_finds,                  /* Cycles without any new paths     */
633       trim_execs,                       /* Execs done to trim input files   */
634       bytes_trim_in,                    /* Bytes coming into the trimmer    */
635       bytes_trim_out,                   /* Bytes coming outa the trimmer    */
636       blocks_eff_total,                 /* Blocks subject to effector maps  */
637       blocks_eff_select,                /* Blocks selected as fuzzable      */
638       start_time,                       /* Unix start time (ms)             */
639       last_sync_time,                   /* Time of last sync                */
640       last_sync_cycle,                  /* Cycle no. of the last sync       */
641       last_find_time,                   /* Time for most recent path (ms)   */
642       last_crash_time,                  /* Time for most recent crash (ms)  */
643       last_hang_time,                   /* Time for most recent hang (ms)   */
644       longest_find_time,                /* Longest time taken for a find    */
645       exit_on_time,                     /* Delay to exit if no new paths    */
646       sync_time,                        /* Sync time (ms)                   */
647       switch_fuzz_mode;                 /* auto or fixed fuzz mode          */
648 
649   u32 slowest_exec_ms,                  /* Slowest testcase non hang in ms  */
650       subseq_tmouts;                    /* Number of timeouts in a row      */
651 
652   u8 *stage_name,                       /* Name of the current fuzz stage   */
653       *stage_short,                     /* Short stage name                 */
654       *syncing_party;                   /* Currently syncing with...        */
655 
656   u8 stage_name_buf[STAGE_BUF_SIZE];    /* reused stagename buf with len 64 */
657 
658   u32 stage_cur, stage_max;             /* Stage progression                */
659   s32 splicing_with;                    /* Splicing with which test case?   */
660   s64 smallest_favored;                 /* smallest queue id favored        */
661 
662   u32 main_node_id, main_node_max;      /*   Main instance job splitting    */
663 
664   u32 syncing_case;                     /* Syncing with case #...           */
665 
666   s32 stage_cur_byte,                   /* Byte offset of current stage op  */
667       stage_cur_val;                    /* Value used for stage op          */
668 
669   u8 stage_val_type;                    /* Value type (STAGE_VAL_*)         */
670 
671   u64 stage_finds[32],                  /* Patterns found per fuzz stage    */
672       stage_cycles[32];                 /* Execs per fuzz stage             */
673 
674   u32 rand_cnt;                         /* Random number counter            */
675 
676   /*  unsigned long rand_seed[3]; would also work */
677   AFL_RAND_RETURN rand_seed[3];
678   s64             init_seed;
679 
680   u64 total_cal_us,                     /* Total calibration time (us)      */
681       total_cal_cycles;                 /* Total calibration cycles         */
682 
683   u64 total_bitmap_size,                /* Total bit count for all bitmaps  */
684       total_bitmap_entries;             /* Number of bitmaps counted        */
685 
686   s32 cpu_core_count,                   /* CPU core count                   */
687       cpu_to_bind;                      /* bind to specific CPU             */
688 
689 #ifdef HAVE_AFFINITY
690   s32 cpu_aff;                          /* Selected CPU core                */
691 #endif                                                     /* HAVE_AFFINITY */
692 
693   struct queue_entry *queue,            /* Fuzzing queue (linked list)      */
694       *queue_cur,                       /* Current offset within the queue  */
695       *queue_top;                       /* Top of the list                  */
696 
697   // growing buf
698   struct queue_entry **queue_buf;
699 
700   struct queue_entry **top_rated;           /* Top entries for bitmap bytes */
701 
702   struct extra_data *extras;            /* Extra tokens to fuzz with        */
703   u32                extras_cnt;        /* Total number of tokens read      */
704 
705   struct auto_extra_data
706       a_extras[MAX_AUTO_EXTRAS];        /* Automatically selected extras    */
707   u32 a_extras_cnt;                     /* Total number of tokens available */
708 
709   /* afl_postprocess API - Now supported via custom mutators */
710 
711   /* CmpLog */
712 
713   char            *cmplog_binary;
714   afl_forkserver_t cmplog_fsrv;     /* cmplog has its own little forkserver */
715 
716   /* Custom mutators */
717   struct custom_mutator *mutator;
718 
719   /* cmplog forkserver ids */
720   s32 cmplog_fsrv_ctl_fd, cmplog_fsrv_st_fd;
721   u32 cmplog_prev_timed_out;
722   u32 cmplog_max_filesize;
723   u32 cmplog_lvl;
724   u32 colorize_success;
725   u8  cmplog_enable_arith, cmplog_enable_transform, cmplog_enable_scale,
726       cmplog_enable_xtreme_transform, cmplog_random_colorization;
727 
728   struct afl_pass_stat *pass_stats;
729   struct cmp_map       *orig_cmp_map;
730 
731   u8 describe_op_buf_256[256]; /* describe_op will use this to return a string
732                                   up to 256 */
733 
734   unsigned long long int last_avg_exec_update;
735   u32                    last_avg_execs;
736   double                 last_avg_execs_saved;
737 
738 /* foreign sync */
739 #define FOREIGN_SYNCS_MAX 32U
740   u8                  foreign_sync_cnt;
741   struct foreign_sync foreign_syncs[FOREIGN_SYNCS_MAX];
742 
743 #ifdef _AFL_DOCUMENT_MUTATIONS
744   u8  do_document;
745   u32 document_counter;
746 #endif
747 
748   /* statistics file */
749   double last_bitmap_cvg, last_stability, last_eps;
750   u64    stats_file_update_freq_msecs;  /* Stats update frequency (msecs)   */
751 
752   /* plot file saves from last run */
753   u32 plot_prev_qp, plot_prev_pf, plot_prev_pnf, plot_prev_ce, plot_prev_md;
754   u64 plot_prev_qc, plot_prev_uc, plot_prev_uh, plot_prev_ed;
755 
756   u64 stats_last_stats_ms, stats_last_plot_ms, stats_last_queue_ms,
757       stats_last_ms, stats_last_execs;
758 
759   /* StatsD */
760   u64                statsd_last_send_ms;
761   struct sockaddr_in statsd_server;
762   int                statsd_sock;
763   char              *statsd_tags_flavor;
764   char              *statsd_tags_format;
765   char              *statsd_metric_format;
766   int                statsd_metric_format_type;
767 
768   double stats_avg_exec;
769 
770   u8 *clean_trace;
771   u8 *clean_trace_custom;
772   u8 *first_trace;
773 
774   /*needed for afl_fuzz_one */
775   // TODO: see which we can reuse
776   u8 *out_buf;
777 
778   u8 *out_scratch_buf;
779 
780   u8 *eff_buf;
781 
782   u8 *in_buf;
783 
784   u8 *in_scratch_buf;
785 
786   u8 *ex_buf;
787 
788   u8 *testcase_buf, *splicecase_buf;
789 
790   u32 custom_mutators_count;
791 
792   struct custom_mutator *current_custom_fuzz;
793 
794   list_t custom_mutator_list;
795 
796   /* this is a fixed buffer of size map_size that can be used by any function if
797    * they do not call another function */
798   u8 *map_tmp_buf;
799 
800   /* queue entries ready for splicing count (len > 4) */
801   u32 ready_for_splicing_count;
802 
803   /* min/max length for generated fuzzing inputs */
804   u32 min_length, max_length;
805 
806   /* This is the user specified maximum size to use for the testcase cache */
807   u64 q_testcase_max_cache_size;
808 
809   /* This is the user specified maximum entries in the testcase cache */
810   u32 q_testcase_max_cache_entries;
811 
812   /* How much of the testcase cache is used so far */
813   u64 q_testcase_cache_size;
814 
815   /* highest cache count so far */
816   u32 q_testcase_max_cache_count;
817 
818   /* How many queue entries currently have cached testcases */
819   u32 q_testcase_cache_count;
820 
821   /* the smallest id currently known free entry */
822   u32 q_testcase_smallest_free;
823 
824   /* How often did we evict from the cache (for statistics only) */
825   u32 q_testcase_evictions;
826 
827   /* Refs to each queue entry with cached testcase (for eviction, if cache_count
828    * is too large) */
829   struct queue_entry **q_testcase_cache;
830 
831   /* Global Profile Data for deterministic/havoc-splice stage */
832   struct havoc_profile *havoc_prof;
833 
834   struct skipdet_global *skipdet_g;
835 
836 #ifdef INTROSPECTION
837   char  mutation[8072];
838   char  m_tmp[4096];
839   FILE *introspection_file;
840   u32   bitsmap_size;
841 #endif
842 
843 } afl_state_t;
844 
845 struct custom_mutator {
846 
847   const char *name;
848   char       *name_short;
849   void       *dh;
850   u8         *post_process_buf;
851   u8          stacked_custom_prob, stacked_custom;
852 
853   void *data;                                    /* custom mutator data ptr */
854 
855   /* hooks for the custom mutator function */
856 
857   /**
858    * Initialize the custom mutator.
859    *
860    * @param afl AFL instance.
861    * @param seed Seed used for the mutation.
862    * @return pointer to internal data or NULL on error
863    */
864   void *(*afl_custom_init)(afl_state_t *afl, unsigned int seed);
865 
866   /**
867    * When afl-fuzz was compiled with INTROSPECTION=1 then custom mutators can
868    * also give introspection information back with this function.
869    *
870    * @param data pointer returned in afl_custom_init by this custom mutator
871    * @return pointer to a text string (const char*)
872    */
873   const char *(*afl_custom_introspection)(void *data);
874 
875   /**
876    * This method is called just before fuzzing a queue entry with the custom
877    * mutator, and receives the initial buffer. It should return the number of
878    * fuzzes to perform.
879    *
880    * A value of 0 means no fuzzing of this queue entry.
881    *
882    * The function is now allowed to change the data.
883    *
884    * (Optional)
885    *
886    * @param data pointer returned in afl_custom_init by this custom mutator
887    * @param buf Buffer containing the test case
888    * @param buf_size Size of the test case
889    * @return The amount of fuzzes to perform on this queue entry, 0 = skip
890    */
891   u32 (*afl_custom_fuzz_count)(void *data, const u8 *buf, size_t buf_size);
892 
893   /**
894    * Opt-out of a splicing input for the fuzz mutator
895    *
896    * Empty dummy function. It's presence tells afl-fuzz not to pass a
897    * splice data pointer and len.
898    *
899    * @param data pointer returned in afl_custom_init by this custom mutator
900    * @noreturn
901    */
902   void (*afl_custom_splice_optout)(void *data);
903 
904   /**
905    * Perform custom mutations on a given input
906    *
907    * (Optional)
908    *
909    * Getting an add_buf can be skipped by using afl_custom_splice_optout().
910    *
911    * @param[in] data Pointer returned in afl_custom_init by this custom mutator
912    * @param[in] buf Pointer to the input data to be mutated and the mutated
913    *     output
914    * @param[in] buf_size Size of the input/output data
915    * @param[out] out_buf The new buffer, under your memory mgmt.
916    * @param[in] add_buf Buffer containing an additional test case (splicing)
917    * @param[in] add_buf_size Size of the additional test case
918    * @param[in] max_size Maximum size of the mutated output. The mutation must
919    * not produce data larger than max_size.
920    * @return Size of the mutated output.
921    */
922   size_t (*afl_custom_fuzz)(void *data, u8 *buf, size_t buf_size, u8 **out_buf,
923                             u8 *add_buf, size_t add_buf_size, size_t max_size);
924 
925   /**
926    * Describe the current testcase, generated by the last mutation.
927    * This will be called, for example, to give the written testcase a name
928    * after a crash ocurred. It can help to reproduce crashing mutations.
929    *
930    * (Optional)
931    *
932    * @param data pointer returned by afl_customm_init for this custom mutator
933    * @paramp[in] max_description_len maximum size avaliable for the description.
934    *             A longer return string is legal, but will be truncated.
935    * @return A valid ptr to a 0-terminated string.
936    *         An empty or NULL return will result in a default description
937    */
938   const char *(*afl_custom_describe)(void *data, size_t max_description_len);
939 
940   /**
941    * A post-processing function to use right before AFL writes the test case to
942    * disk in order to execute the target.
943    *
944    * NOTE: Do not do any random changes to the data in this function!
945    *
946    * PERFORMANCE: If you can modify the data in-place you will have a better
947    *              performance. Modify *data and set `*out_buf = data`.
948    *
949    * (Optional) If this functionality is not needed, simply do not define this
950    * function.
951    *
952    * @param[in] data pointer returned in afl_custom_init by this custom mutator
953    * @param[in] buf Buffer containing the test case to be executed
954    * @param[in] buf_size Size of the test case
955    * @param[out] out_buf Pointer to the buffer storing the test case after
956    *     processing. The external library should allocate memory for out_buf.
957    *     It can chose to alter buf in-place, if the space is large enough.
958    * @return Size of the output buffer.
959    */
960   size_t (*afl_custom_post_process)(void *data, u8 *buf, size_t buf_size,
961                                     u8 **out_buf);
962 
963   /**
964    * This method is called at the start of each trimming operation and receives
965    * the initial buffer. It should return the amount of iteration steps possible
966    * on this input (e.g. if your input has n elements and you want to remove
967    * them one by one, return n, if you do a binary search, return log(n),
968    * and so on...).
969    *
970    * If your trimming algorithm doesn't allow you to determine the amount of
971    * (remaining) steps easily (esp. while running), then you can alternatively
972    * return 1 here and always return 0 in post_trim until you are finished and
973    * no steps remain. In that case, returning 1 in post_trim will end the
974    * trimming routine. The whole current index/max iterations stuff is only used
975    * to show progress.
976    *
977    * (Optional)
978    *
979    * @param data pointer returned in afl_custom_init by this custom mutator
980    * @param buf Buffer containing the test case
981    * @param buf_size Size of the test case
982    * @return The amount of possible iteration steps to trim the input.
983    *        Negative on error.
984    */
985   s32 (*afl_custom_init_trim)(void *data, u8 *buf, size_t buf_size);
986 
987   /**
988    * This method is called for each trimming operation. It doesn't have any
989    * arguments because we already have the initial buffer from init_trim and we
990    * can memorize the current state in global variables. This can also save
991    * reparsing steps for each iteration. It should return the trimmed input
992    * buffer, where the returned data must not exceed the initial input data in
993    * length. Returning anything that is larger than the original data (passed
994    * to init_trim) will result in a fatal abort of AFLFuzz.
995    *
996    * (Optional)
997    *
998    * @param data pointer returned in afl_custom_init by this custom mutator
999    * @param[out] out_buf Pointer to the buffer containing the trimmed test case.
1000    *             The library can reuse a buffer for each call
1001    *             and will have to free the buf (for example in deinit)
1002    * @return the size of the trimmed test case
1003    */
1004   size_t (*afl_custom_trim)(void *data, u8 **out_buf);
1005 
1006   /**
1007    * This method is called after each trim operation to inform you if your
1008    * trimming step was successful or not (in terms of coverage). If you receive
1009    * a failure here, you should reset your input to the last known good state.
1010    *
1011    * (Optional)
1012    *
1013    * @param data pointer returned in afl_custom_init by this custom mutator
1014    * @param success Indicates if the last trim operation was successful.
1015    * @return The next trim iteration index (from 0 to the maximum amount of
1016    *     steps returned in init_trim). Negative on error.
1017    */
1018   s32 (*afl_custom_post_trim)(void *data, u8 success);
1019 
1020   /**
1021    * Perform a single custom mutation on a given input.
1022    * This mutation is stacked with the other muatations in havoc.
1023    *
1024    * (Optional)
1025    *
1026    * @param[in] data pointer returned in afl_custom_init by this custom mutator
1027    * @param[in] buf Pointer to the input data to be mutated and the mutated
1028    *     output
1029    * @param[in] buf_size Size of input data
1030    * @param[out] out_buf The new buffer. It's legal to reuse *buf if it's <
1031    * buf_size.
1032    * @param[in] max_size Maximum size of the mutated output. The mutation must
1033    *     not produce data larger than max_size.
1034    * @return Size of the mutated output (out_size).
1035    */
1036   size_t (*afl_custom_havoc_mutation)(void *data, u8 *buf, size_t buf_size,
1037                                       u8 **out_buf, size_t max_size);
1038 
1039   /**
1040    * Return the probability (in percentage) that afl_custom_havoc_mutation
1041    * is called in havoc. By default it is 6 %.
1042    *
1043    * (Optional)
1044    *
1045    * @param data pointer returned in afl_custom_init by this custom mutator
1046    * @return The probability (0-100).
1047    */
1048   u8 (*afl_custom_havoc_mutation_probability)(void *data);
1049 
1050   /**
1051    * Determine whether the fuzzer should fuzz the current queue entry or not.
1052    *
1053    * (Optional)
1054    *
1055    * @param data pointer returned in afl_custom_init by this custom mutator
1056    * @param filename File name of the test case in the queue entry
1057    * @return Return True(1) if the fuzzer will fuzz the queue entry, and
1058    *     False(0) otherwise.
1059    */
1060   u8 (*afl_custom_queue_get)(void *data, const u8 *filename);
1061 
1062   /**
1063    * This method can be used if you want to send data to the target yourself,
1064    * e.g. via IPC. This replaces some usage of utils/afl_proxy but requires
1065    * that you start the target with afl-fuzz.
1066    *
1067    * (Optional)
1068    *
1069    * @param data pointer returned in afl_custom_init by this custom mutator
1070    * @param buf Buffer containing the test case
1071    * @param buf_size Size of the test case
1072    */
1073   void (*afl_custom_fuzz_send)(void *data, const u8 *buf, size_t buf_size);
1074 
1075   /**
1076    * This method can be used if you want to run some code or scripts each time
1077    * AFL++ executes the target with afl-fuzz.
1078    *
1079    * (Optional)
1080    *
1081    * @param data pointer returned in afl_custom_init by this custom mutator
1082    */
1083   void (*afl_custom_post_run)(void *data);
1084 
1085   /**
1086    * Allow for additional analysis (e.g. calling a different tool that does a
1087    * different kind of coverage and saves this for the custom mutator).
1088    *
1089    * (Optional)
1090    *
1091    * @param data pointer returned in afl_custom_init by this custom mutator
1092    * @param filename_new_queue File name of the new queue entry
1093    * @param filename_orig_queue File name of the original queue entry. This
1094    *     argument can be NULL while initializing the fuzzer
1095    */
1096   u8 (*afl_custom_queue_new_entry)(void *data, const u8 *filename_new_queue,
1097                                    const u8 *filename_orig_queue);
1098   /**
1099    * Deinitialize the custom mutator.
1100    *
1101    * @param data pointer returned in afl_custom_init by this custom mutator
1102    */
1103   void (*afl_custom_deinit)(void *data);
1104 
1105 };
1106 
1107 void afl_state_init(afl_state_t *, uint32_t map_size);
1108 void afl_state_deinit(afl_state_t *);
1109 
1110 /* Set stop_soon flag on all childs, kill all childs */
1111 void afl_states_stop(void);
1112 /* Set clear_screen flag on all states */
1113 void afl_states_clear_screen(void);
1114 /* Sets the skip flag on all states */
1115 void afl_states_request_skip(void);
1116 
1117 /* Setup shmem for testcase delivery */
1118 void setup_testcase_shmem(afl_state_t *afl);
1119 
1120 void read_afl_environment(afl_state_t *, char **);
1121 
1122 /**** Prototypes ****/
1123 
1124 /* Custom mutators */
1125 void setup_custom_mutators(afl_state_t *);
1126 void destroy_custom_mutators(afl_state_t *);
1127 u8   trim_case_custom(afl_state_t *, struct queue_entry *q, u8 *in_buf,
1128                       struct custom_mutator *mutator);
1129 void run_afl_custom_queue_new_entry(afl_state_t *, struct queue_entry *, u8 *,
1130                                     u8 *);
1131 
1132 /* Python */
1133 #ifdef USE_PYTHON
1134 
1135 struct custom_mutator *load_custom_mutator_py(afl_state_t *, char *);
1136 void                   finalize_py_module(void *);
1137 
1138 u32         fuzz_count_py(void *, const u8 *, size_t);
1139 void        fuzz_send_py(void *, const u8 *, size_t);
1140 void        post_run_py(void *);
1141 size_t      post_process_py(void *, u8 *, size_t, u8 **);
1142 s32         init_trim_py(void *, u8 *, size_t);
1143 s32         post_trim_py(void *, u8);
1144 size_t      trim_py(void *, u8 **);
1145 size_t      havoc_mutation_py(void *, u8 *, size_t, u8 **, size_t);
1146 u8          havoc_mutation_probability_py(void *);
1147 u8          queue_get_py(void *, const u8 *);
1148 const char *introspection_py(void *);
1149 u8          queue_new_entry_py(void *, const u8 *, const u8 *);
1150 void        splice_optout(void *);
1151 void        deinit_py(void *);
1152 
1153 #endif
1154 
1155 /* Queue */
1156 
1157 void mark_as_det_done(afl_state_t *, struct queue_entry *);
1158 void mark_as_variable(afl_state_t *, struct queue_entry *);
1159 void mark_as_redundant(afl_state_t *, struct queue_entry *, u8);
1160 void add_to_queue(afl_state_t *, u8 *, u32, u8);
1161 void destroy_queue(afl_state_t *);
1162 void update_bitmap_score(afl_state_t *, struct queue_entry *);
1163 void cull_queue(afl_state_t *);
1164 u32  calculate_score(afl_state_t *, struct queue_entry *);
1165 
1166 /* Bitmap */
1167 
1168 void write_bitmap(afl_state_t *);
1169 u32  count_bits(afl_state_t *, u8 *);
1170 u32  count_bytes(afl_state_t *, u8 *);
1171 u32  count_non_255_bytes(afl_state_t *, u8 *);
1172 void simplify_trace(afl_state_t *, u8 *);
1173 #ifdef WORD_SIZE_64
1174 void discover_word(u8 *ret, u64 *current, u64 *virgin);
1175 #else
1176 void discover_word(u8 *ret, u32 *current, u32 *virgin);
1177 #endif
1178 void init_count_class16(void);
1179 void minimize_bits(afl_state_t *, u8 *, u8 *);
1180 #ifndef SIMPLE_FILES
1181 u8 *describe_op(afl_state_t *, u8, size_t);
1182 #endif
1183 u8 save_if_interesting(afl_state_t *, void *, u32, u8);
1184 u8 has_new_bits(afl_state_t *, u8 *);
1185 u8 has_new_bits_unclassified(afl_state_t *, u8 *);
1186 #ifndef AFL_SHOWMAP
1187 void classify_counts(afl_forkserver_t *);
1188 #endif
1189 
1190 /* Extras */
1191 
1192 void load_extras_file(afl_state_t *, u8 *, u32 *, u32 *, u32);
1193 void load_extras(afl_state_t *, u8 *);
1194 void dedup_extras(afl_state_t *);
1195 void deunicode_extras(afl_state_t *);
1196 void add_extra(afl_state_t *afl, u8 *mem, u32 len);
1197 void maybe_add_auto(afl_state_t *, u8 *, u32);
1198 void save_auto(afl_state_t *);
1199 void load_auto(afl_state_t *);
1200 void destroy_extras(afl_state_t *);
1201 
1202 /* Stats */
1203 
1204 void load_stats_file(afl_state_t *);
1205 void write_setup_file(afl_state_t *, u32, char **);
1206 void write_stats_file(afl_state_t *, u32, double, double, double);
1207 void maybe_update_plot_file(afl_state_t *, u32, double, double);
1208 void write_queue_stats(afl_state_t *);
1209 void show_stats(afl_state_t *);
1210 void show_stats_normal(afl_state_t *);
1211 void show_stats_pizza(afl_state_t *);
1212 void show_init_stats(afl_state_t *);
1213 
1214 /* StatsD */
1215 
1216 void statsd_setup_format(afl_state_t *afl);
1217 int  statsd_socket_init(afl_state_t *afl);
1218 int  statsd_send_metric(afl_state_t *afl);
1219 int  statsd_format_metric(afl_state_t *afl, char *buff, size_t bufflen);
1220 
1221 /* Run */
1222 
1223 void sync_fuzzers(afl_state_t *);
1224 u32  write_to_testcase(afl_state_t *, void **, u32, u32);
1225 u8   calibrate_case(afl_state_t *, struct queue_entry *, u8 *, u32, u8);
1226 u8   trim_case(afl_state_t *, struct queue_entry *, u8 *);
1227 u8   common_fuzz_stuff(afl_state_t *, u8 *, u32);
1228 fsrv_run_result_t fuzz_run_target(afl_state_t *, afl_forkserver_t *fsrv, u32);
1229 
1230 /* Fuzz one */
1231 
1232 u8   fuzz_one_original(afl_state_t *);
1233 u8   pilot_fuzzing(afl_state_t *);
1234 u8   core_fuzzing(afl_state_t *);
1235 void pso_updating(afl_state_t *);
1236 u8   fuzz_one(afl_state_t *);
1237 
1238 /* Init */
1239 
1240 #ifdef HAVE_AFFINITY
1241 void bind_to_free_cpu(afl_state_t *);
1242 #endif
1243 void   setup_post(afl_state_t *);
1244 void   read_testcases(afl_state_t *, u8 *);
1245 void   perform_dry_run(afl_state_t *);
1246 void   pivot_inputs(afl_state_t *);
1247 u32    find_start_position(afl_state_t *);
1248 void   find_timeout(afl_state_t *);
1249 double get_runnable_processes(void);
1250 void   nuke_resume_dir(afl_state_t *);
1251 int    check_main_node_exists(afl_state_t *);
1252 u32    select_next_queue_entry(afl_state_t *afl);
1253 void   create_alias_table(afl_state_t *afl);
1254 void   setup_dirs_fds(afl_state_t *);
1255 void   setup_cmdline_file(afl_state_t *, char **);
1256 void   setup_stdio_file(afl_state_t *);
1257 void   check_crash_handling(void);
1258 void   check_cpu_governor(afl_state_t *);
1259 void   get_core_count(afl_state_t *);
1260 void   fix_up_sync(afl_state_t *);
1261 void   check_asan_opts(afl_state_t *);
1262 void   check_binary(afl_state_t *, u8 *);
1263 void   check_if_tty(afl_state_t *);
1264 void   save_cmdline(afl_state_t *, u32, char **);
1265 void   read_foreign_testcases(afl_state_t *, int);
1266 void   write_crash_readme(afl_state_t *afl);
1267 u8     check_if_text_buf(u8 *buf, u32 len);
1268 #ifndef AFL_SHOWMAP
1269 void setup_signal_handlers(void);
1270 #endif
1271 char *get_fuzzing_state(afl_state_t *afl);
1272 
1273 /* CmpLog */
1274 
1275 u8 common_fuzz_cmplog_stuff(afl_state_t *afl, u8 *out_buf, u32 len);
1276 
1277 /* RedQueen */
1278 u8 input_to_state_stage(afl_state_t *afl, u8 *orig_buf, u8 *buf, u32 len);
1279 
1280 /* our RNG wrapper */
1281 AFL_RAND_RETURN rand_next(afl_state_t *afl);
1282 
1283 /* probability between 0.0 and 1.0 */
1284 double rand_next_percent(afl_state_t *afl);
1285 
1286 /* SkipDet Functions */
1287 
1288 u8 skip_deterministic_stage(afl_state_t *, u8 *, u8 *, u32, u64);
1289 u8 is_det_timeout(u64, u8);
1290 
1291 void plot_profile_data(afl_state_t *, struct queue_entry *);
1292 
1293 /**** Inline routines ****/
1294 
1295 /* Generate a random number (from 0 to limit - 1). This may
1296    have slight bias. */
1297 
rand_below(afl_state_t * afl,u32 limit)1298 static inline u32 rand_below(afl_state_t *afl, u32 limit) {
1299 
1300   if (unlikely(limit <= 1)) return 0;
1301 
1302   /* The boundary not being necessarily a power of 2,
1303      we need to ensure the result uniformity. */
1304   if (unlikely(!afl->rand_cnt--) && likely(!afl->fixed_seed)) {
1305 
1306     ck_read(afl->fsrv.dev_urandom_fd, &afl->rand_seed, sizeof(afl->rand_seed),
1307             "/dev/urandom");
1308     // srandom(afl->rand_seed[0]);
1309     afl->rand_cnt = (RESEED_RNG / 2) + (afl->rand_seed[1] % RESEED_RNG);
1310 
1311   }
1312 
1313   /* Modulo is biased - we don't want our fuzzing to be biased so let's do it
1314    right. See:
1315    https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator
1316    */
1317   u64 unbiased_rnd;
1318   do {
1319 
1320     unbiased_rnd = rand_next(afl);
1321 
1322   } while (unlikely(unbiased_rnd >= (UINT64_MAX - (UINT64_MAX % limit))));
1323 
1324   return unbiased_rnd % limit;
1325 
1326 }
1327 
1328 /* we prefer lower range values here */
1329 /* this is only called with normal havoc, not MOpt, to have an equalizer for
1330    expand havoc mode */
rand_below_datalen(afl_state_t * afl,u32 limit)1331 static inline u32 rand_below_datalen(afl_state_t *afl, u32 limit) {
1332 
1333   if (unlikely(limit <= 1)) return 0;
1334 
1335   switch (rand_below(afl, 3)) {
1336 
1337     case 2:
1338       return (rand_below(afl, limit) % (1 + rand_below(afl, limit - 1))) %
1339              (1 + rand_below(afl, limit - 1));
1340       break;
1341     case 1:
1342       return rand_below(afl, limit) % (1 + rand_below(afl, limit - 1));
1343       break;
1344     case 0:
1345       return rand_below(afl, limit);
1346       break;
1347 
1348   }
1349 
1350   return 1;  // cannot be reached
1351 
1352 }
1353 
rand_get_seed(afl_state_t * afl)1354 static inline s64 rand_get_seed(afl_state_t *afl) {
1355 
1356   if (unlikely(afl->fixed_seed)) { return afl->init_seed; }
1357   return afl->rand_seed[0];
1358 
1359 }
1360 
1361 /* initialize randomness with a given seed. Can be called again at any time. */
1362 void rand_set_seed(afl_state_t *afl, s64 init_seed);
1363 
1364 /* Find first power of two greater or equal to val (assuming val under
1365    2^63). */
1366 
next_p2(u64 val)1367 static inline u64 next_p2(u64 val) {
1368 
1369   u64 ret = 1;
1370   while (val > ret) {
1371 
1372     ret <<= 1;
1373 
1374   }
1375 
1376   return ret;
1377 
1378 }
1379 
1380 /* Returns the testcase buf from the file behind this queue entry.
1381   Increases the refcount. */
1382 u8 *queue_testcase_get(afl_state_t *afl, struct queue_entry *q);
1383 
1384 /* If trimming changes the testcase size we have to reload it */
1385 void queue_testcase_retake(afl_state_t *afl, struct queue_entry *q,
1386                            u32 old_len);
1387 
1388 /* If trimming changes the testcase size we have to replace it  */
1389 void queue_testcase_retake_mem(afl_state_t *afl, struct queue_entry *q, u8 *in,
1390                                u32 len, u32 old_len);
1391 
1392 /* Add a new queue entry directly to the cache */
1393 
1394 void queue_testcase_store_mem(afl_state_t *afl, struct queue_entry *q, u8 *mem);
1395 
1396 #if TESTCASE_CACHE == 1
1397   #error define of TESTCASE_CACHE must be zero or larger than 1
1398 #endif
1399 
1400 #endif
1401 
1402