···33}:
4455let
66- afl-qemu = callPackage ./qemu.nix {};
66+ afl-qemu = callPackage ./qemu.nix { inherit afl; };
77 qemu-exe-name = if stdenv.hostPlatform.system == "x86_64-linux" then "qemu-x86_64"
88 else if stdenv.hostPlatform.system == "i686-linux" then "qemu-i386"
99 else throw "afl: no support for ${stdenv.hostPlatform.system}!";
1010-in
1010+ afl = stdenv.mkDerivation rec {
1111+ name = "afl-${version}";
1212+ version = "2.52b";
11131212-stdenv.mkDerivation rec {
1313- name = "afl-${version}";
1414- version = "2.52b";
1414+ src = fetchurl {
1515+ url = "http://lcamtuf.coredump.cx/afl/releases/${name}.tgz";
1616+ sha256 = "0ig0ij4n1pwry5dw1hk4q88801jzzy2cric6y2gd6560j55lnqa3";
1717+ };
15181616- src = fetchurl {
1717- url = "http://lcamtuf.coredump.cx/afl/releases/${name}.tgz";
1818- sha256 = "0ig0ij4n1pwry5dw1hk4q88801jzzy2cric6y2gd6560j55lnqa3";
1919- };
1919+ # Note: libcgroup isn't needed for building, just for the afl-cgroup
2020+ # script.
2121+ buildInputs = [ makeWrapper llvm which ];
20222121- # Note: libcgroup isn't needed for building, just for the afl-cgroup
2222- # script.
2323- buildInputs = [ makeWrapper llvm which ];
2323+ buildPhase = ''
2424+ make PREFIX=$out
2525+ cd llvm_mode
2626+ make PREFIX=$out
2727+ cd ..
2828+ '';
2929+ installPhase = ''
3030+ # Do the normal installation
3131+ make install PREFIX=$out
24322525- buildPhase = ''
2626- make PREFIX=$out
2727- cd llvm_mode
2828- make PREFIX=$out
2929- cd ..
3030- '';
3131- installPhase = ''
3232- # Do the normal installation
3333- make install PREFIX=$out
3333+ # Install the custom QEMU emulator for binary blob fuzzing.
3434+ cp ${afl-qemu}/bin/${qemu-exe-name} $out/bin/afl-qemu-trace
34353535- # Install the custom QEMU emulator for binary blob fuzzing.
3636- cp ${afl-qemu}/bin/${qemu-exe-name} $out/bin/afl-qemu-trace
3636+ # Install the cgroups wrapper for asan-based fuzzing.
3737+ cp experimental/asan_cgroups/limit_memory.sh $out/bin/afl-cgroup
3838+ chmod +x $out/bin/afl-cgroup
3939+ substituteInPlace $out/bin/afl-cgroup \
4040+ --replace "cgcreate" "${libcgroup}/bin/cgcreate" \
4141+ --replace "cgexec" "${libcgroup}/bin/cgexec" \
4242+ --replace "cgdelete" "${libcgroup}/bin/cgdelete"
37433838- # Install the cgroups wrapper for asan-based fuzzing.
3939- cp experimental/asan_cgroups/limit_memory.sh $out/bin/afl-cgroup
4040- chmod +x $out/bin/afl-cgroup
4141- substituteInPlace $out/bin/afl-cgroup \
4242- --replace "cgcreate" "${libcgroup}/bin/cgcreate" \
4343- --replace "cgexec" "${libcgroup}/bin/cgexec" \
4444- --replace "cgdelete" "${libcgroup}/bin/cgdelete"
4444+ # Patch shebangs before wrapping
4545+ patchShebangs $out/bin
45464646- # Patch shebangs before wrapping
4747- patchShebangs $out/bin
4747+ # Wrap afl-clang-fast(++) with a *different* AFL_PATH, because it
4848+ # has totally different semantics in that case(?) - and also set a
4949+ # proper AFL_CC and AFL_CXX so we don't pick up the wrong one out
5050+ # of $PATH.
5151+ for x in $out/bin/afl-clang-fast $out/bin/afl-clang-fast++; do
5252+ wrapProgram $x \
5353+ --prefix AFL_PATH : "$out/lib/afl" \
5454+ --run 'export AFL_CC=''${AFL_CC:-${clang}/bin/clang} AFL_CXX=''${AFL_CXX:-${clang}/bin/clang++}'
5555+ done
5656+ '';
48574949- # Wrap afl-clang-fast(++) with a *different* AFL_PATH, because it
5050- # has totally different semantics in that case(?) - and also set a
5151- # proper AFL_CC and AFL_CXX so we don't pick up the wrong one out
5252- # of $PATH.
5353- for x in $out/bin/afl-clang-fast $out/bin/afl-clang-fast++; do
5454- wrapProgram $x \
5555- --prefix AFL_PATH : "$out/lib/afl" \
5656- --run 'export AFL_CC=''${AFL_CC:-${clang}/bin/clang} AFL_CXX=''${AFL_CXX:-${clang}/bin/clang++}'
5757- done
5858- '';
5858+ passthru = {
5959+ qemu = afl-qemu;
6060+ };
59616060- passthru = {
6161- qemu = afl-qemu;
6262+ meta = {
6363+ description = "Powerful fuzzer via genetic algorithms and instrumentation";
6464+ longDescription = ''
6565+ American fuzzy lop is a fuzzer that employs a novel type of
6666+ compile-time instrumentation and genetic algorithms to
6767+ automatically discover clean, interesting test cases that
6868+ trigger new internal states in the targeted binary. This
6969+ substantially improves the functional coverage for the fuzzed
7070+ code. The compact synthesized corpora produced by the tool are
7171+ also useful for seeding other, more labor or resource-intensive
7272+ testing regimes down the road.
7373+ '';
7474+ homepage = "http://lcamtuf.coredump.cx/afl/";
7575+ license = stdenv.lib.licenses.asl20;
7676+ platforms = ["x86_64-linux" "i686-linux"];
7777+ maintainers = [ stdenv.lib.maintainers.thoughtpolice ];
7878+ };
6279 };
8080+in afl
63816464- meta = {
6565- description = "Powerful fuzzer via genetic algorithms and instrumentation";
6666- longDescription = ''
6767- American fuzzy lop is a fuzzer that employs a novel type of
6868- compile-time instrumentation and genetic algorithms to
6969- automatically discover clean, interesting test cases that
7070- trigger new internal states in the targeted binary. This
7171- substantially improves the functional coverage for the fuzzed
7272- code. The compact synthesized corpora produced by the tool are
7373- also useful for seeding other, more labor or resource-intensive
7474- testing regimes down the road.
7575- '';
7676- homepage = "http://lcamtuf.coredump.cx/afl/";
7777- license = stdenv.lib.licenses.asl20;
7878- platforms = ["x86_64-linux" "i686-linux"];
7979- maintainers = [ stdenv.lib.maintainers.thoughtpolice ];
8080- };
8181-}
8282+
-335
pkgs/tools/security/afl/qemu-patches/afl-config.h
···11-/*
22- american fuzzy lop - vaguely configurable bits
33- ----------------------------------------------
44-55- Written and maintained by Michal Zalewski <lcamtuf@google.com>
66-77- Copyright 2013, 2014, 2015 Google Inc. All rights reserved.
88-99- Licensed under the Apache License, Version 2.0 (the "License");
1010- you may not use this file except in compliance with the License.
1111- You may obtain a copy of the License at:
1212-1313- http://www.apache.org/licenses/LICENSE-2.0
1414-1515- */
1616-1717-#ifndef _HAVE_CONFIG_H
1818-#define _HAVE_CONFIG_H
1919-2020-#include "afl-types.h"
2121-2222-/******************************************************
2323- * *
2424- * Settings that may be of interest to power users: *
2525- * *
2626- ******************************************************/
2727-2828-/* Comment out to disable terminal colors: */
2929-3030-#define USE_COLOR
3131-3232-/* Comment out to disable fancy ANSI boxes and use poor man's 7-bit UI: */
3333-3434-#define FANCY_BOXES
3535-3636-/* Default timeout for fuzzed code (milliseconds): */
3737-3838-#define EXEC_TIMEOUT 1000
3939-4040-/* Timeout rounding factor when auto-scaling (milliseconds): */
4141-4242-#define EXEC_TM_ROUND 20
4343-4444-/* Default memory limit for child process (MB): */
4545-4646-#ifndef __x86_64__
4747-# define MEM_LIMIT 25
4848-#else
4949-# define MEM_LIMIT 50
5050-#endif /* ^!__x86_64__ */
5151-5252-/* Default memory limit when running in QEMU mode (MB): */
5353-5454-#define MEM_LIMIT_QEMU 200
5555-5656-/* Number of calibration cycles per every new test case (and for test
5757- cases that show variable behavior): */
5858-5959-#define CAL_CYCLES 10
6060-#define CAL_CYCLES_LONG 40
6161-6262-/* The same, but when AFL_NO_VAR_CHECK is set in the environment: */
6363-6464-#define CAL_CYCLES_NO_VAR 4
6565-6666-/* Number of subsequent hangs before abandoning an input file: */
6767-6868-#define HANG_LIMIT 250
6969-7070-/* Maximum number of unique hangs or crashes to record: */
7171-7272-#define KEEP_UNIQUE_HANG 500
7373-#define KEEP_UNIQUE_CRASH 5000
7474-7575-/* Baseline number of random tweaks during a single 'havoc' stage: */
7676-7777-#define HAVOC_CYCLES 5000
7878-7979-/* Maximum multiplier for the above (should be a power of two, beware
8080- of 32-bit int overflows): */
8181-8282-#define HAVOC_MAX_MULT 16
8383-8484-/* Absolute minimum number of havoc cycles (after all adjustments): */
8585-8686-#define HAVOC_MIN 10
8787-8888-/* Maximum stacking for havoc-stage tweaks. The actual value is calculated
8989- like this:
9090-9191- n = random between 1 and HAVOC_STACK_POW2
9292- stacking = 2^n
9393-9494- In other words, the default (n = 7) produces 2, 4, 8, 16, 32, 64, or
9595- 128 stacked tweaks: */
9696-9797-#define HAVOC_STACK_POW2 7
9898-9999-/* Caps on block sizes for cloning and deletion operations. Each of these
100100- ranges has a 33% probability of getting picked, except for the first
101101- two cycles where smaller blocks are favored: */
102102-103103-#define HAVOC_BLK_SMALL 32
104104-#define HAVOC_BLK_MEDIUM 128
105105-#define HAVOC_BLK_LARGE 1500
106106-107107-/* Probabilities of skipping non-favored entries in the queue, expressed as
108108- percentages: */
109109-110110-#define SKIP_TO_NEW_PROB 99 /* ...when there are new, pending favorites */
111111-#define SKIP_NFAV_OLD_PROB 95 /* ...no new favs, cur entry already fuzzed */
112112-#define SKIP_NFAV_NEW_PROB 75 /* ...no new favs, cur entry not fuzzed yet */
113113-114114-/* Splicing cycle count: */
115115-116116-#define SPLICE_CYCLES 20
117117-118118-/* Nominal per-splice havoc cycle length: */
119119-120120-#define SPLICE_HAVOC 500
121121-122122-/* Maximum offset for integer addition / subtraction stages: */
123123-124124-#define ARITH_MAX 35
125125-126126-/* Limits for the test case trimmer. The absolute minimum chunk size; and
127127- the starting and ending divisors for chopping up the input file: */
128128-129129-#define TRIM_MIN_BYTES 4
130130-#define TRIM_START_STEPS 16
131131-#define TRIM_END_STEPS 1024
132132-133133-/* Maximum size of input file, in bytes (keep under 100MB): */
134134-135135-#define MAX_FILE (1 * 1024 * 1024)
136136-137137-/* The same, for the test case minimizer: */
138138-139139-#define TMIN_MAX_FILE (10 * 1024 * 1024)
140140-141141-/* Block normalization steps for afl-tmin: */
142142-143143-#define TMIN_SET_MIN_SIZE 4
144144-#define TMIN_SET_STEPS 128
145145-146146-/* Maximum dictionary token size (-x), in bytes: */
147147-148148-#define MAX_DICT_FILE 128
149149-150150-/* Length limits for auto-detected dictionary tokens: */
151151-152152-#define MIN_AUTO_EXTRA 3
153153-#define MAX_AUTO_EXTRA 32
154154-155155-/* Maximum number of user-specified dictionary tokens to use in deterministic
156156- steps; past this point, the "extras/user" step will be still carried out,
157157- but with proportionally lower odds: */
158158-159159-#define MAX_DET_EXTRAS 200
160160-161161-/* Maximum number of auto-extracted dictionary tokens to actually use in fuzzing
162162- (first value), and to keep in memory as candidates. The latter should be much
163163- higher than the former. */
164164-165165-#define USE_AUTO_EXTRAS 50
166166-#define MAX_AUTO_EXTRAS (USE_AUTO_EXTRAS * 10)
167167-168168-/* Scaling factor for the effector map used to skip some of the more
169169- expensive deterministic steps. The actual divisor is set to
170170- 2^EFF_MAP_SCALE2 bytes: */
171171-172172-#define EFF_MAP_SCALE2 3
173173-174174-/* Minimum input file length at which the effector logic kicks in: */
175175-176176-#define EFF_MIN_LEN 128
177177-178178-/* Maximum effector density past which everything is just fuzzed
179179- unconditionally (%): */
180180-181181-#define EFF_MAX_PERC 90
182182-183183-/* UI refresh frequency (Hz): */
184184-185185-#define UI_TARGET_HZ 5
186186-187187-/* Fuzzer stats file and plot update intervals (sec): */
188188-189189-#define STATS_UPDATE_SEC 60
190190-#define PLOT_UPDATE_SEC 5
191191-192192-/* Smoothing divisor for CPU load and exec speed stats (1 - no smoothing). */
193193-194194-#define AVG_SMOOTHING 16
195195-196196-/* Sync interval (every n havoc cycles): */
197197-198198-#define SYNC_INTERVAL 5
199199-200200-/* Output directory reuse grace period (minutes): */
201201-202202-#define OUTPUT_GRACE 25
203203-204204-/* Uncomment to use simple file names (id_NNNNNN): */
205205-206206-// #define SIMPLE_FILES
207207-208208-/* List of interesting values to use in fuzzing. */
209209-210210-#define INTERESTING_8 \
211211- -128, /* Overflow signed 8-bit when decremented */ \
212212- -1, /* */ \
213213- 0, /* */ \
214214- 1, /* */ \
215215- 16, /* One-off with common buffer size */ \
216216- 32, /* One-off with common buffer size */ \
217217- 64, /* One-off with common buffer size */ \
218218- 100, /* One-off with common buffer size */ \
219219- 127 /* Overflow signed 8-bit when incremented */
220220-221221-#define INTERESTING_16 \
222222- -32768, /* Overflow signed 16-bit when decremented */ \
223223- -129, /* Overflow signed 8-bit */ \
224224- 128, /* Overflow signed 8-bit */ \
225225- 255, /* Overflow unsig 8-bit when incremented */ \
226226- 256, /* Overflow unsig 8-bit */ \
227227- 512, /* One-off with common buffer size */ \
228228- 1000, /* One-off with common buffer size */ \
229229- 1024, /* One-off with common buffer size */ \
230230- 4096, /* One-off with common buffer size */ \
231231- 32767 /* Overflow signed 16-bit when incremented */
232232-233233-#define INTERESTING_32 \
234234- -2147483648LL, /* Overflow signed 32-bit when decremented */ \
235235- -100663046, /* Large negative number (endian-agnostic) */ \
236236- -32769, /* Overflow signed 16-bit */ \
237237- 32768, /* Overflow signed 16-bit */ \
238238- 65535, /* Overflow unsig 16-bit when incremented */ \
239239- 65536, /* Overflow unsig 16 bit */ \
240240- 100663045, /* Large positive number (endian-agnostic) */ \
241241- 2147483647 /* Overflow signed 32-bit when incremented */
242242-243243-/***********************************************************
244244- * *
245245- * Really exotic stuff you probably don't want to touch: *
246246- * *
247247- ***********************************************************/
248248-249249-/* Call count interval between reseeding the libc PRNG from /dev/urandom: */
250250-251251-#define RESEED_RNG 10000
252252-253253-/* Maximum line length passed from GCC to 'as' and used for parsing
254254- configuration files: */
255255-256256-#define MAX_LINE 8192
257257-258258-/* Environment variable used to pass SHM ID to the called program. */
259259-260260-#define SHM_ENV_VAR "__AFL_SHM_ID"
261261-262262-/* Other less interesting, internal-only variables. */
263263-264264-#define CLANG_ENV_VAR "__AFL_CLANG_MODE"
265265-#define AS_LOOP_ENV_VAR "__AFL_AS_LOOPCHECK"
266266-267267-/* Distinctive bitmap signature used to indicate failed execution: */
268268-269269-#define EXEC_FAIL_SIG 0xfee1dead
270270-271271-/* Distinctive exit code used to indicate MSAN trip condition: */
272272-273273-#define MSAN_ERROR 86
274274-275275-/* Designated file descriptors for forkserver commands (the application will
276276- use FORKSRV_FD and FORKSRV_FD + 1): */
277277-278278-#define FORKSRV_FD 198
279279-280280-/* Fork server init timeout multiplier: we'll wait the user-selected
281281- timeout plus this much for the fork server to spin up. */
282282-283283-#define FORK_WAIT_MULT 10
284284-285285-/* Calibration timeout adjustments, to be a bit more generous when resuming
286286- fuzzing sessions or trying to calibrate already-added internal finds.
287287- The first value is a percentage, the other is in milliseconds: */
288288-289289-#define CAL_TMOUT_PERC 125
290290-#define CAL_TMOUT_ADD 50
291291-292292-/* Number of chances to calibrate a case before giving up: */
293293-294294-#define CAL_CHANCES 3
295295-296296-/* Map size for the traced binary (2^MAP_SIZE_POW2). Must be greater than
297297- 2; you probably want to keep it under 18 or so for performance reasons
298298- (adjusting AFL_INST_RATIO when compiling is probably a better way to solve
299299- problems with complex programs). You need to recompile the target binary
300300- after changing this - otherwise, SEGVs may ensue. */
301301-302302-#define MAP_SIZE_POW2 16
303303-#define MAP_SIZE (1 << MAP_SIZE_POW2)
304304-305305-/* Maximum allocator request size (keep well under INT_MAX): */
306306-307307-#define MAX_ALLOC 0x40000000
308308-309309-/* A made-up hashing seed: */
310310-311311-#define HASH_CONST 0xa5b35705
312312-313313-/* Constants for afl-gotcpu to control busy loop timing: */
314314-315315-#define CTEST_TARGET_MS 5000
316316-#define CTEST_BUSY_CYCLES (10 * 1000 * 1000)
317317-318318-/* Uncomment this to use inferior block-coverage-based instrumentation. Note
319319- that you need to recompile the target binary for this to have any effect: */
320320-321321-// #define COVERAGE_ONLY
322322-323323-/* Uncomment this to ignore hit counts and output just one bit per tuple.
324324- As with the previous setting, you will need to recompile the target
325325- binary: */
326326-327327-// #define SKIP_COUNTS
328328-329329-/* Uncomment this to use instrumentation data to record newly discovered paths,
330330- but do not use them as seeds for fuzzing. This is useful for conveniently
331331- measuring coverage that could be attained by a "dumb" fuzzing algorithm: */
332332-333333-// #define IGNORE_FINDS
334334-335335-#endif /* ! _HAVE_CONFIG_H */
···11-/*
22- american fuzzy lop - high-performance binary-only instrumentation
33- -----------------------------------------------------------------
44-55- Written by Andrew Griffiths <agriffiths@google.com> and
66- Michal Zalewski <lcamtuf@google.com>
77-88- Idea & design very much by Andrew Griffiths.
99-1010- Copyright 2015 Google Inc. All rights reserved.
1111-1212- Licensed under the Apache License, Version 2.0 (the "License");
1313- you may not use this file except in compliance with the License.
1414- You may obtain a copy of the License at:
1515-1616- http://www.apache.org/licenses/LICENSE-2.0
1717-1818- This code is a shim patched into the separately-distributed source
1919- code of QEMU 2.2.0. It leverages the built-in QEMU tracing functionality
2020- to implement AFL-style instrumentation and to take care of the remaining
2121- parts of the AFL fork server logic.
2222-2323- The resulting QEMU binary is essentially a standalone instrumentation
2424- tool; for an example of how to leverage it for other purposes, you can
2525- have a look at afl-showmap.c.
2626-2727- */
2828-2929-#include <sys/shm.h>
3030-#include "afl-config.h"
3131-3232-/***************************
3333- * VARIOUS AUXILIARY STUFF *
3434- ***************************/
3535-3636-/* A snippet patched into tb_find_slow to inform the parent process that
3737- we have hit a new block that hasn't been translated yet, and to tell
3838- it to translate within its own context, too (this avoids translation
3939- overhead in the next forked-off copy). */
4040-4141-#define AFL_QEMU_CPU_SNIPPET1 do { \
4242- afl_request_tsl(pc, cs_base, flags); \
4343- } while (0)
4444-4545-/* This snippet kicks in when the instruction pointer is positioned at
4646- _start and does the usual forkserver stuff, not very different from
4747- regular instrumentation injected via afl-as.h. */
4848-4949-#define AFL_QEMU_CPU_SNIPPET2 do { \
5050- if(tb->pc == afl_entry_point) { \
5151- afl_setup(); \
5252- afl_forkserver(env); \
5353- } \
5454- afl_maybe_log(tb->pc); \
5555- } while (0)
5656-5757-/* We use one additional file descriptor to relay "needs translation"
5858- messages between the child and the fork server. */
5959-6060-#define TSL_FD (FORKSRV_FD - 1)
6161-6262-/* This is equivalent to afl-as.h: */
6363-6464-static unsigned char *afl_area_ptr;
6565-6666-/* Exported variables populated by the code patched into elfload.c: */
6767-6868-abi_ulong afl_entry_point, /* ELF entry point (_start) */
6969- afl_start_code, /* .text start pointer */
7070- afl_end_code; /* .text end pointer */
7171-7272-/* Set in the child process in forkserver mode: */
7373-7474-static unsigned char afl_fork_child;
7575-unsigned int afl_forksrv_pid;
7676-7777-/* Instrumentation ratio: */
7878-7979-static unsigned int afl_inst_rms = MAP_SIZE;
8080-8181-/* Function declarations. */
8282-8383-static void afl_setup(void);
8484-static void afl_forkserver(CPUArchState*);
8585-static inline void afl_maybe_log(abi_ulong);
8686-8787-static void afl_wait_tsl(CPUArchState*, int);
8888-static void afl_request_tsl(target_ulong, target_ulong, uint64_t);
8989-9090-static TranslationBlock *tb_find_slow(CPUArchState*, target_ulong,
9191- target_ulong, uint64_t);
9292-9393-9494-/* Data structure passed around by the translate handlers: */
9595-9696-struct afl_tsl {
9797- target_ulong pc;
9898- target_ulong cs_base;
9999- uint64_t flags;
100100-};
101101-102102-103103-/*************************
104104- * ACTUAL IMPLEMENTATION *
105105- *************************/
106106-107107-108108-/* Set up SHM region and initialize other stuff. */
109109-110110-static void afl_setup(void) {
111111-112112- char *id_str = getenv(SHM_ENV_VAR),
113113- *inst_r = getenv("AFL_INST_RATIO");
114114-115115- int shm_id;
116116-117117- if (inst_r) {
118118-119119- unsigned int r;
120120-121121- r = atoi(inst_r);
122122-123123- if (r > 100) r = 100;
124124- if (!r) r = 1;
125125-126126- afl_inst_rms = MAP_SIZE * r / 100;
127127-128128- }
129129-130130- if (id_str) {
131131-132132- shm_id = atoi(id_str);
133133- afl_area_ptr = shmat(shm_id, NULL, 0);
134134-135135- if (afl_area_ptr == (void*)-1) exit(1);
136136-137137- /* With AFL_INST_RATIO set to a low value, we want to touch the bitmap
138138- so that the parent doesn't give up on us. */
139139-140140- if (inst_r) afl_area_ptr[0] = 1;
141141-142142-143143- }
144144-145145- if (getenv("AFL_INST_LIBS")) {
146146-147147- afl_start_code = 0;
148148- afl_end_code = (abi_ulong)-1;
149149-150150- }
151151-152152-}
153153-154154-155155-/* Fork server logic, invoked once we hit _start. */
156156-157157-static void afl_forkserver(CPUArchState *env) {
158158-159159- static unsigned char tmp[4];
160160-161161- if (!afl_area_ptr) return;
162162-163163- /* Tell the parent that we're alive. If the parent doesn't want
164164- to talk, assume that we're not running in forkserver mode. */
165165-166166- if (write(FORKSRV_FD + 1, tmp, 4) != 4) return;
167167-168168- afl_forksrv_pid = getpid();
169169-170170- /* All right, let's await orders... */
171171-172172- while (1) {
173173-174174- pid_t child_pid;
175175- int status, t_fd[2];
176176-177177- /* Whoops, parent dead? */
178178-179179- if (read(FORKSRV_FD, tmp, 4) != 4) exit(2);
180180-181181- /* Establish a channel with child to grab translation commands. We'll
182182- read from t_fd[0], child will write to TSL_FD. */
183183-184184- if (pipe(t_fd) || dup2(t_fd[1], TSL_FD) < 0) exit(3);
185185- close(t_fd[1]);
186186-187187- child_pid = fork();
188188- if (child_pid < 0) exit(4);
189189-190190- if (!child_pid) {
191191-192192- /* Child process. Close descriptors and run free. */
193193-194194- afl_fork_child = 1;
195195- close(FORKSRV_FD);
196196- close(FORKSRV_FD + 1);
197197- close(t_fd[0]);
198198- return;
199199-200200- }
201201-202202- /* Parent. */
203203-204204- close(TSL_FD);
205205-206206- if (write(FORKSRV_FD + 1, &child_pid, 4) != 4) exit(5);
207207-208208- /* Collect translation requests until child dies and closes the pipe. */
209209-210210- afl_wait_tsl(env, t_fd[0]);
211211-212212- /* Get and relay exit status to parent. */
213213-214214- if (waitpid(child_pid, &status, WUNTRACED) < 0) exit(6);
215215- if (write(FORKSRV_FD + 1, &status, 4) != 4) exit(7);
216216-217217- }
218218-219219-}
220220-221221-222222-/* The equivalent of the tuple logging routine from afl-as.h. */
223223-224224-static inline void afl_maybe_log(abi_ulong cur_loc) {
225225-226226- static abi_ulong prev_loc;
227227-228228- /* Optimize for cur_loc > afl_end_code, which is the most likely case on
229229- Linux systems. */
230230-231231- if (cur_loc > afl_end_code || cur_loc < afl_start_code || !afl_area_ptr)
232232- return;
233233-234234- /* Looks like QEMU always maps to fixed locations, so we can skip this:
235235- cur_loc -= afl_start_code; */
236236-237237- /* Instruction addresses may be aligned. Let's mangle the value to get
238238- something quasi-uniform. */
239239-240240- cur_loc = (cur_loc >> 4) ^ (cur_loc << 8);
241241- cur_loc &= MAP_SIZE - 1;
242242-243243- /* Implement probabilistic instrumentation by looking at scrambled block
244244- address. This keeps the instrumented locations stable across runs. */
245245-246246- if (cur_loc >= afl_inst_rms) return;
247247-248248- afl_area_ptr[cur_loc ^ prev_loc]++;
249249- prev_loc = cur_loc >> 1;
250250-251251-}
252252-253253-254254-/* This code is invoked whenever QEMU decides that it doesn't have a
255255- translation of a particular block and needs to compute it. When this happens,
256256- we tell the parent to mirror the operation, so that the next fork() has a
257257- cached copy. */
258258-259259-static void afl_request_tsl(target_ulong pc, target_ulong cb, uint64_t flags) {
260260-261261- struct afl_tsl t;
262262-263263- if (!afl_fork_child) return;
264264-265265- t.pc = pc;
266266- t.cs_base = cb;
267267- t.flags = flags;
268268-269269- if (write(TSL_FD, &t, sizeof(struct afl_tsl)) != sizeof(struct afl_tsl))
270270- return;
271271-272272-}
273273-274274-275275-/* This is the other side of the same channel. Since timeouts are handled by
276276- afl-fuzz simply killing the child, we can just wait until the pipe breaks. */
277277-278278-static void afl_wait_tsl(CPUArchState *env, int fd) {
279279-280280- struct afl_tsl t;
281281-282282- while (1) {
283283-284284- /* Broken pipe means it's time to return to the fork server routine. */
285285-286286- if (read(fd, &t, sizeof(struct afl_tsl)) != sizeof(struct afl_tsl))
287287- break;
288288-289289- tb_find_slow(env, t.pc, t.cs_base, t.flags);
290290-291291- }
292292-293293- close(fd);
294294-295295-}
296296-
-79
pkgs/tools/security/afl/qemu-patches/afl-types.h
···11-/*
22- american fuzzy lop - type definitions and minor macros
33- ------------------------------------------------------
44-55- Written and maintained by Michal Zalewski <lcamtuf@google.com>
66-77- Copyright 2013, 2014, 2015 Google Inc. All rights reserved.
88-99- Licensed under the Apache License, Version 2.0 (the "License");
1010- you may not use this file except in compliance with the License.
1111- You may obtain a copy of the License at:
1212-1313- http://www.apache.org/licenses/LICENSE-2.0
1414-1515- */
1616-1717-#ifndef _HAVE_TYPES_H
1818-#define _HAVE_TYPES_H
1919-2020-#include <stdint.h>
2121-#include <stdlib.h>
2222-2323-typedef uint8_t u8;
2424-typedef uint16_t u16;
2525-typedef uint32_t u32;
2626-2727-/*
2828-2929- Ugh. There is an unintended compiler / glibc #include glitch caused by
3030- combining the u64 type an %llu in format strings, necessitating a workaround.
3131-3232- In essence, the compiler is always looking for 'unsigned long long' for %llu.
3333- On 32-bit systems, the u64 type (aliased to uint64_t) is expanded to
3434- 'unsigned long long' in <bits/types.h>, so everything checks out.
3535-3636- But on 64-bit systems, it is #ifdef'ed in the same file as 'unsigned long'.
3737- Now, it only happens in circumstances where the type happens to have the
3838- expected bit width, *but* the compiler does not know that... and complains
3939- about 'unsigned long' being unsafe to pass to %llu.
4040-4141- */
4242-4343-#ifdef __x86_64__
4444-typedef unsigned long long u64;
4545-#else
4646-typedef uint64_t u64;
4747-#endif /* ^sizeof(...) */
4848-4949-typedef int8_t s8;
5050-typedef int16_t s16;
5151-typedef int32_t s32;
5252-typedef int64_t s64;
5353-5454-#ifndef MIN
5555-# define MIN(_a,_b) ((_a) > (_b) ? (_b) : (_a))
5656-# define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
5757-#endif /* !MIN */
5858-5959-#define SWAP16(_x) ({ \
6060- u16 _ret = (_x); \
6161- (u16)((_ret << 8) | (_ret >> 8)); \
6262- })
6363-6464-#define SWAP32(_x) ({ \
6565- u32 _ret = (_x); \
6666- (u32)((_ret << 24) | (_ret >> 24) | \
6767- ((_ret << 8) & 0x00FF0000) | \
6868- ((_ret >> 8) & 0x0000FF00)); \
6969- })
7070-7171-#define R(x) (random() % (x))
7272-7373-#define STRINGIFY_INTERNAL(x) #x
7474-#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
7575-7676-#define MEM_BARRIER() \
7777- asm volatile("" ::: "memory")
7878-7979-#endif /* ! _HAVE_TYPES_H */