Compare commits

...

2637 Commits
2.62c ... 3.10c

Author SHA1 Message Date
bd0a23de73 Merge pull request #767 from AFLplusplus/dev
Final push for release
2021-03-01 10:12:04 +01:00
4619a1395b ensure proper aligning for skim patch 2021-03-01 09:57:57 +01:00
0c38850f95 3.10c release 2021-03-01 09:43:35 +01:00
07884e0054 feodora qemu lib fix 2021-03-01 09:37:07 +01:00
bdadbb7207 Merge pull request #770 from rchildre3/qasan-print-formats
Fix printf specifiers of (s)size_t in QAsan hooks
2021-02-28 22:02:35 +01:00
e389eb9842 Fix printf specifiers of (s)size_t in QAsan hooks
* size_t specifier is %zu or %zx
* ssize_t specifier is %zd

Helpful for cross compiling
2021-02-28 15:08:59 -05:00
5cf0655071 metrics 2021-02-28 10:01:35 +01:00
f81ef4abf4 fix afl-common compile 2021-02-28 00:12:39 +01:00
6036cf8437 BSD: how to avoid core dumps 2021-02-28 00:24:29 +01:00
1cad645400 fix %ld in hooks.c 2021-02-27 18:30:04 +01:00
36846836ed libqasan: read and write hooks 2021-02-27 18:26:57 +01:00
79f1a44a01 fix qasan search path 2021-02-27 18:14:58 +01:00
c2127e3ff7 disable the generation of core files in DragonFly BSD 2021-02-27 17:58:25 +01:00
2ad495ad0a reworked unicornafl documentation 2021-02-27 17:19:00 +01:00
8e051fd075 fixed rust bindings placement 2021-02-27 16:37:00 +01:00
af628b16d1 added rust binding reference 2021-02-27 16:29:29 +01:00
c219502f0f some rust cleanup 2021-02-27 15:52:36 +01:00
a5da9ce42c custom mutator rust support (#752)
* custom mutator rust support

* clarify how to view documentation for rust mutators

* remove `FuzzResult` hack and clarify lifetimes of CustomMutator::fuzz

* rename TErr associated tyep to Error to be more idiomatic

* fix warnings

* add example for fallible custom mutator

* make Fallible Custom Mutator the default and implement it's handle_err method by default

* rename CustomMutator::handle_err to handle_error

* add example mutator using lain
2021-02-27 15:05:13 +01:00
79e02c2a9b remove debug output 2021-02-26 22:54:35 +01:00
3a461944ec fine tune cmplog 2021-02-26 22:36:19 +01:00
78d96c4dc8 Merge pull request #759 from AFLplusplus/dev
push to stable
2021-02-26 09:45:43 +01:00
ee0ca07f3c changing the -t ...+ meaning to "auto-calculate buth this is the max" 2021-02-25 12:19:46 +01:00
7ae7b0f373 docs update 2021-02-25 11:08:37 +01:00
e2b4bc9310 update changelog 2021-02-25 11:02:59 +01:00
6c9777de13 edges in afl-plot 2021-02-25 10:42:39 +01:00
2f7e57f6aa helper_min3 func 2021-02-25 10:04:41 +01:00
5c239451cf cmplog finetuning 2021-02-25 09:15:54 +01:00
35ca51c5a8 Merge branch 'dev' of github.com:AFLplusplus/AFLplusplus into dev 2021-02-24 21:29:09 +01:00
047f3436e9 edges in plot file 2021-02-24 21:29:00 +01:00
5d181950eb fixes 2021-02-24 21:17:58 +01:00
48a1a29baa typos 2021-02-24 20:34:33 +01:00
c05d392cd9 Merge branch 'dev' of github.com:AFLplusplus/AFLplusplus into dev 2021-02-24 18:07:18 +01:00
cc7c651dc9 tidied up env suggestions 2021-02-24 18:07:08 +01:00
e6ef2ee338 typo 2021-02-24 12:14:10 +01:00
a090b2013f docs 2021-02-24 12:02:44 +01:00
564f491566 redqueen settings opt 2021-02-24 09:29:19 +01:00
2daeeab844 encode double quote in dict 2021-02-23 10:06:15 +01:00
4ab90e739f code format 2021-02-22 22:24:59 +01:00
745bc083d1 fix error msg 2021-02-22 18:22:09 +01:00
7674dac1a1 auto mode for CTX + NGRAM 2021-02-22 18:17:35 +01:00
fb2a6b6941 minimum sync time 2021-02-22 16:56:35 +01:00
70fe872940 ensure a valid seed exists 2021-02-22 16:39:38 +01:00
a252943236 another fix for disabled entries 2021-02-22 12:59:01 +01:00
8c133b607c stdstring fix attempt 2021-02-22 12:43:39 +01:00
2785c8b197 crash fix 2021-02-22 12:34:37 +01:00
a81b5aa921 dict2file fix 2021-02-22 11:08:25 +01:00
8ad78f5b65 fix 2021-02-21 23:42:08 +01:00
ac9cfd89da how to compare afl++ 2021-02-21 23:27:07 +01:00
c67c4ce757 doc update 2021-02-21 23:17:40 +01:00
974aab6cf6 cmplog config.h -> -l option 2021-02-21 17:53:09 +01:00
b957218a3a more attuned colorize repace 2021-02-21 11:30:05 +01:00
f629f4e341 Merge pull request #755 from rchildre3/improve-llvm-build-instructions
Improve LLVM build instructions
2021-02-21 09:15:20 +01:00
871c3c91ec Improve LLVM build instructions
* Enable shell highlighting on code block
* Shallow clone of source due to extensive history
* Line break and sort the CMake options for visibility
* Disable most extraneous options (e.g. docs, tests, benchmarks,
  clang-tools-extra, OpenCL interface)
* Only build for the host architecture by default
* Support other sub-make interfaces, like the recommended Ninja Build
  System
* Harden against paths with spaces
* Prefer linking against the newly built LLVM libraries by prepending to
  LD_LIBRARY_PATH
2021-02-20 19:24:28 -05:00
100aac4dd3 -t help 2021-02-20 14:15:38 +01:00
d941da33ae qemuafl 2021-02-19 21:20:33 +01:00
62767a42dc improved env suggestions 2021-02-19 20:40:38 +01:00
89cf94f0e6 suggested env vars for lazy ppl 2021-02-19 20:33:12 +01:00
17211253b2 libhfcommon not anymore a symlink 2021-02-19 18:25:24 +01:00
6998489b26 Revert "Remove self-referential symlink"
This reverts commit aaf5fcd98a.
2021-02-19 18:21:10 +01:00
4290cb5877 fix hongg mutator API change 2021-02-19 16:07:47 +01:00
801f2449ec Merge pull request #753 from frewsxcv/frewsxcv-libhf
Remove self-referential symlink
2021-02-19 16:02:25 +01:00
aaf5fcd98a Remove self-referential symlink 2021-02-19 09:18:59 -05:00
5edfb7ba85 nicer bib 2021-02-19 15:04:53 +01:00
a5cb522f01 Merge branch 'dev' of github.com:AFLplusplus/AFLplusplus into dev 2021-02-19 15:03:22 +01:00
3195119dad pointer to cite in readme 2021-02-19 15:03:10 +01:00
d6fe6b9537 qemuafl 2021-02-19 10:49:36 +01:00
c0f9fba6d6 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2021-02-18 19:40:22 +01:00
1a713ff420 fix qemu AFL_ENTRYPOINT for arm 32 and 64 bit 2021-02-18 19:39:46 +01:00
89af2ef7a9 update honggfuzz custom mutator 2021-02-18 11:15:59 +01:00
907c5d4276 Merge pull request #751 from AFLplusplus/dev
fix a rare i2s illegal memory access
2021-02-17 19:19:25 +01:00
5dd35f5281 fix a rare i2s illegal memory access 2021-02-17 19:10:05 +01:00
857229654e Merge pull request #750 from AFLplusplus/dev
Push to stable
2021-02-17 17:43:11 +01:00
4c47b242eb fix FPE in colorization 2021-02-17 17:40:01 +01:00
938512a6b9 minor fixes 2021-02-17 09:48:04 +01:00
7444cfa450 Merge pull request #748 from b1gr3db/dev
Regression fix
2021-02-16 17:52:44 +01:00
f091b8d692 Regression fix
Previous fix was undone in a subsequent commit
2021-02-16 11:17:55 -05:00
7d97ffb1e8 check for setuptools instead of easy_install 2021-02-16 16:27:56 +01:00
80bdbf7be0 minor cmplog fix 2021-02-16 09:54:15 +01:00
686719cdca Merge pull request #746 from f0rki/cmplog-intcast-fix
CMPLOG llvm pass: use CreateIntCast to cast to the right integer type
2021-02-16 09:51:31 +01:00
6caec2169c Revert "llvm bug workaround for lto extint"
This reverts commit e3a5c31307.
2021-02-15 19:14:28 +01:00
5212481352 CMPLOG llvm pass: use CreateIntCast to cast to the right integer type 2021-02-15 19:13:50 +01:00
d999725de2 Merge pull request #737 from AFLplusplus/dev
push to stable
2021-02-15 15:20:06 +01:00
145c673a80 finished merge 2021-02-15 15:04:34 +01:00
c5017945f7 merged 2021-02-15 14:07:10 +01:00
5c4c49d9ca black 2021-02-15 14:00:08 +01:00
cebde1f9e6 ran black on python scripts 2021-02-15 13:52:23 +01:00
0298ae82b0 code-format 2021-02-15 13:52:03 +01:00
512f53984c fixed scan-build issues 2021-02-15 13:51:32 +01:00
e3a5c31307 llvm bug workaround for lto extint 2021-02-15 13:25:15 +01:00
dd2fd80274 doc updates 2021-02-15 12:40:10 +01:00
ffc1fc655f qenuafl 2021-02-15 10:27:44 +01:00
fe477e96ae fix configure arguments 2021-02-15 09:24:13 +01:00
98559ea8b0 fix compiler warning 2021-02-15 08:54:53 +01:00
f31d8b8401 redqueen fix compiler warnings for 32 bit 2021-02-15 08:46:19 +01:00
389e348826 fixes 2021-02-14 22:43:52 +01:00
98fd50f78f Merge branch 'stable' into dev 2021-02-14 22:42:13 +01:00
95561ec5a7 dockerfile fix 2021-02-14 21:47:42 +01:00
fe9da70705 disabling march=native due problems on intel platforms 2021-02-14 18:43:43 +01:00
95c77c8486 try qemu build fix 2021-02-14 11:46:23 +01:00
e45333bcf9 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2021-02-13 23:29:04 +01:00
c906c042be fix compiler warning 2021-02-13 23:28:15 +01:00
9bd1e19d7f added AFL_IGNORE_UNKNOWN_ENVS 2021-02-13 22:43:56 +01:00
6ce9230ed6 afl-cmin/afl-showmap -f 2021-02-13 14:29:22 +01:00
1d60c39191 fix new compiler warning 2021-02-13 13:42:37 +01:00
70651d60bd Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2021-02-13 13:32:42 +01:00
385312c658 fix issue #732 afl-cmin and afl-showmap should support '-f' 2021-02-13 13:31:17 +01:00
87a607c7d0 update doc 2021-02-13 11:17:53 +01:00
1ba5d1008e fuck you llvm 13 2021-02-13 10:53:40 +01:00
129a5adaf1 fix 2021-02-13 09:29:35 +01:00
d827bc4580 dont break on llvm 13 2021-02-13 09:12:36 +01:00
64e46dcefc remvoe libcompcov 32 bits warnings 2021-02-12 22:07:17 +01:00
c0b3127b9d remove travis badge 2021-02-12 14:54:24 +01:00
7cfa690d1c typo 2021-02-12 11:05:46 +01:00
22a3c7f7d0 fix #736 (ty b1gr3db) 2021-02-12 09:42:22 +01:00
16ffbb37f5 typo 2021-02-11 22:09:19 +01:00
ea05f3f4cd typos 2021-02-11 21:55:14 +01:00
91f2f057e4 fix #723 2021-02-11 21:17:08 +01:00
d44cf1344d typo 2021-02-11 21:08:10 +01:00
756206e4d7 typo 2021-02-11 20:26:02 +01:00
2ff6e5023f typos 2021-02-11 20:14:48 +01:00
223bd70f1f typo 2021-02-11 20:08:28 +01:00
dd3f4bb41c typos & formatting 2021-02-11 20:05:06 +01:00
f3e783d343 typo 2021-02-11 19:55:21 +01:00
f4cac37b04 typos 2021-02-11 10:20:36 +01:00
5b2634f711 update changelog + ideas 2021-02-10 17:56:27 +01:00
267b085f80 dlmalloc only for non glibc qasan and AFL_QEMU_FORCE_DFL 2021-02-10 15:15:16 +01:00
b6643743d6 fix laf for potential crashes 2021-02-10 10:13:08 +01:00
17cbb03ba7 more cmplog options in config.h 2021-02-09 09:18:24 +01:00
2cd4624779 build docker without march=native 2021-02-09 08:38:33 +01:00
e11665564b fix docker build action 2021-02-09 08:30:49 +01:00
93cebd6c7f Merge pull request #734 from Pamplemousse/build_docker_image_in_actions
Use GitHub Actions to build Docker image
2021-02-09 08:28:31 +01:00
a124540e50 Use GitHub Actions to build Docker image
... then deploy to hub.docker.com .

Signed-off-by: Pamplemousse <xav.maso@gmail.com>
2021-02-08 20:36:06 -07:00
c465e48e27 remove AFL_CC from unset list to allow success for unusual environments 2021-02-07 16:19:27 +01:00
c2c65fd9c1 mark llvm 13 as unsupported (yet) 2021-02-07 09:42:28 +01:00
0ad56167c5 fix scan-build issues 2021-02-07 07:51:29 +01:00
aeb7d70483 remove debug output 2021-02-07 06:16:53 +01:00
209c5ba465 larger map, stats reload fix, code format 2021-02-07 05:33:02 +01:00
01327ad301 Merge pull request #728 from vj-27/dev
load existing stats file when in AFL_AUTORESUME or -i - mode.
2021-02-07 05:20:02 +01:00
96cdc97c98 prev_run_time loaded used only for ui and when writing the stats file 2021-02-07 03:33:47 +05:30
a763c61d89 add missing sancov cmp functions 2021-02-06 12:43:22 +01:00
d920104248 remove compiler warnings 2021-02-06 12:26:51 +01:00
08076f0500 fix qemu build script for Arch Linux ($CROSS) 2021-02-06 12:04:29 +01:00
e81f30828f fix test-qemu-mode.sh to run standalone 2021-02-06 11:24:04 +01:00
f54c4dbfdb set prev_run_time inside afl state 2021-02-06 09:41:15 +00:00
bf289ce50e larger dummy map 2021-02-06 09:31:41 +01:00
1a8c242d28 load run time and donot load pending_* or *_favoured 2021-02-05 19:46:24 +00:00
19d8f00963 doc fix 2021-02-05 13:01:42 +01:00
bed789cd5a fix doc 2021-02-05 13:01:13 +01:00
7e625c3687 more doc, so good 2021-02-05 12:30:21 +01:00
f53a2e4b88 nits 2021-02-05 12:11:18 +01:00
d8a18a03e3 update unicorn ref 2021-02-05 11:44:48 +01:00
1677481726 try if this helps on fuzzbench 2021-02-05 10:47:16 +01:00
6f163bb0c5 load existing stats file when in AFL_AUTORESUME or -i - 2021-02-05 00:26:23 +00:00
3533df9453 Merge pull request #730 from AFLplusplus/replay
update readme
2021-02-04 23:10:32 +01:00
faa9daf260 update readme 2021-02-04 23:09:49 +01:00
bf1198c4db dockerfile: fix qemu built, update llvm to 12 2021-02-04 20:47:51 +01:00
ec737f3368 workaroung for llvm LTO bitcast bug 2021-02-04 18:57:27 +01:00
208254f47c Merge pull request #726 from b1gr3db/dev
Fix for off by one in libqasan's memmem
2021-02-04 13:32:54 +01:00
d0ab2ded00 Create string.c
Off by one error resulted in memmem calling memcmp where h + needle_len is one past the end.
2021-02-03 15:32:06 -05:00
58a5372bf0 typo 2021-02-03 14:18:35 +01:00
ea5d9c42b6 Merge pull request #724 from devnexen/afl_untracer
afl-untracer: Mac M1 build update proposal.
2021-02-03 09:21:41 +01:00
8bd70a50b1 afl-untracer: Mac M1 build update proposal. 2021-02-03 07:38:09 +00:00
6be3896bfa linux performance option 2021-02-02 14:41:31 +01:00
1f71b85426 automagically fix sanitize fuzzer+coverage 2021-02-02 10:05:10 +01:00
654f389e73 try to remove warnings during compilation 2021-02-01 23:36:27 +01:00
cd95ee67bc code format qasan 2021-02-01 23:00:45 +01:00
90fdafa1ad fix warnings and an llvm cmplog+lto panic 2021-02-01 22:59:41 +01:00
b9f469e12f make some really weird targets compile 2021-02-01 20:00:29 +01:00
ba7bf99235 Merge pull request #721 from GanbaruTobi/patch-1
Clarify usage of LD_LIBRARY_PATH in afl_frida
2021-02-01 17:53:08 +01:00
e954c891a0 Clarify usage of LD_LIBRARY_PATH in afl_frida
This will help not *accidentally* trying to set the variable to the library's binary.
2021-02-01 17:32:45 +01:00
80fc6166d0 adjust expand havoc 2021-02-01 16:28:52 +01:00
4018e7f8e5 mv cmplog options to config.h 2021-02-01 16:23:40 +01:00
05472a0fc5 move cmplog compile options to config.h 2021-02-01 16:04:34 +01:00
32110a04c0 fixes 2021-02-01 15:51:04 +01:00
812cf4c9e0 reorder 2021-02-01 15:21:39 +01:00
374fa8af47 add case when cmplog map neds to be larger 2021-02-01 14:56:22 +01:00
fc5f865796 reorder check 2021-02-01 14:02:31 +01:00
88155d2c3b make dominik more happy - no auto map size for qemu+unicorn 2021-02-01 13:04:39 +01:00
d808a8401e import cmplog opts 2021-02-01 12:16:55 +01:00
bca4026f62 Merge pull request #718 from AFLplusplus/cmplog_lowfail
cmplog lower fail
2021-02-01 12:07:13 +01:00
965b854803 correct afl-showmap be_quiet state 2021-02-01 12:05:54 +01:00
981ffb27a8 making AFL_MAP_SIZE obsolete 2021-02-01 12:01:23 +01:00
522eacce71 qemuafl 2021-01-31 21:48:30 +01:00
19d02d7bf6 update qemu and main makefile for qasan 2021-01-31 17:45:55 +01:00
cc0210426a code-format 2021-01-31 17:32:24 +01:00
459dd8cb07 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2021-01-31 17:30:17 +01:00
e5116c6d55 fix -Z, remove q->next 2021-01-31 17:29:37 +01:00
7a861498c2 added support for __afl_coverage_interesting 2021-01-31 15:04:40 +01:00
893cd47d9c disable trimming for -M 2021-01-31 13:03:00 +01:00
9d08f0d098 added AFL_CMPLOG_ONLY_NEW feature 2021-01-30 15:39:47 +01:00
3b3565269d foreign sync from ctime to mtime (libfuzzer) 2021-01-30 14:57:17 +01:00
2f96f1e920 afl-frida faster for x86_x64 2021-01-30 10:28:34 +01:00
1b557d1a70 remove warnings 2021-01-30 09:01:06 +01:00
b06e3d9f2b Merge pull request #715 from AFLplusplus/qasan
Qasan
2021-01-29 18:52:45 +01:00
aaec45b652 changelog 2021-01-29 18:51:44 +01:00
af24d87220 qasan readme 2021-01-29 18:48:46 +01:00
2e3bc3b613 update qemuafl 2021-01-29 18:42:21 +01:00
29c1131fe0 working AFL_USE_QASAN 2021-01-29 18:32:28 +01:00
debd832f36 32bit fix 2021-01-29 18:25:25 +01:00
8a8ecef6f5 cmplog lower fail 2021-01-29 18:13:45 +01:00
66c290f804 fix compile 2021-01-29 17:23:19 +01:00
40f609c735 better cmplog arithmetic 2021-01-29 15:57:47 +01:00
28e1aaa0f1 qasan support in aflpp 2021-01-29 15:47:25 +01:00
6f5746d428 AFL_USE_QASAN 2021-01-29 15:38:49 +01:00
4488e8e10a fix qemu build script 2021-01-29 15:16:35 +01:00
d21ca3e480 libqasan and use target cross compiler to compile target qemu libs 2021-01-29 15:14:20 +01:00
1b1006ddd4 qemuafl 2021-01-29 13:04:03 +01:00
cb428e55bb Merge pull request #714 from AFLplusplus/vanhauser-thc-patch-1
Update issue templates
2021-01-29 10:17:53 +01:00
0c616087e0 Update issue templates 2021-01-29 10:17:32 +01:00
ce673ccab3 remove snapshot reference 2021-01-28 19:19:57 +01:00
d5a170655f update qemuafl 2021-01-28 19:08:36 +01:00
2a9fcd2a87 warn on afl-gcc/afl-clang instrumentation 2021-01-28 18:01:27 +01:00
a61a30dee0 fix another pending_not_fuzzed location 2021-01-28 14:11:33 +01:00
d62c83d58f Merge pull request #712 from zodf0055980/dev
Fix getopt arg string
2021-01-28 10:46:36 +01:00
ad63ba49c1 Fix getopt arg string
There is no '-P' case here.
2021-01-28 17:21:54 +08:00
1dfea4e91a Merge pull request #711 from wideglide/patch-1
enable warnings for LTO mode 's/warn /warning /'
2021-01-28 08:26:30 +01:00
47f62eb0ca Fix dev branch for android (#710)
* android: replace rindex with strrchr

* android: support 64bit only due to 128bit integer not supported by 32bit system

Co-authored-by: joeyjiaojg@qq.com <joeyjiaojg@163.com>
2021-01-28 05:51:45 +01:00
9bc8c7518f enable warnings for LTO mode 's/warn /warning /' 2021-01-27 22:39:33 -05:00
2044c7e2b5 fix include 2021-01-27 08:41:45 +01:00
6b721900d5 Merge pull request #707 from ampanasiuk/bug-703-wrong-src-attribute-in-sync-stage-filenames
Bug 703 wrong src attribute in sync stage filenames
2021-01-27 08:35:21 +01:00
f5127c0e2b Merge pull request #706 from fuzzah/dev
include limits.h to fix build on BSD systems
2021-01-27 08:33:28 +01:00
f571f074a8 update envs 2021-01-27 08:21:22 +01:00
d046b28f2f Fix "src" attribute in sync stage filenames (#703) 2021-01-27 03:04:06 +00:00
a754694ac4 include limits.h to fix build on BSD systems 2021-01-27 05:48:59 +03:00
36b5336152 better foreign sync name 2021-01-26 22:45:59 +01:00
9c393adbb9 real fix plus code format 2021-01-26 17:12:11 +01:00
e0663c91b9 wip fix 2021-01-26 12:15:13 +01:00
7c381a782e enable cmplog combine 2021-01-25 20:18:42 +01:00
cd8668ad3a mopt fix 2021-01-25 13:55:09 +01:00
9a7531942d fix rpc_stats.md 2021-01-25 10:04:21 +01:00
107b624224 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2021-01-25 04:24:57 +01:00
822aea3cb4 unicorn fix 2021-01-25 04:24:43 +01:00
52af7caf8a Add StatsD readme (#702)
* Adding draft notes for statsd readme

* Add statsd dashboard json template & image.
2021-01-25 02:07:51 +01:00
afc15965c0 updated unicornalf, bindings 2021-01-25 02:01:34 +01:00
e82cd40440 added cargo lock 2021-01-23 19:39:34 +01:00
08c716da9c removed lock' 2021-01-23 19:39:16 +01:00
0a3a708f9b less stack mem req 2021-01-23 10:01:09 +01:00
a22c8ffdf2 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2021-01-23 06:45:16 +01:00
4179affe2c enabled persistent mode 2021-01-23 06:42:55 +01:00
46cef4bc11 fixed rust example 2021-01-23 06:39:55 +01:00
fea0286989 tried to fix rust example 2021-01-23 06:03:15 +01:00
b0a8bc28d2 changelog 2021-01-23 00:13:32 +01:00
e37e432952 updated uc ref 2021-01-23 00:10:59 +01:00
c4118e869d unicorn speedtest initial commit 2021-01-23 00:02:59 +01:00
258ae1632a stack 2 heap 2021-01-22 21:10:23 +01:00
1c19804834 fix for cmplog stdstring 2021-01-22 16:41:31 +01:00
9ed533a0e3 fix debug output 2021-01-22 16:01:00 +01:00
baf1ac2e69 basic cmplog std::string support 2021-01-22 15:58:12 +01:00
46010a8704 prepare for cmplog rtn std::string support for llvm and g++ 2021-01-22 13:50:16 +01:00
ac21e4dd73 typos 2021-01-22 00:41:23 +01:00
f0be89a5b6 Merge pull request #699 from Edznux/origin/statsd-env-doc
Add more docs for AFL_STATSD_TAGS_FLAVOR
2021-01-22 00:37:35 +01:00
0a12d519f7 Add better doc for AFL_STATSD_TAGS_FLAVOR 2021-01-22 00:18:56 +01:00
2ef8dc4378 afl-cmin -m none 2021-01-21 21:42:15 +01:00
30148bc1a9 fix afl-showmap and gcc plugin test 2021-01-21 19:58:25 +01:00
60764ebdf1 forkserver debug flag support 2021-01-21 18:43:06 +01:00
040bf5a61d fix silly mistake 2021-01-21 18:26:08 +01:00
b850951c72 code format and not setting sanitizers if debug and settings present 2021-01-21 17:15:14 +01:00
43edd969d8 fix qemu x86 cmplog issue 2021-01-21 16:57:19 +01:00
e8c1b43a3d fix docs 2021-01-21 15:24:34 +01:00
3903dac1f5 fix gcc plugin test 2021-01-21 14:17:08 +01:00
1ee0946f69 update changelog 2021-01-21 12:11:12 +01:00
fc3f06caec Merge pull request #689 from AFLplusplus/cmplog_merge
cmplog merge
2021-01-21 12:03:21 +01:00
0d472adef0 temp conflict resolve 2021-01-21 12:02:50 +01:00
ba47bee252 pre merge changes 2021-01-21 11:41:25 +01:00
f7c93d741c base64 solving done 2021-01-21 03:52:46 +01:00
cf5fee7c52 remove debug output 2021-01-20 21:03:55 +01:00
d20a50a413 hex en/decode works now 2021-01-20 20:59:17 +01:00
b39b87b2f7 Merge pull request #693 from vishesh-sharma-123/patch-2
Update README.md
2021-01-20 19:13:02 +01:00
068bef5eab Merge pull request #691 from AFLplusplus/dev
push to stable
2021-01-20 19:12:52 +01:00
5174eb6741 Update README.md
typo and correction in link
2021-01-20 22:31:21 +05:30
b9e855b7b5 Merge pull request #695 from joeyjiaojg/dev
Fix Porting of AFLplusplus for Android
2021-01-20 14:00:26 +01:00
f380487bb4 wip 2021-01-20 13:51:57 +01:00
02079d8ef9 android: Remove frida-gum package 2021-01-20 19:16:57 +08:00
9dff3495d5 better cmp map fsrv fix 2021-01-20 10:01:34 +01:00
2cd3010f82 Merge pull request #694 from rchildre3/wine-preload
LD_PRELOAD in the QEMU environ and enforce arch
2021-01-20 09:55:00 +01:00
bb9d275350 afl_frida: Add AFL_FRIDA_TEST_INPUT env to debug input 2021-01-20 15:48:48 +08:00
f3ef91e8d6 Migrates DebugLoc::get to DILocation::get
- Refer to https://reviews.llvm.org/D93087
2021-01-20 15:48:48 +08:00
ac1117ffae android: Fix runtime for mutator 2021-01-20 15:46:41 +08:00
7ad8f6c717 android: Add libprotobuf aflpp custom_mutator example 2021-01-20 15:46:41 +08:00
9d9e148e5c android: build custom mutators for symcc, radamsa 2021-01-20 15:46:41 +08:00
1e2da1dfb9 android: port libfuzzer-mutator 2021-01-20 15:46:41 +08:00
6dc20fc298 afl_frida: fix target lib 2021-01-20 15:46:41 +08:00
868ef6c10c android: afl_frida: get target lib/function from command line 2021-01-20 15:46:41 +08:00
52f1d535bd android: port afl_frida for arm64 2021-01-20 15:46:41 +08:00
0306261fec Fix build error for Android
- LTO not work yet
2021-01-20 15:46:39 +08:00
17e3e65d96 LD_PRELOAD in the QEMU environ and enforce arch 2021-01-20 01:02:28 -05:00
e3835b4d68 Update README.md
Typo
2021-01-20 09:22:28 +05:30
e7b572af36 bugfix and new transform detection feature 2021-01-20 01:49:32 +01:00
473b3e5fb0 updated unicornafl qemu versions 2021-01-19 19:45:53 +01:00
86c567fa3a update qemuafl + unicorn for include changes 2021-01-19 16:49:00 +01:00
ed9f94c5b9 fix CI 2021-01-19 14:20:43 +01:00
0367f6c723 cleanup and rename _DISCARD->_SKIP 2021-01-19 14:03:10 +01:00
292f91a55f tiny scan-build nags fixed 2021-01-19 13:16:39 +01:00
95ee2cdd57 cleanup 2021-01-19 13:05:42 +01:00
e91f3b0de6 codeql fix 2021-01-19 10:41:42 +01:00
ca1eb32552 fix compiles 2021-01-19 10:16:12 +01:00
a9ebf72a84 cmp map memset fix 2021-01-18 22:19:04 +01:00
e2d9dc16e3 fix compiler warning avoid signess difference in comparisons 2021-01-18 21:36:19 +01:00
0b545aaeb4 use enums, support cmplog map collisions 2021-01-18 20:18:18 +01:00
94a15b8ca7 arithmetic also for <= >= 2021-01-18 13:20:40 +01:00
0c061186cf less logging 2021-01-18 12:13:36 +01:00
bbfaa6092d refactoring 2021-01-18 11:12:20 +01:00
a8b0629163 introspection, favor extint over long double 2021-01-18 09:26:16 +01:00
7b97410060 cmplog introspection 2021-01-17 23:47:04 +01:00
8951f90623 no cmplog when no taint is found 2021-01-17 17:03:08 +01:00
6b375489ed better extint cmplog 2021-01-17 16:50:10 +01:00
c8c0983ab8 make combined test a define option 2021-01-17 15:51:38 +01:00
c71ce79963 fix colorization 2021-01-17 15:18:20 +01:00
d36af0d576 fix msg 2021-01-15 17:32:43 +01:00
a0e884cf8b merge cmplog 2021-01-15 16:56:40 +01:00
fba8790e32 better error reporting 2021-01-15 15:12:27 +01:00
8eb00a5dfa remove warning 2021-01-15 14:55:58 +01:00
d5049da5e4 better error message 2021-01-15 14:50:51 +01:00
9646960f88 update doc 2021-01-14 21:36:52 +01:00
7ba17d182f more sync in deterministic mode 2021-01-14 21:26:46 +01:00
c42875ddea Merge pull request #688 from murx-/dev
Update documentation to reflect new default power schedule
2021-01-14 14:15:01 +01:00
53c7aaa57b Update documentation to reflect new default power schedule 2021-01-14 13:46:03 +01:00
68acd3d101 Merge pull request #686 from AFLplusplus/weight
better seed selection
2021-01-14 00:26:08 +01:00
0ddbffd80e fix 2021-01-12 17:36:10 +01:00
b9ba2805e5 minor changes 2021-01-12 17:31:29 +01:00
efd8042431 fix lto cmplog instability 2021-01-12 13:42:00 +01:00
dc81f681c9 fix weight calc, thanks to Marcel 2021-01-10 13:12:44 +01:00
4581ad3df9 code fmt 2021-01-08 18:19:40 +01:00
3196a5f666 cleaned up and added comments to forkserver exits 2021-01-08 18:17:52 +01:00
20a47cb23e Merge pull request #679 from AFLplusplus/dev
Dev
2021-01-08 15:43:13 +01:00
813627cbd3 better gcc_plugin error msg 2021-01-08 13:01:46 +01:00
1827c65596 better gcc_plugin error msg 2021-01-08 12:55:05 +01:00
3d1a25ce4e added check to silence scan-build 2021-01-08 11:54:35 +01:00
34732e3c5e refactored kill signal env parsing 2021-01-08 11:36:40 +01:00
7b8c8cf12f fix 2021-01-08 00:47:52 +01:00
7eaca9c840 Merge branch 'stable' of github.com:aflplusplus/aflplusplus into dev 2021-01-07 23:37:57 +01:00
a06b25538f cleaned up AFL_KILL_SIGNAL 2021-01-07 23:21:10 +01:00
9cdf5c4150 User defined kill signal value (#678)
* Adding AFL_KILL_SIGNAL environment variable

Controlling the kill signal used to end forked processes.

* Checking validity of AFL_KILL_SIGNAL env variable

This commit also sets a valid value in the environment to avoid
duplicating code in at_exit(). Changing data type of
fsrv->kill_signal to u8 to match last_kill_signal.

* Adding afl_kill_signal to AFL (environment) state

This commit simply introduces a struct member for future use. The
env variable is not used from the afl struct but from fsrv, where
its validity is checked, resulting in a FATAL in case of errors.
2021-01-07 22:35:34 +01:00
52c221fc48 selective coverage fix 2021-01-06 09:35:47 +01:00
4c78bb7080 cpp fix 2021-01-05 22:13:55 +01:00
59b86b0db0 haiku fix 2021-01-05 19:20:10 +01:00
1a85fca49f haiku fix 2021-01-05 19:14:51 +01:00
9d4614ce2f haiku support 2021-01-05 19:06:27 +01:00
faefad564b Haiku afl-system-config disable debugger, afl-cc.c avoid -lrt 2021-01-05 16:49:04 +00:00
6b54310452 selective instrumentation documented 2021-01-05 12:30:26 +01:00
caf1fbd632 selective_coverage implementation in afl-compiler-rt 2021-01-05 11:52:55 +01:00
a561de6e97 forgot struct keyword 2021-01-05 10:40:46 +01:00
7acf410ab6 afl coverage feature example 2021-01-05 10:35:12 +01:00
6c095b3937 code format 2021-01-04 23:13:56 +01:00
d367b033a2 add missing FCMP_UEQ to split-compares-pass.so.cc 2021-01-04 23:08:46 +01:00
7f4b3a460a more code cleanup (instrumentation) 2021-01-04 22:23:04 +01:00
251e72f136 mehr code cleanup 2021-01-04 21:25:53 +01:00
c6e038fe25 code cleanups (shadowed vars, (un)signed type mismatches, format types, etc.) 2021-01-04 20:40:53 +01:00
5c22472616 cmplog fix 2021-01-04 18:20:02 +01:00
b7cd6d4035 code cleanup 2021-01-04 18:11:51 +01:00
1842c8390f fix for llvm < 11 2021-01-04 17:53:47 +01:00
9c15f53a47 fix for changes in llvm 12 2021-01-04 17:45:52 +01:00
b7af98e945 code cleanups (from cppcheck mostly) 2021-01-04 15:32:22 +01:00
5cdbfeef4a Revert "code cleanups (from cppcheck)"
This reverts commit 33a7d6f168.
2021-01-04 15:17:39 +01:00
33a7d6f168 code cleanups (from cppcheck) 2021-01-04 15:14:20 +01:00
c423aebb1a FP support for cmplog 2021-01-04 12:57:29 +01:00
58039d181a stability fix 2021-01-03 12:34:23 +01:00
880513651d cmplog cleanup 2021-01-03 10:13:55 +01:00
1857df8d06 cleanup 2021-01-03 00:37:56 +01:00
3c88de565a afl-cmin tests: allow leading whitespace in wc -l output 2021-01-02 23:17:30 +01:00
8bcb17b11f Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2021-01-02 23:16:37 +01:00
848db92196 build_unicorn_support.sh: allow DragonFly to build 2021-01-02 23:15:55 +01:00
6ed465bacc afl-system-config: cosmetic support for DragonFly 2021-01-02 23:14:29 +01:00
e83a1bc0d1 test-basic.sh: fix color GRAY to GREY 2021-01-02 20:18:26 +01:00
33abd70647 typo 2021-01-02 20:06:02 +01:00
84d3192f01 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2021-01-02 20:01:19 +01:00
d2a1f05a69 add first support for DragonFly OS 2021-01-02 19:59:06 +01:00
7620f6f396 Merge branch 'dev' of github.com:AFLplusplus/AFLplusplus into dev 2021-01-02 11:36:17 +01:00
214da5c42e fix qemu linking error with mips 2021-01-02 11:36:06 +01:00
697e3e285b add missing git submodule sync 2021-01-02 08:35:27 +01:00
fac373ec9e try new weighting 2021-01-01 13:42:58 +01:00
16d2bd3177 doc update 2021-01-01 13:34:24 +01:00
af10a635f5 Merge pull request #670 from devnexen/libdislocator_build_fix
libdislocator, ptr algo warning fix on clang/Xcode (m1).
2020-12-31 15:56:57 +01:00
935724557f libdislocator, ptr algo warning fix on clang/Xcode (m1). 2020-12-31 11:38:35 +00:00
7e6645d5a2 float2double 2020-12-31 11:51:10 +01:00
271116f870 Merge pull request #666 from AFLplusplus/dev
push to stable
2020-12-30 18:13:55 +01:00
84e72b0a51 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-12-30 13:03:13 +01:00
b0d69f1b69 cleanup of hot fix for -s on 32-bit 2020-12-30 13:02:11 +01:00
f38595f6b4 better weighting 2020-12-30 12:32:55 +01:00
5a99e67e02 add less to Dockerfile 2020-12-30 11:02:00 +01:00
0246fe9200 fix 32-bit mode, fix weighting 2020-12-30 10:34:22 +01:00
5d560c1ece tests: let afl-fuzz run with -D, so more test cases are produced 2020-12-29 23:54:10 +01:00
d687fbdfb4 fix CodeQL warning on theoretically possible unsigned overflow 2020-12-29 19:53:56 +01:00
e9a306a50e fix localtime warnings from CodeQL 2020-12-29 10:25:48 +01:00
107c79b84b now fix afl-clang compiles on 32-Bit properly 2020-12-29 18:17:50 +01:00
80767480f0 Revert "fix afl-clang on 32-Bit systems"
This reverts commit 83c1378fc1.
2020-12-29 18:13:36 +01:00
83c1378fc1 fix afl-clang on 32-Bit systems 2020-12-29 14:19:35 +01:00
871d42e389 Merge pull request #665 from mboehme/patch-1
Handle disabled seeds properly in distribution-based schedule
2020-12-29 12:18:02 +01:00
0922763db1 Update afl-fuzz-queue.c 2020-12-29 14:57:05 +11:00
d103e39f58 fix instrumentation type display 2020-12-28 17:06:55 +01:00
3f871d1d8f allow tests when utils/aflpp_driver fails to build (platform support) 2020-12-28 16:29:30 +01:00
688f4ffb89 added corpus introspection 2020-12-28 14:01:48 +01:00
41dad9ab7d Merge pull request #664 from AFLplusplus/dev
fix CFLAGS for extra libs
2020-12-28 13:54:17 +01:00
108e28ff10 fix CFLAGS for extra libs 2020-12-28 13:53:11 +01:00
e22db8d609 Merge pull request #663 from AFLplusplus/dev
Fix Dockerfile
2020-12-28 13:32:51 +01:00
f1b4b38152 fix dockerfile for older CPUs 2020-12-28 13:31:20 +01:00
8e2b59ffca more flexible system support for afl-frida 2020-12-26 23:04:21 +01:00
7375d8fcb7 Merge pull request #661 from Manouchehri/dev
Fix missing Apple headers for afl_frida
2020-12-26 22:09:03 +01:00
2c4b51b437 utils/afl_frida is not 5% faster 2020-12-26 22:01:49 +01:00
fe0dca9d96 fixed a few forgotten old afl-llvm-rt references 2020-12-26 21:33:54 +01:00
159707f74c Include Apple headers. 2020-12-26 15:32:22 -05:00
4af0065f4a Fix missing include for macOS. (#660) 2020-12-26 20:23:59 +01:00
fa933036a7 Merge pull request #658 from AFLplusplus/dev
fix exec/s display
2020-12-26 13:29:07 +01:00
0b9ca807f2 fix exec/s display 2020-12-26 13:15:05 +01:00
450fd17451 Merge pull request #654 from AFLplusplus/dev
fix LTO
2020-12-25 12:25:05 +01:00
a4fd4ea0f4 fix LTO 2020-12-25 12:13:45 +01:00
949f075247 revert condition on llvm-config.h (it did not work) 2020-12-24 12:08:01 +01:00
895d0778b6 fix conditional include 2020-12-24 11:40:02 +01:00
dbdb95bc23 use positive logic to be future safe 2020-12-24 10:46:59 +01:00
92bf656cd3 better wording, typo 2020-12-24 09:57:33 +01:00
849b8cd084 typo 2020-12-23 18:38:12 +01:00
03849d147a warn on _AFL and __AFL env vars 2020-12-23 17:56:39 +01:00
1c79687dfe faster llvm compile, update README 2020-12-23 15:56:25 +01:00
1fe3af0418 update unicorn checkout 2020-12-23 15:55:02 +01:00
7dc433a0c0 Merge pull request #637 from AFLplusplus/dev
minor push to stable
2020-12-23 14:58:52 +01:00
8d10d12ab3 Merge pull request #629 from rchildre3/qemu-flags
Cleanup QEMU configuration options
2020-12-23 12:51:45 +01:00
ceed19f275 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-12-22 20:33:56 +01:00
9a5ea5b5c2 workaround for Solaris: NAME_MAX is not defined 2020-12-22 20:33:06 +01:00
e790667fd2 one more with nonstd array initializers 2020-12-22 20:29:22 +01:00
8241ded12e more portability non std array initializers 2020-12-22 20:19:43 +01:00
f18afa8ccd Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-12-22 19:42:00 +01:00
2a994e457a portability: avoid void * arithmetic (UB), avoid GNU extension for array initializations 2020-12-22 19:39:49 +01:00
9759320266 afl-clang-fast fix 2020-12-22 12:33:58 +01:00
27b9ba4502 better gcc and clang support for afl-cc 2020-12-22 10:51:40 +01:00
e8374e3deb temporary fix for unusual builds where CC is set 2020-12-21 17:04:58 +01:00
f37cc223d8 Merge branch 'stable' into dev 2020-12-21 14:25:50 +01:00
6f0f167b73 test: skip afl-fuzz test if too few locations were instrumented 2020-12-21 14:05:58 +01:00
a39228def6 make ubuntu 18.04 ci work 2020-12-21 13:36:09 +01:00
f7ceafab1c fix BSD 2020-12-21 13:21:40 +01:00
2a22dc433c ci fix 2020-12-21 13:01:56 +01:00
6e27c66058 ci fix 2020-12-21 12:48:02 +01:00
7172302be8 ci fix 2020-12-21 12:38:12 +01:00
b42f405e60 ci fix 2020-12-21 12:35:09 +01:00
816ba61080 fix ci 2020-12-21 12:27:06 +01:00
7e27448dac another 32 bit fix 2020-12-21 12:19:22 +01:00
2a0d066121 update ci 2020-12-21 12:14:08 +01:00
1078409875 Create ci.yml 2020-12-21 12:06:06 +01:00
45a68760ee fix 32 bit 2020-12-21 12:02:01 +01:00
ed85d5374b switch to github actions 2020-12-21 11:56:01 +01:00
47e04548d4 Merge pull request #649 from AFLplusplus/skim_romu
switch to romu and skim
2020-12-21 11:19:18 +01:00
6d1f17d78d Merge branch 'dev' into skim_romu 2020-12-21 11:02:09 +01:00
c28ecbbb2b update codeql yml 2020-12-21 10:59:29 +01:00
bf3ba489a0 Merge pull request #648 from AFLplusplus/add-codeql
Add codeql
2020-12-21 09:52:38 +01:00
f9d9ff2cd2 Create codeql-analysis.yml 2020-12-21 09:52:20 +01:00
0b4f6adfee Merge pull request #647 from rchildre3/binary-only-make
Remove binary-only target's depend on source tools
2020-12-21 01:57:59 +01:00
81e3e991a7 Test Python and Shared Memory in binary-only mode 2020-12-20 19:54:40 -05:00
eddabf6b05 Remove binary-only target's depend on source tools
The `binary-only` target currently depends on the `all` target which
always build the source tools, such as afl-cc and afl-as.  This is
unnecessary if the user specifically is asking for only binary fuzzing
tools.
2020-12-20 19:39:28 -05:00
2e3cf10070 document AFL_LLVM_INSTRUMENT option NATIVE 2020-12-20 22:53:41 +01:00
59c1c6a431 fix for non-default gcc installations 2020-12-20 14:42:45 +01:00
98ee17bc47 fix endless loop in afl-cc allow/blocklists starting a line with a comment 2020-12-20 14:30:06 +01:00
a6116ed533 Merge pull request #646 from pr0xy-t/dev
fixed typo in include/forkserver.h
2020-12-20 12:15:31 +01:00
bc9f956c84 update changelog 2020-12-20 11:30:11 +01:00
e1a7ed9d6e fixed typo in include/forkserver.h 2020-12-20 18:54:32 +09:00
7374503f14 add tinyinst to binary fuzzing tools 2020-12-19 09:55:51 +01:00
12ebb351dc apply nocolor changes 2020-12-18 21:10:39 +01:00
73dd6d86ab dont fail with ASAN_BUILD 2020-12-18 16:38:24 +01:00
2748d5c962 fix 2020-12-18 16:16:22 +01:00
ea9db86bb8 mem error fix 2020-12-18 10:20:43 +01:00
4ff9eb0e67 fix compile 2020-12-18 10:02:26 +01:00
f0b6576f97 fix 2020-12-18 09:55:47 +01:00
3ee12009c0 Merge pull request #641 from AFLplusplus/dev
Dev
2020-12-18 09:36:22 +01:00
0011f2047b merge romu and skim 2020-12-18 09:33:52 +01:00
79c98731c9 small improvements: dump output on error in test-llvm, fix compiler warnings 2020-12-18 09:22:58 +01:00
b6b907705e afl-cmin: skip instrumentation check if AFL_SKIP_BIN_CHECK is set 2020-12-18 00:18:30 +01:00
fd6bff727a fix crash for very fast targets 2020-12-17 22:57:28 +01:00
3282775a15 Cleanup QEMU configuration options
Take into account `STATIC`, `DEBUG`, and `PROFILING`

Turn off most options

Remove non-exsistant config options (e.g. bluez)
2020-12-17 14:23:16 -05:00
d07b0169cb skim import 2020-12-17 10:55:33 +01:00
14c67f15c9 small fixes 2020-12-16 14:22:09 +01:00
6e0aeb9833 allow instrumenting LLVMFuzzerTestOneInput 2020-12-15 18:17:55 +01:00
db76b06e01 add dummy Makefile to instrumentation/ 2020-12-15 18:07:01 +01:00
1fc0918ac0 v3.01a init 2020-12-15 09:55:33 +01:00
8e712d1a74 Merge pull request #628 from AFLplusplus/dev
Final push to stable
2020-12-15 09:39:10 +01:00
149ec41e90 v3.00c 2020-12-15 09:38:26 +01:00
e0ab846f7f v3.00c 2020-12-15 09:37:52 +01:00
df7c72fd66 code format 2020-12-13 11:24:49 +01:00
76117b0471 fix afl-clang tests 2020-12-13 11:23:56 +01:00
ce9e127529 remove debugging sh 2020-12-12 22:56:09 +01:00
c5c852dada add tests for the missing afl-compiler (afl-gcc or afl-clang) 2020-12-12 22:54:34 +01:00
7382cf5f00 afl-as.c, fix compiler warnings (overflowing is UB) 2020-12-12 19:30:56 +01:00
109560e73a tmpdir not needed with sharedmap fuzzing 2020-12-12 17:53:42 +01:00
befb1a2f39 remove stray debugging fprintf 2020-12-12 16:40:13 +01:00
fd30a4184a typo 2020-12-12 16:37:23 +01:00
e4a113b953 small fix in error handling 2020-12-12 13:26:25 +01:00
7f50aa26db let the check for afl-gcc not abort 'make tests' 2020-12-12 11:25:10 +01:00
54f59c7403 add an extra test for afl-gcc and check for -B support 2020-12-12 11:21:13 +01:00
dbbbeea36e typos 2020-12-11 18:24:14 +01:00
1825e5f313 typo 2020-12-11 17:01:46 +01:00
609f3d0265 fixed gcc analyzer warnings 2020-12-11 13:29:45 +01:00
12d62d5393 Merge pull request #617 from AFLplusplus/dev
push to stable
2020-12-11 11:38:22 +01:00
d5ded820e5 Merge branch 'stable' into dev 2020-12-11 11:36:35 +01:00
cc781e44f3 code format 2020-12-11 11:21:28 +01:00
2bf68a0bf4 fix MMAP 2020-12-11 11:19:26 +01:00
8a1acac559 schedule improvements, new default is FAST 2020-12-11 10:28:39 +01:00
1a3c9bc36d Merge pull request #627 from AFLplusplus/other_weight
Other weight
2020-12-11 10:23:42 +01:00
161c80014e change search order for afl-showmin in afl-cmin* 2020-12-10 17:25:22 +01:00
af403e5872 install more llvm 2020-12-10 15:58:00 +01:00
a686c1361c fix afl-cc library search 2020-12-10 15:31:26 +01:00
b8a590b84d grammar in error messages 2020-12-10 11:56:41 +01:00
2c24cdbfc3 fix qbdi path for code format 2020-12-09 22:25:37 +01:00
e5c50037d5 fix oversight for accessing nfuzz 2020-12-09 12:03:11 +01:00
a8e568f248 move libdislocator, libtokencap and qbdi_mode to utils/ 2020-12-09 11:30:04 +01:00
39a4fac941 better examples 2020-12-09 11:07:14 +01:00
3997d06cbd fix DUSEMMAP 2020-12-09 10:53:31 +01:00
2641082a76 Fix -DUSEMMAP 2020-12-09 10:51:20 +01:00
cebbedd238 fix cmin/tmin potential overflow on too large files 2020-12-09 08:58:07 +01:00
d1eb4eeb7f weighting for explore and exploit 2020-12-09 08:34:54 +01:00
a7125c68eb optimize a bit 2020-12-08 23:51:22 +01:00
1dbb1c7193 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-12-08 23:27:14 +01:00
9534bb87b1 fix some copmpiler warnings for USEMMAP 2020-12-08 23:26:28 +01:00
4e96447b43 fix showmap output 2020-12-08 23:26:08 +01:00
ad29eef271 Merge branch 'dev' of github.com:AFLplusplus/AFLplusplus into dev 2020-12-08 22:43:05 +01:00
c70b7ffd80 fix memory limit issue with cmplog without -m flag 2020-12-08 22:42:50 +01:00
6fb74342b8 add TEST_MMAP 2020-12-08 22:32:51 +01:00
2b543a64af small fixes 2020-12-08 22:12:05 +01:00
5bb51688e4 small fixes 2020-12-08 21:54:18 +01:00
6e61b2345c more reporting on errors 2020-12-08 20:33:41 +01:00
cf0c49dec5 typos/wording 2020-12-08 17:46:29 +01:00
064e63962f make unicornafl checkout version work again 2020-12-08 12:37:40 +01:00
6d2ac3e314 fix grammar download script 2020-12-08 12:36:19 +01:00
8999023432 fixes for grammar scripts 2020-12-08 12:29:47 +01:00
da6cddab90 fix asserts 2020-12-08 11:30:05 +01:00
46156957bd fix aflfast changes 2020-12-08 11:07:11 +01:00
2f4166d5d6 Merge pull request #624 from mboehme/dev
Sampling next seed by weight (hit_count, bitmap_size, exec_us)
2020-12-08 10:51:45 +01:00
e707a8d738 fix warning 2020-12-08 10:15:09 +01:00
eda068751e streamlined grammar mutator submodule 2020-12-08 10:09:35 +01:00
5d6b1129f0 Fix Grammar Mutator Submodule (#623)
Fixes: 651ad18e21 ("added the grammar mutator as a git submodule ...")

* Project pointer never pushed
* Reduces dirctory complexity
* Building and dependencies for the subproject should be isolated to the
  subproject's documentation
* Fix broken link to README
* Use `--init` for `git submodule`
2020-12-08 09:30:17 +01:00
06ec5ab3d7 Sampling next seed by weight (hit_count, bitmap_size, exec_us) 2020-12-07 21:32:25 +00:00
e6de85861c fixes and code format 2020-12-07 14:36:04 +01:00
4c2e375e22 little fixes 2020-12-07 14:29:59 +01:00
8f79116a15 fix find_object proc search (#elsif -> #elif), optimize static if away 2020-12-05 09:48:55 +01:00
f8c33f29e8 Typos 2020-12-05 09:19:14 +01:00
9e8e25729a Merge pull request #620 from ThomasTNO/add_missing_qemu_env_var
Add missing env var used in https://github.com/qemu/qemu/blob/bec7edf…
2020-12-04 18:08:58 +01:00
9a7d045897 build_unicorn_support no longer fetches qemuafl 2020-12-04 17:59:11 +01:00
d59d1fcd9f Add missing env var used in bec7edf41d/accel/tcg/cpu-exec.c (L389) and ./qemu_mode/README.persistent.md 2020-12-04 17:15:25 +01:00
1aebbd7490 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-12-04 15:41:24 +01:00
330f33a435 updated helper_scripts from battelle/afl-unicorn 2020-12-04 15:40:38 +01:00
3d233b34b8 Restore contribution list (#619) 2020-12-04 15:10:07 +01:00
eb85ded6ee Merge branch 'custom_describe' into dev 2020-12-04 14:52:11 +01:00
c18ca63519 unicorn updated 2020-12-04 14:51:31 +01:00
1dbefc14ea fixed bugs in custom_describe, reported by wizche 2020-12-04 14:26:48 +01:00
1f34b9f8e1 added python mutator, documentation 2020-12-04 14:26:48 +01:00
a19b3022d9 afl_custom_describe api added 2020-12-04 14:26:47 +01:00
aca5b55b6d test-pre.sh revert removal of afl-clang 2020-12-04 08:46:46 +01:00
e9a342f3d9 common.h change from user header include to system header include 2020-12-04 08:43:58 +01:00
b31d5a7cef afl-cmin usage fix 2020-12-04 07:32:56 +01:00
f0e81b2301 updated unicorn 2020-12-03 22:26:28 +01:00
295ddaf96b fix for afl-cc 2020-12-03 15:19:10 +01:00
a2e2fae840 AFL_CRASH_EXITCODE env var added, u8->bool 2020-12-03 14:43:06 +01:00
0f803c63df move debug print 2020-12-02 15:08:08 +01:00
1890d7b9cf very complete runtime lookup rewrite 2020-12-02 15:03:21 +01:00
16a6bbb3c9 typo 2020-12-02 13:26:38 +01:00
0942158ad1 remove docs/README symlink and update references 2020-12-01 23:17:20 +01:00
c05e4efbe9 renamed examples/ to utils/ 2020-12-01 14:40:30 +01:00
8584f9d2b5 added AFL_NO_AUTODICT 2020-12-01 13:13:11 +01:00
f7d8643dc4 update clang-format to 11 2020-11-30 22:08:26 +01:00
e769102491 more DEBUGF 2020-11-30 21:54:18 +01:00
1b75cc9f74 add DEBUGF 2020-11-30 21:38:15 +01:00
403b8a1086 update persistent doc 2020-11-30 21:13:16 +01:00
e865f274f1 fix wrong rename in test 2020-11-30 13:36:27 +01:00
856968c13b persistent_demo -> persistent_mode 2020-11-30 13:03:51 +01:00
63c317218b persistent_demo -> persistent_mode 2020-11-30 13:03:33 +01:00
aff4ccb0b2 more explanation 2020-11-30 12:56:47 +01:00
e83426a79b fix make DEBUG=1 2020-11-28 19:09:13 +01:00
fdac887660 no fancy special options for the fundamental test compile (no unnecessary dependencies) 2020-11-27 21:10:55 +01:00
b792c59080 remove wrong quoting 2020-11-27 21:02:27 +01:00
d1259d0914 add -lm, afl-fuzz-queue.c wants log2(), fix GNUmakefile syntax 2020-11-27 20:54:07 +01:00
4d9eb9bda1 Merge pull request #607 from AFLplusplus/dev
push to stable
2020-11-18 21:25:35 +01:00
cd0a25be5e Use buffer protocol to retrieve result from python post_process (#605)
Saves an extra copy, gives post processing functions more flexibility
2020-11-18 20:29:17 +01:00
b260204b72 Solaris/Illumos build fix. (#609) 2020-11-18 19:13:03 +01:00
211a6eb411 typos and wording 2020-11-18 08:40:12 +01:00
108a89b559 typo 2020-11-18 08:33:06 +01:00
68e18dbb7a more info about child_debug 2020-11-18 03:09:50 +01:00
631b6d0187 fixed simple yet stupid bug 2020-11-18 03:03:49 +01:00
f80f62f14b renamed env var to AFL_DEBUG_CHILD 2020-11-18 03:02:13 +01:00
57f8aec381 brought back missing env vars 2020-11-18 02:41:35 +01:00
23f37ff505 fixed alloc errors, code format 2020-11-18 02:33:47 +01:00
54fdec0e51 fix: avoid preprocessor logic in macro arguments (not portable) 2020-11-17 21:07:29 +01:00
add108ec23 fix two exotic mem leaks detected by cppcheck 2020-11-17 21:06:47 +01:00
d042a63ab4 micro optimization: allocate only when needed 2020-11-17 20:09:52 +01:00
c06b5a1564 fix sync issue 2020-11-17 17:02:33 +01:00
99c783821f Merge pull request #601 from Rumata888/fixing_symcc
Fixing symcc custom mutator
2020-11-17 10:13:57 +01:00
9d22c8a02c Fixed fd leak on early exit and closed pipes before early exits and PFATAL 2020-11-17 12:00:06 +03:00
1cc637a0a0 support AFL_LLVM_INSTRUMENT env for our own PCGUARD 2020-11-16 10:59:09 +01:00
7000f2a2cf Merge pull request #604 from virtuald/optional-py-fuzz
Actually make python 'fuzz' method optional
2020-11-15 12:37:47 +01:00
ea689076b3 Actually make python 'fuzz' method optional
At some point mutator->afl_custom_fuzz was allowed to be NULL, so do that instead of crashing
2020-11-14 19:58:32 -05:00
3ac953ec33 typo 2020-11-14 20:09:33 +01:00
76c5b8a3b4 fix error handling in fauxserver 2020-11-14 19:38:06 +01:00
40e10895a2 now really fix -n 2020-11-14 17:21:43 +01:00
e750a5c856 add sanity check for -M/-S arguments 2020-11-14 12:36:28 +01:00
30cd8a8397 fix non instrumented mode, fix check_binary 2020-11-14 12:28:51 +01:00
bd313d4039 no binary checking in noninstrumented mode 2020-11-14 11:31:18 +01:00
81493e4fe1 Merge pull request #603 from musicinmybrain/dev
Minor typo and phrasing fixes in README.md and CONTRIBUTING.md
2020-11-14 09:13:56 +01:00
389ee822e8 More idiomatic phrasing in CONTRIBUTING.md 2020-11-13 19:04:54 -05:00
fb38de8d73 In README.md, change “in the website” to “on the website,” which is more idiomatic. 2020-11-13 19:01:29 -05:00
155c2767a0 fix you/your typo in README.md 2020-11-13 18:58:50 -05:00
622f942555 Fixed memleaks, change exit to PFATAL 2020-11-13 14:54:36 +03:00
7db5d87a32 restore qemuafl submodule 2020-11-13 10:08:13 +01:00
79ed86da3f updated README to point out that if several laf-intel instances are used, -M main should be one of them to be able to share the intermediate results 2020-11-13 10:05:00 +01:00
119d7d0025 fix frida example debug output 2020-11-13 09:02:44 +01:00
54a312a5fe more small fixes 2020-11-13 00:44:08 +01:00
4a4c14c9a9 more fixes, leaks and compile errors 2020-11-12 23:47:49 +01:00
35fd6847fe another two mem leaks 2020-11-12 21:51:44 +01:00
ffe41e6fce fix two mem leaks detected by cppcheck 2020-11-12 20:26:53 +01:00
c05c5b787b Fixed name collision problem 2020-11-12 02:36:08 +03:00
bb218b330f Formatted changed/added files 2020-11-12 01:29:17 +03:00
20a8a93fd1 Fixed symcc custom mutator 2020-11-12 01:13:57 +03:00
14e76cf3c9 update qemuafl 2020-11-11 14:03:44 +01:00
5357ae5f91 remove duplicate include 2020-11-10 19:20:13 +01:00
a3928e5a62 small fix to actually document custom mutator introspection 2020-11-10 14:20:41 +01:00
1dfd7df7c0 small fix to actually document custom mutator introspection 2020-11-10 14:16:36 +01:00
8e1047f5ef support custom mutator introspection 2020-11-10 14:08:21 +01:00
1661303248 fix libfuzzer custom mutator and add introspection function 2020-11-10 13:43:48 +01:00
4c59c5234a Merge pull request #598 from AFLplusplus/dev
fix afl-cc bug for llvm 10.0.0
2020-11-08 17:11:57 +01:00
82d1c3e18d fix wrong llvm version comparison 2020-11-08 17:08:30 +01:00
585ba4c1dd fix for llvm 10.0.0 2020-11-08 16:33:25 +01:00
a728e8f9a5 better scriptable output from introspection 2020-11-06 16:42:02 +01:00
3b799c09cd Merge pull request #594 from AFLplusplus/dev
push to stable
2020-11-06 09:37:14 +01:00
50c98445fe do not try to compile pcguard if llvm is not current enough 2020-11-06 09:15:18 +01:00
665802673d typo fixed 2020-11-05 22:58:55 +01:00
f8bbbf31ec remove duplicate headers, make '#include VirtualFileSystems.h' version dependent 2020-11-05 22:45:07 +01:00
61fe059ba2 ignore build error (unsupported platform), so top level 'make tests' can be run 2020-11-05 21:11:31 +01:00
6abe4d124e require llvm 10.0.1+ for enhanced pcguard, correct 1MB checks 2020-11-05 08:53:16 +01:00
a8de605637 typo 2020-11-04 17:13:12 +01:00
c43a12919d add missing newline at the end 2020-11-04 16:23:18 +01:00
3cfc0174f7 fix -N for forkserver 2020-11-03 16:00:29 +01:00
7b4d1c4089 revert out_fd copy 2020-11-03 15:52:19 +01:00
245f511a1d fsrv copy: out_fd = 0 on stdin 2020-11-03 15:15:58 +01:00
8bccf56553 fsrv copy: out_fd = -1 2020-11-03 15:13:04 +01:00
7ed0bfb6f5 copy fsrv: copy out_file ptr 2020-11-03 15:09:57 +01:00
d795ec0451 added better error handling to forkserver fd 2020-11-03 13:41:06 +01:00
350c3b323a fix for #562 2020-11-02 21:17:37 +01:00
d026a9a9c5 typos 2020-11-02 20:06:55 +01:00
445d8f9917 more typos 2020-11-02 19:28:18 +01:00
eab60a084c do not fail for llvm < 10 2020-11-02 17:41:54 +01:00
050354a9de code-format 2020-11-02 17:34:58 +01:00
26d78ce2ec more llvm 10.0.0 fixes 2020-11-02 17:21:07 +01:00
80401940e3 more llvm 10.0.0 fixes 2020-11-02 17:08:05 +01:00
0863d940fe more llvm 10.0.0 fixes 2020-11-02 16:24:16 +01:00
7d944e9512 support llvm svn checkout 2020-11-02 16:17:16 +01:00
fd20432deb typos 2020-11-02 14:17:44 +01:00
a260d34b49 persistent hook example 2020-11-02 14:15:44 +01:00
54ed02ef47 Merge branch 'dev' of github.com:AFLplusplus/AFLplusplus into dev 2020-11-02 13:56:36 +01:00
fdc364046e doc for qemuafl 2020-11-02 13:56:24 +01:00
e24f8ba4b0 fix SancovPCGUARD for 10.0.0 2020-11-02 13:53:27 +01:00
52512aa0af specify testcache is enabled by default 2020-11-02 13:11:21 +01:00
cbfd1c6535 fix release version display 2020-11-02 13:08:50 +01:00
e0fe546459 disable indirect calls in pcguard 2020-11-02 11:55:14 +01:00
416e01d3c6 match mopt to havoc 2020-11-02 11:04:35 +01:00
0fd98ae8b0 added mutation introspection make target 2020-11-01 21:34:08 +01:00
a0c0cf9712 update todo 2020-11-01 10:02:21 +01:00
ded80870a9 reenable afl-clang(++) 2020-11-01 06:22:18 +01:00
5a84db7c67 Fix reference, add missing word 'directory' 2020-11-24 20:14:32 +01:00
27c3423fb6 test-pre.sh: remove old uses of afl-clang, afl-cc.c: add missing env.var. AFL_LLVM_LAF_ALL 2020-11-24 19:38:55 +01:00
ed2f82eaf4 fix compiler warning turned error on NetBSD 2020-11-24 16:13:58 +01:00
cf30f52f25 fix links 2020-11-23 10:07:15 +01:00
e32b7eeb83 fixed child not killed with -c 2020-11-19 16:14:19 +01:00
5ecc4ae0ab add helper script repo 2020-10-31 18:53:35 +01:00
f810639ab1 add our own inline trace-pc-guard 2020-10-31 14:18:58 +01:00
dfb847a51b review, mark env variables, linkify 2020-10-30 14:37:06 +01:00
efd27bd8ce recover heikos faq changes 2020-10-30 14:01:59 +01:00
e0bdfd87b6 fix ck_alloc call 2020-10-30 09:44:06 +01:00
b33306ca2c fix ck_alloc call 2020-10-30 09:43:03 +01:00
a2739ef5ff extras: afl_realloc -> ck_realloc 2020-10-30 09:40:51 +01:00
bdadba60f7 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-10-29 23:58:47 +01:00
158efe49ac typo 2020-10-29 23:57:51 +01:00
2decf1d088 typo 2020-10-29 23:55:00 +01:00
3e17a90faa typo 2020-10-29 23:45:22 +01:00
46a828212e typo 2020-10-29 23:43:58 +01:00
d4b04f0790 fix compile warning in FreeBSD 2020-10-29 20:06:55 +01:00
9e3b818c35 fix warning on Debian 32 bit 2020-10-29 18:47:00 +01:00
9347ad49b8 Don't crash for unset out_file (fixed #562) 2020-10-29 11:05:07 +01:00
abac876b3a better warn if skipping large dict 2020-10-29 10:45:32 +01:00
7c8b0af84a updated unicorn/next 2020-10-29 08:12:24 +01:00
b5686eb63e fixes two huge bugs 2020-10-29 00:05:28 +01:00
17c0d928e8 disable afl-dyninst libs until it's container is ready 2020-10-28 17:09:30 +01:00
1f46171b39 Merge pull request #592 from rhtenhove/dev
add gnuplot and afl-dyninst shared libs to Dockerfile
2020-10-28 16:19:30 +01:00
587f66f1b3 whoops.. 2020-10-28 15:42:07 +01:00
93c9093817 merge conflict 2020-10-28 14:36:49 +01:00
fe705bb956 expand havoc if not new findings in the last 5 seconds 2020-10-28 14:32:53 +01:00
0b9b4adbd3 show supplied -t option so we know it's used 2020-10-28 14:03:01 +01:00
a09a6459ed add name, forgot that last time 2020-10-28 11:36:06 +01:00
55dd04132f add afl-dyninst shared libraries 2020-10-28 11:30:21 +01:00
d4bf0c7db7 add suggestion for using a ramdisk in docker 2020-10-28 11:27:11 +01:00
90e04d4909 cache is already removed here 2020-10-28 11:02:44 +01:00
0f14057812 this package was getting uninstalled anyway 2020-10-28 11:00:50 +01:00
0d0e220b4b word-o 2020-10-28 10:39:58 +01:00
8cdf04ec90 quote the source lines 2020-10-28 10:39:45 +01:00
987ddb72b1 use fewer layers and remove apt cache
also use full-upgrade to ensure all conflicts are resolved
2020-10-28 10:38:43 +01:00
29a9d3aa49 add gnuplot for afl-plot 2020-10-28 10:36:34 +01:00
424438edfc stop using deprecated MAINTAINER instruction, use LABEL instead 2020-10-28 10:35:07 +01:00
868cb61ea6 hopeful the final testcache improvement ... 2020-10-26 15:24:33 +01:00
44c65fa0a0 add no splicing compile option and print used compile options in afl-fuzz help 2020-10-26 14:44:05 +01:00
029d44a6ec asan_build for tmin and analyze 2020-10-24 19:20:27 +02:00
ca938e7c4e asan_build for tmin and analyze 2020-10-24 19:11:41 +02:00
18ad8a097c travis test 2020-10-24 18:08:54 +02:00
aac0ab8c67 travis test 2020-10-24 17:57:05 +02:00
e5f30c6908 fix testcache bug 2020-10-24 16:28:46 +02:00
e5c2779d56 symbolize=1 for travis 2020-10-24 12:16:30 +02:00
eefc3608e7 added UBSAN, MSAN options 2020-10-24 03:31:41 +02:00
4e99e3b36c initializing testcase_buf 2020-10-24 03:16:22 +02:00
4a5df3dcfe symobile=1 for travis 2020-10-23 23:19:17 +02:00
2e8ec1e339 allow symbolize=1 for asan/debug 2020-10-23 22:49:20 +02:00
aa0d378520 better cache entry algo 2020-10-23 15:21:21 +02:00
0e748ccda7 set max testcache entries automated if not specified by the user 2020-10-23 14:05:34 +02:00
c866aef37f maybe enhancement to cache algo 2020-10-22 21:07:37 +02:00
8d75c08938 change queue cache algo 2020-10-22 15:48:09 +02:00
982260c134 fix timeout bug in read_s32_timed on non linux OSes 2020-10-20 20:48:33 +02:00
fa191017b5 Merge pull request #586 from b1gr3db/dev
qemu argv index was still wrong
2020-10-20 18:47:24 +02:00
73c0e1357f qemu argv index was still wrong 2020-10-20 05:16:34 -07:00
d0cdbc48ae always close file descriptor when opened, use standard types 2020-10-20 00:07:40 +02:00
ac1c3b8701 mini improvements 2020-10-19 11:34:57 +02:00
d8a058bf59 fix AFL_CMIN_CRASHES_ONLY=1 afl-showmap 2020-10-17 14:34:14 +02:00
fcea01a8ea add eviction stat 2020-10-17 11:38:55 +02:00
d5c3b4bafd directly add new queue to cache 2020-10-16 09:35:35 +02:00
b82e9ad3db next afl-showmap fix attempt 2020-10-16 09:16:35 +02:00
fffe53136c Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-10-15 23:30:55 +02:00
bded51e4ea fix issue #583: afl-cmin -C incompatibility 2020-10-15 23:30:36 +02:00
190a9cf1e4 Down with Markdown 2020-10-15 19:42:23 +02:00
1818d1c6a7 Added citation instruction 2020-10-15 19:41:27 +02:00
ee66cd7b27 testcache_size = 2 ok fix 2020-10-15 17:08:45 +02:00
f41aafa4f7 retake from mem if possible 2020-10-15 15:48:39 +02:00
354bda2846 fix reget of testcase after trim 2020-10-15 15:33:47 +02:00
0f8529a3db prepare halloween fuzzbench run 2020-10-15 15:22:40 +02:00
ea0851c654 fix previous commit 2020-10-15 12:54:18 +02:00
d1e18f9edf fix afl_swap_bufs usage? 2020-10-15 12:20:33 +02:00
0139b8cdcb add missing swap bufs 2020-10-15 10:28:11 +02:00
24e0c9cf65 add missing swap bufs 2020-10-15 10:22:40 +02:00
7ca5524e55 Merge pull request #584 from devnexen/dfbsd_build_fix
DragonFlyBSD build fix proposal.
2020-10-14 17:37:21 +02:00
638bf19b65 DragonFlyBSD build fix proposal. 2020-10-14 17:21:22 +01:00
735e8c3956 check for minimum cache size 2020-10-14 17:32:51 +02:00
23872d6f2c add documentation 2020-10-14 16:38:29 +02:00
56ac3fcdc5 configurable testcache with malloc (#581)
* cache item number to cache memory size

* reload testcase if trimming changed the size

* fix splicing selection

* slim splicing

* import sync fix

* write testcache stats to fuzzer_stats

* fix new seed selection algo

* malloc+read instead of mmap

* fix

* testcache is configurable now and no reference counts

* fixes compilation, test script

* fixes

* switch TEST_CC to afl-cc in makefile

* code format

* fix

* fix crash

* fix crash

* fix env help output

* remove unnecessary pointer resets

* fix endless loop bug

* actually use the cache if set

* one more fix

* increase default cache entries, add default cache size value to config.h

Co-authored-by: hexcoder- <heiko@hexco.de>
2020-10-14 15:30:30 +02:00
5ee63a6e62 fix link 2020-10-14 12:54:59 +02:00
c20ba2c2c5 fix custom mutator doc 2020-10-13 15:51:58 +02:00
d9b63766df fix new seed selection algo 2020-10-12 11:12:16 +02:00
5427f7ca98 fix tests for sync mode 2020-10-12 05:02:11 +02:00
15099f7f5a fix afl-cc.8 generation 2020-10-12 04:48:02 +02:00
aef0cd5877 fix sync mode 2020-10-12 04:41:04 +02:00
d6da5605c8 fix splicing selection 2020-10-12 04:03:42 +02:00
b7e0490bcd Revert "Merge branch 'memcache_marc' into dev"
This reverts commit c03fbcedaa, reversing
changes made to dab017ddda.
2020-10-12 03:44:34 +02:00
c03fbcedaa Merge branch 'memcache_marc' into dev 2020-10-12 03:18:54 +02:00
dab017ddda no -M/-S: auto-set -S default 2020-10-12 02:26:14 +02:00
55e1726b23 Merge pull request #579 from Edznux/add_statsd_docs
Add documentation for StatsD
2020-10-12 02:07:14 +02:00
59815cd447 Add documentation for StatsD 2020-10-11 23:06:37 +02:00
6a397d6111 add new seed selection algo and make it the default 2020-10-11 14:31:31 +02:00
01ec0cce47 fix for afl-analyze thanks to JJY-sec! 2020-10-10 15:44:47 +02:00
5540a055c5 afl-showmap: free malloced coverage map 2020-10-10 11:19:45 +02:00
445aba9221 determinstic fuzzing is now disabled by default 2020-10-10 10:55:56 +02:00
5dc3bc175b fix typo 2020-10-10 10:41:30 +02:00
c075003bd2 Merge pull request #571 from Edznux/statsd_implem
Statsd support implementation
2020-10-10 10:36:48 +02:00
1ab83d7d89 fix afl-cc build for no llvm present 2020-10-10 00:21:55 +02:00
cbf8212fe0 fix afl-cc build for no llvm present 2020-10-10 00:18:08 +02:00
e5de66e463 fix afl-cc build for no llvm present 2020-10-10 00:16:52 +02:00
125f8b6ba7 -m none is the default now 2020-10-09 23:23:44 +02:00
4cb4772e2a Remove ==1 in the condition 2020-10-09 18:58:27 +02:00
43d8296504 increase default cache size 2020-10-09 16:45:27 +02:00
0220a8ff66 Add env var toggle for StatsD 2020-10-08 20:48:46 +02:00
fd4a2dfec2 fix persistent_demo_new.c 2020-10-08 17:51:16 +02:00
deab5a1532 Add documentation/help for AFL_STATSD_TAGS_FLAVOR 2020-10-07 19:44:02 +02:00
c12b98e0a4 efficient queue jump 2020-10-07 17:45:54 +02:00
794e8d2d67 change HAVOC_MAX_MULT* to 64 2020-10-07 08:32:58 +02:00
1fd2ffaf14 Fix read on undefined char*. 2020-10-07 00:51:31 +02:00
3e16cf5fbf Remove statsd_socket_init, just let it init when doing the first iteration 2020-10-07 00:20:13 +02:00
17abe7d36e Fixed segfault because wrong order in args 2020-10-06 23:23:45 +02:00
3d7bdc9f0b [WIP: segfault on non dogstatsd] Adding MACROS for format 2020-10-06 23:00:11 +02:00
f519fff7bc fix compiler warning on 32-bit platforms 2020-10-06 21:56:17 +02:00
231420775f fix test-performance.sh 2020-10-06 19:49:48 +02:00
2d5fadc1e6 hunting ref underflow 2020-10-06 16:45:25 +02:00
4f207b4eba fixed ref check 2020-10-06 16:20:32 +02:00
693252c737 fixed missing quote warning 2020-10-06 16:17:53 +02:00
74dc227c44 code format 2020-10-06 15:38:36 +02:00
a4b60ca5b6 testcase cache added 2020-10-06 15:37:59 +02:00
fd4efd04a1 fixed gcc 10 warning 2020-10-05 23:07:22 +02:00
9ac9aa2511 Fix code format 2020-10-05 22:21:24 +02:00
916b6fd317 Refactor global var into afl_state_t struct 2020-10-05 22:21:01 +02:00
2bf3a70e2b Correctly handle env var. 2020-10-05 22:01:50 +02:00
9b112fde1a Add help for AFL_STATSD_HOST &
AFL_STATSD_PORT env var
2020-10-05 19:29:37 +02:00
bab60b68d9 changed the default schedule to coe 2020-10-04 20:45:59 +02:00
1a12db1b59 Code format 2020-10-04 16:11:05 +02:00
1e0bc2e5c3 Merge remote-tracking branch 'origin/dev' into statsd_implem 2020-10-04 16:03:15 +02:00
b0de6fed11 Mention tags format in macro's name 2020-10-04 14:29:50 +02:00
ca6106a1dc Refactor 2020-10-04 14:24:25 +02:00
6006cce0cf Define config, change parent func to show_stats 2020-10-04 03:24:09 +02:00
ff8c6d2415 Adds other metrics 2020-10-04 03:22:28 +02:00
26dcddab0c Add config ifdef 2020-10-03 23:56:55 +02:00
2239743361 Rewrote format metric to be simpler/more static 2020-10-01 00:11:01 +02:00
383cd487a2 small improvements to Marcel's patch, fix laf-intel + redqueen crashes 2020-09-29 15:02:57 +02:00
fe08482c1b Merge pull request #568 from mboehme/dev
Patching and improving AFLFast schedules.
2020-09-29 14:06:20 +02:00
e87eca7fe8 Patching and improving AFLFast schedules. 2020-09-29 11:53:27 +00:00
e69b25e34b increase havoc_stack_pow2 on no finds 2020-09-28 10:13:00 +02:00
e85fde201e OpenBSD build fix (#566)
* OpenBSD build fix proposal.
Mainly the gcc plugin, using one of the egcc/eg++ version available.
Needs pthread flag to r/w lock api.

* README update
2020-09-26 19:02:19 +02:00
e301822c68 readme 2020-09-26 12:41:13 +02:00
a55e0d1189 WIP envs 2020-09-25 23:28:15 +02:00
fc75d2b181 remove warnings 2020-09-25 13:14:54 +02:00
6b3b1775b6 improving on splice candidate check patch 2020-09-25 12:03:24 +02:00
3334eeb4eb Merge pull request #564 from wakolzin/dev
Fix potential endless loop in custom_mutator_stage
2020-09-25 11:39:25 +02:00
e38ca0e750 setting HAVOC_STACK_POW2 to 4, as fuzzbench shows that too mach mutation is less effective 2020-09-25 10:48:08 +02:00
a75e7594f7 Add comments
Co-authored-by: Ivan Gulakov <gulakov@ispras.ru>
2020-09-24 18:50:59 +03:00
888d63748a Fix potential endless loop in custom_mutator_stage
Co-authored-by: Ivan Gulakov <gulakov@ispras.ru>
2020-09-24 18:25:32 +03:00
818c05cf29 qemuafl 2020-09-23 19:53:37 +02:00
60ef1f7305 Update Changelog.md 2020-09-23 02:28:19 +02:00
b3b5e25091 examples: fixed path for docs (#563) 2020-09-23 01:58:11 +02:00
f4a0407270 add comment for future 2020-09-22 20:06:39 +02:00
daa2285083 fix LTO autodictionary for ints > 64 bits 2020-09-22 09:32:16 +02:00
639372b644 code-format, and no code-format for custom mutators 2020-09-22 02:11:10 +02:00
52c135e1a2 fix warning 2020-09-22 02:05:31 +02:00
093754f6bf dict2file fix for integers > 64 bit 2020-09-22 02:04:23 +02:00
207cbd5cf7 fix and update libfuzzer custom mutator 2020-09-21 15:47:10 +02:00
f34fe1f81e updated unicornafl 2020-09-21 13:13:03 +02:00
5f52f72761 set explore as default, fix schedule display 2020-09-20 14:58:08 +02:00
6d99695108 fix travis 2020-09-19 17:25:39 +02:00
a18523f018 fix exploit, mmopt and rare schedule 2020-09-19 15:13:58 +02:00
7ff9800804 fix exploit, mmopt and rare schedule 2020-09-19 15:13:15 +02:00
44c0dc6d96 fix expand havoc 2020-09-18 12:19:27 +02:00
1225f3aa70 improved defaults from fuzzbench results 2020-09-18 10:29:49 +02:00
9eed8fe588 portability: type -> command -v, compiler warnings 2020-09-18 09:02:43 +02:00
4561a9590f WIP. basic state working: submitting statsd metrics (path, crashes, hangs) 2020-09-17 01:29:09 +02:00
5241d1221b fix if no clang is present 2020-09-14 15:46:36 +02:00
a95427a873 fix if no clang is present 2020-09-14 15:15:53 +02:00
c5c5570d97 fix if no clang is present 2020-09-14 15:08:07 +02:00
3abace4f54 Haiku build fix. (#556) 2020-09-13 16:58:06 +02:00
7cdbe3173e fixed ngram size unset 2020-09-13 15:00:10 +02:00
7f94fe3587 code format 2020-09-13 14:26:57 +02:00
060dbe1239 wine argv fix 2020-09-13 14:26:24 +02:00
a9ba907676 Fix qemu argv construction (#555) 2020-09-13 14:25:02 +02:00
fe39e0184f gcc_plugin switch CC to gcc when cc is something else 2020-09-13 00:02:42 +02:00
688e2c87df portability: make llvm-dict2file compilable under Ubuntu xenial (llvm 3.8.0) 2020-09-11 22:13:42 +02:00
38e6de1eff portability: make new gcc-plugin compilable under Ubuntu 16.04 (gcc 5.4.0) 2020-09-11 21:46:20 +02:00
862b6d0382 fix for afl-compiler-rt to only send dictionary data if there is some 2020-09-11 08:56:28 +02:00
543765bc0d fix unittests 2020-09-10 16:41:40 +02:00
380051868a add libfuzzer custom mutator, minor enhancements and fixes 2020-09-10 15:26:46 +02:00
fdb0452245 update documentation 2020-09-10 08:54:57 +02:00
454a860020 update gcc readme 2020-09-09 23:25:01 +02:00
a4cac3fce5 new custom mutator: symcc 2020-09-09 17:49:43 +02:00
f8c0182e16 fix travis 2020-09-09 12:49:49 +02:00
d3282ef1fe fix makefile 2020-09-09 10:37:04 +02:00
9b6564f0a3 fix for gcc_plugin 2020-09-09 09:36:27 +02:00
eb9f323d7c Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-09-08 20:58:44 +02:00
fe98e2d760 update qemuafl 2020-09-08 20:58:35 +02:00
ab744abc4b code-format 2020-09-08 17:54:01 +02:00
2802245da7 update instrumenation/README.instrument_file.md for gcc_plugin 2020-09-08 17:15:32 +02:00
c091340a85 new gcc_plugin integration 2020-09-08 16:15:31 +02:00
3890225c35 Merge pull request #551 from AdaCore/topic/plugin
rewrite gcc plugin
2020-09-08 15:21:55 +02:00
9544b3dbf2 rewrite gcc plugin
When we started using AFL, it did not have an integrated GCC plugin.
There was one proposed by Austin Seipp, but for various reasons we
ended up using some of its infrastructure (runtime and wrapper), but
writing the GCC plugin proper from scratch.

With AFL++'s renewed interest in a GCC plugin, we rebased ours, with
some features that are or were missing in the one that was integrated:

* efficient, fully-functional inline and out-of-line instrumentation

Inline instrumentation was work in progress in the original plugin.
Controlled by AFL_GCC_OUT_OF_LINE.

* reproducible instrumentation

Obey -frandom-seed for pseudorandom number generation.

* licensing clarity and strict compliance

GPLv3+ for the plugin, that uses GCC internals; add a copy of the
license, as required.

* allow/deny list support

Copied and adjusted from the LLVM plugin implementation.

* neverZero support

Not as compact as the asm-wrapper version, but likely more efficient.
Both are quite thread-unsafe, with different caveats.
Controlled with AFL_GCC_SKIP_NEVERZERO.
2020-09-08 14:55:19 +02:00
43cb626ad3 revert for unicorn_mode 2020-09-08 14:03:53 +02:00
13f2ac83a9 fix GNUmakefile for new qemuafl 2020-09-08 11:48:31 +02:00
374e068f97 set correct error code when -V 2020-09-08 11:37:09 +02:00
10f775be07 conflicts 2020-09-08 11:19:17 +02:00
3565641c41 arm64 travis 2020-09-08 11:13:16 +02:00
679b2d63a8 qemuafl + arm 2020-09-08 10:56:37 +02:00
6404abd7d6 bugfix for fixed seeds 2020-09-07 17:30:28 +02:00
7bcbfd48e5 update ideas 2020-09-06 15:12:23 +02:00
06ac2850c5 bcmp for compare-transform-pass 2020-09-06 13:53:40 +02:00
6114a48b89 add std::string and bcmp to dictionary functions 2020-09-06 13:29:32 +02:00
e065ba9497 update gitignore 2020-09-06 12:47:14 +02:00
8ec41b2585 fix various warnings 2020-09-06 11:40:41 +02:00
bd007c151d fix unicorn clean 2020-09-06 11:23:59 +02:00
163e5ffd10 -p seek is now the default 2020-09-05 17:40:39 +02:00
ded4d093ff skip crashes but keep for splices 2020-09-05 16:16:56 +02:00
2508922288 cmp dict for LTO 2020-09-05 15:49:10 +02:00
39c020ec74 Merge pull request #549 from AFLplusplus/ignore_unstable_edges
ignore unstable edges
2020-09-05 13:26:46 +02:00
81b1d85f61 Merge pull request #548 from AFLplusplus/pre-3
Pre 3.0 changes
2020-09-05 13:26:08 +02:00
2f90f2faba code-format 2020-09-05 13:19:19 +02:00
e30b2c6af6 final changes for pre-3.0 2020-09-05 13:18:28 +02:00
4b3ad5f037 add cull queue, -i subdir traversal 2020-09-05 12:32:10 +02:00
996986bed5 first batch of changes 2020-09-05 12:11:48 +02:00
ee206da389 Merge pull request #545 from AFLplusplus/dev
v2.68c
2020-09-04 22:51:43 +02:00
fac108476c v2.68c 2020-09-04 22:50:45 +02:00
4f7a8a4c70 Merge pull request #542 from AFLplusplus/dev
push to stable
2020-09-04 22:48:46 +02:00
976ee9022c fix assignment 2020-09-04 22:47:37 +02:00
0625eb0a05 avoid signed ints for amounts (which are positive) 2020-09-04 22:26:39 +02:00
77b824d101 compile fix 2020-09-04 17:56:17 +02:00
b7b38205d8 fix travis 2020-09-04 17:37:11 +02:00
6c715f1a69 more changes to fuzzer_setup 2020-09-04 17:04:42 +02:00
fc19aa96f7 Merge pull request #544 from ThomasTNO/export_env_vars
Export set afl_environment_variables to stats
2020-09-04 16:30:15 +02:00
50f61b64b1 Make open_file() inline 2020-09-04 16:22:22 +02:00
809a7cffe2 Write set environment variables in an env file style. 2020-09-04 16:02:09 +02:00
6399f84ba2 fix example 2020-09-04 16:02:02 +02:00
8459bcdf85 fix example 2020-09-04 16:01:08 +02:00
6adaacbb3a Seperate fuzzer_setup from fuzzer_stats, only write fuzzer_setup at the start 2020-09-04 15:54:57 +02:00
6c846bcf2c fix driver test 2020-09-04 15:27:02 +02:00
e45ae8e5da Export set afl_environment_variables to stats 2020-09-04 13:48:43 +02:00
cea2fadbf4 fix afl-whatsup time 2020-09-03 10:27:32 +02:00
4c48d3a3ad update xxh3 to 0.8.0, fix is_ascii 2020-09-03 09:59:23 +02:00
c39a552cc0 ignore unstable 2020-09-02 20:30:26 +02:00
020b8a4964 minor FAQ fixes 2020-09-02 20:19:49 +02:00
08f6e1d66a children terminate on sigpipe 2020-09-02 17:54:54 +02:00
28e457e8d8 add temporary travis target 2020-09-02 10:18:10 +02:00
c7255f2e26 bugfix for Ubuntu trusty: avoid unknown compiler option 2020-09-01 18:55:37 +00:00
6340674a23 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-09-01 19:54:18 +02:00
4538f689ed split-compares-pass: bugfix add missing instrument_file filtering in some places 2020-09-01 19:51:53 +02:00
415b759ed1 update qemuafl 2020-09-01 16:20:14 +02:00
e4a86b40a5 child cleanup 2020-09-01 13:42:33 +02:00
b8d3a97a4f build with qemuafl 2020-09-01 13:08:32 +02:00
75c38d6243 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-09-01 12:36:13 +02:00
6f75100602 qemuafl envs 2020-09-01 12:36:04 +02:00
07cee6b750 fix unicorn clean 2020-09-01 11:13:26 +02:00
651ad18e21 added the grammar mutator as a git submodule + documentation 2020-09-01 10:52:39 +02:00
664daa2f3c add qemu driver env var 2020-09-01 01:12:40 +02:00
ed6243df5a Review FAQ.md 2020-09-01 00:49:26 +02:00
bd57784664 code format 2020-08-31 23:59:10 +02:00
7f621509ee Merge pull request #540 from AFLplusplus/dev
Dev
2020-08-31 23:04:09 +02:00
4261e17b3e replace non portable echo -n with printf 2020-08-31 22:08:54 +02:00
8ca4414d70 merge conflicts 2020-08-31 20:34:28 +02:00
6090bb1bca better fix for #539 2020-08-31 20:33:56 +02:00
a552631d3b update changelog 2020-08-31 20:22:20 +02:00
c552229c4d Merge pull request #539 from hazimeh/dev
Fixed stack use-after-return bug in strntoll
2020-08-31 20:20:36 +02:00
2dffed1cff Merge pull request #534 from AFLplusplus/dev
push to stable for GSOC
2020-08-31 19:04:37 +02:00
e93f78eca5 Merge pull request #538 from ploppelop/patch-1
Update parallel_fuzzing.md
2020-08-31 18:44:28 +02:00
9bbbec3fa8 Fixed stack use-after-return bug in strntoll 2020-08-31 18:39:50 +02:00
338638b124 Update parallel_fuzzing.md
fix multisystem example
2020-08-31 18:34:27 +02:00
17e1a72b3b Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-08-31 18:32:33 +02:00
3e6471b949 added files to gitignore 2020-08-31 18:32:28 +02:00
e4de4e3500 update gitignore 2020-08-31 18:32:01 +02:00
bea76b346c fixed build error 2020-08-31 18:29:45 +02:00
53e63e9ded added forkserver init timeout 2020-08-31 18:28:36 +02:00
b1b5e21600 removed dummy 2020-08-31 18:20:39 +02:00
d765740707 hopefully finally fix ancient apple gmake 2020-08-31 18:18:40 +02:00
192cadee34 fix docs 2020-08-31 18:10:18 +02:00
d7d8afa512 fix afl-gcc help output 2020-08-31 17:54:21 +02:00
01fcee1190 fixed make install on mac os 2020-08-31 17:36:16 +02:00
0805437222 fix make man 2020-08-31 17:10:13 +02:00
4398b9b517 fix network server 2020-08-31 16:50:26 +02:00
909262f6c5 fix non portable option -T for 'install' 2020-08-31 16:44:18 +02:00
155ef8875a Fix few warnings for FreeBSD case. (#536) 2020-08-31 16:37:46 +02:00
58cf030546 fix for MacOS sudo 2020-08-31 16:34:57 +02:00
18ea9a8447 omit linker option '--dynamic-list' for MacOS 2020-08-31 16:19:09 +02:00
ebd1e6bc4b Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-08-31 15:40:47 +02:00
45d866d548 typo 2020-08-31 15:40:20 +02:00
8087cf7988 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-08-31 15:17:51 +02:00
9e8b3f13e1 fixed warning on mac 2020-08-31 15:17:37 +02:00
ce4700ca6e Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-08-31 15:17:24 +02:00
8253f90134 typos/wording 2020-08-31 15:16:55 +02:00
86421f3469 Merge pull request #535 from rhertzog/manpages
Fix manpages generated by llvm_mode/GNUMakefile
2020-08-31 15:05:54 +02:00
811ef13b20 Fix manpages generated by llvm_mode/GNUMakefile
* Use a build date derived from SOURCE_DATE_EPOCH like in the main
  Makefile
* Fix the path to the binary
2020-08-31 14:56:02 +02:00
7fb72f1038 typos 2020-08-31 14:47:22 +02:00
d2c9e4baa7 fix warnings and weird code insert 2020-08-31 13:12:59 +02:00
81767287c3 improve documentation 2020-08-31 13:02:40 +02:00
6c980e2a02 rewrite documentation 2020-08-31 12:56:14 +02:00
e7db4d4fe0 fix sync script, update remote sync documentation 2020-08-31 12:36:30 +02:00
567042d146 typos fixed. 2020-08-31 12:32:31 +02:00
4697e4a5a5 description for AFL_MAX_DET_EXTRAS added 2020-08-31 12:26:41 +02:00
92b1f9cf36 added SO link about rand for clarification 2020-08-31 12:11:38 +02:00
bbf00204ea Merge pull request #531 from rhertzog/extend-cflags-safe
Add -fdebug-prefix-map to CFLAGS_SAFE
2020-08-31 11:38:09 +02:00
a42b74b624 Merge pull request #530 from rhertzog/add-cppflags
Pass CPPFLAGS to all calls of the C compiler
2020-08-31 11:33:34 +02:00
7ee255cbcf Merge pull request #529 from rhertzog/manpages
Manual pages related changes
2020-08-31 11:21:52 +02:00
961ddfd7f8 Merge pull request #528 from rhertzog/fix-symlinks
Fix the /usr/bin/afl-clang and afl-clang++ symlinks
2020-08-31 11:19:16 +02:00
4566bcf122 code-format 2020-08-31 10:57:01 +02:00
ca0105ddf6 fix make DEBUG=1 (error seen with gcc 10.2.0) 2020-08-29 21:45:23 +02:00
41bb359428 Fix various spelling errors (#532)
All those spelling errors have been caught by lintian's built-in
spellchecker:
https://lintian.debian.org/tags/spelling-error-in-binary.html
2020-08-28 23:04:25 +02:00
146ede0f29 Add -fdebug-prefix-map to CFLAGS_SAFE
In Debian, we override CFLAGS to include -fdebug-prefix-map to avoid
hardcoding the build path in any generated debug information. This is
to help with getting the package to build reproducibly.

However you seem to voluntarily not honor CFLAGS but only CFLAGS_SAFE
for a limited number of source files. This resulted in a lintian warning
on Debian's side (https://lintian.debian.org/tags/file-references-package-build-path.html)
pointing to /usr/lib/afl/afl-llvm-rt-64.o and /usr/lib/afl/afl-llvm-rt.o.

With this commit, I'm manually adding -fdebug-prefix-map as a safe
build flag to CFLAGS_SAFE.
2020-08-28 22:16:08 +02:00
c0fd7ba6d1 Pass CPPFLAGS to all calls of the C compiler
This variable is a standard way to inject options for the C
preprocessor. It's respected by the implicit rules of make
and autoconf/automake.

Debian sets this variable during package build to inject
`-D_FORTIFY_SOURCE=2` and we would like afl++ to respect it.

Note that this commit also adds $(CFLAGS) in the build of
afl-performance.o where it was missing. It might have been
on purpose but we want to keep CFLAGS everywhere as well
since Debian injects various options through that variable
(for hardening and reproducibility).
2020-08-28 21:55:52 +02:00
b0b2a15891 Improve the generated manual page to be compatible with whatis
And generate the manual page for afl-g++ too.
2020-08-28 21:34:36 +02:00
ff3c9cbd73 Fix installation path of manual pages
Manual pages are stored in /usr/share/man/.
2020-08-28 21:34:08 +02:00
6e839f0f6a Fix the /usr/bin/afl-clang and afl-clang++ symlinks
Right now they are created pointing to '../afl-clang-fast' instead
of 'afl-clang-fast. Given that all the binaries are in the same directory,
the symlinks are effectively broken.
2020-08-28 21:26:32 +02:00
a3cd523250 todo update 2020-08-27 15:24:38 +02:00
b44620f0b0 Merge pull request #526 from h1994st/dev
Prevent afl-fuzz from modifying stage_max during fuzzing
2020-08-27 08:56:08 +02:00
9a6a32775f Prevent afl-fuzz from modifying stage_max during fuzzing 2020-08-27 00:32:53 -04:00
3e8beaafc8 fixing wrong fatal ... 2020-08-26 21:22:24 +02:00
33e58c1d4e some warnings fixes 2020-08-26 14:45:59 +02:00
4be0ea596b rand unlikely added 2020-08-26 13:04:03 +02:00
96ef7083c8 using unbiased rand_below 2020-08-26 05:28:33 +02:00
78eaa6b203 lintokencap: fix compiler complains on Solaris 11. (#525) 2020-08-25 17:11:15 +02:00
1efc6e59b7 Added out_file value when using stdio (#524) 2020-08-24 21:18:51 +02:00
19eddbb0c7 make py functions as optional as they are in the doc 2020-08-24 18:12:08 +02:00
6a34c5aa3e fix python implementation for new function 2020-08-24 18:06:07 +02:00
c7f0d30668 added afl_custom_fuzz_count 2020-08-24 17:32:41 +02:00
a7c3f252d5 unicorn build warning for MUSL based linux distros. (#510) 2020-08-24 12:06:04 +02:00
b9b6f06429 Allow Large Extras (#523)
* allow large extras

* skipping large testcases again
2020-08-24 12:04:29 +02:00
a1442bd1ac no longer warns for prob. extras 2020-08-23 11:21:49 +02:00
4d9d52e3d9 code format 2020-08-23 11:00:46 +02:00
6184832ea9 added more env var docs, fsrv fixes for cmin, tmin 2020-08-23 10:59:56 +02:00
e2b54bfa05 code format 2020-08-23 10:40:46 +02:00
425908a00c Option for specifying forkserver initialization timeout via environment variable (#522)
* Addition of AFL_FORKSRV_INIT_TMOUT env var

This commit introduces a new environment variable which allows to
specify the timespan AFL should wait for initial contact with the
forkserver.

This is useful for fuzz-targets requiring a rather long setup time
before the actual fuzzing can be started (e.g., unicorn).

* add .swp files to .gitignore

* Inherit init_tmout in afl_fsrv_init_dup

Without this patch, the forkserver would spawn with a timeout of 0 in
cmplog mode, leading to an immediate crash.

Additionally, this commit removes a spurious whitespace.

* Initialize afl->fsrv.init_tmout in afl_fsrv_init

Not all afl-components will need the new AFL_FORKSRV_INIT_TMOUT
environment variable. Hence, it's initialized to the safe "default"
value from before in afl_fsrv_init now.
2020-08-23 10:39:34 +02:00
1301552101 added AFL_MAX_DET_EXTRAS env var 2020-08-23 01:48:36 +02:00
c4f71ab201 enable autodict for cmplog compile, it is ensure not be used in the forkserver 2020-08-22 10:01:45 +02:00
42ef1968a5 Merge pull request #521 from AFLplusplus/dev
Push to stable to fix wrong free on exit
2020-08-22 01:30:21 +02:00
5ec91fce23 fix for bad free (#520) 2020-08-21 23:03:08 +02:00
47878f6974 add execs_done to plot file 2020-08-21 23:33:35 +02:00
d5c77a9e96 update todo 2020-08-21 15:45:15 +02:00
4d2694c114 fix semicolon 2020-08-21 15:26:43 +02:00
017c8a6940 fix global id documentation for LTO pcguard 2020-08-21 14:39:47 +02:00
b0a783e86f code format 2020-08-21 11:18:18 +02:00
714e4d2b46 fixed for LTO llvm 11 2020-08-21 11:17:03 +02:00
85a4c5e724 only compile SanitizerCoverage for LTO 2020-08-21 10:50:06 +02:00
182b8b3e14 remove doc reference for SKIPSINGLEBLOCK 2020-08-20 19:00:15 +02:00
4ce5ed370a LTO: sancov made default, deprecated SKIPSINGLEBLOCK, deactivate LTO autodict for cmplog binaries 2020-08-20 18:57:05 +02:00
f7bac482e9 Merge pull request #518 from AFLplusplus/ltopcguard
sancov ported to LTO
2020-08-20 18:33:53 +02:00
bd074e9150 add missing features for sancov lto 2020-08-20 18:32:22 +02:00
d52ea44c27 fix wrong var 2020-08-20 18:27:22 +02:00
9c1b6cfb99 Merge pull request #517 from AFLplusplus/custommut-readme
Custom Mutator readme
2020-08-20 14:21:42 +02:00
631d3f274a move afl_loop check 2020-08-20 13:49:11 +02:00
3cdaf4dcf2 sancov enhancement 2020-08-20 13:37:34 +02:00
572944d726 Merge pull request #514 from AFLplusplus/dev
push to stable
2020-08-20 11:00:07 +02:00
779d8f6b7e support current llvm12 changes 2020-08-20 10:56:51 +02:00
322847755a Merge pull request #513 from fouzhe/patch-1
fix typo
2020-08-19 17:58:35 +02:00
f9f28b9c7c fix typo 2020-08-19 23:54:45 +08:00
c3bc0145e7 Merge pull request #512 from AFLplusplus/stable
activate travis for stable
2020-08-19 16:21:03 +02:00
17d403b8f8 activate travis for stable 2020-08-19 16:19:31 +02:00
9faf7b6fc8 v2.67d 2020-08-18 20:08:29 +02:00
5c759953f4 Merge pull request #511 from AFLplusplus/stable
push to dev
2020-08-18 20:05:56 +02:00
1c64048d0f 2.67c 2020-08-18 19:56:47 +02:00
b504b9313a code-format, changelog 2020-08-18 01:36:49 +02:00
1a94cfe2af moved autodict extras away from extras_a 2020-08-18 01:31:40 +02:00
7470b475a9 Reworked maybe_grow to take a single ptr, renamed to afl_realloc (#505)
* maybe_grow takes a single ptr

* fixed use_deflate

* reworked maybe_grow_bufsize

* helper to access underlying buf

* remove redundant realloc_block

* code format

* fixes

* added unit tests

* renamed maybe_grow to afl_realloc

* BUF_PARAMS -> AFL_BUF_PARAM
2020-08-18 00:50:52 +02:00
0a6084f361 Merge pull request #499 from AFLplusplus/dev
important push to stable
2020-08-17 23:42:45 +02:00
f92607cff1 pcguard for lto 2020-08-17 22:56:48 +02:00
9532499ef5 install libafldrivers 2020-08-16 14:14:24 +02:00
1d56de6c1d fix lto autodict for long strings 2020-08-16 13:29:24 +02:00
266b51a842 final afl-llvm-rt.o.c that takes care of all eventualities 2020-08-16 10:53:38 +02:00
cc1fe2f2d2 skip instrumenting blocks following __afl_loop to improve stability in LTO. not in afl-llvm-pass and instrim because they are outdated, sancov cant be fixed 2020-08-15 22:59:49 +02:00
43214d6b46 more likely 2020-08-15 22:10:28 +02:00
2f28ecd3a5 more unlikely 2020-08-15 20:51:57 +02:00
73a629d6f2 important bugfix for large covmaps 2020-08-15 18:14:44 +02:00
0a251f93e0 increase initial memory sized 2020-08-15 13:34:51 +02:00
1cf4738487 more FAQ 2020-08-15 10:27:40 +02:00
af14acf2c1 Revert "Merge branch 'debug' into dev"
This reverts commit a7537b5511, reversing
changes made to 15e799f7ae.
2020-08-14 14:35:05 +02:00
a7537b5511 Merge branch 'debug' into dev 2020-08-14 13:23:14 +02:00
15e799f7ae fix for llvm 11 2020-08-14 12:42:45 +02:00
5f0a9c90c8 fixes lots of llvm warnings 2020-08-14 12:06:00 +02:00
9ff9ff2ad2 more secure way to work with a dynamic map 2020-08-14 11:40:26 +02:00
d86b13384f remove unnecessary code, increase init map size 2020-08-14 11:25:13 +02:00
17a4e9fadf remove debug 2020-08-14 10:11:04 +02:00
ce513c4f3e fix llvm12 -fuseld warning 2020-08-14 10:10:23 +02:00
ce92adcb9b formatting 2020-08-14 08:33:36 +02:00
e94cc1fae0 new faq entries 2020-08-14 07:09:01 +02:00
32fe047894 fix AFL_LLVM_MAP_DYNAMIC 2020-08-14 06:46:22 +02:00
d1bc0207cc no longer using alloc for autodict 2020-08-14 01:33:03 +02:00
69f8c62955 code-format 2020-08-14 00:46:48 +02:00
83df65a66b cleaned up maybe_add_auto calls 2020-08-14 00:46:15 +02:00
c3a6e7e870 testcases indicate count 2020-08-14 00:20:04 +02:00
d0ab83a202 Changelog wording/whitespace 2020-08-13 23:19:05 +02:00
b5d1a021ef fix llvm and afl-showmap 2020-08-13 22:34:11 +02:00
e9fb5f4cbc fix for llvm < 11 2020-08-13 21:46:27 +02:00
212bb990b7 LTO: apply laf-intel+redqueen/cmplog at link time 2020-08-13 21:27:11 +02:00
8e984c2aa0 fix for sancov 2020-08-13 18:24:36 +02:00
7f435ec5f1 refactor get filename 2020-08-13 16:29:00 +02:00
47faf3dd33 code review: fixed some typos 2020-08-13 15:44:03 +02:00
c4e52e20c9 fix warning 2020-08-13 12:58:10 +02:00
2c5e103278 make cmplog deterministic 2020-08-13 12:39:18 +02:00
7a6867e2f8 split up __afl_manual_init, added internal AFL_DISABLE_LLVM_INSTRUMENTATION, skipping ctor+ifunc functions for all llvm, code-format 2020-08-12 16:06:30 +02:00
8044ae28be Merge pull request #496 from AFLplusplus/dev
push to stable
2020-08-12 14:29:34 +02:00
b38837f4ff setting attribute hot intelligently gives 0.5% speed 2020-08-12 14:14:44 +02:00
c25479264d fix LLVM version check 2020-08-12 13:28:31 +02:00
e9b3da5d96 llvm 9 workaround 2020-08-12 11:03:33 +02:00
132b57cf03 nozero for llvm pcguard 2020-08-12 10:41:09 +02:00
ee548df05f improve readme 2020-08-11 22:58:57 +02:00
052d74b16c added new githubsecurity blog entry 2020-08-11 18:44:57 +02:00
83281503b3 Merge pull request #498 from AFLplusplus/taint
dont merge
2020-08-11 18:26:30 +02:00
b604f5eafc finalize first beta! yay! 2020-08-11 18:06:18 +02:00
220dc4a43d review done, pray 2020-08-11 16:25:35 +02:00
457f627101 move taint_mode var 2020-08-11 15:10:18 +02:00
4f695b6f4c fixes 2020-08-11 11:16:48 +02:00
3ec1b23743 cleanup minor issues 2020-08-11 10:36:34 +02:00
0ba09ee85a enhancements 2020-08-11 10:24:45 +02:00
67dac15226 Merge branch 'debug' into taint 2020-08-11 03:40:12 +02:00
9cf8637fab break up llvm rt afl init 2020-08-11 03:37:02 +02:00
50e76fce12 adding ctor function skipping in LTO fixed map mode 2020-08-11 02:05:39 +02:00
432638404f ignoring ifuncs on fixed map LTO 2020-08-11 01:31:44 +02:00
1e38c10efb remove warning, fix text 2020-08-10 23:48:13 +02:00
701fb95d24 LTO: make dynamic map the default 2020-08-10 23:42:33 +02:00
7b5a18428e fixed __func__ 2020-08-10 23:17:39 +02:00
7d7a8c7c39 code-format 2020-08-10 19:05:22 +02:00
a422fcaa40 fixed minor inconsistencies, reenabled warnings 2020-08-10 19:04:51 +02:00
fee58a4d1b segfault info 2020-08-10 14:32:35 +02:00
3ecafde29d increase stack size 2020-08-10 13:59:30 +02:00
8428b18d2a fix another segfault 2020-08-10 13:30:25 +02:00
9c953ab51f memory grab at startup to prevent crashes 2020-08-10 13:03:59 +02:00
f181a8307b put ! in .new map 2020-08-10 12:48:15 +02:00
84b9d551fd disable expand havoc mopt for taint 2020-08-10 12:11:49 +02:00
8f8555dfdf fix segfault 2020-08-10 12:05:30 +02:00
464c27082a fuzzbench integration 2020-08-10 11:45:32 +02:00
3aa7d8081d fuzzbench integration 2020-08-10 11:23:33 +02:00
fb84103ffb please no -Werror in the dev branch 2020-08-10 09:39:43 +02:00
c270646722 fix wrong incomplete 2020-08-10 09:37:32 +02:00
87da1e7af6 fix driver 2020-08-10 09:16:55 +02:00
9b71f7e5e4 debug 2020-08-10 08:47:52 +02:00
9945c1648b fix driver 2020-08-10 01:34:45 +02:00
e5d24827de force llvm map 2020-08-10 01:28:26 +02:00
a6521e89fc different driver 2020-08-10 01:04:50 +02:00
5e36fb32a8 readme 2020-08-10 00:56:08 +02:00
fb0181f5bc readme 2020-08-10 00:53:50 +02:00
6fa2c213ef add driver 2020-08-10 00:24:27 +02:00
9ec223c844 final touches for first testing 2020-08-09 23:47:51 +02:00
558a82891a finalize havoc 2020-08-09 22:02:44 +02:00
4fc16b542e havoc copy 2020-08-09 21:32:15 +02:00
ff40359a60 fixes 2020-08-09 21:09:07 +02:00
e99d7e9730 integration in fuzz_one 2020-08-09 20:24:56 +02:00
b60663c031 taint integration done 2020-08-09 18:48:12 +02:00
32db31b555 fixes 2020-08-09 12:35:52 +02:00
a1129b67c2 changes 2020-08-09 12:15:36 +02:00
8a1cf3f0f9 Merge pull request #497 from murx-/dev
Add support for specific custom mutator name
2020-08-09 01:19:55 +02:00
0bb59ba116 code format 2020-08-09 01:09:26 +02:00
e4a0237cbc step 1 2020-08-09 00:35:12 +02:00
d8f5502d83 initial integration 2020-08-08 20:29:56 +02:00
45d0e4765e fix stderr output 2020-08-08 19:37:15 +02:00
9a1d526ed4 Add support for specific custom mutator name 2020-08-08 18:34:54 +02:00
ebc6f52868 cp inc 2020-08-08 12:55:35 +02:00
a19b31bf82 cp inc 2020-08-08 12:53:39 +02:00
28251a495a reformatted table 2020-08-08 12:41:35 +02:00
f4592a8fb4 merged readme changes 2020-08-08 12:38:10 +02:00
b29d91edf5 add stub directory 2020-08-08 11:17:05 +02:00
986af28df2 README.md: show afl-gcc as intel only 2020-08-07 22:06:36 +02:00
27abecbff5 compile fixes on 32-bit OSs 2020-08-07 21:07:05 +02:00
33141cf8a3 tests: cleanup core files, more time for llvm cmplog 2020-08-07 20:22:13 +02:00
8551d8e48e Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-08-07 19:53:32 +02:00
32558bc807 minor test fixes for Raspberry Pi Linux 64-bit 2020-08-07 19:41:39 +02:00
934cdc32f4 Merge branch 'dev' of https://github.com/vanhauser-thc/AFLplusplus into dev 2020-08-07 17:32:52 +02:00
699ebaa8e2 code format 2020-08-07 17:32:41 +02:00
44ad516edd remove debug 2020-08-07 17:23:11 +02:00
fd9a7e719d fixed wextra 2020-08-07 17:20:24 +02:00
e51f1ea5a5 Merge branch 'dev' of https://github.com/vanhauser-thc/AFLplusplus into dev 2020-08-07 16:56:12 +02:00
22d3a5e90a enabled Wextra, fixed bugs 2020-08-07 16:55:58 +02:00
673ace2a4b test-llvm.sh: clear file errors after test 2020-08-07 16:34:10 +02:00
4a6d66d8c5 fix typos 2020-08-07 14:43:17 +02:00
1978629d87 Custom Mutator readme (#495) 2020-08-07 14:21:12 +02:00
6b1ad311da Custom Mutator readme 2020-08-07 14:20:38 +02:00
5b06166144 reverse cmplog temps 2020-08-07 11:10:17 +02:00
a0fab35bbf temporary fix for cmplog 2020-08-07 10:42:33 +02:00
420b202124 temporary fix for cmplog 2020-08-07 10:37:28 +02:00
fb14e55cc9 fix -N description 2020-08-07 09:05:40 +02:00
e2434cf8c6 remove datalen in havoc 2020-08-06 23:27:50 +02:00
d94681186d Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-08-06 20:26:06 +02:00
58a710d192 check cmp map null in sancov trace switch 2020-08-06 20:25:57 +02:00
716eb226b2 enforce __afl_cmp_map points to a dummy by default 2020-08-06 20:06:57 +02:00
cb3631a322 add cmplog map to aflpp driver 2020-08-06 20:02:47 +02:00
bd1d148f83 Merge pull request #494 from AFLplusplus/test
aflpp driver fix for early callers
2020-08-06 19:43:56 +02:00
7e0c9a36ef update persistent doc 2020-08-06 19:42:33 +02:00
bbfff7d472 fix 2020-08-06 19:37:13 +02:00
e048d95660 fix 2020-08-06 19:13:04 +02:00
970d75d681 fix 2020-08-06 19:07:52 +02:00
51f3a81037 fix 2020-08-06 19:05:57 +02:00
8190436f8f fix 2020-08-06 18:51:16 +02:00
08bcaa135f dummy mem test 2020-08-06 18:44:12 +02:00
c4e5f75728 install dynamic list 2020-08-05 15:02:21 +02:00
1064c7114e code format 2020-08-05 13:30:43 +02:00
0281872ddf remove shared_linking check 2020-08-05 13:05:30 +02:00
c6bf23377d update dynamic list 2020-08-05 12:59:48 +02:00
2d650f8c22 merge conflict 2020-08-05 12:54:52 +02:00
19631851f6 dynamic symbols export for dlopen 2020-08-05 12:53:46 +02:00
f30ca1476c fix short write 2020-08-05 11:17:15 +02:00
0712d44cbc minor fixes 2020-08-05 10:42:41 +02:00
15f3210d93 Merge pull request #492 from dozernz/stable
Fix support for mips in qemu mode
2020-08-05 10:36:48 +02:00
9864d9c189 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-08-05 10:28:00 +02:00
bd36aac60a remove shared_linking case 2020-08-05 10:27:48 +02:00
4a859aff70 travis fixes 2020-08-05 10:25:53 +02:00
8fc727e597 port patch from https://github.com/google/AFL/pull/112 2020-08-05 10:01:58 +02:00
585ec04503 silly rand_below_datalen fix 2020-08-05 09:21:39 +02:00
a1c93f24d4 Fix support for mips in qemu mode 2020-08-05 12:19:43 +12:00
f6c89ec3a9 workaround travis 2020-08-05 01:29:05 +02:00
3d8f054580 readme fix 2020-08-05 01:19:31 +02:00
6d364dd2cb add sancov-like allow/denylist instrument feature 2020-08-05 01:13:51 +02:00
8ed6207b5c update honggfuzz custom mutator. make update is all it takes to stay current :) 2020-08-04 23:33:35 +02:00
c8354d7516 new rand mode for data offsets that prefer low offset values 2020-08-04 23:22:42 +02:00
79f873a597 posix compatible sourcing 2020-08-04 21:57:56 +02:00
8850e1a5bf chmod for testcase 2020-08-04 21:47:21 +02:00
194188fe56 split up testcases 2020-08-04 21:33:29 +02:00
cc74efa35e fix test for nixos 2020-08-04 15:10:20 +02:00
e7f2770275 Merge pull request #490 from AFLplusplus/dev
makefile fix?
2020-08-04 14:35:33 +02:00
af277a0b56 makefile fix? 2020-08-04 14:20:38 +02:00
4163f47e09 fix example 2020-08-04 13:54:13 +02:00
b2aa8b03d9 Merge pull request #488 from AFLplusplus/dev
Dev
2020-08-04 13:30:08 +02:00
e1d20706ca fix cmplog with lto 2020-08-04 13:17:53 +02:00
76888fdf59 bugfix libtokencap Makefile 2020-08-03 23:11:58 +02:00
e6e38d1703 give document edge id a unique id per module 2020-08-03 21:25:32 +02:00
44060590b4 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-08-03 20:51:00 +02:00
38bed607d1 code format 2020-08-03 20:50:47 +02:00
ed63364a77 add touch shmem in forkserver, add binary library and patches.txt for easy testing 2020-08-03 18:13:06 +02:00
55bd24b0c7 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-08-03 15:17:47 +02:00
f18c2eb8ae no support for DragonFlyBSD. 2020-08-03 15:16:46 +02:00
898353c87a enforce no built-ins for lto 2020-08-03 14:17:51 +02:00
d5d8d664d0 Merge pull request #477 from AFLplusplus/dev
Push to stable
2020-08-03 13:39:55 +02:00
409e4ae945 fix expand havoc for ..._only modes 2020-08-03 13:13:32 +02:00
f335c48686 better PS1 in dockerfile 2020-08-03 11:50:10 +02:00
9d82c3cf5e test for llvm cmplog 2020-08-03 11:30:34 +02:00
491cee669f fix #483 2020-08-03 11:15:12 +02:00
e0d1529061 edge id documentation example for sancov 2020-08-03 10:03:45 +02:00
1cddd51662 refactoring debug/be_quiet, fatal on dont_optimize and instrument_file 2020-08-02 22:28:16 +02:00
6041b1c486 fix LTO document id feature, warnings for INSTRUMENT_FILE 2020-08-02 15:00:49 +02:00
349fed3fcd warn on old llvm 2020-08-02 11:08:47 +02:00
b708cf7d45 fix lto single block and no zero 2020-08-01 19:43:29 +02:00
a267ff1ab5 better LTO mode detection warnings 2020-08-01 18:31:11 +02:00
8e0c776137 more flexible use of shmem persistent vars 2020-08-01 17:58:37 +02:00
4512377fa1 compile persistent mode without afl 2020-08-01 17:39:27 +02:00
9439ba1dac document env var 2020-08-01 16:32:01 +02:00
9c9c4a6b2b remove forced -shared for lto, seems unneeded 2020-08-01 14:27:18 +02:00
6efe51a8a7 improve chances to compile with lto 2020-08-01 13:56:10 +02:00
593940c39a refer to llvm 12 for partial instrumentation for PCGUARD 2020-07-31 20:20:30 +02:00
8ea19d4266 easier float test 2020-07-31 19:37:05 +02:00
b7bcc50c61 reenable cpu tests in test.sh 2020-07-31 19:09:04 +02:00
e939677726 fix travis 2020-07-31 18:43:30 +02:00
ca17ec3fe9 Merge pull request #481 from devnexen/haiku_settings
Haiku set explicitly to performance.
2020-07-31 18:42:06 +02:00
54d9668580 Haiku set explicitly to performance.
No command line to set through afl-system-config (the only one is a GUI).
2020-07-31 17:27:01 +00:00
16b674c652 fix find free cpu 2020-07-31 18:35:43 +02:00
25ad992c62 fix travis 2020-07-31 18:26:18 +02:00
37f1b7cddb fix travis 2020-07-31 18:18:05 +02:00
729445b64f Bind cpu (#480)
* silence compiletime warning

* refactored cpu binding

* formatted code
2020-07-31 18:17:03 +02:00
185f443659 add LTO AFL_LLVM_DOCUMENT_IDS feature 2020-07-31 17:53:01 +02:00
c101a3f5ab readme update 2020-07-31 17:23:31 +02:00
cf9cb73afe Review as requested (watch out for XXX) 2020-07-31 16:27:50 +02:00
071fcac430 building docker from cloned repo 2020-07-31 15:55:48 +02:00
a74ec89461 fixed dockerfile 2020-07-31 15:37:50 +02:00
630d2a934b less gotos 2020-07-31 14:36:58 +02:00
d5758c138b update todo 2020-07-31 11:04:22 +02:00
149b0021b7 improve README 2020-07-31 10:49:25 +02:00
68f46f6178 remove travis debug 2020-07-31 10:44:54 +02:00
cd576fa59d fixes 2020-07-31 10:42:43 +02:00
320f26d26f add -b option to afl-fuzz 2020-07-30 19:00:41 +02:00
c661587128 cdecl void 2020-07-30 18:06:25 +02:00
486e5365d9 fix float splitting if not on a tty 2020-07-30 18:01:18 +02:00
8e809d8593 added NULL check 2020-07-30 17:51:32 +02:00
ea9ba53cdb fix oob reads, code-format 2020-07-30 17:09:22 +02:00
1ba48a5ba0 :Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-07-30 17:02:13 +02:00
7cb00b69f0 warnings reenabled 2020-07-30 17:01:57 +02:00
cbe8f0a9d0 cleanup messages in floating point test case 2020-07-30 17:00:10 +02:00
da8b464e67 fix test.sh 2020-07-30 16:07:47 +02:00
13350bf22f Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-07-30 13:48:16 +02:00
5ce55d87ec make travis green again (floating point testcase), but all laf testcases need AFL_DEBUG=1 (that is another bug) 2020-07-30 13:46:52 +02:00
fc401f1acc fix post process check 2020-07-30 11:51:13 +02:00
fe39e4dfdf remove unneeded stuff 2020-07-30 11:30:37 +02:00
49b77207dd aflpp driver cpp -> c 2020-07-30 11:11:30 +02:00
35a448ee92 enhance for custom trim buffer 2020-07-30 09:20:22 +02:00
3f9f00a798 Merge pull request #460 from rish9101/dev
Add post-process functionality in write_with_gap
2020-07-30 09:15:42 +02:00
ffe5619a9d fix snapshot include 2020-07-29 14:30:22 +02:00
3b194e1690 Merge pull request #476 from AFLplusplus/new_lkm
New snapshot lkm support
2020-07-29 14:15:39 +02:00
45b6508339 fix typo 2020-07-29 13:00:55 +02:00
22921c493f improve docs, enable laf compare if float is set 2020-07-29 12:58:02 +02:00
f32811922e minor opt 2020-07-29 11:56:38 +02:00
6cfa27d78a remove dead code, code-format 2020-07-29 11:47:32 +02:00
8e3ca8eaa9 Merge pull request #473 from AFLplusplus/text_inputs
add splice
2020-07-29 11:41:54 +02:00
4550613f58 Merge branch 'dev' into text_inputs 2020-07-29 11:39:00 +02:00
015fde3703 fix ffmpeg lto example 2020-07-28 22:25:48 +02:00
827ecd61f6 add new example/guideline 2020-07-28 22:13:37 +02:00
565da10a8f Minor change to write_with_gap 2020-07-29 01:05:05 +05:30
d64c0e8887 lkm new api 2020-07-28 16:31:07 +02:00
0b8c44cbb1 add FAQ 2020-07-28 16:29:47 +02:00
a22f4dd1ac new snapshot api 2020-07-28 16:13:32 +02:00
952e5b47eb allow custom mut with mopt if -L is -1 2020-07-28 16:02:15 +02:00
b3f5b566b0 update contribute doc 2020-07-28 13:29:50 +02:00
0b3332d579 finalize new readme 2020-07-28 13:27:18 +02:00
a76e375d5c import lost PR when switching to stable, updated todo 2020-07-28 11:05:00 +02:00
8b21c2e472 unnice 2020-07-28 09:55:32 +02:00
23718e5198 forgot getopt 2020-07-28 09:52:28 +02:00
031aa240bc unnice2 2020-07-27 23:09:26 +02:00
7944009a65 unrenice 2020-07-27 13:07:55 +02:00
4eb06bb54b Merge pull request #465 from electricworry/wine-fix
Fixes AFLplusplus/AFLplusplus#464 winepath path translation for .cur_…
2020-07-27 10:41:07 +02:00
bd5308d839 fix readme 2020-07-27 10:27:57 +02:00
b508532c78 format 2020-07-27 10:09:00 +02:00
fb9888a068 Merge pull request #468 from Kirin-say/fix_qemu_mode
Fix bug in qemu mode
2020-07-27 10:07:12 +02:00
11f25747a9 child renice 2020-07-27 09:39:15 +02:00
8ebed3471f fix readme 2020-07-27 09:30:42 +02:00
85684cd8b7 fix readme 2020-07-27 09:25:30 +02:00
2585a33005 fix readme 2020-07-27 09:21:07 +02:00
1bbeef48e1 update readme, renice -20 2020-07-27 09:10:48 +02:00
7f3317110e update new readme 2020-07-27 00:16:09 +02:00
298ff5c7d0 update new readme 2020-07-27 00:14:28 +02:00
c3f65bff5b update new readme 2020-07-27 00:13:03 +02:00
2323c30b5b fix honggfuzz dict 2020-07-26 22:05:14 +02:00
80f4b32f0b new readme --- in progress 2020-07-26 18:41:54 +02:00
16e362d2b9 add last 60s exec/s stat 2020-07-26 15:55:03 +02:00
23da490f26 Merge pull request #469 from devnexen/haiku_gcc_build_fix
gcc plugin forcing USEMMAP on Haiku
2020-07-26 15:30:47 +02:00
ff107714f1 remove test input mutation in havoc 2020-07-26 15:00:44 +02:00
7e4703c328 Fix typo for afl_custom_deinit (#470) 2020-07-26 14:10:24 +02:00
ae41cedafe gcc plugin forcing USEMMAP on Haiku 2020-07-25 16:14:27 +00:00
a879f72131 fix 2020-07-25 17:38:40 +02:00
131df8bec9 try to fix travis 2020-07-25 16:39:36 +02:00
89557d1607 fix bug in qemu mode 2020-07-25 00:36:36 +08:00
7959808384 llvm12 support 2020-07-24 16:39:50 +02:00
ecb0601bc1 massage chances 2020-07-24 13:42:39 +02:00
30c0991543 better text mutation 2020-07-24 13:26:07 +02:00
9cddbc0420 add -F option to sync to foreign fuzzer queues 2020-07-24 12:26:52 +02:00
2fa31dab60 Remove reduntant copying from write_with_gap function 2020-07-23 23:48:26 +05:30
4898db80cb Add post-process functionality in write_with_gap 2020-07-23 23:16:04 +05:30
aa3856261d fix warning 2020-07-23 17:17:44 +02:00
3e04dbd5a1 no cycle on expand 2020-07-23 16:43:25 +02:00
72b46a07d6 added honggfuzz custom mutator :) 2020-07-23 15:58:13 +02:00
2ba88dcd8a skip large files, dont bail 2020-07-23 14:17:29 +02:00
1ddb70e0d9 fix compilation 2020-07-23 05:08:20 +02:00
024a88a6bb Fixes AFLplusplus/AFLplusplus#464 winepath path translation for .cur_input. 2020-07-22 20:19:55 +01:00
af10c05ac3 ascii redqueen 2020-07-22 18:22:31 +02:00
a46a733dbe fix bugs 2020-07-22 17:04:57 +02:00
b015e4f07a epand havoc now env 2020-07-22 16:15:16 +02:00
44928a0265 write expand havoc value to fuzzer_stats 2020-07-22 02:41:19 +02:00
d90328f6be Allow the custom mutator to generate larger trimmed data (#463) 2020-07-22 00:00:21 +02:00
ce9b4698fe added andrea's splicing, added cycle_schedules 2020-07-21 20:53:51 +02:00
9a33a29b4a Merge pull request #462 from AFLplusplus/dev
Dev
2020-07-21 13:17:29 +02:00
b6e65f9882 Merge pull request #461 from AFLplusplus/new_splicing
New splicing
2020-07-21 13:15:59 +02:00
6c163910ee debug test for rng 2020-07-20 12:08:31 +02:00
9151cb9ba2 update link 2020-07-20 11:40:34 +02:00
204ae75d7b add superion custom mutator link 2020-07-20 10:31:07 +02:00
f2d9b0096e Merge pull request #458 from h1994st/dev
Allow the custom trim function to return 0 bytes
2020-07-20 10:19:14 +02:00
67d2e6319b Skip the empty test case generated by the custom trimming 2020-07-18 23:20:32 -04:00
5e10f660e8 Allow the fuzzer to write empty buffer (i.e., len == 0) to the file 2020-07-18 02:16:04 -04:00
0da0b5cba0 Merge pull request #456 from h1994st/dev
Fix typo
2020-07-17 08:41:26 +02:00
67d7c364f6 Fix typo 2020-07-16 21:59:50 -04:00
67d58e2437 doc updates 2020-07-16 20:24:01 +02:00
c2b04bdf6c queue buffer and new splice havoc mutation 2020-07-16 14:32:41 +02:00
6513bca07e Update post_library_gif.so.c (#454) 2020-07-16 11:47:36 +02:00
0b0366d9b4 removed debug print and code format 2020-07-16 02:27:07 +02:00
f465a75b65 added initial defork example 2020-07-16 02:17:05 +02:00
4314e59af9 code format 2020-07-16 02:03:52 +02:00
a84c958647 fixed mem leak in redqueen 2020-07-16 01:00:39 +02:00
1ec2615a3e tiny fixes 2020-07-16 00:53:08 +02:00
2077309c8d fix afl-frida 2020-07-16 00:24:37 +02:00
08d3169df4 fix afl-frida 2020-07-15 16:58:40 +02:00
3cc0445e27 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-07-15 10:35:51 +02:00
ee77fe4094 improve len encoding in redqueen 2020-07-15 10:35:38 +02:00
133dfc8b69 update documentation 2020-07-15 10:32:07 +02:00
a8726b8254 ensure afl-frida uses persistent mode 2020-07-15 00:08:38 +02:00
c5963f707c make fuzzing of test-floatingpoint reproducible 2020-07-14 23:42:47 +02:00
383b280531 added frida gum extension 2020-07-14 23:26:11 +02:00
95276f7da6 test float splitting increase timeout to 30 seconds 2020-07-13 23:17:21 +02:00
e1d4621796 Merge pull request #450 from devnexen/haiku_build_fix
Haiku build fix. librt is necessary for Linux primarly and SunOS
2020-07-13 18:06:38 +02:00
e137b40eb5 Haiku build fix. librt is necessary for Linux primarly and SunOS 2020-07-13 16:22:18 +00:00
4d929f80fb fix for laf intel float split not enabled if not not on a tty 2020-07-13 17:57:02 +02:00
6b79e1f76d test.sh: FP fuzzing: check for crashes 2020-07-13 11:27:08 +02:00
5a26656ea1 add floating point test cases. One for fuzzing (test-floatingpoint.c) and one for testing all cases with the instrumented program (test-fp_cases.c) 2020-07-13 10:35:43 +02:00
abb0d47985 little untracer enhancements 2020-07-12 23:53:29 +02:00
b126a5d5a8 LTO: autodict default, instrim disabled 2020-07-12 13:44:25 +02:00
571031a467 fix several cases in floating point comparison splitting 2020-07-11 00:56:35 +02:00
2981f2025f increase shm for travis 2020-07-09 23:14:33 +02:00
c3a6065a21 shm + mem info in travis 2020-07-09 23:02:04 +02:00
60bb1afc72 code format 2020-07-09 21:32:06 +02:00
84a320f834 skip -fuse-ld parameters when in LTO mode 2020-07-09 21:31:15 +02:00
88bd460100 Merge pull request #449 from devnexen/illumos_typo
illumos littlefixes: little typo for cpu binding and
2020-07-09 19:05:05 +02:00
90adc2cb85 illumos littlefixes: little typo for cpu binding and
even tough gcc plugin less good than LLVM, clang
is more buggy on this os.
2020-07-09 15:43:05 +01:00
7c8d823396 dockerfile updates 2020-07-09 12:07:29 +02:00
83790d65af eliminate race condition for cpu affinity on -M/-S 2020-07-08 11:16:39 +02:00
70bd0f799d fix afl-whatsup if fuzzer_stats is still empty 2020-07-08 09:39:26 +02:00
cbe029664e fix issue #446 2020-07-07 12:59:00 +02:00
cade0214db Merge pull request #445 from toralf/fix-y-axis-of-low_freq.png
afl-plot: scale y-axis of low_freq.png with integers
2020-07-06 22:29:23 +02:00
2f5cdb72c8 afl-plot: set xlabel to show that times are in UTC
Signed-off-by: Toralf Förster <toralf.foerster@gmx.de>
2020-07-06 19:23:13 +02:00
0aed549df1 warn rather than fail if AFL_MAP_SIZE is set and not understood by instrumenter 2020-07-06 14:11:21 +02:00
75fa1ac3b0 warn rather than fail if AFL_MAP_SIZE is set and not understood by instrumenter 2020-07-06 14:10:14 +02:00
b5a00312e0 rtf.dict: make it more complete (and unique) and fix some entries 2020-07-06 10:27:48 +02:00
37697127dc afl-plot: scale y-axis of low_freq.png with integers
Signed-off-by: Toralf Förster <toralf.foerster@gmx.de>
2020-07-05 15:35:24 +02:00
8acc8b5389 Merge pull request #441 from bmwiedemann/man
Fix generation of afl-system-config.8
2020-07-05 13:53:51 +02:00
8644c42482 check for enough plot data 2020-07-05 13:48:14 +02:00
20e63078f0 Fix generation of afl-system-config.8
and afl-whatsup.8

Without this patch, afl-system-config.8 varied between build hosts
because it contained lines such as
 ./afl-system-config: line 30: sysctl: command not found
 ./afl-system-config: line 31: /sys/kernel/mm/transparent_hugepage/enabled: Permission denied
 It is recommended to boot the kernel with lots of security off

See https://reproducible-builds.org/ for why this matters.

afl-system-config.8 is generated by the %.8 target in GNUmakefile
that calls commands with -hh to fill the OPTIONS section of man-pages.

This PR was done while working on reproducible builds for openSUSE.
2020-07-05 13:41:50 +02:00
95fd080ca1 code format 2020-07-05 11:08:22 +02:00
7d0af01d8b fix rtf.dict 2020-07-05 11:05:33 +02:00
0f0230b068 Merge pull request #437 from devnexen/fbsd_build_fix_llvm_mode
llvm mode shared segment fix for FreeBSD.
2020-07-05 11:01:58 +02:00
869c602b99 Merge pull request #438 from EliaGeretto/fix-typo
Fix typo in compiler wrapper for LLVM instrumentation
2020-07-05 11:01:24 +02:00
3144f72e1c Merge pull request #440 from devnexen/libdislocator_solaris_upd
libdislocator: hugepage enabled for illumos too.
2020-07-05 11:00:45 +02:00
147b0a151c fix laf-intel/compare-transform-pass for 32-Bit 2020-07-04 17:34:03 +02:00
29102d6bf1 libdislocator: hugepage enabled for illumos too. 2020-07-04 12:36:53 +01:00
4fd145c52e llvm_mode: Fix typo in compiler wrapper 2020-07-03 18:37:53 +02:00
e6d4d29af5 llvm mode shared segment fix for FreeBSD.
MAP_EXCL|MAP_FIXED is a (genuine) equivalent to Linux's MAP_FIXED_NOREPLACE.
2020-07-03 15:21:33 +01:00
139665c01d ubsan options 2020-07-03 10:20:10 +02:00
509b991607 Merge pull request #435 from devnexen/libtokencap_solaris
libtokencap illumos/solaris support proposal.
2020-07-03 09:45:19 +02:00
c671ecb511 Fix map list iteration. 2020-07-02 10:23:56 +01:00
1aa7c87ea8 libtokencap illumos/solaris support proposal. 2020-07-02 07:10:43 +01:00
00abb999e3 v2.66d init 2020-07-01 18:24:00 +02:00
4a51cb71fb Merge pull request #434 from AFLplusplus/dev
Last Minute Unicornafl Update
2020-07-01 16:52:05 +02:00
f2efea4b46 Revert "Revert "updated unicorn version""
This reverts commit 857046ede5.
2020-07-01 16:05:04 +02:00
e15a013696 Merge pull request #433 from AFLplusplus/dev
final push to stable before release?
2020-07-01 15:58:26 +02:00
857046ede5 Revert "updated unicorn version"
This reverts commit 4515e06ca8.
2020-07-01 15:57:48 +02:00
4515e06ca8 updated unicorn version 2020-07-01 15:50:25 +02:00
97cef46b62 warn on deprecated env vars 2020-07-01 10:03:34 +02:00
4ec29928bf because github errors reput typo fix 2020-07-01 09:30:14 +02:00
ba79777bc5 Merge pull request #432 from AFLplusplus/dev
v2.66c
2020-07-01 09:28:13 +02:00
b67905c40f Merge branch 'stable' into dev 2020-07-01 09:19:32 +02:00
6b98157c1a v2.66c release preparation 2020-07-01 09:15:47 +02:00
4d2ccd18f6 comments fix 2020-07-01 07:55:58 +02:00
52a0410d92 fix text 2020-07-01 07:49:07 +02:00
d898418037 restore credit for afl-tmin fork server patch 2020-07-01 07:43:14 +02:00
2aaa60e4fc comments fix 2020-07-01 07:39:55 +02:00
e9dce31496 comments fixed 2020-07-01 07:35:42 +02:00
b201279ae5 text fix 2020-07-01 07:27:53 +02:00
be83f06b2f renaming remains fixed 2020-07-01 07:25:33 +02:00
9d5007b18e Big renaming (#429)
* first commit, looks good

* fix ascii percentage calc

* fix ascii percentage calc

* modify txt configs for test

* further refinement

* Revert "Merge branch 'text_inputs' into dev"

This reverts commit 6d9b29daca, reversing
changes made to 07648f75ea.

* blacklist -> ignore renaming

* rename whitelist -> instrumentlist

* reduce the time interval in which the secondaries sync

Co-authored-by: root <root@localhost.localdomain>
2020-06-30 23:34:26 +02:00
7527c76c74 reduce the time interval in which the secondaries sync 2020-06-30 17:33:47 +02:00
06264df168 rename whitelist -> instrumentlist 2020-06-30 17:28:21 +02:00
878b27af76 blacklist -> ignore renaming 2020-06-30 16:52:48 +02:00
4b99ebbf22 Revert "Merge branch 'text_inputs' into dev"
This reverts commit 6d9b29daca, reversing
changes made to 07648f75ea.
2020-06-29 18:48:17 +02:00
fc5cfc6cb3 Merge pull request #428 from AFLplusplus/dev
Dev
2020-06-29 18:36:06 +02:00
6d9b29daca Merge branch 'text_inputs' into dev 2020-06-29 18:35:51 +02:00
3f1288e2f9 Merge pull request #427 from AFLplusplus/dev
workaround for recent afl++ versions
2020-06-29 18:32:12 +02:00
8f1b78f49e Merge pull request #426 from AFLplusplus/dev
Dev
2020-06-29 18:19:35 +02:00
07648f75ea workaround for recent afl++ versions 2020-06-29 12:21:14 +02:00
3a0c91b862 fix unittest 2020-06-29 01:23:30 +02:00
e5e485fcdb fix autodict 2020-06-29 00:58:05 +02:00
16f3df7cc6 fix for shmem+autodict 2020-06-29 00:18:29 +02:00
6d0f086d9c less problematic definitions 2020-06-28 23:50:25 +02:00
c25a602a03 less problematic definitions 2020-06-28 23:47:57 +02:00
81974c4d5e debug code 2020-06-28 22:50:18 +02:00
5f3b7e6cdf typo aonce -> once 2020-06-28 21:21:27 +02:00
910b9f3f25 O2 instead of O3 for .o target files 2020-06-28 16:53:31 +02:00
4fd2cb2ce0 update idea list 2020-06-28 14:51:49 +02:00
e234a6ae4e update schedules in readme 2020-06-28 14:46:57 +02:00
ee17782e61 fix output for LTOinstrim 2020-06-28 00:13:31 +02:00
cd6954e3c1 fix make static 2020-06-27 23:11:10 +02:00
29e41a09d5 fix typos 2020-06-27 18:16:27 +02:00
4103687f76 afl-sharedmem.c: fix leaks on error paths (SysV shared memory) 2020-06-27 00:13:24 +02:00
976e99b1d4 original fix for calibration error 2020-06-26 10:17:21 +02:00
da7c548452 afl-plot remove error print 2020-06-26 09:53:54 +02:00
1ecfd78418 implement sharedmem mmap for cmplog 2020-06-26 09:13:07 +02:00
07fead0466 fix shared memory leaks in afl-showmap, initialize cmplog_mode 2020-06-26 01:14:21 +02:00
8bd8442bcc fix for schedules 2020-06-25 22:44:46 +02:00
5904083231 remove debug 2020-06-25 22:28:56 +02:00
171b1923e9 shmem release fix 2020-06-25 22:02:02 +02:00
8d5eb9487d make llvm_mode pcguard instrumentation collision free 2020-06-25 20:09:56 +02:00
633a3feab9 fix makefile 2020-06-25 17:51:48 +02:00
c8f60a7fbf initialized variable 2020-06-25 17:25:16 +02:00
3a62bb68e0 updated unicornafl 2020-06-25 17:13:16 +02:00
8178f4dfdd remove radamsa, add radamsa custom mutator 2020-06-25 16:51:29 +02:00
4a3305c007 Merge pull request #425 from dgmelski/fix-recalibration
Fix saturated maps & stability cliff in recalibration
2020-06-25 15:16:10 +02:00
9858bc81a3 GNUmakefile: warn about '.' being first path in PATH environment variable. This causes recursion in 'as'. (seen in Haiku) 2020-06-25 13:28:34 +02:00
b5573b3adb add seek power schedule, remove update stats in calibration, fix help output 2020-06-25 10:33:59 +02:00
15dd4ad177 fix plot 2020-06-25 08:50:34 +02:00
d540971443 Fix saturated maps & stability cliff in recalibration
I have observed two problems:

  1. A sudden "stability cliff" where stability drops precipitously.

  2. A sudden jump to a 100% saturated "density map".

Both issues are due to attempted "recalibration" of a case at the
beginning of fuzz_one_original() or mopt_common_fuzzing().  See the
comments "CALIBRATION (only if failed earlier on)" in those functions
and the subsequent call to calibrate_case().

At those calls to calibrate_case(), afl->fsrv.trace_bits holds
trace_bits for a run of the SUT on a prior queue entry.  However,
calibrate_case() may use the trace_bits as if they apply to the
current queue entry (afl->queue_cur).

Most often this bug causes the "stability cliff".  Trace bits are
compared for runs on distinct inputs, which can be very different.
The result is a sudden drop in stability.

Sometimes it leads to the "saturated map" problem.  A saturated
density map arises if the trace bits on the previous entry were
"simplified" by simplify_trace().  Simplified traces only contain the
values 1 and 128.  They are meant to be compared against
virgin_crashes and virgin_tmouts.

However, this bug causes the (stale) simplified trace to be compared
against virgin_bits during a call to has_new_bits(), which causes
every byte in vigin_bits to be something other than 255.  The overall
map density is determined by the percentage of bytes not 255, which
will be 100%.  Worse, AFL++ will be unable to detect novel occurrences
of edge counts 1 and 128 going forward.

This patch avoids the above issues by clearing q->exec_cksum when
calibration fails.  Recalibrations are forced to start with a fresh
trace on the queue entry.

Thanks to @andreafioraldi for suggesting the current, improved patch.
2020-06-24 17:59:04 -04:00
1d7c76d141 decrease time to sync for main 2020-06-24 17:37:16 +02:00
224a49341a update .gitignore 2020-06-24 17:04:28 +02:00
fce010f051 add -D option for -S 2020-06-24 11:14:00 +02:00
bdc8e3b79e create .synced/NAMES.last to document last sync attempts 2020-06-24 11:09:33 +02:00
9289af040c gitignore 2020-06-24 08:23:31 +02:00
49a769ac06 lto whitelist in test.sh 2020-06-23 21:23:10 +02:00
2b450aeb20 fix test.sh 2020-06-23 18:21:50 +02:00
5f1c0111a6 fix make files 2020-06-23 18:06:08 +02:00
89f0dc2d14 fix gcc mode for travis 2020-06-23 17:43:04 +02:00
cffb0e9a25 fix gcc makefile 2020-06-23 17:36:05 +02:00
2b26e3867f fix gcc makefile 2020-06-23 17:31:52 +02:00
aad433e11e Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-06-23 15:08:49 +02:00
59e1a18197 Merge pull request #422 from devnexen/haiku__build_upd
Haiku  build upd
2020-06-23 11:01:22 +02:00
8f98044d69 Libdislocator Haiku build fix 2020-06-23 09:41:38 +00:00
6c414409d4 libtokencap Haiku support 2020-06-23 09:29:57 +00:00
7119bf5d86 Added rand, hash unittests 2020-06-22 21:58:23 +02:00
ea1222b33f old compiler fix 2020-06-22 21:40:02 +02:00
37edfe2de9 shmem support for afl-tmin and afl-showmap 2020-06-22 19:56:34 +02:00
76a2d9b59b further refinement 2020-06-22 13:48:59 +02:00
87f127722c fix afl-cmin.bash 2020-06-22 08:28:41 +02:00
a49b5ef072 allow /tmp 2020-06-22 07:16:24 +02:00
5cad92e57e fix unicorn mode for CFLAGS 2020-06-21 18:07:30 +02:00
f6ef1fe65e fix libcompcov for CFLAGS 2020-06-21 16:43:55 +02:00
048e429356 remove -Werror and add include for libdislocator 2020-06-21 16:33:55 +02:00
eb3cb4bbf8 fix for s=0 2020-06-21 16:21:59 +02:00
b0866f59cc fix for -s 0 2020-06-21 14:08:41 +02:00
b3b016a4a3 fix libradamsa see issue #419 2020-06-20 22:39:12 +02:00
341e17bf53 Merge pull request #418 from jonasmollerlarsen/dev
Fix when env. PATH contains spaces
2020-06-20 13:37:22 +02:00
eb4561e3a6 afl-plot: fix issue #417, also check relative paths for directories 2020-06-20 13:09:47 +02:00
990b234067 Fix when env. PATH contains spaces 2020-06-20 11:50:53 +02:00
07a4e6370a modify txt configs for test 2020-06-20 10:55:02 +02:00
1381e96d8c fix ascii percentage calc 2020-06-20 09:22:14 +02:00
5ca303393f fix ascii percentage calc 2020-06-20 09:21:02 +02:00
de2c565953 first commit, looks good 2020-06-19 18:05:04 +02:00
2a254fce8f fix afl-clang-fast for default pcguard mode 2020-06-19 14:21:34 +02:00
758f136d3e update todo 2020-06-18 20:39:06 +02:00
5d3d86c680 update todo 2020-06-18 15:33:16 +02:00
d8d5adeb61 Merge pull request #416 from Mem2019/patch-2
`fault == afl->crash_mode` should be likely
2020-06-18 07:08:11 +02:00
003456f770 fault == afl->crash_mode should be likely
Since during normal fuzzing, crash_mode is FSRV_RUN_OK, and fault is also usually FSRV_RUN_OK since most executions are valid executions, thus it should be likely instead of unlikely
2020-06-18 11:23:10 +08:00
25c3a29004 Merge pull request #414 from AFLplusplus/dev
work around for llvm 11 bug
2020-06-17 23:56:17 +02:00
394d8ade15 work around for llvm 11 bug 2020-06-17 22:21:09 +02:00
118cc88429 Merge pull request #412 from AFLplusplus/dev
fix displayed schedule
2020-06-17 16:46:54 +02:00
61107c59cf fix displayed schedule 2020-06-17 16:46:30 +02:00
0dc9967984 Merge pull request #403 from AFLplusplus/dev
push to master
2020-06-17 15:05:14 +02:00
889e54eab8 unit tests: fix stupid compiler warning for gcc 4.8.4 2020-06-16 23:07:33 +02:00
a14f3c90a8 fix unit tests when exit is called at the end 2020-06-16 22:37:56 +02:00
e05ed58bf8 fix test.sh for failing unit tests 2020-06-16 19:44:52 +02:00
d6824d540b Merge pull request #408 from Minilulatsch/dev
Fixed missing cast in afl-clang-fast.c, which results in a compilation error when using __AFL_FUZZ_TESTCASE_BUF in a C++ target
2020-06-16 19:36:11 +02:00
2e35326040 Fixed missing cast in afl-clang-fast.c, which results in a compilation error when using __AFL_FUZZ_TESTCASE_BUF in a C++ target 2020-06-16 18:04:38 +02:00
e5dcaa818e set class afl instrumentation if llvm <= 6 2020-06-16 15:59:09 +02:00
bac2da8669 fix for *BSD: remove all HAVE_ARC4RANDOM dependencies 2020-06-16 01:29:07 +02:00
9c293b5b7b code format 2020-06-15 22:05:37 +02:00
6804065a8d using XX64 for 32 bit hash 2020-06-15 22:03:01 +02:00
246444dd57 tidied hash32, unicorn 2020-06-15 21:40:37 +02:00
6a216b5708 make aflpp driver performant again 2020-06-15 21:39:45 +02:00
f6d2da27e3 switched to new MOpt dictionary support 2020-06-15 21:07:35 +02:00
ada59feda8 improve performance for default power schedule 2020-06-15 20:02:28 +02:00
af8d4d49ed add new dictionary from antonio-morales ftp fuzzing 2020-06-15 16:30:41 +02:00
dc002b4b35 code format 2020-06-15 11:08:24 +02:00
acb0a2f027 fixed potential bugs 2020-06-15 11:07:57 +02:00
43bbbbf4e0 rust unicornafl++ 2020-06-15 00:20:13 +02:00
05da66b5e9 unicornafl update 2020-06-14 23:30:36 +02:00
b8cea84195 disable focal on travis temporarily 2020-06-14 18:48:49 +02:00
741dce3ca6 Merge pull request #404 from devnexen/haiku_porting
Porting to Haiku.
2020-06-14 17:38:17 +02:00
67d87dd2a9 Porting to Haiku.
getrusage does not implement resident memory gathering, no shm api neither.
2020-06-14 15:32:02 +00:00
ab142282a3 kill targets on exit 2020-06-14 16:08:58 +02:00
bfe5b88e78 code format 2020-06-13 14:28:42 +02:00
fc26001b50 fix shmem 2020-06-13 13:47:43 +02:00
1542c7f49c fix typos 2020-06-13 10:58:30 +02:00
615ab1a7b8 fix resize window crash and slightly more performant timed_read 2020-06-13 00:14:14 +02:00
ce1af1bc9c code-format killed the compilation 2020-06-12 16:57:33 +02:00
ab0e3fdd82 code-format killed the compilation 2020-06-12 16:50:36 +02:00
40aca0b6b3 fix for checksums 2020-06-12 16:33:20 +02:00
a632c00b0d switch to faster and better hash + random 2020-06-12 16:08:49 +02:00
db2e04361d shm debug and fixes 2020-06-12 11:57:54 +02:00
7d19b108c4 fix warnings 2020-06-12 09:23:38 +02:00
818afe6232 added MOpt dictionary support from repo 2020-06-12 08:27:03 +02:00
e8da5f9e28 code format and debug 2020-06-11 19:30:28 +02:00
b3fee6cab2 rust bindings for unicornafl 2020-06-11 16:36:45 +02:00
da7a8ce60a issue #401: remove all TAB characters from dictionary files 2020-06-10 21:53:58 +02:00
a6386bd640 Merge pull request #400 from devnexen/gotcpu_illumos
start of illumos cpu binding implementation.
2020-06-10 20:29:55 +02:00
b3feda052d start of illumos cpu binding implementation.
The current user needs the proc_owner permission, not something doable
 via the settings script.
2020-06-10 16:16:47 +01:00
c1eb2bccaa more output in uc-tests 2020-06-10 12:09:45 +02:00
5cb6dc7795 Merge pull request #398 from devnexen/array_subscript_warn_fix
Disable array subscript warning
2020-06-10 09:25:31 +02:00
af66d8027b Merge pull request #399 from devnexen/non_aff_build_fix
systems w/o affinity support build fix
2020-06-10 09:25:06 +02:00
4ee4495120 Disable array subscript warning 2020-06-09 22:43:31 +01:00
c02721775a updated unicorn 2020-06-09 23:15:24 +02:00
cbdcd32959 systems w/o affinity support build fix 2020-06-09 22:14:13 +01:00
12bdefe00e Merge pull request #392 from AFLplusplus/dev
Push to master
2020-06-09 19:25:09 +02:00
81829d132b always set status 2020-06-09 17:09:34 +02:00
5fa0f8f55b fix debug output in stats 2020-06-09 17:01:41 +02:00
7e818e877a fixing travis 2020-06-09 15:45:50 +02:00
32a40ab5c5 add cpu affinity to fuzzer_stats 2020-06-09 11:22:27 +02:00
c2087b7c13 more unicornafl fixes 2020-06-09 04:18:02 +02:00
feffae60dd code format 2020-06-09 03:48:50 +02:00
8e3f6fe2dc added persistent mode testcase 2020-06-09 03:46:17 +02:00
92b8c5bb60 fixed shmap fuzzing 2020-06-09 03:03:21 +02:00
646237e234 fix x86 notzero 2020-06-08 11:52:49 +02:00
b4f71c7cc7 Merge pull request #396 from Kyle-Kyle/master
fix a fundamental bug: favor random branches
2020-06-08 08:57:25 +02:00
73334207ce fix a fundamental bug: favor random branch randomly 2020-06-07 15:14:25 -07:00
e8a6b1cfb5 updated unicorn 2020-06-07 16:22:39 +02:00
748238d6ab Revert "updated unicorn"
This reverts commit 5fcd4bb082.
2020-06-07 16:19:51 +02:00
5fcd4bb082 updated unicorn 2020-06-07 00:41:46 +02:00
a1aef91e39 Merge pull request #395 from toralf/dev
unicorn_mode/samples/persistent/harness.c: fix comment
2020-06-06 16:53:43 +02:00
c2c128dd67 unicorn_mode/samples/persistent/harness.c: fix comment
Signed-off-by: Toralf Förster <toralf.foerster@gmx.de>
2020-06-06 16:41:40 +02:00
372206e159 aflpp_debug 2020-06-06 11:45:08 +02:00
c036108b59 Merge pull request #394 from devnexen/libtoken_api_nbsd_upd
libdislocator, adding subset of specific NetBSD api.
2020-06-05 17:50:52 +02:00
b5c77cf4f6 libdislocator, adding subset of specific NetBSD api. 2020-06-05 15:32:27 +01:00
2b33be939a fix qemu mode 2020-06-05 09:55:22 +02:00
e01cad2f7d qemu debug 2020-06-05 09:42:17 +02:00
a1beb72cad qemu_mode: fix error handling of mmap 2020-06-04 22:27:46 +02:00
a9348e0acc fix cmplog for shmem persistent mode 2020-06-04 16:31:53 +02:00
9a1e22afab typo 2020-06-04 15:31:27 +02:00
855ee06247 add afl-ld-lto for LTO 2020-06-04 13:57:16 +02:00
f1ad9bdaea fix 2020-06-04 09:10:58 +02:00
2f73215d4f update libfuzzer driver 2020-06-04 08:53:05 +02:00
155405e0d0 Merge branch 'master' into dev 2020-06-04 03:18:41 +02:00
88e83c7322 code format 2020-06-04 02:53:24 +02:00
35ddec7aeb fix shmem persistent mode 2020-06-04 02:37:05 +02:00
e11922e5cc adapted unicornafl to new shmap 2020-06-03 19:27:59 +02:00
a79c002145 Merge pull request #390 from devnexen/obsd_no_retpoline
OpenBSD build update and llvm mode fix
2020-06-03 18:32:44 +02:00
ea91cfdf9a fix shmem 2020-06-03 18:09:06 +02:00
031e4300a5 switch order of shmem fuzz 2020-06-03 16:19:09 +02:00
dd0ca7335f switch shmem_len to the map 2020-06-03 15:49:23 +02:00
686d8823eb OpenBSD: add missing limits.h header for PATH_MAX 2020-06-03 17:43:33 +02:00
a5d554c3ef improved unicornafl speed 2020-06-03 15:18:07 +02:00
177db9cf79 no inline in qemu driver 2020-06-03 11:51:35 +02:00
2d8c3d2934 fix conflicts 2020-06-03 11:41:30 +02:00
f1192b2d16 AFL_QEMU_DRIVER_NO_HOOK 2020-06-03 11:38:44 +02:00
fc164e4709 code format 2020-06-03 10:50:49 +02:00
1c95e2e8e0 aflpp libfuzzer driver for qemu mode 2020-06-03 10:34:29 +02:00
9962de1a4c shared mem input for qemu persistent hook 2020-06-03 09:57:44 +02:00
304a72c1ff added shmem support to unicornafl 2020-06-03 02:00:58 +02:00
83112ed5e0 got rid of questionable phrasing 2020-06-02 14:54:24 +02:00
fbd781fc83 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-06-02 14:10:44 +02:00
62306f5ce8 minor fixes 2020-06-02 14:10:40 +02:00
1d15048f2f hopeful finally change for libfuzzer driver 2020-06-01 15:30:44 +02:00
adcffce0a0 fix libfuzzer driver 2020-06-01 14:57:05 +02:00
9a65fe904d small changes to libfuzzer driver 2020-06-01 13:37:50 +02:00
ac998e9222 minimal changes to a test 2020-06-01 13:15:34 +02:00
15c0ad60c5 minimal changes to a test 2020-06-01 13:15:16 +02:00
0de25f08ba code format 2020-06-01 12:30:55 +02:00
bca7ce8043 fixed persistent mode shared mem fuzzing 2020-06-01 12:30:20 +02:00
ee14785f68 starting shmap support for unicorn 2020-05-31 04:13:41 +02:00
c0ed118ba5 comment 2020-05-30 20:38:01 +02:00
0adb664a31 OpenBSD build update and llvm mode fix
Unlike upstream version, LLVM in OpenBSD enable by default anti ROP gadget
 leading to bigger binaries and lower performances.
On OpenBSD, it needs to link to c++ abi for th unwind symbols.
2020-05-30 19:28:47 +01:00
4a54328901 rename var time->time_ms 2020-05-30 17:11:45 +02:00
24508194c2 removed read_timed 2020-05-30 14:03:52 +02:00
95b46b4278 reverted extendended read_timed 2020-05-30 13:53:00 +02:00
b16ccb4811 Revert "code format"
This reverts commit 8f19becb62.
2020-05-30 13:51:29 +02:00
4119752f83 fix forkserver change 2020-05-30 13:37:27 +02:00
b7b5fdf42a fix vor afl-clang 2020-05-30 13:31:10 +02:00
dbd9423fc0 PowerPc support 2020-05-30 11:32:11 +02:00
8f19becb62 code format 2020-05-30 11:05:53 +02:00
38e5c32a55 corrected read_timed for values > 4 2020-05-30 11:02:34 +02:00
0c50945303 update readme 2020-05-30 07:22:51 +02:00
8726d7b0a3 simplified read_timed 2020-05-30 06:51:51 +02:00
408ef5298b Merge pull request #383 from dgmelski/fix-read-timed
Fix read_timed when accumulating short reads
2020-05-29 18:58:25 +02:00
2ce243bc6e whitelist wildcard for LTO 2020-05-29 16:27:01 +02:00
255594ba3a Merge pull request #385 from sirmc/dev
Support UNIX-style wildcards in AFL_LLVM_WHITELIST file
2020-05-29 16:21:54 +02:00
8bb0232ace Remove AFL_LLVM_WHITELIST_FNMATCH env variable 2020-05-29 15:47:34 +02:00
e3efacaae6 Merge pull request #386 from AFLplusplus/dev
code format
2020-05-29 14:44:04 +02:00
a550df4301 code format 2020-05-29 14:43:03 +02:00
710dda5221 Merge pull request #374 from AFLplusplus/dev
Dev
2020-05-29 14:35:05 +02:00
c3b864d8d4 add Perl dictionaries from RootUp 2020-05-29 12:55:46 +02:00
6892018142 Revert "perl.dict"
This reverts commit 4ad3144f50.
2020-05-29 12:48:06 +02:00
84df805ed3 Do clang-format 2020-05-29 12:11:19 +02:00
9c286da29b gcc_plugin: better error message when compiler and plugin versions do not match 2020-05-29 12:10:45 +02:00
92b7974f44 .gitignore: add *.pyc 2020-05-29 12:07:09 +02:00
38860323de Fix typos in LLVM whitelist README 2020-05-29 12:01:06 +02:00
8316425375 Add AFL_LLVM_WHITELIST_FNMATCH env var
Only enable UNIX pattern matching on the whitelist when
AFL_LLVM_WHITELIST_FNMATCH is set. The reason being that we keep
backwards compatibility with old whitelists.
2020-05-29 11:55:02 +02:00
0cedc8014b Support filename pattern matching in whitelist
Allow the whitelist specified by AFL_LLVM_WHITELIST contain entries with
UNIX shell-style wildcard pattern matching.
2020-05-29 10:51:34 +02:00
8aae1fc5d7 Merge pull request #384 from RootUp/patch-4
Grammar for fuzzing Perl
2020-05-29 10:14:33 +02:00
4ad3144f50 perl.dict 2020-05-29 10:55:35 +04:00
4b01d594c4 Fix read_timed when accumulating short reads
The existing code appears to use 'len_read' in several places where
'total_read' was intended.  The function may work if the first 1 or 2
iterations of the loop read the requested 'len' bytes.

If the first two reads are "short" and a third read is done, the bytes
will be placed over previously read bytes in buf and more than 'len'
bytes may be read in total, though buf is never overrun.

This commit changes read_timed to

  (1) correctly append short reads in buf
  (2) correctly terminate when the sum of the short reads
      equals the requested 'len' bytes
  (3) return an error when read() returns -1 or 0

The function also depends on select() decrementing the timeout
structure, as it does on Linux.  On other platforms, the exec_ms
returned is likely incorrect.  This patch does not attempt to address
this issue.
2020-05-28 20:25:30 -04:00
5e4cd05e04 Merge pull request #382 from ivachyou/master
change qemu-mode AFL_REGS_NUM to 16 for TARGET_ARM
2020-05-28 23:35:55 +02:00
7cf01b10b7 Delete action.yml 2020-05-29 04:28:32 +07:00
eb7d1e22e5 simplify u64 2020-05-28 22:56:15 +02:00
0555b26161 Merge pull request #375 from risicle/ris-llvm-compare-transform-var-sized-dev
llvm_mode compare-transform-pass: add handling of sized comparisons with non-const size
2020-05-28 22:47:13 +02:00
bb0a31158a test.sh OpenBSD6.7, 32bit: add 'i386' to known intel strings 2020-05-28 22:24:06 +02:00
bfd2b6298e OpenBSD6.7, 32bit fix add linker option -z notext 2020-05-28 22:23:30 +02:00
b87d97aa2b make dockerfile better 2020-05-28 14:34:50 +02:00
48b2028af8 remove actions, we do this via docker hub 2020-05-28 12:22:28 +02:00
92be4ea871 change qemu-mode AFL_REGS_NUM to 16 for TARGET_ARM 2020-05-28 16:42:38 +07:00
8a2656681f GNUmakefile: make binary-only: make qemu build optional, so unicornafl can be build 2020-05-28 08:27:21 +02:00
5671cae225 actions 2020-05-28 02:41:27 +02:00
ef8d252843 fix Dockerfile 2020-05-28 01:29:57 +02:00
af670ca138 enable snapshot lkm for llvm_mode persistent mode 2020-05-27 17:17:33 +02:00
aace0d1192 code format 2020-05-27 11:28:29 +02:00
cee4b4593b Merge pull request #379 from arnow117/master
Fix MOpt implementation flaws
2020-05-27 11:27:11 +02:00
434ccf3df4 allow for copy paste from documentation 2020-05-27 11:24:09 +02:00
b81df11d8a fix 64bit support for powerpc, risc, etc. 2020-05-27 11:07:54 +02:00
dab498c3b7 fix MOPT implementation flaws in core fuzzing 2020-05-27 16:01:44 +08:00
d5bb9731fe Revert "libfuzzer driver, better rt compilation"
This reverts commit 46a0f812b1.
2020-05-26 17:41:24 +02:00
9dd0b7c6de make examples better 2020-05-26 15:57:15 +02:00
1cae68dde3 persistent mode shared memory fuzzing - done 2020-05-26 15:20:42 +02:00
996e1515b3 better performance compilation options for afl++ and targets 2020-05-26 13:19:57 +02:00
f6808158c5 llvm_mode compare-transform-pass: add handling of sized comparisons with non-const size
this involved insertion of an extra length-checking bb for each character
to see if we've hit the sized limit.
2020-05-25 23:38:45 +01:00
7e4c5b3636 tests: add test of compiled compcov binary's functionality 2020-05-25 23:38:45 +01:00
0994972c07 more performance testing 2020-05-25 22:19:50 +02:00
a0da531170 libfuzzer driver + llvm_mode compilation optimization 2020-05-25 22:09:00 +02:00
46a0f812b1 libfuzzer driver, better rt compilation 2020-05-25 21:58:00 +02:00
de78f867a4 Changelog: typos 2020-05-25 18:16:37 +02:00
707145c491 persistent mode: shared memory test case transfer 2020-05-25 16:40:55 +02:00
1e597a64dc llvm_mode compare-transform-pass: refactor comparison length determination
make this clearer and handle case with embedded null characters in
const string properly
2020-05-25 13:53:17 +01:00
4c394a9d7b new todo 2020-05-25 10:57:15 +02:00
3eef1560a2 remove not needed error description 2020-05-25 09:14:30 +02:00
fc574086ec fix cmplog 2020-05-24 15:15:17 +02:00
68e66fa920 fix compare-transform for strn?casecmp 2020-05-24 01:59:08 +02:00
38df6eb3a9 LTO whitelist functionality rewritten, now anything can be skipped 2020-05-23 17:00:02 +02:00
0245f8438d forkserver: missing space in message 2020-05-23 08:15:20 +02:00
d7ea8356a7 installing llvm 11 2020-05-23 01:53:42 +02:00
c64ea49432 AFL_LLVM_LAF_ALL 2020-05-23 01:37:21 +02:00
38fe1c6066 more help for LTO issues 2020-05-22 20:59:32 +02:00
74f01881e3 small enhancements for llvm11 2020-05-22 16:56:05 +02:00
0f8da71588 more test.sh fixes 2020-05-22 13:50:39 +02:00
7d3cfcfd0b more test.sh fixes 2020-05-22 13:49:50 +02:00
536397b22f travis debug 2020-05-22 13:31:16 +02:00
6253bea73c fix test.sh 2020-05-22 12:51:21 +02:00
a5ef93c83a fix cmplog for llvm 11-dev 2020-05-22 11:42:04 +02:00
5b9dfa0600 fix llvm_mode selection 2020-05-22 11:22:30 +02:00
5d0bcf8152 switching llvm_mode default to pcguard 2020-05-22 10:24:00 +02:00
83007f77f5 update docs 2020-05-21 10:31:37 +02:00
c456e20750 better sync - lesser and better imports 2020-05-20 23:12:33 +02:00
982017a2ab remove master file on exit 2020-05-20 22:52:33 +02:00
3b4cd98498 add local include paths for DronFlyBSD 2020-05-19 17:57:56 +02:00
0ed767fac5 forgot the unlink ... 2020-05-19 19:54:10 +02:00
25fbec6638 if no master is present a slave becomes a temporary master 2020-05-19 19:51:54 +02:00
ae6c30a711 upgrade Dockerfile to Ubunutu 20.04 with llvm 11 and gcc 10 for afl-clang-lto 2020-05-19 19:22:11 +02:00
c7b1ed2395 Merge pull request #367 from devnexen/example_network_build_fix
Build fix proposal mainly for Android which did not bother
2020-05-18 22:51:15 +02:00
5d0f020648 Build fix proposal mainly for Android which did not bother
implementing this dinosaur.
2020-05-18 21:44:27 +01:00
74e6fbab82 update changelog 2020-05-18 12:26:40 +02:00
30824bc58e afl-as fast system fix 2020-05-18 10:48:39 +02:00
d146965025 Update Changelog.md 2020-05-17 21:43:33 +02:00
e1e155022f adjust documentation for new minimum llvm version 3.4 2020-05-17 21:35:10 +02:00
d37a8f72d6 fix master creation file 2020-05-17 01:36:03 +02:00
9dd3e3e38a fix -M check 2020-05-17 00:13:55 +02:00
b927b80e10 GNUmakefile: add paths for FreeBSD 3rd party packages 2020-05-16 20:30:07 +02:00
af6736c356 dictionary files: fix missing newlines 2020-05-16 13:16:37 +02:00
6e98b3ebb2 non GNU Makefiles: message when gmake is not found, gcc_plugin portability 2020-05-16 12:15:03 +02:00
afb81b8005 added lots of dictionaries 2020-05-16 11:17:36 +02:00
2b922e9e68 fix possible null ptr deref in afl-prealloc.h 2020-05-15 17:07:30 +02:00
57637ba0b0 removed overlooked post_lib references, added post_lib examples to examples/custom_mutators 2020-05-15 13:39:42 +02:00
d536ddc240 change: slaves only sync from masters 2020-05-15 09:27:15 +02:00
564399bd75 v2.65d init 2020-05-15 09:04:55 +02:00
87a693d1a9 Merge pull request #360 from AFLplusplus/dev
new code formatting + applied
2020-05-15 08:36:51 +02:00
49bd24144a v2.65c 2020-05-15 08:35:46 +02:00
182b8a4582 llvm_mode: lower llvm version reqs to 3.4 (LLInsTrim will not be
available)
2020-05-15 01:55:33 +02:00
97bddc8cfa added critical whitespace 2020-05-15 01:52:56 +02:00
a55e26959b fixed recursive clean 2020-05-15 01:31:02 +02:00
63e2222af1 code format 2020-05-15 01:24:27 +02:00
9637fe8a74 travis for focal 2020-05-15 00:58:17 +02:00
c084458294 updated 20.04 Dockerfile 2020-05-15 00:51:57 +02:00
498e9f4298 adding 20.04 test 2020-05-14 23:54:07 +02:00
13033034db nuicornafl build script fix setuptools check 2020-05-14 23:23:55 +02:00
749c63d3b3 removed accidental shell injection 2020-05-14 22:39:11 +02:00
73c2619c33 .gitignore: better be explicit 2020-05-14 22:30:44 +02:00
65f9553365 unicorn mode may run scripts 2020-05-14 22:25:50 +02:00
3f621c8ed4 update .gitignore 2020-05-14 21:57:32 +02:00
11f3b487ee corrected info about python 2020-05-14 21:51:51 +02:00
4c253aedae use --python flag to point to python executable for qemu build 2020-05-14 21:49:36 +02:00
efdad526ee darn IDE 2020-05-14 21:49:36 +02:00
4081a8f7b6 should install python3 setuptools here too 2020-05-14 21:49:36 +02:00
867f948bb2 create temp symlink to python3 for qemu mode if python isn't found 2020-05-14 21:49:36 +02:00
767ed8c5da add python setuptools to travis builds 2020-05-14 21:49:36 +02:00
f0aadc3d0b qemu build expects python on PATH 2020-05-14 21:49:36 +02:00
d95c4483fd correct binary already chosen before 2020-05-14 21:49:36 +02:00
00a147b244 info about py3 setuptools 2020-05-14 21:49:26 +02:00
74eae83b54 use only python3 in new builds 2020-05-14 21:47:04 +02:00
324b44872c unicornafl: python/module check with faster method 2020-05-14 21:13:36 +02:00
94a1d4d3ac test unicornafl: copy from build script 2020-05-14 20:32:04 +02:00
a3392007cd next try 2020-05-14 20:30:00 +02:00
4ac06a4eef and more 2020-05-14 20:10:10 +02:00
0495ded87d unicornafl build script more debug 2020-05-14 19:58:32 +02:00
64b80b3201 unicornafl build script: debugging version for travis 2020-05-14 19:23:07 +02:00
fa20eb1de7 GNUmakefile: add standard path for NetBSD, test for git and svn before use 2020-05-14 18:47:44 +02:00
ae15803bf1 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-05-14 18:41:44 +02:00
9e375179d8 test.sh: make sure the right python version (with setuptools available) is being used 2020-05-14 18:40:26 +02:00
460760d7b6 unicornafl build script: find matching python and setuptools 2020-05-14 18:00:48 +02:00
682b620922 fix afl-clang-fast help output 2020-05-14 16:25:07 +02:00
6b69cd2e57 Makefile: for convenience forward targets to GNUmake 2020-05-14 09:00:17 +00:00
56a86bb9e2 added unicornafl fix info 2020-05-14 01:35:35 +02:00
00ad2ffc61 unicornafl version 2020-05-14 01:33:03 +02:00
a16e92800d prefer python3 2020-05-14 01:20:33 +02:00
7c9ff4bfe7 if target crashes add LTO fixed map as a possible reason 2020-05-14 01:12:00 +02:00
d334093606 deprecated AFL_POST_LIBRARY 2020-05-14 01:00:11 +02:00
044bd3cb41 init/deinit need to be optional for post lib 2020-05-13 18:58:32 +02:00
4e192db13c better clean 2020-05-13 18:24:01 +02:00
8cc5442401 fix GNUmakefile 2020-05-13 18:20:06 +02:00
bd94d5fce7 unicornafl build script: python version is critical 2020-05-13 17:39:00 +02:00
b6be906082 GNUmakefile: avoid tabs 2020-05-13 17:03:59 +02:00
60a5df5262 code-format and slight -S/-M modifications 2020-05-13 16:49:00 +02:00
c384a17b41 GNUmakefile: add paths /usr/local/... for OpenBSD, add check for ASAN 2020-05-13 16:42:20 +00:00
6fdd6004f2 unicornafl build script: fix sed call for OpenBSD, use present python
bug fixes:
2020-05-13 16:39:25 +00:00
c4fe6f5277 Merge pull request #361 from rish9101/pre_save_format
Add post library API as custom mutator and rename pre_save
2020-05-13 16:39:23 +02:00
645e331559 Fix previous commit bugs 2020-05-13 19:46:30 +05:30
45bddcd808 Fix bugs, remove intial post library test 2020-05-13 19:25:23 +05:30
9627458ecc Add post library API as custom mutator and rename pre_save 2020-05-13 18:59:12 +05:30
f8b3d34225 move has_new_bits for better performance 2020-05-13 00:41:24 +02:00
5273c61cd8 Darwin tests: grep --binary-files=text for laf-intel and skipping of unittests 2020-05-12 23:19:51 +02:00
0c1c947aaf updated uc ref 2020-05-12 22:42:41 +02:00
6224ae1c60 test/test.sh: prefer python3 over python for unicornafl, avoid realpath and readlink dependencies 2020-05-12 20:59:48 +02:00
72f4a9f678 missing env var 2020-05-12 19:40:04 +02:00
060f4ea320 enforce mandatary custom functions 2020-05-12 17:05:12 +02:00
6177954773 fix custom mutators and add real test cases 2020-05-12 16:32:40 +02:00
7b40d7b942 new code formatting + applied 2020-05-12 11:12:25 +02:00
1317433a51 Merge pull request #359 from AFLplusplus/dev
push to master
2020-05-12 11:04:18 +02:00
a578d719e1 llvm_mode: more support for Darwin/MacOSX (WIP) 2020-05-12 10:34:52 +02:00
8bb10c3bf1 fix issue in describe_op showing time inside src 2020-05-12 09:20:02 +02:00
b920cd2f23 blacklist llvmfuzzer functions 2020-05-11 23:30:28 +02:00
38dac93f63 fix typos 2020-05-11 22:44:44 +02:00
6f66be12f6 merge makefile 2020-05-11 15:30:00 +02:00
4ee93331dc updated unicornafl 2020-05-11 15:11:11 +02:00
30a675ab87 silened warnings 2020-05-11 14:40:42 +02:00
845522f59b remove warnings 2020-05-11 13:34:57 +02:00
f37be09a92 fixed unicornafl bug 2020-05-11 13:18:06 +02:00
ed877f5e3e add missing include 2020-05-11 12:46:27 +02:00
d916403927 document workaround for targets with _init for LTO 2020-05-11 11:33:33 +02:00
41f6aa7940 bigger initial map when LTO 2020-05-11 10:45:20 +02:00
50a63777ec python formatter: enhance detection of #define, needed for multi line macros
@andreafioraldi : please have a look at it. Goal is to detect forms of ' # define' also.
2020-05-11 10:12:32 +02:00
26fe7a9d66 final code-format fixes, remove test-multiple-mutators when done 2020-05-10 15:53:47 +02:00
07a0e2caf7 hopefully final fixes from code-format disaster :-( 2020-05-10 15:36:46 +02:00
30bfd44dfd indenting preprocessor directives breaks compilation and cant be fixed, reverting ... :-( 2020-05-10 12:09:37 +02:00
26f8708fed fix warning, code format 2020-05-10 11:35:31 +02:00
3beec8d4fa clang-format: indent preprocessor directives, so nesting levels can be better seen 2020-05-10 11:11:40 +02:00
2e553bcd69 code-format 2020-05-10 10:24:24 +02:00
0e5a5f1805 Merge pull request #358 from rish9101/update_docs
Specify usage of multiple custom mutators
2020-05-10 08:59:36 +02:00
d02cfc54b6 LTO fixes for fuzzbench 2020-05-10 08:51:40 +02:00
7b9ac9d414 Specify usage of multiple custom mutators 2020-05-10 12:21:19 +05:30
515de0d68d Illumos biuld fix (#357) 2020-05-10 00:21:26 +02:00
1eeb6785ad Merge pull request #356 from devnexen/netbsd_build_fix_tokencap
NetBSD build fix
2020-05-09 20:39:18 +02:00
20392878f1 qemu_mode: make building warning free 2020-05-09 20:02:32 +02:00
102067d43d LLVMInsTrim.so.cc: fix for LLVM 3.8.0 2020-05-09 19:08:54 +02:00
6c88e21459 NetBSD build fix 2020-05-09 18:02:53 +01:00
041f19494e minor fixes 2020-05-09 18:51:33 +02:00
8e9f507bbc unicorn_mode/samples/persistent/Makefile: fix non-Linux support 2020-05-09 18:49:32 +02:00
c380819e02 remove debug output 2020-05-09 11:58:47 +02:00
fa84e52af0 custom mutator code enhancements and code-format 2020-05-09 11:35:54 +02:00
cf9238e09d Update docs and Changelog for custom_mutators (#355) 2020-05-09 00:01:11 +02:00
190f3024da Support multiple custom mutators (#282)
* Make a list of custom mutators using env variable

* Set up multiple custom mutators

* Add destroy custom mutator and changes to load_custom_mutator

* Use array instead of list, make changes to afl-fuzz-one for multiple mutators

* Make change to fuzz-one custom_queue_get to support multiple mutators

* Modify custom python mutator support

* Fix bug

* Fix missing afl->mutator->data

* Revert to list with max count

* Change custom_pre_save hook and code format

* Free custom_mutator struct in the list

* Add testcase for multiple custom mutators

* Resolve merge conflict
2020-05-08 20:08:27 +02:00
768053b6f2 add AFL_DEBUG check to all isatty checks 2020-05-08 16:28:39 +02:00
bdd2a412c4 change docs/README.md to symlink to toplevel README.md 2020-05-07 18:47:23 +02:00
d217c7df05 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-05-07 18:33:38 +02:00
9484da57ed convert docs/README.md into a symlink to toplevel README.md (helps website content) 2020-05-07 18:32:36 +02:00
ef2ccc8117 added AFL_LLVM_SKIPSINGLEBLOCK and changed default behaviour to instrument single block functions 2020-05-07 14:59:12 +02:00
02887dc164 fix static and profiling compilation and add profiling calculation 2020-05-07 14:09:58 +02:00
d048af11cd calculate correct collisions for classic in InsTrimLTO 2020-05-07 11:57:12 +02:00
0559d1d171 fix typos 2020-05-07 10:27:24 +02:00
37b681ac11 untracer README: one typo fixed 2020-05-07 10:09:08 +02:00
f065ddbdb2 Merge pull request #354 from jtpereyda/readme-apt-flex
add flex to apt install list
2020-05-07 09:31:00 +02:00
140053502b import transform fix into autodict, code-format 2020-05-07 08:08:20 +02:00
58fad91b0b add flex to apt install list 2020-05-06 16:00:23 -07:00
01b5aa123d better README for untracer 2020-05-06 17:20:42 +02:00
8cdf767bf5 doc update 2020-05-06 15:57:38 +02:00
e910882e32 fix untracer 2020-05-06 15:43:39 +02:00
a1c9c497d5 aarch64 support for afl-untracer 2020-05-06 15:37:49 +02:00
a63c838b10 make build options for qemu more visible 2020-05-06 14:16:19 +02:00
b7e574607c rename pass 2020-05-06 13:27:12 +02:00
10e6b4e454 fix STATIC compilation 2020-05-06 13:24:18 +02:00
ec5b1924c4 CTX+NGRAM != LTO 2020-05-06 11:55:50 +02:00
80ddb484de added InsTrimLTO :-) 2020-05-06 11:51:28 +02:00
cafb2e540e Merge pull request #353 from AFLplusplus/dev
update llvm version in README
2020-05-06 01:04:37 +02:00
b4e3f22259 update llvm version in README 2020-05-06 01:04:13 +02:00
df52157834 Merge pull request #352 from AFLplusplus/dev
Pull to master because of crash in string compare transform
2020-05-06 00:58:13 +02:00
a13958b32b updated unicornafl 2020-05-05 23:44:02 +02:00
a31b58eeea add one more alternative to python requirements: python-dev 2020-05-05 22:59:26 +02:00
e31b816aa0 fix unit tests when printf is a macro 2020-05-05 22:46:48 +02:00
0e5027d8d8 maybe_grow->ck_maybe_grow 2020-05-05 21:46:31 +02:00
dc79533191 more typos fixed 2020-05-05 20:29:40 +02:00
128e4d5565 more typos fixed 2020-05-05 20:23:16 +02:00
ad3960580d fixed typos 2020-05-05 20:19:04 +02:00
00683d06c2 fix LTO mode 2020-05-05 20:10:54 +02:00
a38980c80b unsized string compare fix 2020-05-05 17:57:56 +02:00
664a180d72 cleanup todo list 2020-05-05 15:39:15 +02:00
d6346561db ctx+ngram for instrim 2020-05-05 15:37:02 +02:00
d82ada89fe support older llvm versions 2020-05-05 14:08:24 +02:00
9d384b4e38 ctx and ngram fix 2020-05-05 12:46:49 +02:00
6e45e55d82 fix crash in AFL_LLVM_LAF_TRANSFORM_COMPARES 2020-05-05 10:38:44 +02:00
ecaccd9739 Merge pull request #351 from dpmdpm2/master
Fix typo in README.lto.md
2020-05-04 21:02:49 +02:00
95a2d49232 Fix typo in README.lto.md 2020-05-04 11:34:07 -07:00
16c16b3e6e ctx and ngram can be used together now 2020-05-04 18:01:47 +02:00
945e00b73f final touches for afl_network_proxy 2020-05-04 12:51:38 +02:00
e592b4bcf0 nw fixes 2020-05-04 10:37:45 +02:00
96ef2d3821 makefile fix 2020-05-04 10:24:29 +02:00
2d126dc750 Fix Unicorn support build script (#349)
* Fix Unicorn support build script for WSL.

Co-authored-by: Dominik Maier <domenukk@gmail.com>
2020-05-04 10:14:49 +02:00
13a32e9595 fix makefile 2020-05-04 10:08:29 +02:00
73f7164048 add GNUmakefile 2020-05-04 09:53:59 +02:00
5b1b986c89 fix for afl-tmin -f 2020-05-03 14:19:03 +02:00
1c53bbea52 doubled the speed of afl_network_proxy 2020-05-03 14:09:32 +02:00
0c5c172a30 makefile fix 2020-05-02 12:57:33 +02:00
ff1643d81f todo update 2020-05-02 00:43:33 +02:00
378573ab8b AFL_LLVM_SKIP_NEVERZERO added 2020-05-02 00:39:13 +02:00
33ddf6ea0e add ghidra script and workaround ghidra/linux/ida weirdness 2020-05-01 17:07:44 +02:00
a2bc3538f7 python no longer needed for build 2020-05-01 12:03:41 +02:00
636e98d151 Merge remote-tracking branch 'origin/master' into dev 2020-05-01 02:13:24 +02:00
9f01737fa7 updated unicorn 2020-05-01 02:08:04 +02:00
be4e5d2617 minor sample things 2020-05-01 02:07:35 +02:00
cc78fb721b code format 2020-05-01 01:11:54 +02:00
bb7d2a7347 Merge pull request #345 from devnexen/afl_untracer_libs_display
afl-untracer little change to display libraries mapping on FreeBSD.
2020-05-01 01:03:53 +02:00
9d03763d94 at some point we have to do a rewrite of llvm_mode/GNUmakefile 2020-05-01 00:57:20 +02:00
3cf4529f3c afl-untracer little change to display libraries mapping on FreeBSD. 2020-04-30 23:01:46 +01:00
477fb58311 Merge pull request #344 from devnexen/afl_untracer_fbsd
afl-untracer raw freebsd support.
2020-04-30 23:38:01 +02:00
59043b24cc afl-untracer raw freebsd support. 2020-04-30 21:31:37 +01:00
15547eb654 fix send child status 2020-04-30 21:17:13 +02:00
16f9cc7369 afl-network-client fix 2020-04-30 21:13:45 +02:00
efa9df24c2 afl-untracer completed 2020-04-30 17:59:59 +02:00
a37eca9df5 afl-untracer - next step 2020-04-30 16:27:31 +02:00
e68d2345d5 test.sh: continue after failed test case qemu persistent mode 2020-04-29 22:25:10 +02:00
fced3e00ce wip: afl-untracer 2020-04-29 20:44:30 +02:00
c53663c7ac afl-proxy -> afl_proxy 2020-04-29 15:21:51 +02:00
bc2e65e482 added afl_network_proxy 2020-04-29 15:18:03 +02:00
ce2814967d add readme for afl-proxy 2020-04-29 02:56:51 +02:00
781725aeaf added afl-proxy to examples 2020-04-29 02:54:57 +02:00
9276dc9e6c fix #329 2020-04-28 10:55:22 +02:00
c7de368dc2 Merge pull request #342 from AFLplusplus/dev
fix for afl-showmap with -Q
2020-04-27 22:12:56 +02:00
fbd9994f6f better fix for showmap 2020-04-27 22:11:58 +02:00
087c368242 better fix for showmap 2020-04-27 22:10:08 +02:00
a56354a893 fix for afl-showmap with -Q 2020-04-27 19:30:32 +02:00
a5d4c8d532 Merge pull request #340 from AFLplusplus/dev
dev -> master
2020-04-27 12:12:43 +02:00
a46fe3ad43 fix for older llvm versions 2020-04-27 06:51:45 +02:00
4ffa5b0636 fix negative stability bug (hopefully) 2020-04-26 18:42:42 +02:00
62ec52dd95 Merge pull request #336 from AFLplusplus/dev
pull again ...
2020-04-26 16:51:21 +02:00
ea876e59a8 moved defines to type 2020-04-26 14:45:00 +02:00
66eee34709 refactored global lists 2020-04-26 02:32:09 +02:00
85627516a4 map_size one liner 2020-04-26 02:05:17 +02:00
b26ee09f71 minor fixes 2020-04-26 01:59:38 +02:00
fb89b042f8 Merge pull request #337 from devnexen/android_support_arc4_api
Android supports arc4 api.
2020-04-26 01:25:39 +02:00
646aeb2b18 try unicorn build without -j 2020-04-26 00:54:02 +02:00
2a60ceb694 fix issue #333 2020-04-25 21:29:19 +02:00
80916a3613 Android supports arc4 api. 2020-04-25 20:17:10 +01:00
0c3d06c41e refactored whitelist and blacklist in llvm_mode 2020-04-25 17:53:38 +02:00
07db922024 add to changelog 2020-04-25 13:09:27 +02:00
fa610270ab remove empty line 2020-04-25 13:08:42 +02:00
cefefba244 Merge branch 'master' into dev 2020-04-25 13:05:25 +02:00
42017bbeda fix python detection for Ubuntu and others 2020-04-25 12:57:45 +02:00
a3ee281e2b fix python detection for Ubuntu and others 2020-04-25 12:55:01 +02:00
232290108e only build afl-gcc-fast if afl-gcc-pass could be build 2020-04-25 12:51:14 +02:00
5c017d7071 travis Dockerfiles for testing and debugging 2020-04-25 12:48:48 +02:00
62aacf88ab fix simple names 2020-04-24 23:26:38 +02:00
b3e77d3d50 update documentation 2020-04-24 13:56:04 +02:00
766085293d variable map size fix, error reporting through forkserver, code format 2020-04-24 12:09:25 +02:00
4a593d0405 Merge pull request #331 from Mindavi/feature/fail-on-invalid-binary-name
afl-gcc and afl-clang: fail when binary name can't be used to determine build mode
2020-04-24 10:32:00 +02:00
82b6b8c87e afl-gcc and afl-clang: fail when binary name can't be used to determine build mode
This is a continuation of PR #318.
The goal is to prevent issues where binaries with the wrong name will
silently pass control to the C compiler instead of failing.
This makes it more explicit that aflplusplus relies on the name of the
binary for correct compiler execution.
2020-04-23 23:21:38 +02:00
b6f9f4c436 minor changes 2020-04-23 16:08:36 +02:00
b120ca27f8 add documentation for LTO fixed map address feature 2020-04-23 12:20:58 +02:00
5eb1f3a4c6 use mmap in llvm_mode if LTO is enabled 2020-04-23 12:02:15 +02:00
8ada9d06e8 fix make clean error 2020-04-23 11:51:32 +02:00
cce8c4dbae fixed map location support for LTO 2020-04-23 08:56:06 +02:00
3502db1ac5 more sanitizer functions for blacklist 2020-04-23 07:28:25 +02:00
df8a0e8418 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-04-22 13:51:40 +02:00
b8a25063f6 fix sed errors in afl_shm_init when using mmap 2020-04-22 13:51:36 +02:00
6df21f3489 GNUmakefile/unit tests: suppress compilation commandline output 2020-04-22 08:40:04 +02:00
dcba2c3642 test.sh: custom mutator test; make it compilable with available instrumenting
compiler
2020-04-22 08:02:46 +02:00
059c963467 unicornafl build script: fix prerequisite search for setuptools 2020-04-21 23:15:25 +02:00
ce9c6df456 libdislocator android build fix. (#327)
Fix function signature for bionic libc
2020-04-21 13:14:34 +02:00
0aef3b4040 add NULL check to malloc_usable_size 2020-04-21 13:14:34 +02:00
4cc0589440 unicornafl updated 2020-04-21 13:14:34 +02:00
96722083d8 add line 2020-04-21 13:14:34 +02:00
ee238eb00d Move comment about adding 8 bytes to buffer length to the line where we
actually add 8 bytes
Remove defunct TODO for posix_memalign as the function now exists
Add wrapper for malloc_usable_size
2020-04-21 13:14:34 +02:00
45ccc7d475 script to update uc refs; new unicornafl version 2020-04-21 13:14:34 +02:00
a32d2ad193 removed done todo 2020-04-21 13:14:34 +02:00
f25919ad56 dont error on git reset 2020-04-21 13:14:34 +02:00
ae524d856d clang warning fixed 2020-04-21 13:14:34 +02:00
9be4f9c055 code format 2020-04-21 13:14:34 +02:00
40e5b285f2 updated unicorn 2020-04-21 13:14:34 +02:00
3ca787ba76 wording 2020-04-21 13:14:34 +02:00
137b9ecf5e double include removed 2020-04-21 13:14:34 +02:00
2509624add android ashmem fix 2020-04-21 13:14:34 +02:00
8c6fcd98be reset git on deepclean 2020-04-21 13:14:34 +02:00
7dc825dbe9 typo 2020-04-21 13:14:34 +02:00
6b3336d107 switched to clang-format-10 2020-04-21 13:14:34 +02:00
ceeb266273 clean and deepclean Makefile updates 2020-04-21 13:14:34 +02:00
9bb0733eb5 clang-tidy readability-braces (#323) 2020-04-21 13:14:34 +02:00
22cdad2d20 make clean removes unicornafl dir if not in git 2020-04-21 13:14:34 +02:00
8b3befea6d update documentation 2020-04-21 13:14:34 +02:00
5b9928f1a9 fix some gcc dependencies and build problems on debian 32-Bit,
adapted qemu_mode AFL_ENTRYPOINT test case for 32 bit
2020-04-21 13:14:34 +02:00
856a59901e no need to rm folder 2020-04-21 13:14:34 +02:00
19d0961020 clean doesn't fail without unicornafl 2020-04-21 13:14:34 +02:00
3bd5e65edc clean no longer deletes unicornafl folder 2020-04-21 13:14:34 +02:00
b520046ab6 fix submodule 2020-04-21 13:14:34 +02:00
d22550a520 git for travis? 2020-04-21 13:14:34 +02:00
6f994ec56b fix compilation on Debian 32-bit (thanks to Marc) 2020-04-21 13:14:34 +02:00
09c8e40363 better detection of intel cpu on 32-bit Linux 2020-04-21 13:14:34 +02:00
8e44c06a13 fix docs typos 2020-04-21 13:14:34 +02:00
358f17f615 small portability fix (32-bit) for warning (size_t %lu -> %zu) 2020-04-21 13:14:34 +02:00
b109e31722 submodule path changed 2020-04-21 13:14:34 +02:00
b77458ae81 unicornafl updaetd 2020-04-21 13:14:34 +02:00
cfeb8e83f7 latest unicornafl 2020-04-21 13:14:34 +02:00
0fa9ad46ae added version 2020-04-21 13:14:34 +02:00
cfb11177cd submodule 2020-04-21 13:14:34 +02:00
0a1979fd20 examples Makefiles: silence errors when there is no 32-bit support installed 2020-04-21 13:14:34 +02:00
0dc64b93d8 v2.64d init 2020-04-21 13:14:34 +02:00
f6c9acd518 libdislocator android build fix. (#327)
Fix function signature for bionic libc
2020-04-21 10:17:11 +02:00
68218dd31c Merge pull request #326 from dpmdpm2/master
Add malloc_usable_size to libdislocator.so
2020-04-21 00:07:33 +02:00
441b64b467 add NULL check to malloc_usable_size 2020-04-20 15:00:48 -07:00
8b319969f3 unicornafl updated 2020-04-20 23:49:12 +02:00
41b1787565 add line 2020-04-20 23:27:09 +02:00
e6fccdd9c1 Move comment about adding 8 bytes to buffer length to the line where we
actually add 8 bytes
Remove defunct TODO for posix_memalign as the function now exists
Add wrapper for malloc_usable_size
2020-04-20 14:24:47 -07:00
0ffef8c79d script to update uc refs; new unicornafl version 2020-04-20 23:11:11 +02:00
3d52079a7c removed done todo 2020-04-20 22:18:39 +02:00
e47c29e728 dont error on git reset 2020-04-20 22:14:41 +02:00
280374f739 clang warning fixed 2020-04-20 22:07:47 +02:00
ce15937717 code format 2020-04-20 21:54:55 +02:00
c8f2ba5b49 updated unicorn 2020-04-20 21:40:34 +02:00
3dbfd18f36 wording 2020-04-20 21:18:32 +02:00
4be0ae2008 double include removed 2020-04-20 21:06:16 +02:00
67b39050df android ashmem fix 2020-04-20 21:05:02 +02:00
4ccd8c1400 reset git on deepclean 2020-04-20 21:03:06 +02:00
4f997665f1 typo 2020-04-20 16:10:06 +02:00
b6a15d9719 switched to clang-format-10 2020-04-20 11:32:44 +02:00
e90194093e Revert "fix compilation use CFLAGS_FLTO for afl-gotcpu also (thanks Marc)"
This reverts commit b408fdffcc.
2020-04-20 07:58:48 +02:00
4c90293e44 clean and deepclean Makefile updates 2020-04-19 16:48:42 +02:00
8197e9b2e4 clang-tidy readability-braces (#323) 2020-04-19 16:42:40 +02:00
baec99079f make clean removes unicornafl dir if not in git 2020-04-19 12:30:58 +02:00
16a5e6bf16 update documentation 2020-04-19 10:15:28 +02:00
39f715982d Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-04-19 00:38:57 +02:00
724d4ec3de fix some gcc dependencies and build problems on debian 32-Bit,
adapted qemu_mode AFL_ENTRYPOINT test case for 32 bit
2020-04-19 00:37:23 +02:00
e4670d3abc no need to rm folder 2020-04-18 23:16:00 +02:00
8aa86d063a clean doesn't fail without unicornafl 2020-04-18 22:33:56 +02:00
c1d9e00044 clean no longer deletes unicornafl folder 2020-04-18 22:31:21 +02:00
0827a447d3 fix submodule 2020-04-18 22:10:30 +02:00
2874565b36 git for travis? 2020-04-18 21:28:35 +02:00
8ed3126f28 fix compilation on Debian 32-bit (thanks to Marc) 2020-04-18 20:07:12 +02:00
b408fdffcc fix compilation use CFLAGS_FLTO for afl-gotcpu also (thanks Marc) 2020-04-18 19:54:54 +02:00
d9cd600c1b better detection of intel cpu on 32-bit Linux 2020-04-18 18:39:03 +02:00
68f18923ab fix docs typos 2020-04-18 11:32:06 +02:00
9e74a7dfe1 small portability fix (32-bit) for warning (size_t %lu -> %zu) 2020-04-18 10:48:24 +02:00
0b5b888f82 submodule path changed 2020-04-17 21:52:57 +02:00
46854b439a unicornafl updaetd 2020-04-17 21:44:33 +02:00
8ffed4b859 latest unicornafl 2020-04-17 21:43:55 +02:00
3b8cd9652a added version 2020-04-17 21:43:55 +02:00
269050aee3 submodule 2020-04-17 21:43:55 +02:00
6e753f8f0f examples Makefiles: silence errors when there is no 32-bit support installed 2020-04-17 19:42:03 +02:00
9adcc73d61 v2.64d init 2020-04-17 19:39:32 +02:00
ddea300822 Merge pull request #321 from AFLplusplus/dev
Push for next release
2020-04-17 19:25:34 +02:00
9900c92ebc locked to unicornafl version 2020-04-17 16:28:22 +02:00
0bd1264faf headers for clang-tidy 2020-04-17 14:30:36 +02:00
49753eb2d0 unused var 2020-04-17 14:27:28 +02:00
c9605f2251 ++2.64c 2020-04-17 14:10:18 +02:00
6ee11c2a6f little more speed for queue analysis 2020-04-17 14:08:40 +02:00
ef1d384184 add missing limits.h include for PATH_MAX (OpenBSD) 2020-04-17 13:45:22 +02:00
a6d4f04019 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-04-17 13:30:12 +02:00
87d27b8616 add AFL_NO_PYTHON to list of env variables 2020-04-17 13:29:32 +02:00
f22d8120ef fix afl-showmap for PATH_MAX on *BSD 2020-04-17 13:22:39 +02:00
8ecfbcdf34 removed tmp alloc in queue 2020-04-17 13:15:24 +02:00
263daaacaf remove static from tmp var in qemu 2020-04-17 12:04:16 +02:00
d3254d8066 llvm fix 2020-04-17 12:00:28 +02:00
76e15a0695 refactoring getting the map size 2020-04-17 11:56:08 +02:00
1931838a11 remove unnecessary map_size variables 2020-04-17 11:39:38 +02:00
6bd49b1d5c final fix for map_size 2020-04-17 11:24:40 +02:00
2d4d16755c merged upstream 2020-04-17 11:20:09 +02:00
bfcf6db17a fixes 2020-04-17 11:18:04 +02:00
bda4d8812e forgot MAP_SIZE for afl struct maps 2020-04-17 11:15:04 +02:00
f70d4a6fd4 added bugfix infos 2020-04-17 11:07:03 +02:00
90ff345d73 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-04-17 11:01:20 +02:00
8fa5d4c313 clearer code 2020-04-17 11:01:14 +02:00
2162fd8e1a preliminary stuff for AFL_MAP_SIZE and afl-llvm-pass 2020-04-17 10:46:35 +02:00
248a2f2f0b added AFL_MAP_SIZE to env help output 2020-04-17 10:21:41 +02:00
ef311ec70c done implementing AFL_MAP_SIZE 2020-04-17 10:08:56 +02:00
5b70d23211 added AFL_MAP_SIZE (wip) 2020-04-17 09:10:49 +02:00
16ce555845 fixed 2 unimportant leaks 2020-04-17 07:52:21 +02:00
c961925356 fix plot_data output and code-format 2020-04-17 07:10:42 +02:00
23ea727915 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-04-16 19:53:51 +02:00
f157bca548 fix missing out_fd for cmplog forkserver 2020-04-16 19:53:42 +02:00
35937e6263 leak? 2020-04-16 19:33:40 +02:00
69bd7c16eb silence some clang warnings 2020-04-16 19:15:14 +02:00
6940e13629 removed redundent funcs 2020-04-16 17:50:08 +02:00
380ff114e9 the least radamsa 2020-04-16 16:51:23 +02:00
5e53002303 less radamsa 2020-04-16 16:48:40 +02:00
872d1c1d98 less radamsa 2020-04-16 16:47:53 +02:00
94187837c7 removed unused functions 2020-04-16 16:37:33 +02:00
ede3545d8b missing-decls reremoved 2020-04-16 16:25:02 +02:00
cdac882834 untitest decl 2020-04-16 16:09:52 +02:00
1ee224652c libradamsa fix 2020-04-16 16:05:39 +02:00
8511638afb hunting non-static functions 2020-04-16 15:38:43 +02:00
b10007a7b5 renamed duplicated func names 2020-04-16 15:32:04 +02:00
19ce862810 decoupled run and classify 2020-04-16 15:21:34 +02:00
124665b392 code-format 2020-04-16 14:47:08 +02:00
b420ccdbf8 fixed timeout flag to u32 2020-04-16 14:42:38 +02:00
5e8f385705 revert test.sh changes 2020-04-16 13:24:16 +02:00
dcc889a264 fix travis for cmpcov 2020-04-16 13:11:44 +02:00
f3789801f2 little has_new_bits improvement 2020-04-16 12:09:33 +02:00
0f08b13fa0 somewhat unified write_to_testcase 2020-04-15 23:22:23 +02:00
2ce6e7a7fb fix laf-intel transform disable 2020-04-15 23:01:33 +02:00
83d5864203 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-04-15 22:29:54 +02:00
7e2c52f2b9 disable compare-transform-pass when lto_mode and autodictionary is used. 2020-04-15 22:27:32 +02:00
e88f364282 add new github security writeup 2020-04-15 22:27:20 +02:00
21f696f02e fix document mode 2020-04-15 22:26:30 +02:00
ef1ea07e68 wrong bytes set 2020-04-15 20:22:32 +02:00
0c02a8f4d3 changed run_target 2020-04-15 19:23:26 +02:00
48f7f7a17b afl-clang-fast: fail when binary name can't be used to determine build mode (#318) 2020-04-15 12:08:33 +02:00
115ee8bad5 fix Makefile for examples/argv_fuzzing and socket_fuzzing 2020-04-14 21:19:03 +02:00
c009896c34 code format 2020-04-14 19:29:18 +02:00
6dc36f1e6e unified forkservered run_target, fixes #308 2020-04-14 19:27:25 +02:00
f4436f118c fixed #317 2020-04-14 17:21:15 +02:00
8440aaea5a Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-04-14 13:02:53 +02:00
0d0338012b one byte cmp in cmplog 2020-04-14 13:02:49 +02:00
5ac1b6e940 status 0 initialized 2020-04-14 13:01:54 +02:00
92aaaef381 code format 2020-04-14 12:42:38 +02:00
2c87e68ad6 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-04-14 12:40:03 +02:00
26e690c220 cmplog loop detection 2020-04-14 12:39:29 +02:00
b63dd7a464 NO_PYTHON documented 2020-04-14 12:07:46 +02:00
d2a7628748 fix travis fails 2020-04-14 11:26:07 +02:00
b1e7b834ac add missing default names for AFL_LLVM_INSTRUMENT 2020-04-14 11:24:53 +02:00
9eb47a924a UR -> rand_below 2020-04-14 10:42:29 +02:00
1d62bf1c37 solve conflicts 2020-04-14 10:12:41 +02:00
982d46e7cb solve conflicts 2020-04-14 10:11:22 +02:00
1fbface656 cmplog is now better 2020-04-14 10:09:03 +02:00
1374e65401 no more waitpid warning 2020-04-13 20:39:52 +02:00
0fab4e1955 c files static 2020-04-13 20:23:24 +02:00
a2574169e2 added NO_PYTHON support 2020-04-13 17:44:48 +02:00
4b88e059ef more robust search for clang for afl-clang-fast 2020-04-13 17:05:43 +02:00
12a7059ae8 added ignore info 2020-04-13 16:58:35 +02:00
a897f355a9 code format 2020-04-13 16:57:41 +02:00
326ab632c3 fixed uaf and warnings 2020-04-13 16:57:19 +02:00
dda096da03 allow -L -1 to enable mopt in parallel to classic mutation 2020-04-13 12:12:27 +02:00
5daec436f9 fix bug forksever fail not detected when using read_timed 2020-04-13 11:43:34 +02:00
033c743a41 fix all cmplog errors 2020-04-13 11:37:48 +02:00
459d8f9ba2 qemu cmplog test.sh 2020-04-13 10:53:37 +02:00
0022cc4782 fix some cmplog refactoring bugs 2020-04-13 10:40:24 +02:00
995e556065 cmplog forkserver tidying 2020-04-13 08:54:59 +02:00
a93268acec update todo 2020-04-12 22:45:54 +02:00
e70c54547e remove warnings with llvm11 2020-04-12 17:23:41 +02:00
7919545499 Better solution for ARM64 build fix (#315) 2020-04-12 16:55:52 +02:00
5a8db5954c update test.sh to new compcov features 2020-04-12 14:38:47 +02:00
ee4e1936d0 build on arm64 fix. tested on Android. (#313) 2020-04-12 14:20:10 +02:00
ec67780854 fix 32/64 bit LTO 2020-04-12 14:04:17 +02:00
aaf8835cdb updated changelog 2020-04-12 12:18:06 +02:00
0a525f768b local/global var for compare-transform-pass and code-format 2020-04-12 12:13:01 +02:00
4ed43b7632 m32/m64 support for LTO and code-format for test/ 2020-04-12 11:00:01 +02:00
5e09e13ece m32/m64 support for LTO and code-format for test/ 2020-04-12 10:58:58 +02:00
eec725a345 add global and local var support to autodictionary 2020-04-12 10:34:03 +02:00
fd63344ffc Fixed qbdi_mode/build.sh script (#311)
Co-authored-by: pyno <pyno@fearless>
2020-04-11 20:04:22 +02:00
90a9f22c3d fix #312 2020-04-11 18:31:46 +02:00
cc3ac932d9 fix -E/-V 2020-04-11 09:16:30 +02:00
d8947d1fa4 add extended forkserver feature to gcc_plugin and qemu_mode 2020-04-11 08:15:42 +02:00
32ba60185e more refactoring and update changelog 2020-04-11 08:02:54 +02:00
8bcfba8231 add missing file 2020-04-11 07:35:54 +02:00
68f269437d Autodictionary (#309)
* lto module clean-up

* step 1/3

* step 1/3 completed

* if tmp is ever made non-static

* parts 2 and 3 - autodictionary is complete

* variable map_size support

* variable map size: changed overlooked functions

* remove debug for autodict

* 64 bit alignment of map size

* fix review comments

* force 64 bit alignment on both sides

* typo

* better map transfer, display snapshot in UI

* update readme
2020-04-11 07:32:42 +02:00
29ee3a1ffc refactored cmplog 2020-04-11 01:09:07 +02:00
39e8b91806 code format 2020-04-10 22:54:31 +02:00
3ab7fcf5dd fixed fauxserver msg 2020-04-10 22:53:59 +02:00
3a509c6168 LTO optimization, variable map size, autodictionary (#307)
* lto module clean-up

* step 1/3

* step 1/3 completed

* if tmp is ever made non-static

* parts 2 and 3 - autodictionary is complete

* variable map_size support

* variable map size: changed overlooked functions

* remove debug for autodict

* 64 bit alignment of map size

* fix review comments

* force 64 bit alignment on both sides

* typo
2020-04-10 22:33:11 +02:00
6dcbc4dff4 void * types in allocs 2020-04-10 21:03:48 +02:00
d928b148d8 tackeled some warnings 2020-04-10 20:57:46 +02:00
3209a9d4e8 removed vla for tmpfile 2020-04-10 20:35:16 +02:00
f0f83bab52 resize fix + code format 2020-04-10 17:47:22 +02:00
6aa6af04ac files opened with fdopen should be closed with fclose 2020-04-10 16:45:45 +02:00
5b977453cb another mem leak fix for master/slave usage 2020-04-10 15:06:31 +02:00
a60e425d39 fix small memory leak for in_place_resume 2020-04-10 14:52:59 +02:00
4e3739cdf2 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-04-10 14:50:05 +02:00
e51b4700e2 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-04-10 14:34:24 +02:00
0b9f7c4c89 added back afl_state_deinit 2020-04-10 14:34:17 +02:00
9dcdbbb649 README: minor additions and typo fixes 2020-04-10 12:07:21 +02:00
ac2f0c9896 remove GNU makefile variants 2020-04-10 11:44:43 +02:00
fbf5e08425 merge PR#306 from neoni (thanks), silence test when bash is not found 2020-04-09 18:11:39 +00:00
df5c264754 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-04-09 16:27:07 +02:00
66f535ad61 check for empty AFL env vars 2020-04-09 16:27:00 +02:00
b8d84ababb lto module clean-up (#303) 2020-04-09 16:27:00 +02:00
b485b7a252 fix compilers for empty AFL_CC/AFL_CXX env 2020-04-09 16:27:00 +02:00
c1395bb543 LTO llvm11 (#302)
* new LTO mode for llvm 11

* remove unneeded afl-ld and env vars
2020-04-09 16:27:00 +02:00
0c2e998f69 2.63d init 2020-04-09 16:27:00 +02:00
504529c3aa fix crash triage example (#304) 2020-04-09 13:46:21 +02:00
1fab45024b check for empty AFL env vars 2020-04-09 13:17:56 +02:00
e354235ebb lto module clean-up (#303) 2020-04-09 13:13:07 +02:00
d55196352c fix compilers for empty AFL_CC/AFL_CXX env 2020-04-09 11:49:40 +02:00
45e569845e LTO llvm11 (#302)
* new LTO mode for llvm 11

* remove unneeded afl-ld and env vars
2020-04-09 10:36:28 +02:00
b55421d4a1 2.63d init 2020-04-09 10:30:24 +02:00
fb8da3e4b1 push new version 2020-04-09 10:23:37 +02:00
a9c0f9a165 fix indention 2020-04-09 10:23:37 +02:00
4b5c4d58dc Update README.snapshot.md 2020-04-09 10:23:37 +02:00
b0e58b5b14 fixed critical whitespace 2020-04-09 10:23:37 +02:00
858c81a19b fix compile for MacOSX -DFORTIFY_SOURCE=2 is problematic 2020-04-09 10:23:37 +02:00
04360a35ed fix review comments by Heiko 2020-04-09 10:23:37 +02:00
c8ca944fac fix review comments by Heiko 2020-04-09 10:23:37 +02:00
b5e4d1a491 fix gcc_plugin Makefile (VPATH) 2020-04-09 10:23:37 +02:00
20cb846c95 Makefile cleanup 2020-04-09 10:23:37 +02:00
a1e531589e unicorn_mode/samples/persistent Makefile portable version 2020-04-09 10:23:37 +02:00
d6b680de48 remove todo 2020-04-09 10:23:37 +02:00
28314632bd fix travis - heiko test your changes on linux pls ;) 2020-04-09 10:23:37 +02:00
09ab904354 one more include move 2020-04-09 10:23:37 +02:00
5c0cf60ec1 fix damage in test.sh 2020-04-09 10:23:37 +02:00
698caed9c0 llvm_mode ctx: move function terminator instrumentation before skipping blocks 2020-04-09 10:23:37 +02:00
ae05f5c4b0 afl-fuzz: add usage info when no python support is there, use it in test.sh 2020-04-09 10:23:37 +02:00
d397bba6b2 llvm_mode android fix 2020-04-09 10:23:37 +02:00
7a6b66e684 fix limits.h include 2020-04-09 10:23:37 +02:00
e6daeef55c fix compilation in OpenBSD 2020-04-09 10:23:37 +02:00
c36c1b8992 update todo 2020-04-09 10:23:37 +02:00
1d1f575b5c add missing piece for CTX coverage 2020-04-09 10:23:37 +02:00
ecdffa03f8 added snapshot feature to documentation 2020-04-09 10:23:37 +02:00
6688184bfd argv_fuzzing Makefile: portable version 2020-04-09 10:23:37 +02:00
84a4fd40a0 fix travis 2020-04-09 10:23:37 +02:00
d37a195392 socket_fuzzing Makefile: make it portable 2020-04-09 10:23:37 +02:00
11e76af819 libdislocator: make Makefile portable 2020-04-09 10:23:37 +02:00
ed8c0d173e gcc_plugin: portable Makefile 2020-04-09 10:23:37 +02:00
c57fdbedaf gcc_plugin fix compile for USEMMAP 2020-04-09 10:23:37 +02:00
bd9676aa04 Android build fix proposal.
LTO flag is recognised but however broken on Android (tested with armv7 arch).
Thus giving the choice not to enable it.
In fortify mode, open required O_CREAT or O_TMPFILE when mode is set.
2020-04-09 10:23:37 +02:00
e5d0a9ecdf update readme 2020-04-09 10:23:37 +02:00
314debb799 ctx done 2020-04-09 10:23:37 +02:00
24ad714d0d update env with AFL_NO_SNAPSHOT 2020-04-09 10:23:37 +02:00
41225b53fa small fixes 2020-04-09 10:23:37 +02:00
5efd306f7b snapshot() in llvm mode 2020-04-09 10:23:37 +02:00
ccbcb5c8d3 added AFL_LLVM_INSTRUMENT, made USE_TRACE_PC obselete and llvm_mode Makefile fix, fixed for FUSELD (for LTO) 2020-04-09 10:23:37 +02:00
2f172d6c5a GNUmakefile: python config add --ldflags, silence tests 2020-04-09 10:23:37 +02:00
1eb81fdf36 unicorn_mode build script: find setuptools more reliably 2020-04-09 10:23:37 +02:00
62b6af693d Makefile bugfix macros are generally not expanded in shell calls 2020-04-09 10:23:37 +02:00
a49988afbf fix silly error with uname -s 2020-04-09 10:23:37 +02:00
03495beadb libtokencap, portable Makefile (for GNUmake and BSDmake) 2020-04-09 10:23:37 +02:00
079fdbf9bc portable version of Makefile (tested with bsdmake and GNUmake) 2020-04-09 10:23:37 +02:00
002e3840e6 update todo 2020-04-09 10:23:37 +02:00
96c558bec4 update todo 2020-04-09 10:23:37 +02:00
a267263420 unit tests cleaning 2020-04-09 10:23:37 +02:00
c14fd1ad18 code format, small improvements 2020-04-09 10:23:37 +02:00
88782ae43c custom mutator readme 2020-04-09 10:23:37 +02:00
70e777d031 no random timing for -s fixed_seed 2020-04-09 10:23:37 +02:00
9e1482ad04 fix make install regarding MANPAGES target 2020-04-09 10:23:37 +02:00
fef08192ad restore portable Makefiles 2020-04-09 10:23:37 +02:00
5488422471 fix UI bug for bit flip yields 2020-04-09 10:23:37 +02:00
e8e6dbf839 small enhancements and code-format 2020-04-09 10:23:37 +02:00
5602a09cc6 remove MaybeAlign 2020-04-09 10:23:37 +02:00
164a01e723 fix make install 2020-04-09 10:23:37 +02:00
f7f106c42a remove maybe_linking artifacts 2020-04-09 10:23:37 +02:00
7f817fe583 rename all 'Makefile' to 'GNUmakefile', use -Werror for -flto checks 2020-04-09 10:23:37 +02:00
5e66d95fbd better asan 2020-04-09 10:23:37 +02:00
d064b2e4af el no longer has to be used in loop 2020-04-09 10:23:37 +02:00
9d067d26da fix unit test case for long list 2020-04-09 10:23:37 +02:00
8e417ecb5c makefile asan fix 2020-04-09 10:23:37 +02:00
a9d072ad02 O3 again 2020-04-09 10:23:37 +02:00
5630c2e72c list testcase added 2020-04-09 10:23:37 +02:00
29ff59cc8a fixing unit tests (again) remove CFLAGS_FLTO, put LDFLAGS near the end 2020-04-09 10:23:37 +02:00
dab429521b added (broken) list test 2020-04-09 10:23:37 +02:00
48fc106905 added prealloc testcase 2020-04-09 10:23:37 +02:00
ee72d5d01d add Make rule for new unit test 2020-04-09 10:23:37 +02:00
378f4dd46d fix make target unit test (tested on Ubuntu 16.04) 2020-04-09 10:23:37 +02:00
2455f081fc llvm_mode: using MaybeAlign wrapper over the deprecated setter.
seems to be available even on LLVM 3.7
2020-04-09 10:23:37 +02:00
f06acc4e27 push new version 2020-04-09 09:14:12 +02:00
3c546341e3 fix indention 2020-04-09 09:08:04 +02:00
650bd1c179 Update README.snapshot.md 2020-04-09 08:58:35 +02:00
9efa96fe0c fixed critical whitespace 2020-04-09 01:40:03 +02:00
361c2ac576 fix compile for MacOSX -DFORTIFY_SOURCE=2 is problematic 2020-04-08 23:45:28 +02:00
54359be31a fix review comments by Heiko 2020-04-08 23:16:49 +02:00
77949acaee fix review comments by Heiko 2020-04-08 23:15:42 +02:00
88a852ef0f fix gcc_plugin Makefile (VPATH) 2020-04-08 22:21:32 +00:00
cb52b1757d Makefile cleanup 2020-04-08 21:39:11 +02:00
b4869d0663 unicorn_mode/samples/persistent Makefile portable version 2020-04-08 21:23:18 +02:00
30fa7b8006 remove todo 2020-04-08 19:17:21 +02:00
7793ca4055 fix travis - heiko test your changes on linux pls ;) 2020-04-08 18:28:35 +02:00
3353a23fcb one more include move 2020-04-08 18:19:38 +02:00
b32b9bd1d5 fix damage in test.sh 2020-04-08 18:16:08 +02:00
133a8cea1c llvm_mode ctx: move function terminator instrumentation before skipping blocks 2020-04-08 17:57:11 +02:00
729dbf7dda afl-fuzz: add usage info when no python support is there, use it in test.sh 2020-04-08 17:53:25 +00:00
67e9ef43a7 llvm_mode android fix 2020-04-08 17:22:31 +02:00
1b5b54fe94 fix limits.h include 2020-04-08 15:49:34 +02:00
9b3e6112ff Merge branch 'dev' of https://github.com/vanhauser-thc/AFLplusplus into dev 2020-04-08 17:39:19 +02:00
7663e7dd05 fix compilation in OpenBSD 2020-04-08 17:38:45 +02:00
2e29e64a3f Merge pull request #295 from devnexen/android_build_fix
Android build fix proposal.
2020-04-08 15:25:29 +02:00
15e0319c98 update todo 2020-04-08 13:12:14 +02:00
055ca98fb2 add missing piece for CTX coverage 2020-04-08 12:52:14 +02:00
968295ed81 added snapshot feature to documentation 2020-04-08 12:34:01 +02:00
48e366d7a8 argv_fuzzing Makefile: portable version 2020-04-08 10:44:42 +02:00
9aa10ef7ca fix travis 2020-04-08 10:39:32 +02:00
a85b8d69ef Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-04-08 10:21:46 +02:00
2900d51e5d socket_fuzzing Makefile: make it portable 2020-04-08 10:20:53 +02:00
63cc113f12 Merge pull request #298 from AFLplusplus/snapshot
Snapshot for LLVM mode in dev
2020-04-08 09:36:04 +02:00
3bf88da091 libdislocator: make Makefile portable 2020-04-08 08:50:30 +02:00
11e3122843 gcc_plugin: portable Makefile 2020-04-08 08:16:55 +02:00
dbe6b1da44 gcc_plugin fix compile for USEMMAP 2020-04-08 08:14:42 +02:00
91dc7776ec Android build fix proposal.
LTO flag is recognised but however broken on Android (tested with armv7 arch).
Thus giving the choice not to enable it.
In fortify mode, open required O_CREAT or O_TMPFILE when mode is set.
2020-04-08 04:57:01 +01:00
a5036499d2 update readme 2020-04-08 04:28:13 +02:00
9ef4b45609 ctx done 2020-04-08 03:56:12 +02:00
5b160f187d update env with AFL_NO_SNAPSHOT 2020-04-07 11:26:18 +02:00
604f17b897 small fixes 2020-04-07 10:56:31 +02:00
da1f3bf41e snapshot() in llvm mode 2020-04-07 10:50:21 +02:00
452acf3a75 added AFL_LLVM_INSTRUMENT, made USE_TRACE_PC obselete and llvm_mode Makefile fix, fixed for FUSELD (for LTO) 2020-04-06 13:33:49 +02:00
5ad50adaa8 GNUmakefile: python config add --ldflags, silence tests 2020-04-04 18:42:51 +02:00
c165165b58 unicorn_mode build script: find setuptools more reliably 2020-04-04 18:38:38 +02:00
0303d315fc Makefile bugfix macros are generally not expanded in shell calls 2020-04-04 16:45:59 +02:00
2129257454 fix silly error with uname -s 2020-04-04 16:16:13 +02:00
a7e9ce2e33 libtokencap, portable Makefile (for GNUmake and BSDmake) 2020-04-04 01:39:01 +02:00
b9851cdabe Merge branch 'dev' of https://github.com/vanhauser-thc/AFLplusplus into dev 2020-04-04 00:17:31 +02:00
a9261c6d64 portable version of Makefile (tested with bsdmake and GNUmake) 2020-04-04 00:15:08 +02:00
064131887b update todo 2020-04-03 14:17:31 +02:00
6b5d5b11b0 update todo 2020-04-03 14:00:29 +02:00
3f2859ec16 unit tests cleaning 2020-04-03 10:43:52 +02:00
5340f2f2eb code format, small improvements 2020-04-03 10:31:37 +02:00
8610b0e406 Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-04-03 09:39:12 +02:00
ffb4767fc1 custom mutator readme 2020-04-03 09:39:09 +02:00
97cae2df99 no random timing for -s fixed_seed 2020-04-02 23:33:55 +02:00
dc0369eb10 fix make install regarding MANPAGES target 2020-04-02 22:14:39 +02:00
71f0bd003f Merge branch 'dev' of https://github.com/vanhauser-thc/AFLplusplus into dev 2020-04-02 17:00:58 +02:00
cc65e91eeb restore portable Makefiles 2020-04-02 17:00:35 +02:00
2ae0208d3b fix UI bug for bit flip yields 2020-04-02 16:46:31 +02:00
7114663f52 small enhancements and code-format 2020-04-02 16:41:33 +02:00
26e45e41ed remove MaybeAlign 2020-04-02 15:38:32 +02:00
38b14c5c44 fix make install 2020-04-02 15:18:05 +02:00
0c76d7e621 remove maybe_linking artifacts 2020-04-02 14:37:28 +02:00
c69c84da09 Merge pull request #288 from devnexen/llvm_mode_little_upd
llvm_mode: using MaybeAlign wrapper over the deprecated setter.
2020-04-02 10:55:58 +02:00
0565fe4213 rename all 'Makefile' to 'GNUmakefile', use -Werror for -flto checks 2020-04-02 12:24:39 +02:00
cb0bc98576 better asan 2020-04-02 02:44:49 +02:00
ef4eeede86 el no longer has to be used in loop 2020-04-01 20:42:50 +02:00
1cce581ffe fix unit test case for long list 2020-04-01 20:37:13 +02:00
989a85bb05 makefile asan fix 2020-04-01 18:56:59 +02:00
db3645c76b O3 again 2020-04-01 18:22:02 +02:00
b5c5496b2f list testcase added 2020-04-01 18:19:43 +02:00
4aec6dabde fixing unit tests (again) remove CFLAGS_FLTO, put LDFLAGS near the end 2020-04-01 16:18:44 +02:00
0fac7bd373 added (broken) list test 2020-04-01 15:56:27 +02:00
9c1c1062be added prealloc testcase 2020-04-01 15:56:27 +02:00
36a03e3bc8 add Make rule for new unit test 2020-04-01 15:51:34 +02:00
dfb0a65e07 fix make target unit test (tested on Ubuntu 16.04) 2020-04-01 15:39:36 +02:00
d40866add2 unittest for prealloc added 2020-04-01 14:39:03 +02:00
9ca8ff77f3 Merge branch 'master' of github.com:aflplusplus/aflplusplus into dev 2020-04-01 13:10:14 +02:00
e95ac10ff7 fix ASAN check 2020-04-01 13:10:07 +02:00
c7cf2c17a2 fix ASAN bulid for old gcc versions 2020-04-01 13:10:07 +02:00
29b1e30126 fixed asan mem limit 2020-04-01 13:10:07 +02:00
24b9eddc7e disable memory limits for ASAN build 2020-04-01 13:10:07 +02:00
effa766d4a fix cmocka fixup 2020-04-01 13:10:07 +02:00
b9783e44a3 cmocka mocks 2020-04-01 13:10:07 +02:00
35c817ccd0 mocking cmocka 1 for cmocka 0.x 2020-04-01 13:10:07 +02:00
77d68bc7bd old cmocka is old 2020-04-01 13:10:07 +02:00
6392a349ce add assert_ptr_equal fallback 2020-04-01 13:10:07 +02:00
4489dd24a8 typo fix 2020-04-01 13:10:07 +02:00
d374648ce3 docs 2020-04-01 13:10:07 +02:00
d611e7d50e next_p2 replaced by next_pow2 2020-04-01 13:10:07 +02:00
25d6d21617 code format 2020-04-01 13:10:07 +02:00
74b4096570 one less alloc 2020-04-01 13:10:07 +02:00
eca55be4fb minor changes 2020-04-01 13:10:07 +02:00
71372c4d2f fixed docu 2020-04-01 13:10:07 +02:00
a0693d466c try to fix forkserver 2020-04-01 13:10:07 +02:00
14d2456c35 fix gcc 2020-04-01 13:10:07 +02:00
c8bdf0790f reenabled custom mutator report 2020-04-01 13:10:07 +02:00
0b8a5cb4bb travis: dont fail on custom mutator - currently 2020-04-01 13:10:07 +02:00
8f98d5a8f8 fix unit test compilation 2020-04-01 13:10:07 +02:00
b83a2c1a00 make travis happy 2020-04-01 13:10:07 +02:00
5a4d4ad736 fixed bug in cmplog 2020-04-01 13:10:07 +02:00
5bc6dccbbd src doku is now markdown 2020-04-01 13:10:07 +02:00
42ee300e92 dropped make switches 2020-04-01 13:10:07 +02:00
582f5103d9 enabled fortify source 2020-04-01 13:10:07 +02:00
abef859925 Update regexp.dict 2020-04-01 13:10:07 +02:00
6eb79c28d1 Update regexp.dict 2020-04-01 13:10:07 +02:00
84a096561a tiny fixes 2020-04-01 13:10:07 +02:00
9a1f105869 fix ubuntu cmocka pkgname 2020-04-01 13:10:07 +02:00
677f2c6ca9 mutator docs 2020-04-01 13:10:07 +02:00
508230e91b code format 2020-04-01 13:10:07 +02:00
9cab515e58 added unittests to test.sh 2020-04-01 13:10:07 +02:00
514036898f added unit target to make help and README 2020-04-01 13:10:07 +02:00
19415f2554 Add test cases for the custom mutator (#276)
* Minor update

* Fix the soft link of `afl-clang-fast++`

* Add a test case for the custom mutator

- Update the Makefile in examples/custom_mutators
- Add a test program for testing the custom mutator
- Update test.sh for testing the custom mutator
- [TODO] Update the result checking criterias of the custom mutator in
test.sh

* Fix nullptr in the custom mutator

* Fix typo

* Fix invalid memory access bug in `afl_custom_pre_save` of example.c

* example.py: add deinit()

* python mutator: fix nullptr for python mutator data

* test.sh: "trusty-amd64" does not work well with "realpath". Use
"readlink -f" for Ubuntu instead.

* Fix heap allocation bug

- Reason: `afl->out_size` is not consistent with the actual allocation
of `afl->out_buf`. The deleted line in `src/afl-fuzz-one.c` may change
`afl->out_size`, but `afl->out_buf` is not changed

* test.sh: redirect command line output

* afl-fuzz-one.c: minor update

Co-authored-by: Dominik Maier <domenukk@gmail.com>
2020-04-01 13:10:07 +02:00
710a29a1e0 fixed testcase 2020-04-01 13:10:07 +02:00
c36c34cf9e fixed example 2020-04-01 13:10:07 +02:00
e910c224da afl-fuzz-one.c: minor update 2020-04-01 13:10:07 +02:00
ea95453975 test.sh: redirect command line output 2020-04-01 13:10:07 +02:00
61ea398612 Fix heap allocation bug
- Reason: `afl->out_size` is not consistent with the actual allocation
of `afl->out_buf`. The deleted line in `src/afl-fuzz-one.c` may change
`afl->out_size`, but `afl->out_buf` is not changed
2020-04-01 13:10:07 +02:00
64e1d3a975 test.sh: "trusty-amd64" does not work well with "realpath". Use
"readlink -f" for Ubuntu instead.
2020-04-01 13:10:07 +02:00
50fc7327f2 python mutator: fix nullptr for python mutator data 2020-04-01 13:10:07 +02:00
71edae4a0f example.py: add deinit() 2020-04-01 13:10:07 +02:00
0dd8ed9171 Fix invalid memory access bug in afl_custom_pre_save of example.c 2020-04-01 13:10:07 +02:00
d568559f01 Fix typo 2020-04-01 13:10:06 +02:00
1e290542bb rebase 2020-04-01 13:10:06 +02:00
245304f593 Add a test case for the custom mutator
- Update the Makefile in examples/custom_mutators
- Add a test program for testing the custom mutator
- Update test.sh for testing the custom mutator
- [TODO] Update the result checking criterias of the custom mutator in
test.sh
2020-04-01 13:10:06 +02:00
be441dc176 upstream changes 2020-04-01 13:10:06 +02:00
da1a0249d7 merged dev 2020-04-01 13:10:06 +02:00
d07587885c added untitest to gitignore 2020-04-01 13:10:06 +02:00
376b45c199 code format 2020-04-01 13:10:06 +02:00
b247366c4e regec dict additions 2020-04-01 13:10:06 +02:00
7c383094d9 added unittest for unit_maybe_alloc 2020-04-01 13:10:06 +02:00
9721990507 code cleanup 2020-04-01 13:10:06 +02:00
452067ffca added read_timed 2020-04-01 13:10:06 +02:00
3ce5efc44b llvm_mode/Makefile: replace lexical version comparison with a numerical one 2020-04-01 13:10:06 +02:00
1e8c1a4c46 review adaptions for afl-llvm-pass 2020-04-01 13:10:06 +02:00
b53ec1b247 afl-llvm-pass.so.cc: fix compile for llvm 3.8.0 @Marc: please review 2020-04-01 13:10:06 +02:00
4ccfbe4e5a .gitignore: add afl-ld and ld 2020-04-01 13:10:06 +02:00
7698c051aa qemu_mode: compiler warnings, strncpy() leave one byte for terminator 2020-04-01 13:10:06 +02:00
1950f09bde qemu_mode: fix more compiler warnings 2020-04-01 13:10:06 +02:00
e41b03eb30 qemu_mode: silence two compiler warnings 2020-04-01 13:10:06 +02:00
98545f30aa code format 2020-04-01 13:10:06 +02:00
81873d97f8 error handling for custom mutators 2020-04-01 13:10:06 +02:00
cda56ca129 types.h: silence some compiler warnings regarding redeclaration of
likely/unlikely
2020-04-01 13:10:06 +02:00
ab5e0703da tiny changes in custom mut api 2020-04-01 13:10:06 +02:00
f370ef38c4 alloc-inl.h/ck_maybe_grow(): restore original exponential allocs 2020-04-01 13:10:06 +02:00
1119a2e185 alloc-inl.h/ck_maybe_grow() back to size_t, reimplement overflow check 2020-04-01 13:10:06 +02:00
9d7ac3d99f alloc_inl.h/ck_maybe_grow(): fix compiler warning 2020-04-01 13:10:06 +02:00
0732e66da9 gcc_plugin: fix compiler warnings regarding -O and FORTIFY_SOURCE 2020-04-01 13:10:06 +02:00
e56e2f4c18 llvm_mode: fix compiler warnings FORTIFY_SOURCE needs -O 2020-04-01 13:10:06 +02:00
23d9649aec making 'CFLAGS="-m32" make source-only tests' work 2020-04-01 13:10:06 +02:00
738a245c3e fix warning in afl-fuzz-run, tested with '-m32' also 2020-04-01 13:10:06 +02:00
78d73720a2 fix detection compiles (e.g. python) when using CFLAGS="-m32" 2020-04-01 13:10:05 +02:00
e59282fe20 if exponential growth is too much, don't doo it 2020-04-01 13:10:05 +02:00
9785b15ed2 more custom mutator remodelling 2020-04-01 13:10:05 +02:00
8c94a3d177 added nullptr fix by h1994st 2020-04-01 13:10:05 +02:00
5bd8aa489b fixed leak 2020-04-01 13:10:05 +02:00
e71c2937de code format 2020-04-01 13:10:05 +02:00
3d6c58df53 part1 make it compilable for llvm 3.8.0 (ubuntu 16.04) 2020-04-01 13:10:05 +02:00
34c090a31d add CFI sanitizer 2020-04-01 13:10:05 +02:00
762421b355 less allocs 2020-04-01 13:10:05 +02:00
b7f3d180aa not allocating paths anymore 2020-04-01 13:10:05 +02:00
71f8cc9dd2 almost 2020-04-01 13:10:05 +02:00
3c7bc6fd42 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-04-01 12:53:10 +02:00
af60844aea fix ASAN bulid for old gcc versions 2020-04-01 12:53:03 +02:00
c4c13dd235 fix ASAN check 2020-04-01 12:52:54 +02:00
ba4f0186dd fixed asan mem limit 2020-04-01 12:43:26 +02:00
a5c09e4c11 disable memory limits for ASAN build 2020-04-01 12:19:54 +02:00
c7818714ac fix cmocka fixup 2020-04-01 09:42:40 +02:00
cec3d74497 cmocka mocks 2020-04-01 03:39:36 +02:00
10b226418c mocking cmocka 1 for cmocka 0.x 2020-04-01 03:20:22 +02:00
c843085a28 old cmocka is old 2020-04-01 02:59:19 +02:00
101c5a275f add assert_ptr_equal fallback 2020-04-01 02:28:54 +02:00
acf4b0981e typo fix 2020-04-01 02:09:33 +02:00
98c0908185 docs 2020-04-01 02:07:52 +02:00
ead3701f5b next_p2 replaced by next_pow2 2020-04-01 02:03:46 +02:00
0349b0a735 code format 2020-04-01 02:00:03 +02:00
11cad9fb20 one less alloc 2020-04-01 01:58:34 +02:00
7f44fec0a5 minor changes 2020-04-01 01:55:13 +02:00
d4c8a2058d fixed docu 2020-04-01 01:38:45 +02:00
d73e63bd70 try to fix forkserver 2020-04-01 01:24:44 +02:00
48655c2e12 llvm_mode: using MaybeAlign wrapper over the deprecated setter.
seems to be available even on LLVM 3.7
2020-03-31 19:25:24 +01:00
d0d5518ea8 fix gcc 2020-03-31 18:06:14 +02:00
822e75f7c2 reenabled custom mutator report 2020-03-31 14:01:22 +02:00
08b6b4ec4e travis: dont fail on custom mutator - currently 2020-03-31 07:37:30 +02:00
3253e3f315 fix unit test compilation 2020-03-31 07:14:25 +02:00
e58e54c2db make travis happy 2020-03-31 04:51:38 +02:00
0a7dc10dd3 fixed bug in cmplog 2020-03-31 04:22:22 +02:00
3914aec72f src doku is now markdown 2020-03-31 03:41:51 +02:00
9b63fc758e dropped make switches 2020-03-31 03:22:46 +02:00
d3130ace30 enabled fortify source 2020-03-31 02:41:11 +02:00
daa09a5fbb Update regexp.dict 2020-03-31 01:41:16 +02:00
a249dadfb0 Update regexp.dict 2020-03-31 01:41:16 +02:00
64e9f1f3a2 tiny fixes 2020-03-30 23:53:10 +02:00
9110097e11 fix ubuntu cmocka pkgname 2020-03-30 18:55:54 +02:00
ac48b58184 mutator docs 2020-03-30 18:46:12 +02:00
8f5fb47082 code format 2020-03-30 18:38:39 +02:00
a58382d3ff added unittests to test.sh 2020-03-30 18:37:16 +02:00
5ef8e3cf29 Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-03-30 18:22:43 +02:00
6544014ced Add test cases for the custom mutator (#276)
* Minor update

* Fix the soft link of `afl-clang-fast++`

* Add a test case for the custom mutator

- Update the Makefile in examples/custom_mutators
- Add a test program for testing the custom mutator
- Update test.sh for testing the custom mutator
- [TODO] Update the result checking criterias of the custom mutator in
test.sh

* Fix nullptr in the custom mutator

* Fix typo

* Fix invalid memory access bug in `afl_custom_pre_save` of example.c

* example.py: add deinit()

* python mutator: fix nullptr for python mutator data

* test.sh: "trusty-amd64" does not work well with "realpath". Use
"readlink -f" for Ubuntu instead.

* Fix heap allocation bug

- Reason: `afl->out_size` is not consistent with the actual allocation
of `afl->out_buf`. The deleted line in `src/afl-fuzz-one.c` may change
`afl->out_size`, but `afl->out_buf` is not changed

* test.sh: redirect command line output

* afl-fuzz-one.c: minor update

Co-authored-by: Dominik Maier <domenukk@gmail.com>
2020-03-30 18:21:03 +02:00
3fcb3e2ed3 fixed testcase 2020-03-30 18:20:20 +02:00
caebc9347f added unit target to make help and README 2020-03-30 17:45:17 +02:00
1f257c5875 fixed example 2020-03-30 16:46:54 +02:00
e2a3de71ca afl-fuzz-one.c: minor update 2020-03-30 16:46:54 +02:00
57a0134b0c test.sh: redirect command line output 2020-03-30 16:46:54 +02:00
d9b18ec853 Fix heap allocation bug
- Reason: `afl->out_size` is not consistent with the actual allocation
of `afl->out_buf`. The deleted line in `src/afl-fuzz-one.c` may change
`afl->out_size`, but `afl->out_buf` is not changed
2020-03-30 16:46:54 +02:00
6c14415664 test.sh: "trusty-amd64" does not work well with "realpath". Use
"readlink -f" for Ubuntu instead.
2020-03-30 16:46:54 +02:00
567b3985ab python mutator: fix nullptr for python mutator data 2020-03-30 16:46:54 +02:00
45561d552e example.py: add deinit() 2020-03-30 16:46:54 +02:00
fbd5bd8f37 Fix invalid memory access bug in afl_custom_pre_save of example.c 2020-03-30 16:46:54 +02:00
048beb752d Fix typo 2020-03-30 16:46:53 +02:00
87621b6345 rebase 2020-03-30 16:46:50 +02:00
ff14dfc0fc Add a test case for the custom mutator
- Update the Makefile in examples/custom_mutators
- Add a test program for testing the custom mutator
- Update test.sh for testing the custom mutator
- [TODO] Update the result checking criterias of the custom mutator in
test.sh
2020-03-30 16:46:11 +02:00
c624831717 upstream changes 2020-03-30 16:46:05 +02:00
c697a003d1 merged dev 2020-03-30 16:45:13 +02:00
6bdd7a1609 added untitest to gitignore 2020-03-30 16:08:07 +02:00
50a195fe59 code format 2020-03-30 16:07:25 +02:00
738016952f Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-03-30 16:01:33 +02:00
209aa25d27 added unittest for unit_maybe_alloc 2020-03-30 16:01:29 +02:00
1279c935e2 regec dict additions 2020-03-30 11:33:42 +02:00
28e5a8031c code cleanup 2020-03-30 00:50:32 +02:00
f4844e2c0c added read_timed 2020-03-30 00:50:14 +02:00
ef3a13fa63 llvm_mode/Makefile: replace lexical version comparison with a numerical one 2020-03-29 09:48:01 +02:00
699f769385 review adaptions for afl-llvm-pass 2020-03-28 23:01:12 +01:00
2548b657d8 afl-llvm-pass.so.cc: fix compile for llvm 3.8.0 @Marc: please review 2020-03-28 20:25:00 +01:00
02d19dafb2 .gitignore: add afl-ld and ld 2020-03-28 14:23:54 +01:00
78009d9d07 qemu_mode: compiler warnings, strncpy() leave one byte for terminator 2020-03-28 14:15:04 +01:00
2aa7ddf1a8 qemu_mode: fix more compiler warnings 2020-03-28 13:51:35 +01:00
3c142efecf qemu_mode: silence two compiler warnings 2020-03-28 13:38:49 +01:00
23b3e3c84d Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-03-28 13:06:05 +01:00
8b8600fdab types.h: silence some compiler warnings regarding redeclaration of
likely/unlikely
2020-03-28 13:05:26 +01:00
1938a12222 code format 2020-03-28 12:59:41 +01:00
4c11ef5d20 error handling for custom mutators 2020-03-28 12:58:56 +01:00
6ac40e2cc5 Merge branch 'dev' of https://github.com/vanhauser-thc/AFLplusplus into dev 2020-03-28 12:16:01 +01:00
5625e059e1 alloc-inl.h/ck_maybe_grow(): restore original exponential allocs 2020-03-28 12:15:01 +01:00
11767bec0e tiny changes in custom mut api 2020-03-28 11:55:10 +01:00
7a92bf974d alloc-inl.h/ck_maybe_grow() back to size_t, reimplement overflow check 2020-03-28 11:01:29 +01:00
fc46e9c9a0 alloc_inl.h/ck_maybe_grow(): fix compiler warning 2020-03-28 10:23:11 +01:00
7a752d0795 gcc_plugin: fix compiler warnings regarding -O and FORTIFY_SOURCE 2020-03-28 10:00:23 +01:00
0cff53785b llvm_mode: fix compiler warnings FORTIFY_SOURCE needs -O 2020-03-28 09:54:40 +01:00
4ad885001a making 'CFLAGS="-m32" make source-only tests' work 2020-03-28 09:31:30 +01:00
a0dec909e7 fix warning in afl-fuzz-run, tested with '-m32' also 2020-03-28 08:38:50 +01:00
2a660b19a7 fix detection compiles (e.g. python) when using CFLAGS="-m32" 2020-03-28 08:32:54 +01:00
8992c44c41 if exponential growth is too much, don't doo it 2020-03-28 05:01:01 +01:00
53fd8fe6ea more custom mutator remodelling 2020-03-28 04:57:44 +01:00
0059d16731 added nullptr fix by h1994st 2020-03-28 01:14:24 +01:00
18bc344cf5 fixed leak 2020-03-28 00:44:52 +01:00
e04f4b3f20 code format 2020-03-27 23:30:15 +01:00
5e389a0970 Less allocs 2020-03-27 23:24:42 +01:00
1141459607 less allocs 2020-03-27 23:23:11 +01:00
02659df6ba not allocating paths anymore 2020-03-27 23:06:57 +01:00
14bd424d2a almost 2020-03-27 21:59:08 +01:00
7c76b7db04 part1 make it compilable for llvm 3.8.0 (ubuntu 16.04) 2020-03-27 21:03:28 +01:00
a7553eae28 add CFI sanitizer 2020-03-27 12:09:06 +01:00
5cc50bb979 important llvm_mode Makefile fix 2020-03-27 11:06:06 +01:00
932eae7343 example fixed 2020-03-27 11:06:06 +01:00
604f122819 docu 2020-03-27 11:06:06 +01:00
d6a7630fe2 more api 2020-03-27 11:06:06 +01:00
fc4b03ee74 Code Format (#275) 2020-03-27 11:06:06 +01:00
e9c7610cb7 edited custom mutator pre_save api 2020-03-27 11:06:06 +01:00
3c3a5aa503 updated with required changes 2020-03-27 11:06:06 +01:00
6d3dc83c5d code format 2020-03-27 11:06:06 +01:00
89512d4e05 fixed call of custom mutators 2020-03-27 11:06:06 +01:00
b1d71136b0 fixed typos in README.md 2020-03-27 11:06:06 +01:00
8cf47f2425 add "time without finds" to afl-whatsup 2020-03-27 11:06:06 +01:00
c75b403bb7 fix doc link 2020-03-27 11:06:06 +01:00
ae284610cf important llvm_mode Makefile fix 2020-03-27 10:08:09 +01:00
5a7d33330a example fixed 2020-03-26 19:48:26 +01:00
12a9a1001e docu 2020-03-26 19:47:16 +01:00
97a1af39f7 more api 2020-03-26 19:44:44 +01:00
6832435326 Code Format (#275) 2020-03-26 18:47:48 +01:00
62bb94c50b Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-03-25 21:54:59 +01:00
eeb7e12b9f edited custom mutator pre_save api 2020-03-25 21:54:52 +01:00
f796537712 Merge pull request #272 from ashiscs/master
fixed typos in README.md
2020-03-25 17:32:32 +01:00
469446a02b updated with required changes 2020-03-25 19:35:38 +05:30
b24ef50f7b Merge pull request #271 from fuzzah/aflpp_time_without_finds
add "time without finds" to afl-whatsup
2020-03-25 12:50:42 +01:00
f6466214c6 code format 2020-03-25 11:31:01 +01:00
9c4d32b5b8 fixed call of custom mutators 2020-03-24 22:40:14 +01:00
50be709e91 fixed typos in README.md 2020-03-25 01:21:02 +05:30
2e060f856d Merge branch 'dev' of github.com:aflplusplus/aflplusplus into dev 2020-03-24 18:46:43 +01:00
c9a2401983 fix doc link 2020-03-24 18:46:25 +01:00
ce58790fc0 add "time without finds" to afl-whatsup 2020-03-24 15:12:08 +03:00
7f3e04cbc4 fix doc link 2020-03-24 08:44:18 +01:00
3fb346fe29 Merge pull request #269 from AFLplusplus/dev
Dev
2020-03-23 20:42:10 +01:00
36213dba7d Merge branch 'dev' of github.com:vanhauser-thc/AFLplusplus into dev 2020-03-23 20:19:20 +01:00
65817144ac include afl-llvm-rt.o not only when linking 2020-03-23 20:19:07 +01:00
82432195a8 Merge pull request #266 from AFLplusplus/dev 2020-03-23 18:19:20 +01:00
77b81e7361 custom mutators might work again like this 2020-03-23 18:18:54 +01:00
83f925ccc9 unsafer 2020-03-23 15:02:26 +01:00
39208eeb9a typo 2020-03-23 12:06:43 +01:00
f32d1022bd surgical_havoc_mutate() in custom mutator helpers 2020-03-23 10:47:17 +01:00
ee9447de01 libasan.so is not a thing. libclang-rt.asan-ARCH.so is the asan DSO and it is not linked by default. Search for __asan_init instead. 2020-03-23 10:09:55 +01:00
dcfc24501b update readme 2020-03-23 10:05:08 +01:00
e65e723e03 update readme 2020-03-23 09:50:12 +01:00
94e30002e7 better man page for afl-clang-* 2020-03-23 09:25:05 +01:00
37603272be more fixes and code-format 2020-03-23 08:58:17 +01:00
4263519479 more fixes 2020-03-23 08:48:57 +01:00
db302ff18b minor fixes 2020-03-23 08:44:27 +01:00
cbde30e9d4 less branches, cleanup 2020-03-23 00:14:03 +01:00
c0fd8f4e15 Merge pull request #265 from devnexen/unicorn_python3_4_mac
Enforcing python3 for Mac too.
2020-03-22 19:09:43 +01:00
d39e9ea11c little performance enhancements 2020-03-22 19:06:39 +01:00
5b64681867 a little bit more performance 2020-03-22 18:27:04 +01:00
0132657432 Enforcing python3 for Mac too. 2020-03-22 12:31:58 +00:00
aac7c7d75d detect arm in build_qemu_support.sh 2020-03-22 12:09:52 +01:00
bd239d7e3d nice -n -20 to commit test script 2020-03-22 11:28:09 +01:00
da1f2f3c17 fix travis 2020-03-22 10:24:29 +01:00
7374af51d1 silly, silly typo 2020-03-22 10:07:59 +01:00
38fa2fe0b1 add commit test script test/checkcommit.sh 2020-03-22 09:32:13 +01:00
5a0cc43ee1 all afl msgs to stdout and only read AFL_BENCH_JUST_ONE once 2020-03-22 09:26:46 +01:00
f08a3fedf6 renamed UB to rand_below 2020-03-21 22:26:13 +01:00
5cf3426834 remove debug code 2020-03-21 22:17:57 +01:00
96736309a7 support for arm platform when building qemu 2020-03-21 22:11:07 +01:00
42ece199c8 revert test.sh patch 2020-03-21 22:04:52 +01:00
54d01fec43 moved string formatting to header 2020-03-21 21:48:52 +01:00
f8d717d195 test.sh fix 2020-03-21 21:42:32 +01:00
c6db05c5ae test.sh with -no-pie 2020-03-21 21:10:38 +01:00
6f78b67f03 adjusted int_bufs 2020-03-21 20:28:01 +01:00
a5af81506f qemu_mode/unicorn_mode scripts: fix '==' in '[' 2020-03-21 19:31:15 +01:00
087bc6daeb qemu_mode and unicorn_mode build scripts: replace type with command -v 2020-03-21 19:22:55 +01:00
f18dbb0b40 afl-gotcpu.c: compielr warning fixed: initialize variable v2 2020-03-21 19:13:39 +01:00
6cbd0f1faf avoid calling awk for 'which' replacement, use POSIX 'command -v' instead 2020-03-21 18:51:43 +01:00
dcd9cd638b fix stat display 2020-03-21 17:42:00 +01:00
350530f664 unicorn build script: list all missing prereqs in one invocation,
replace which with type
2020-03-21 10:59:58 +01:00
dabce05ec6 qemu_mode/build script: add more missing prereqs 2020-03-21 10:46:23 +01:00
993bf03af9 Merge branch 'dev' of https://github.com/AFLplusplus/AFLplusplus into dev 2020-03-21 10:36:18 +01:00
2508008b53 qemu_mode, build script: avoid which, add patch to prereqs, list all
missing prereqs in one invocation
2020-03-21 10:31:39 +01:00
a0012c9e82 forgot readme for ngram 2020-03-20 17:56:24 +01:00
c63956b8ec Merge branch 'dev' of https://github.com/vanhauser-thc/AFLplusplus into dev 2020-03-20 17:32:42 +01:00
6965797286 unicorn: increase timeout for unicorn test in build script 2020-03-20 17:31:48 +01:00
5a74cffa0f added llvm_mode ngram coverage 2020-03-20 17:10:44 +01:00
f21ff8bac8 show cycles_without_finds in afl-whatsup 2020-03-20 12:19:22 +01:00
5d932398df expose cycles_wo_finds in fuzzer_stats 2020-03-20 09:44:51 +01:00
5532fc1102 added missing descriptions of entries in fuzzer_stats 2020-03-20 09:28:43 +01:00
60d66ebc0d clean was missing ld symlink 2020-03-20 09:06:54 +01:00
29853549c3 add RARE schedule. also fixes doc_path 2020-03-20 08:54:09 +01:00
d0b5cd64c3 install llvm_mode READMEs 2020-03-19 23:55:28 +01:00
cd4243b6ad update doc 2020-03-19 23:40:45 +01:00
cd2be88707 travis for dev branch 2020-03-19 23:29:33 +01:00
5b9d306cdf no more (?) statics 2020-03-19 22:54:09 +01:00
0fa47bb867 removed unneeded func 2020-03-19 21:33:17 +01:00
b22e890ec2 fixed resize; removed more statics 2020-03-19 21:32:08 +01:00
b6fa63abdf code format 2020-03-19 19:23:58 +01:00
51a346bcbe 50% less globals 2020-03-19 19:22:57 +01:00
fd9587d26e Merge pull request #262 from rish9101/remove_alarm
Port the fauxserver changes to afl-cmplog and code format
2020-03-19 17:01:57 +01:00
0e1d82dd9f describe branches setup in README 2020-03-19 15:27:12 +01:00
be261b3e69 moved repository to https://github.com/AFLplusplus/AFLplusplus and updated links 2020-03-19 15:20:39 +01:00
f6847b0314 test.sh: replace 'which' with 'type' 2020-03-19 00:19:25 +01:00
eca6bdb85d afl-cmin: replace 'which' with 'type' 2020-03-19 00:15:48 +01:00
a3bd1c71ca Makefiles: replace 'which' with 'type' 2020-03-18 23:51:54 +01:00
b19039ba8b Merge branch 'master' of https://github.com/vanhauser-thc/AFLplusplus 2020-03-18 22:56:19 +01:00
94a4cc8415 Makefiles: prefer POSIX 'type' over 'which' for checking 2020-03-18 22:55:14 +01:00
2e4fda6d4c fix #261 2020-03-18 21:18:55 +01:00
cd7e234445 try to fix regression due to rtn cmplog 2020-03-18 21:07:31 +01:00
a5e747af14 rework docs installation 2020-03-18 17:26:21 +01:00
5060861545 qemu_mode/libcompcov/Makefile install: fix installation of README 2020-03-18 16:26:54 +01:00
992cf3dd25 libtokencap Makefile install: forgot -T for README 2020-03-18 16:23:54 +01:00
1dee73cdde libtokencap: install correct README without name collision 2020-03-18 16:19:14 +01:00
3aa7242925 added mmopt power schedule 2020-03-17 21:42:36 +01:00
4009f3a987 fix reading env vars in afl-fuzz 2020-03-17 21:02:06 +01:00
cfd451c6f3 cmplog was neither quiet nor where its llvm passes installed 2020-03-17 16:26:51 +01:00
8e07fbf636 cmplog was neither quiet nor where its llvm passes installed 2020-03-17 16:26:36 +01:00
dae249dc71 minor fix to qemu_persistent_hook example 2020-03-17 16:10:34 +01:00
e194acdd79 PR #257 from chibinz, enhance afl-whatsup, (adapted for portability) 2020-03-17 14:26:08 +01:00
287d430fcf better explain AFL_QEMU_DEBUG_MAPS 2020-03-17 12:37:20 +01:00
d1d2fceed8 Port the fauxserver changes to afl-cmplog and code format 2020-03-17 15:19:24 +05:30
8cc39a3590 fix link in readme 2020-03-17 09:01:55 +01:00
a57896a7ce fixed segfault on early bailout 2020-03-17 00:00:36 +01:00
35720304be not all opt are compiled with polly support 2020-03-16 20:10:42 +01:00
09b2565b1b fix broken MOpt mode that was broken by Dominiks no-global patch :p 2020-03-16 20:09:46 +01:00
5b9335be10 fix compilation for Darwin/MacOSX 2020-03-16 14:04:21 +01:00
9ce0617cda fix for instrim with and without AFL_LLVM_INSTRIM_SKIPSINGLEBLOCK 2020-03-16 07:28:31 +01:00
61ba214f19 print a completed UI screen on exit without bugs :) 2020-03-15 22:51:22 +01:00
bfe076748b fix test failure with qemu compcov 2020-03-15 21:42:04 +01:00
070412b9c1 Merge pull request #259 from devnexen/afl_globals_little_tweaks
Just compute the current len on env comparison once.
2020-03-15 20:03:27 +01:00
ccb21a745d Just compute the current len once.
Fix env var types assignments.
2020-03-15 18:57:18 +00:00
87599de782 fix errors in last commit (u8)afl_get_env 2020-03-15 19:39:03 +01:00
126d1f1cd1 Move afl-fuzz related env variables into afl_state_t (#252)
* Move afl-fuzz related env variables into afl_state_t

* Move the env variables assignment from fuzz_init and code Format

* Fix typo

* Remove redundant env variables from afl_env struct

* Rename function to read_afl_environment
2020-03-15 18:29:23 +01:00
7685893cdb fix afl-fuzz-document 2020-03-15 17:09:52 +01:00
f9f163e48f fix afl-fuzz-document 2020-03-15 17:07:06 +01:00
15ba6249fc fauxserver 2020-03-15 17:02:48 +01:00
f3799f94bf fix compiler warning on MacOS 2020-03-14 16:40:05 +01:00
e77c431582 fix compilation under FreeBSD: ugly name clash of LIST_FOREACH (FreeBSDs fault) 2020-03-14 13:21:39 +01:00
338daa1282 Merge branch 'master' of https://github.com/vanhauser-thc/AFLplusplus 2020-03-14 11:45:25 +01:00
c616fcafe8 fix some compiler warnings from Open/FreeBSD 2020-03-14 11:44:21 +01:00
08fe1e2cd7 afl-common.c: fix my error: argv is a copy (ck_alloc based)
Now unicorn_mode works with ASAN_BUILD and _WANT_ORIGINAL_AFL_ALLOC
and DEBUG_BUILD also.
2020-03-13 20:37:39 +01:00
746a2a0ed0 afl-fuzz-init.c, afl-fuzz.c: fix more wrong free() calls (found with
ASAN_BUILD=1 CFLAGS="-D_WANT_ORIGINAL_AFL_ALLOC -DDEBUG_BUILD")
2020-03-13 17:23:23 +01:00
d2787519e3 afl-common.c: ... but that breaks unicorn_mode, which it should not. 2020-03-13 10:06:02 +01:00
23d0cea3c9 afl-common.c: avoid AFL++'s allocation API for libc's argv[] and reduce
complexity for cwd
2020-03-13 01:21:07 +01:00
530bd2b341 test.sh: make afl-cmin.bash test dependent on bash 2020-03-12 22:52:20 +01:00
8adc2648f8 fix afl-common.c for *BSD 2020-03-12 21:43:53 +01:00
0c45918d54 Fixed typo (#253) 2020-03-11 22:53:50 +01:00
288432843b updated README, ideas and a missing clean in Makefile 2020-03-11 12:03:44 +01:00
684f4dd1c4 honor afl_quiet on env var checks + code-format 2020-03-11 11:42:57 +01:00
d8d89507b5 afl-cmin delete output directory when aborted 2020-03-11 11:25:58 +01:00
f1ef398909 remove wrong call to write_to_file when aborted by user 2020-03-11 11:11:22 +01:00
66e8faaaa9 Fix typo (#247) 2020-03-11 00:48:52 +01:00
f17a3dde1a Replace timer with select in forkserver, where possible (#246) 2020-03-11 00:34:51 +01:00
88ced831c1 forkserver defaults 2020-03-10 22:56:26 +01:00
cc1d6b33b1 unified pointer placement 2020-03-10 22:04:05 +01:00
2832cb643d removed debug output 2020-03-10 16:27:28 +01:00
cd377f3d99 Replace alarms with select and threads (#243)
* Use select to monitor forkserver for timeouts instead of alarm

* Remove redundent conditons in select monitoring of fdsin forkserver and cmplog

* Replace SIGALARM with POSIX timers in afl-fuzz-run

* Make changes to Makefile to use POSIX timers

* Resolve Merge Conflicts and rename variables accordingly

* Change forkserver and cmplog to handle exec_tmout = 0

* Handle timeout function bug rectify

* Add error handling to afl-fuzz run timers

* Add timer_delete to afl-fuzz-run

* Remove memory leaks
2020-03-10 13:07:29 +01:00
0def6e3471 this should fix travis 2020-03-10 07:18:23 +01:00
1148a2d0d1 document new environment variables and code format 2020-03-10 07:14:42 +01:00
38d9aedb26 code-format - and afl-cmin/afl-showmap was fixed in the bugfix for afl-tmin 2020-03-10 06:54:31 +01:00
1467776a3f imported InsTrim algo fix 2020-03-10 06:47:11 +01:00
f678731234 afl-tmin is fixed via default initialization in forkserver 2020-03-10 06:44:24 +01:00
e04d2a6efa removed unused vars 2020-03-09 21:58:39 +01:00
1136e887bd now wiht 90% less leaks 2020-03-09 21:34:11 +01:00
416020daef quickfix for first big bug that use_stdin was not correctly initialized and could not be set 2020-03-09 19:42:23 +01:00
73a1b39446 quickfix for first big bug that use_stdin was not correctly initialized and could not be set 2020-03-09 19:40:59 +01:00
253bbf3a5c replaced free with ck_free 2020-03-09 19:36:02 +01:00
782cffb130 fixed numerous leaks 2020-03-09 19:30:26 +01:00
a24352ddfd fix leaks 2020-03-09 15:52:14 +01:00
2f41663673 copyleft note 2020-03-09 14:43:40 +01:00
cdd1dd3d20 changelog 2020-03-09 14:37:34 +01:00
dea1dbfba4 updated changelog and todo 2020-03-09 12:33:06 +01:00
988a32ced5 code-format 2020-03-09 12:21:54 +01:00
188a6f5ec5 disable leaksanitizer when "make" ... more 2020-03-09 12:17:59 +01:00
aa4050d406 disable leaksanitizer when "make" 2020-03-09 12:04:35 +01:00
581097d58d expanded test-instr to also work with input files via "-f @@" and changed the test.sh values 2020-03-09 11:39:12 +01:00
dba3595c0a AFL without globals (#220)
* moved globals to afl, shm and fsrv 

* moved argv to afl state, less bugs

* fixed unicorn docu

* lists everywhere

* merged custom mutators

* fixed leaks in afl-fuzz
2020-03-09 11:24:10 +01:00
c159b872ef removed warning in afl-gcc-pass.so.cc 2020-03-09 11:23:29 +01:00
df74edeb45 more honoring be_quiet 2020-03-09 11:08:50 +01:00
dcf7d85cba honor no_quiet for missing llvm_mode output, also print to stderr with afl-*-rt.o.c instead of stdout for errors plus two potential bad free() fixes 2020-03-09 10:56:53 +01:00
8e953d9931 Merge pull request #240 from rish9101/refactor
Remove get_cut_time function from multiple places and refactor code
2020-03-09 09:30:25 +01:00
9f89bbd5ec reactivated LTO persistent mode to test.sh 2020-03-09 08:51:37 +01:00
6a6dd84b39 more detail to the fact that LTO mode can fail easily 2020-03-09 08:33:08 +01:00
36ce9c1fb9 more code format 2020-03-09 08:30:28 +01:00
0581f6ec00 bug fixes to afl-ld and intensive README.lto.md update on errors and how to do the steps by hand, plus global code format 2020-03-09 08:27:23 +01:00
1a582d54e5 Remove get_cut_time function from multiple places and refactor code 2020-03-09 10:04:32 +05:30
a3161b902e fix null ptr deferef in pre_save python mutator call 2020-03-08 22:02:57 +01:00
783f3b0957 afl-ld fixes for -L/-l .a libary loads 2020-03-08 19:12:04 +01:00
8ff0161d58 "fixed" symbol multiply defined problems with LTO 2020-03-08 18:20:28 +01:00
9f7bcca91e mark AFL_PYTHON_ONLY deprecated 2020-03-08 16:56:44 +01:00
891f6985ed Merge pull request #238 from h1994st/master
Two new hooks for the custom mutator
2020-03-08 12:38:01 +01:00
98ffef26dc Merge pull request #239 from 0x1eadbead/fix-qemu-32-on-64
fix qemu persistent mode for 32-bit target on 64-bit host
2020-03-08 11:50:44 +01:00
81179b4829 fix qemu persistent mode for 32-bit target on 64-bit host 2020-03-08 13:39:06 +03:00
e7bc3e09a3 Update .gitignore 2020-03-07 16:30:31 -05:00
8f93cf5c55 Add two new hooks for the custom mutator
- `afl_custom_queue_get` and `afl_custom_queue_new_entry`
- Update the corresponding document and examples
2020-03-07 16:28:48 -05:00
dc0b2dda5e Merge branch 'master' of https://github.com/vanhauser-thc/AFLplusplus 2020-03-07 10:29:14 -05:00
ed5d65b54f solve linking error when python is not available 2020-03-07 14:26:33 +01:00
172d384bf2 custom havoc mutation 2020-03-07 12:11:06 +01:00
1e30c3a941 afl-tmin hang mode added 2020-03-07 03:40:42 +01:00
a10a3f2fa7 Merge branch 'master' of https://github.com/vanhauser-thc/AFLplusplus 2020-03-06 16:28:26 -05:00
2287534ec6 Merge branch 'master' of github.com:vanhauser-thc/AFLplusplus 2020-03-06 21:23:54 +01:00
27d6d35893 small fix to run cmplog binaries outside afl-fuzz 2020-03-06 21:23:47 +01:00
13429d204d adapt child handling to nawk from *BSD 2020-03-06 20:57:28 +01:00
0d4f2da8db terminate afl-cmin early when signalled SIGINT 2020-03-06 19:33:02 +01:00
47fdbf3817 Merge pull request #235 from antonio-morales/patch-1
Fixing 2 little mistakes
2020-03-06 16:53:10 +01:00
1d4a3c87f5 cmplog routines instrumentation for qemu mode on x86 2020-03-06 16:43:18 +01:00
c18f6c2618 Fixing 2 little mistakes
This example doesn't compile due to two little errors:
- There is a missing semicolon
- "data" array doesn't exist. I think "buf" should be used instead.
2020-03-06 16:09:43 +01:00
6e8f249b20 fix #227 2020-03-05 20:43:28 +01:00
3ac568c40c Fix leaks when stopping afl (#228) 2020-03-05 20:23:04 +01:00
90409f383a added AFL_QUIET - be_quiet to afl-showmap and small changes to test.sh 2020-03-05 11:36:37 +01:00
cc72f5dfd0 clarify -N option 2020-03-05 11:04:55 +01:00
6d620f5e0c fix travis 2020-03-05 11:03:36 +01:00
9d686ba523 Add LTO collision free llvm_mode (#223)
* first new implementation, only works with AFL_DONT_OPTIMIZE

* bug hunting

* interim commit

* finalized LTO non-collision solution

* update documentation

* merge resulted in some problems, fixing these

* added lto env to env check

* fixed llvm weirdness to messes up our instrumentation due CFG rewrite optimizations

* all llvm instrumentation issues have been resolved! :-)

* llvm 9 is required (so far)

* update lto readme
2020-03-05 10:52:26 +01:00
9e5c4973eb Fix variable name 2020-03-04 14:58:29 -05:00
70a67ca67d fix null ptr deref before trim_case_custom call 2020-03-04 19:28:29 +01:00
e43473faef Merge pull request #221 from h1994st/master
Uniform Python and custom mutator API
2020-03-04 18:38:03 +01:00
38e7dd2b9e Update examples of the custom mutator
- Merge `examples/python_mutators` into `examples/custom_mutators`
- Remove `examples/python_mutators`
- Update existing examples to demonstrate new APIs
2020-03-04 01:09:37 -05:00
42ce48db39 Fix typo 2020-03-03 23:18:47 -05:00
445d4b7e59 Update the documents of the custom mutator
- Merge python_mutators.md into custom_mutator.md
- Remove python_mutators.md
2020-03-03 23:17:24 -05:00
05a3418f86 added __afl_final_loc to all compile RTs 2020-03-04 01:51:41 +01:00
df46521658 Finish refactoring APIs for the custom mutator and Python module
- Remove AFL_PYTHON_ONLY (env) and python_only (variable)
- Unify fuzz API of the custom mutator and Python module
- Merge the custom mutator into the old python_stage, which is now renamed to custom_mutator_stage
2020-03-03 19:48:13 -05:00
d559d5a374 fix prev commit 2020-03-03 11:15:07 +01:00
469b8ee022 Merge branch 'master' of github.com:vanhauser-thc/AFLplusplus 2020-03-03 11:07:49 +01:00
385f7da77f allow custom cflags on llvm makefile 2020-03-03 11:07:41 +01:00
90506479e7 Refactoring fuzz_py API 2020-03-02 21:30:10 -05:00
b2a2b0fc21 Add initialization funcation wrapper for Python mutator 2020-03-02 19:30:05 -05:00
7862416844 Uniform API for both Python and custom mutator 2020-03-02 19:29:41 -05:00
031946136b Merge branch 'master' of https://github.com/vanhauser-thc/AFLplusplus 2020-03-02 15:27:31 -05:00
7b59e05600 Add new APIs for the custom mutator 2020-03-02 15:27:29 -05:00
f6050ab804 Silenced output of if python not found 2020-03-02 16:12:12 +01:00
43e97a5aa2 Autoresume added to help 2020-03-02 16:10:08 +01:00
f0cf9c2cdf make afl-showmap quiet when called from afl-cmin* 2020-03-01 22:30:38 +01:00
3e0a3ec45f migrated autoresume to use get_afl_env 2020-03-01 14:09:21 +01:00
6865cd8d69 Added AFL_AUTORESUME option 2020-03-01 13:47:33 +01:00
59b80cb01e fix #218 for GCC plugin 2020-03-01 11:51:15 +01:00
d946be29b9 fix #218 2020-03-01 11:16:43 +01:00
95322c11d9 print OKF if an environment variable is successfully loaded - feebdack to this please ... 2020-02-29 20:49:16 +01:00
76ca6adbc5 afl-clang-fast: only show the official env vars 2020-02-29 15:12:27 +01:00
45aa579f68 Added missing dependency to the docu (#216)
* Added missing dependency to the documentation. Tested on Debian 10

* Added documentation for Debian users

Co-authored-by: adamgrimm99 <55899195+adamgrimm99@users.noreply.github.com>
2020-02-29 14:42:19 +01:00
9ddd7e0e3f wget is no longer necessary for unicornafl which is cloned now. (#217) 2020-02-29 14:39:29 +01:00
6730b6a15a code-format, env.md fixes and adding -hh for env usage display into afl-fuzz and Makefile 2020-02-29 14:23:44 +01:00
6e08be1d0b add env info to afl-fuzz (please review!), small clarifications in docs/env_variables.md 2020-02-28 22:02:55 +01:00
0b21441590 add env info to afl-gcc-fast 2020-02-28 19:50:07 +01:00
449a14d1d0 more examples for README and custom_mutator README 2020-02-28 14:07:38 +01:00
57495a794d updated contribution info 2020-02-28 10:23:23 +01:00
7d0ae2939d update todo 2020-02-28 07:07:27 +01:00
7fa289316a fix for qemu_mode where capstone 4.0+ is installed 2020-02-28 06:50:15 +01:00
0e8388d3ea add env info to afl-clang-fast, small Android change 2020-02-28 05:00:22 +01:00
caa8fea8e2 add env info to afl-showmap, in qemu_mode add forgotten MacOSX env var to afl-analyze, afl-fuzz, afl-tmin 2020-02-28 03:31:50 +01:00
212e5d1a72 v2.62d 2020-02-28 01:16:36 +01:00
537 changed files with 157917 additions and 53676 deletions

View File

@ -10,7 +10,7 @@ AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
@ -52,7 +52,7 @@ ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
@ -72,7 +72,7 @@ IncludeCategories:
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentPPDirectives: None
IndentPPDirectives: BeforeHash
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave

View File

@ -29,30 +29,31 @@ CLANG_FORMAT_BIN = os.getenv("CLANG_FORMAT_BIN")
if CLANG_FORMAT_BIN is None:
o = 0
try:
p = subprocess.Popen(["clang-format-8", "--version"], stdout=subprocess.PIPE)
p = subprocess.Popen(["clang-format-11", "--version"], stdout=subprocess.PIPE)
o, _ = p.communicate()
o = str(o, "utf-8")
o = o[len("clang-format version "):].strip()
o = o[:o.find(".")]
o = re.sub(r".*ersion ", "", o)
# o = o[len("clang-format version "):].strip()
o = o[: o.find(".")]
o = int(o)
except:
print ("clang-format-8 is needed. Aborted.")
print("clang-format-11 is needed. Aborted.")
exit(1)
#if o < 7:
# if o < 7:
# if subprocess.call(['which', 'clang-format-7'], stdout=subprocess.PIPE) == 0:
# CLANG_FORMAT_BIN = 'clang-format-7'
# elif subprocess.call(['which', 'clang-format-8'], stdout=subprocess.PIPE) == 0:
# CLANG_FORMAT_BIN = 'clang-format-8'
# elif subprocess.call(['which', 'clang-format-9'], stdout=subprocess.PIPE) == 0:
# CLANG_FORMAT_BIN = 'clang-format-9'
# elif subprocess.call(['which', 'clang-format-10'], stdout=subprocess.PIPE) == 0:
# CLANG_FORMAT_BIN = 'clang-format-10'
# elif subprocess.call(['which', 'clang-format-11'], stdout=subprocess.PIPE) == 0:
# CLANG_FORMAT_BIN = 'clang-format-11'
# else:
# print ("clang-format 7 or above is needed. Aborted.")
# exit(1)
else:
CLANG_FORMAT_BIN = 'clang-format-8'
CLANG_FORMAT_BIN = "clang-format-11"
COLUMN_LIMIT = 80
for line in fmt.split("\n"):
line = line.split(":")
@ -68,26 +69,47 @@ def custom_format(filename):
in_define = False
last_line = None
out = ""
for line in src.split("\n"):
if line.startswith("#"):
if line.startswith("#define"):
if line.lstrip().startswith("#"):
if line[line.find("#") + 1 :].lstrip().startswith("define"):
in_define = True
if "/*" in line and not line.strip().startswith("/*") and line.endswith("*/") and len(line) < (COLUMN_LIMIT-2):
if (
"/*" in line
and not line.strip().startswith("/*")
and line.endswith("*/")
and len(line) < (COLUMN_LIMIT - 2)
):
cmt_start = line.rfind("/*")
line = line[:cmt_start] + " " * (COLUMN_LIMIT-2 - len(line)) + line[cmt_start:]
line = (
line[:cmt_start]
+ " " * (COLUMN_LIMIT - 2 - len(line))
+ line[cmt_start:]
)
define_padding = 0
if last_line is not None and in_define and last_line.endswith("\\"):
last_line = last_line[:-1]
define_padding = max(0, len(last_line[last_line.rfind("\n")+1:]))
define_padding = max(0, len(last_line[last_line.rfind("\n") + 1 :]))
if last_line is not None and last_line.strip().endswith("{") and line.strip() != "":
if (
last_line is not None
and last_line.strip().endswith("{")
and line.strip() != ""
):
line = (" " * define_padding + "\\" if in_define else "") + "\n" + line
elif last_line is not None and last_line.strip().startswith("}") and line.strip() != "":
elif (
last_line is not None
and last_line.strip().startswith("}")
and line.strip() != ""
):
line = (" " * define_padding + "\\" if in_define else "") + "\n" + line
elif line.strip().startswith("}") and last_line is not None and last_line.strip() != "":
elif (
line.strip().startswith("}")
and last_line is not None
and last_line.strip() != ""
):
line = (" " * define_padding + "\\" if in_define else "") + "\n" + line
if not line.endswith("\\"):
@ -96,14 +118,15 @@ def custom_format(filename):
out += line + "\n"
last_line = line
return (out)
return out
args = sys.argv[1:]
if len(args) == 0:
print ("Usage: ./format.py [-i] <filename>")
print ()
print (" The -i option, if specified, let the script to modify in-place")
print (" the source files. By default the results are written to stdout.")
print("Usage: ./format.py [-i] <filename>")
print()
print(" The -i option, if specified, let the script to modify in-place")
print(" the source files. By default the results are written to stdout.")
print()
exit(1)
@ -119,4 +142,3 @@ for filename in args:
f.write(code)
else:
print(code)

65
.dockerignore Normal file
View File

@ -0,0 +1,65 @@
.test
.test2
.sync_tmp
*.o
*.so
*.pyc
*.dSYM
as
ld
in
out
core*
afl-analyze
afl-as
afl-clang
afl-clang\+\+
afl-clang-fast
afl-clang-fast\+\+
afl-clang-lto
afl-clang-lto\+\+
afl-fuzz
afl-g\+\+
afl-gcc
afl-gcc-fast
afl-g\+\+-fast
afl-gotcpu
afl-ld
afl-ld-lto
afl-qemu-trace
afl-showmap
afl-tmin
afl-analyze.8
afl-as.8
afl-clang-fast\+\+.8
afl-clang-fast.8
afl-clang-lto.8
afl-clang-lto\+\+.8
afl-cmin.8
afl-cmin.bash.8
afl-fuzz.8
afl-gcc.8
afl-gcc-fast.8
afl-g\+\+-fast.8
afl-gotcpu.8
afl-plot.8
afl-showmap.8
afl-system-config.8
afl-tmin.8
afl-whatsup.8
qemu_mode/libcompcov/compcovtest
qemu_mode/qemu-*
unicorn_mode/samples/*/\.test-*
unicorn_mode/samples/*/output
unicorn_mode/unicornafl
test/unittests/unit_maybe_alloc
test/unittests/unit_preallocable
test/unittests/unit_list
test/unittests/unit_rand
test/unittests/unit_hash
examples/afl_network_proxy/afl-network-server
examples/afl_network_proxy/afl-network-client
examples/afl_frida/afl-frida
examples/afl_frida/libtestinstr.so
examples/afl_frida/frida-gum-example.c
examples/afl_frida/frida-gum.h

31
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@ -0,0 +1,31 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**IMPORTANT**
1. You have verified that the issue to be present in the current `dev` branch
2. Please supply the command line options and relevant environment variables, e.g. a copy-paste of the contents of `out/default/fuzzer_setup`
Thank you for making afl++ better!
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. ...
2. ...
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screen output/Screenshots**
If applicable, add copy-paste of the screen output or screenshot that shows the issue. Please ensure the output is in **English** and not in Chinese, Russian, German, etc.
**Additional context**
Add any other context about the problem here.

View File

@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -0,0 +1,27 @@
name: Publish Docker Images
on:
push:
branches: [ stable ]
paths:
- Dockerfile
pull_request:
branches: [ stable ]
paths:
- Dockerfile
jobs:
push_to_registry:
name: Push Docker images to Dockerhub
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Login to Dockerhub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Publish aflpp to Registry
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: aflplusplus/aflplusplus:latest

28
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,28 @@
name: CI
on:
push:
branches: [ stable, dev ]
pull_request:
branches: [ stable, dev ]
jobs:
build:
runs-on: '${{ matrix.os }}'
strategy:
matrix:
os: [ubuntu-20.04, ubuntu-18.04]
steps:
- uses: actions/checkout@v2
- name: debug
run: apt-cache search plugin-dev | grep gcc- ; echo ; apt-cache search clang-format- | grep clang-format-
- name: install packages
run: sudo apt-get install -y -m -f --install-suggests build-essential git libtool libtool-bin automake bison libglib2.0-0 clang llvm-dev libc++-dev findutils libcmocka-dev python3-dev python3-setuptools
- name: compiler installed
run: gcc -v ; echo ; clang -v
- name: install gcc plugin
run: sudo apt-get install -y -m -f --install-suggests $(readlink /usr/bin/gcc)-plugin-dev
- name: build afl++
run: make distrib ASAN_BUILD=1
- name: run tests
run: sudo -E ./afl-system-config ; export AFL_SKIP_CPUFREQ=1 ; make tests

32
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,32 @@
name: "CodeQL"
on:
push:
branches: [ stable, dev ]
pull_request:
branches: [ stable, dev ]
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: [ 'cpp' ]
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

51
.gitignore vendored
View File

@ -1,28 +1,51 @@
.test
.test2
.sync_tmp
.vscode
*.o
*.so
*.swp
*.pyc
*.dSYM
as
a.out
ld
in
out
core*
compile_commands.json
afl-analyze
afl-as
afl-clang
afl-clang++
afl-clang-fast
afl-clang-fast++
afl-clang-lto
afl-clang-lto++
afl-fuzz
afl-g++
afl-gcc
afl-gcc-fast
afl-g++-fast
afl-gotcpu
afl-ld
afl-ld-lto
afl-qemu-trace
afl-showmap
afl-tmin
afl-analyze.8
afl-as.8
afl-clang-fast++.8
afl-clang-fast.8
afl-clang-lto.8
afl-clang-lto++.8
afl-cmin.8
afl-cmin.bash.8
afl-fuzz.8
afl-c++.8
afl-cc.8
afl-gcc.8
afl-g++.8
afl-gcc-fast.8
afl-g++-fast.8
afl-gotcpu.8
@ -31,10 +54,32 @@ afl-showmap.8
afl-system-config.8
afl-tmin.8
afl-whatsup.8
afl-c++
afl-cc
afl-lto
afl-lto++
afl-lto++.8
afl-lto.8
qemu_mode/libcompcov/compcovtest
as
qemu_mode/qemu-*
unicorn_mode/unicornafl/
qemu_mode/qemuafl
unicorn_mode/samples/*/\.test-*
unicorn_mode/samples/*/output/
core\.*
unicorn_mode/unicornafl
test/unittests/unit_maybe_alloc
test/unittests/unit_preallocable
test/unittests/unit_list
test/unittests/unit_rand
test/unittests/unit_hash
examples/afl_network_proxy/afl-network-server
examples/afl_network_proxy/afl-network-client
examples/afl_frida/afl-frida
examples/afl_frida/libtestinstr.so
examples/afl_frida/frida-gum-example.c
examples/afl_frida/frida-gum.h
examples/aflpp_driver/libAFLDriver.a
examples/aflpp_driver/libAFLQemuDriver.a
libAFLDriver.a
libAFLQemuDriver.a
test/.afl_performance
gmon.out

9
.gitmodules vendored Normal file
View File

@ -0,0 +1,9 @@
[submodule "unicorn_mode/unicornafl"]
path = unicorn_mode/unicornafl
url = https://github.com/AFLplusplus/unicornafl
[submodule "custom_mutators/grammar_mutator"]
path = custom_mutators/grammar_mutator/grammar_mutator
url = https://github.com/AFLplusplus/Grammar-Mutator
[submodule "qemu_mode/qemuafl"]
path = qemu_mode/qemuafl
url = https://github.com/AFLplusplus/qemuafl

View File

@ -1,53 +0,0 @@
language: c
sudo: required
branches:
only:
- master
matrix:
include:
- os: linux
dist: bionic
env: NAME="bionic-amd64" MODERN="yes" GCC="7"
- os: linux
dist: xenial
env: NAME="xenial-amd64" MODERN="no" GCC="5" EXTRA="libtool-bin clang-6.0"
- os: linux
dist: trusty
env: NAME="trusty-amd64" MODERN="no" GCC="4.8"
# - os: linux # until travis can fix this!
# dist: xenial
# arch: arm64
# env: NAME="xenial-arm64" MODERN="no" GCC="5" EXTRA="libtool-bin clang-6.0" AFL_NO_X86="1" CPU_TARGET="aarch64"
# - os: osx
# osx_image: xcode11.2
# env: NAME="osx" HOMEBREW_NO_ANALYTICS="1" LINK="http://releases.llvm.org/9.0.0/" NAME="clang+llvm-9.0.0-x86_64-darwin-apple"
jobs:
allow_failures:
- os: osx
env:
- AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 AFL_NO_UI=1 AFL_STOP_MANUALLY=1
# - AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 AFL_NO_UI=1 AFL_EXIT_WHEN_DONE=1
# TODO: test AFL_BENCH_UNTIL_CRASH once we have a target that crashes
# - AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 AFL_NO_UI=1 AFL_BENCH_JUST_ONE=1
before_install:
# export LLVM_DIR=${TRAVIS_BUILD_DIR}/${LLVM_PACKAGE}
- echo Testing on $NAME
- if [ "$TRAVIS_OS_NAME" = "osx" ]; then wget "$LINK""$NAME".tar.xz ; export LLVM_CONFIG=`pwd`/"$NAME" ; tar xJf "$NAME".tar.xz ; fi
- if [ "$MODERN" = "yes" ]; then sudo apt update ; sudo apt upgrade ; sudo apt install -y libtool libtool-bin automake bison libglib2.0 build-essential clang gcc-"$GCC" gcc-"$GCC"-plugin-dev libc++-"$GCC"-dev findutils ; fi
- if [ "$MODERN" = "no" ]; then sudo apt update ; sudo apt install -y libtool $EXTRA libpixman-1-dev automake bison libglib2.0 build-essential gcc-"$GCC" gcc-"$GCC"-plugin-dev libc++-dev findutils ; fi
script:
- gcc -v
- clang -v
- sudo -E ./afl-system-config
- if [ "$TRAVIS_OS_NAME" = "osx" ]; then export LLVM_CONFIG=`pwd`/"$NAME" ; make source-only ASAN_BUILD=1 ; fi
- if [ "$TRAVIS_OS_NAME" = "linux" -a "$TRAVIS_CPU_ARCH" = "amd64" ]; then make distrib ASAN_BUILD=1 ; fi
- if [ "$TRAVIS_CPU_ARCH" = "arm64" ] ; then echo DEBUG ; find / -name llvm-config.h 2>/dev/null; apt-cache search clang | grep clang- ; apt-cache search llvm | grep llvm- ; dpkg -l | egrep 'clang|llvm'; echo DEBUG ; export LLVM_CONFIG=llvm-config-6.0 ; make ASAN_BUILD=1 ; cd qemu_mode && sh ./build_qemu_support.sh ; cd .. ; fi
- make tests
- travis_terminate 0

View File

@ -1,7 +1,16 @@
cc_defaults {
name: "afl-defaults",
sanitize: {
never: true,
},
local_include_dirs: [
"include",
"instrumentation",
],
cflags: [
"-flto=full",
"-funroll-loops",
"-Wno-pointer-sign",
"-Wno-pointer-arith",
@ -10,24 +19,35 @@ cc_defaults {
"-Wno-unused-function",
"-Wno-format",
"-Wno-user-defined-warnings",
"-DUSE_TRACE_PC=1",
"-DAFL_LLVM_USE_TRACE_PC=1",
"-DBIN_PATH=\"out/host/linux-x86/bin\"",
"-DDOC_PATH=\"out/host/linux-x86/shared/doc/afl\"",
"-D__USE_GNU",
"-D__aarch64__",
"-DDEBUG_BUILD",
"-U_FORTIFY_SOURCE",
"-ggdb3",
"-g",
"-O0",
"-fno-omit-frame-pointer",
],
}
cc_binary {
name: "afl-fuzz",
static_executable: true,
host_supported: true,
compile_multilib: "64",
defaults: [
"afl-defaults",
],
srcs: [
"afl-fuzz.c",
"src/afl-fuzz*.c",
"src/afl-common.c",
"src/afl-sharedmem.c",
"src/afl-forkserver.c",
"src/afl-performance.c",
],
}
@ -41,7 +61,11 @@ cc_binary {
],
srcs: [
"afl-showmap.c",
"src/afl-showmap.c",
"src/afl-common.c",
"src/afl-sharedmem.c",
"src/afl-forkserver.c",
"src/afl-performance.c",
],
}
@ -55,7 +79,11 @@ cc_binary {
],
srcs: [
"afl-tmin.c",
"src/afl-tmin.c",
"src/afl-common.c",
"src/afl-sharedmem.c",
"src/afl-forkserver.c",
"src/afl-performance.c",
],
}
@ -69,7 +97,10 @@ cc_binary {
],
srcs: [
"afl-analyze.c",
"src/afl-analyze.c",
"src/afl-common.c",
"src/afl-sharedmem.c",
"src/afl-performance.c",
],
}
@ -83,12 +114,13 @@ cc_binary {
],
srcs: [
"afl-gotcpu.c",
"src/afl-gotcpu.c",
"src/afl-common.c",
],
}
cc_binary_host {
name: "afl-clang-fast",
name: "afl-cc",
static_executable: true,
defaults: [
@ -98,44 +130,144 @@ cc_binary_host {
cflags: [
"-D__ANDROID__",
"-DAFL_PATH=\"out/host/linux-x86/lib64\"",
"-DAFL_CLANG_FLTO=\"-flto=full\"",
"-DUSE_BINDIR=1",
"-DLLVM_BINDIR=\"prebuilts/clang/host/linux-x86/clang-r383902b/bin\"",
"-DLLVM_LIBDIR=\"prebuilts/clang/host/linux-x86/clang-r383902b/lib64\"",
"-DCLANGPP_BIN=\"prebuilts/clang/host/linux-x86/clang-r383902b/bin/clang++\"",
"-DAFL_REAL_LD=\"prebuilts/clang/host/linux-x86/clang-r383902b/bin/ld.lld\"",
"-DLLVM_LTO=1",
"-DLLVM_MAJOR=11",
"-DLLVM_MINOR=2",
],
srcs: [
"llvm_mode/afl-clang-fast.c",
],
}
cc_binary_host {
name: "afl-clang-fast++",
static_executable: true,
defaults: [
"afl-defaults",
"src/afl-cc.c",
"src/afl-common.c",
],
cflags: [
"-D__ANDROID__",
"-DAFL_PATH=\"out/host/linux-x86/lib64\"",
],
srcs: [
"llvm_mode/afl-clang-fast.c",
symlinks: [
"afl-clang-fast",
"afl-clang-fast++",
],
}
cc_library_static {
name: "afl-llvm-rt",
compile_multilib: "both",
compile_multilib: "64",
vendor_available: true,
host_supported: true,
recovery_available: true,
sdk_version: "9",
apex_available: [
"com.android.adbd",
"com.android.appsearch",
"com.android.art",
"com.android.bluetooth.updatable",
"com.android.cellbroadcast",
"com.android.conscrypt",
"com.android.extservices",
"com.android.cronet",
"com.android.neuralnetworks",
"com.android.media",
"com.android.media.swcodec",
"com.android.mediaprovider",
"com.android.permission",
"com.android.runtime",
"com.android.resolv",
"com.android.tethering",
"com.android.wifi",
"com.android.sdkext",
"com.android.os.statsd",
"//any",
],
defaults: [
"afl-defaults",
],
srcs: [
"llvm_mode/afl-llvm-rt.o.c",
"instrumentation/afl-compiler-rt.o.c",
],
}
cc_library_headers {
name: "libafl_headers",
vendor_available: true,
host_supported: true,
export_include_dirs: [
"include",
],
}
cc_prebuilt_library_static {
name: "libfrida-gum",
compile_multilib: "64",
strip: {
none: true,
},
srcs: [
"utils/afl_frida/android/libfrida-gum.a",
],
export_include_dirs: [
"utils/afl_frida/android",
],
}
cc_library_shared {
name: "libtestinstr",
srcs: [
"utils/afl_frida/libtestinstr.c",
],
cflags: [
"-O0",
"-fPIC",
],
}
cc_binary {
name: "afl-frida",
compile_multilib: "64",
defaults: [
"afl-defaults",
],
cflags: [
"-g",
"-O0",
"-Wno-format",
"-Wno-pointer-sign",
"-fpermissive",
"-fPIC",
],
static_libs: [
"afl-llvm-rt",
"libfrida-gum",
],
shared_libs: [
"libdl",
"liblog",
],
srcs: [
"utils/afl_frida/afl-frida.c",
],
local_include_dirs: [
"utils/afl_frida",
"utils/afl_frida/android",
],
}
subdirs = [
"custom_mutators",
]

View File

@ -1 +0,0 @@
Makefile

View File

@ -1,19 +1,24 @@
# How to submit a Pull Request to AFLplusplus
All contributions (pull requests) must be made against our `dev` branch.
Each modified source file, before merging, must be formatted.
```
make code-formatter
make code-format
```
This should be fine if you modified one of the files already present in the
project, otherwise run:
project, or added a file in a directory we already format, otherwise run:
```
./.custom-format.py -i file-that-you-have-created.c
```
Regarding the coding style, please follow the AFL style.
No camel case at all and use the AFL's macros when possible (e.g. WARNF, FATAL, ...).
No camel case at all and use AFL's macros wherever possible
(e.g. WARNF, FATAL, MAP_SIZE, ...).
Remember that AFLplusplus has to build and run on many platforms, so generalize your Makefiles (or your patches to our pre-existing Makefiles) to be as much general as possible.
Remember that AFLplusplus has to build and run on many platforms, so
generalize your Makefiles/GNUmakefile (or your patches to our pre-existing
Makefiles) to be as generic as possible.

View File

@ -1,37 +1,70 @@
FROM ubuntu:eoan
MAINTAINER David Carlier <devnexen@gmail.com>
#
# This Dockerfile for AFLplusplus uses Ubuntu 20.04 focal and
# installs LLVM 11 from llvm.org for afl-clang-lto support :-)
# It also installs gcc/g++ 10 from the Ubuntu development platform
# since focal has gcc-10 but not g++-10 ...
#
FROM ubuntu:20.04 AS aflplusplus
LABEL "maintainer"="afl++ team <afl@aflplus.plus>"
LABEL "about"="AFLplusplus docker image"
RUN apt-get update && apt-get -y install \
--no-install-suggests --no-install-recommends \
ARG DEBIAN_FRONTEND=noninteractive
env NO_ARCH_OPT 1
RUN apt-get update && \
apt-get -y install --no-install-suggests --no-install-recommends \
automake \
bison \
ninja-build \
bison flex \
build-essential \
clang \
clang-9 \
flex \
git \
python3.7 \
python3.7-dev \
gcc-9 \
gcc-9-plugin-dev \
gcc-9-multilib \
libc++-9-dev \
libtool \
libtool-bin \
python3 python3-dev python3-setuptools python-is-python3 \
libtool libtool-bin \
libglib2.0-dev \
llvm-9-dev \
python-setuptools \
python2.7-dev \
wget \
ca-certificates \
wget vim jupp nano bash-completion less \
apt-utils apt-transport-https ca-certificates gnupg dialog \
libpixman-1-dev \
gnuplot-nox \
&& rm -rf /var/lib/apt/lists/*
ARG CC=gcc-9
ARG CXX=g++-9
ARG LLVM_CONFIG=llvm-config-9
RUN echo "deb http://apt.llvm.org/focal/ llvm-toolchain-focal-12 main" >> /etc/apt/sources.list && \
wget -qO - https://apt.llvm.org/llvm-snapshot.gpg.key | apt-key add -
RUN git clone https://github.com/vanhauser-thc/AFLplusplus
RUN echo "deb http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu focal main" >> /etc/apt/sources.list && \
apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 1E9377A2BA9EF27F
RUN cd AFLplusplus && make clean && make distrib && \
make install && cd .. && rm -rf AFLplusplus
RUN apt-get update && apt-get full-upgrade -y && \
apt-get -y install --no-install-suggests --no-install-recommends \
gcc-10 g++-10 gcc-10-plugin-dev gcc-10-multilib gdb lcov \
clang-12 clang-tools-12 libc++1-12 libc++-12-dev \
libc++abi1-12 libc++abi-12-dev libclang1-12 libclang-12-dev \
libclang-common-12-dev libclang-cpp12 libclang-cpp12-dev liblld-12 \
liblld-12-dev liblldb-12 liblldb-12-dev libllvm12 libomp-12-dev \
libomp5-12 lld-12 lldb-12 llvm-12 llvm-12-dev llvm-12-runtime llvm-12-tools \
&& rm -rf /var/lib/apt/lists/*
RUN update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-10 0
RUN update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-10 0
ENV LLVM_CONFIG=llvm-config-12
ENV AFL_SKIP_CPUFREQ=1
ENV AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1
RUN git clone --depth=1 https://github.com/vanhauser-thc/afl-cov /afl-cov
RUN cd /afl-cov && make install && cd ..
COPY . /AFLplusplus
WORKDIR /AFLplusplus
RUN export CC=gcc-10 && export CXX=g++-10 && make clean && \
make distrib && make install && make clean
RUN echo 'alias joe="jupp --wordwrap"' >> ~/.bashrc
RUN echo 'export PS1="[afl++]$PS1"' >> ~/.bashrc
ENV IS_DOCKER="1"
# Disabled until we have the container ready
#COPY --from=aflplusplus/afl-dyninst /usr/local/lib/libdyninstAPI_RT.so /usr/local/lib/libdyninstAPI_RT.so
#COPY --from=aflplusplus/afl-dyninst /afl-dyninst/libAflDyninst.so /usr/local/lib/libAflDyninst.so

662
GNUmakefile Normal file
View File

@ -0,0 +1,662 @@
#
# american fuzzy lop++ - makefile
# -----------------------------
#
# Originally written by Michal Zalewski
#
# Copyright 2013, 2014, 2015, 2016, 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# For Heiko:
#TEST_MMAP=1
# the hash character is treated differently in different make versions
# so use a variable for '#'
HASH=\#
PREFIX ?= /usr/local
BIN_PATH = $(PREFIX)/bin
HELPER_PATH = $(PREFIX)/lib/afl
DOC_PATH = $(PREFIX)/share/doc/afl
MISC_PATH = $(PREFIX)/share/afl
MAN_PATH = $(PREFIX)/man/man8
PROGNAME = afl
VERSION = $(shell grep '^$(HASH)define VERSION ' ../config.h | cut -d '"' -f2)
# PROGS intentionally omit afl-as, which gets installed elsewhere.
PROGS = afl-fuzz afl-showmap afl-tmin afl-gotcpu afl-analyze
SH_PROGS = afl-plot afl-cmin afl-cmin.bash afl-whatsup afl-system-config
MANPAGES=$(foreach p, $(PROGS) $(SH_PROGS), $(p).8) afl-as.8
ASAN_OPTIONS=detect_leaks=0
ifdef NO_SPLICING
override CFLAGS += -DNO_SPLICING
endif
ifdef ASAN_BUILD
$(info Compiling ASAN version of binaries)
override CFLAGS += $(ASAN_CFLAGS)
LDFLAGS += $(ASAN_LDFLAGS)
endif
ifdef UBSAN_BUILD
$(info Compiling UBSAN version of binaries)
override CFLAGS += -fsanitize=undefined -fno-omit-frame-pointer
override LDFLAGS += -fsanitize=undefined
endif
ifdef MSAN_BUILD
$(info Compiling MSAN version of binaries)
CC := clang
override CFLAGS += -fsanitize=memory -fno-omit-frame-pointer
override LDFLAGS += -fsanitize=memory
endif
ifeq "$(findstring android, $(shell $(CC) --version 2>/dev/null))" ""
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) $(CFLAGS) -Werror -x c - -flto=full -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
CFLAGS_FLTO ?= -flto=full
else
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) $(CFLAGS) -Werror -x c - -flto=thin -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
CFLAGS_FLTO ?= -flto=thin
else
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) $(CFLAGS) -Werror -x c - -flto -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
CFLAGS_FLTO ?= -flto
endif
endif
endif
endif
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) -fno-move-loop-invariants -fdisable-tree-cunrolli -x c - -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
SPECIAL_PERFORMANCE += -fno-move-loop-invariants -fdisable-tree-cunrolli
endif
#ifeq "$(shell echo 'int main() {return 0; }' | $(CC) $(CFLAGS) -Werror -x c - -march=native -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
# ifndef SOURCE_DATE_EPOCH
# HAVE_MARCHNATIVE = 1
# CFLAGS_OPT += -march=native
# endif
#endif
ifneq "$(shell uname)" "Darwin"
#ifeq "$(HAVE_MARCHNATIVE)" "1"
# SPECIAL_PERFORMANCE += -march=native
#endif
# OS X does not like _FORTIFY_SOURCE=2
ifndef DEBUG
CFLAGS_OPT += -D_FORTIFY_SOURCE=2
endif
endif
ifeq "$(shell uname)" "SunOS"
CFLAGS_OPT += -Wno-format-truncation
LDFLAGS = -lkstat -lrt
endif
ifdef STATIC
$(info Compiling static version of binaries, disabling python though)
# Disable python for static compilation to simplify things
PYTHON_OK = 0
PYFLAGS=
PYTHON_INCLUDE = /
CFLAGS_OPT += -static
LDFLAGS += -lm -lpthread -lz -lutil
endif
ifdef PROFILING
$(info Compiling with profiling information, for analysis: gprof ./afl-fuzz gmon.out > prof.txt)
CFLAGS_OPT += -pg -DPROFILING=1
LDFLAGS += -pg
endif
ifdef INTROSPECTION
$(info Compiling with introspection documentation)
CFLAGS_OPT += -DINTROSPECTION=1
endif
ifneq "$(shell uname -m)" "x86_64"
ifneq "$(patsubst i%86,i386,$(shell uname -m))" "i386"
ifneq "$(shell uname -m)" "amd64"
ifneq "$(shell uname -m)" "i86pc"
AFL_NO_X86=1
endif
endif
endif
endif
ifdef DEBUG
$(info Compiling DEBUG version of binaries)
CFLAGS += -ggdb3 -O0 -Wall -Wextra -Werror
else
CFLAGS ?= -O3 -funroll-loops $(CFLAGS_OPT)
endif
override CFLAGS += -g -Wno-pointer-sign -Wno-variadic-macros -Wall -Wextra -Wpointer-arith \
-I include/ -DAFL_PATH=\"$(HELPER_PATH)\" \
-DBIN_PATH=\"$(BIN_PATH)\" -DDOC_PATH=\"$(DOC_PATH)\"
ifeq "$(shell uname -s)" "FreeBSD"
override CFLAGS += -I /usr/local/include/
LDFLAGS += -L /usr/local/lib/
endif
ifeq "$(shell uname -s)" "DragonFly"
override CFLAGS += -I /usr/local/include/
LDFLAGS += -L /usr/local/lib/
endif
ifeq "$(shell uname -s)" "OpenBSD"
override CFLAGS += -I /usr/local/include/ -mno-retpoline
LDFLAGS += -Wl,-z,notext -L /usr/local/lib/
endif
ifeq "$(shell uname -s)" "NetBSD"
override CFLAGS += -I /usr/pkg/include/
LDFLAGS += -L /usr/pkg/lib/
endif
ifeq "$(shell uname -s)" "Haiku"
SHMAT_OK=0
override CFLAGS += -DUSEMMAP=1 -Wno-error=format -fPIC
LDFLAGS += -Wno-deprecated-declarations -lgnu
SPECIAL_PERFORMANCE += -DUSEMMAP=1
endif
AFL_FUZZ_FILES = $(wildcard src/afl-fuzz*.c)
ifneq "$(shell command -v python3m 2>/dev/null)" ""
ifneq "$(shell command -v python3m-config 2>/dev/null)" ""
PYTHON_INCLUDE ?= $(shell python3m-config --includes)
PYTHON_VERSION ?= $(strip $(shell python3m --version 2>&1))
# Starting with python3.8, we need to pass the `embed` flag. Earlier versions didn't know this flag.
ifeq "$(shell python3m-config --embed --libs 2>/dev/null | grep -q lpython && echo 1 )" "1"
PYTHON_LIB ?= $(shell python3m-config --libs --embed --ldflags)
else
PYTHON_LIB ?= $(shell python3m-config --ldflags)
endif
endif
endif
ifeq "$(PYTHON_INCLUDE)" ""
ifneq "$(shell command -v python3 2>/dev/null)" ""
ifneq "$(shell command -v python3-config 2>/dev/null)" ""
PYTHON_INCLUDE ?= $(shell python3-config --includes)
PYTHON_VERSION ?= $(strip $(shell python3 --version 2>&1))
# Starting with python3.8, we need to pass the `embed` flag. Earier versions didn't know this flag.
ifeq "$(shell python3-config --embed --libs 2>/dev/null | grep -q lpython && echo 1 )" "1"
PYTHON_LIB ?= $(shell python3-config --libs --embed --ldflags)
else
PYTHON_LIB ?= $(shell python3-config --ldflags)
endif
endif
endif
endif
ifeq "$(PYTHON_INCLUDE)" ""
ifneq "$(shell command -v python 2>/dev/null)" ""
ifneq "$(shell command -v python-config 2>/dev/null)" ""
PYTHON_INCLUDE ?= $(shell python-config --includes)
PYTHON_LIB ?= $(shell python-config --ldflags)
PYTHON_VERSION ?= $(strip $(shell python --version 2>&1))
endif
endif
endif
# Old Ubuntu and others dont have python/python3-config so we hardcode 3.7
ifeq "$(PYTHON_INCLUDE)" ""
ifneq "$(shell command -v python3.7 2>/dev/null)" ""
ifneq "$(shell command -v python3.7-config 2>/dev/null)" ""
PYTHON_INCLUDE ?= $(shell python3.7-config --includes)
PYTHON_LIB ?= $(shell python3.7-config --ldflags)
PYTHON_VERSION ?= $(strip $(shell python3.7 --version 2>&1))
endif
endif
endif
# Old Ubuntu and others dont have python/python2-config so we hardcode 2.7
ifeq "$(PYTHON_INCLUDE)" ""
ifneq "$(shell command -v python2.7 2>/dev/null)" ""
ifneq "$(shell command -v python2.7-config 2>/dev/null)" ""
PYTHON_INCLUDE ?= $(shell python2.7-config --includes)
PYTHON_LIB ?= $(shell python2.7-config --ldflags)
PYTHON_VERSION ?= $(strip $(shell python2.7 --version 2>&1))
endif
endif
endif
ifdef SOURCE_DATE_EPOCH
BUILD_DATE ?= $(shell date -u -d "@$(SOURCE_DATE_EPOCH)" "+%Y-%m-%d" 2>/dev/null || date -u -r "$(SOURCE_DATE_EPOCH)" "+%Y-%m-%d" 2>/dev/null || date -u "+%Y-%m-%d")
else
BUILD_DATE ?= $(shell date "+%Y-%m-%d")
endif
ifneq "$(filter Linux GNU%,$(shell uname))" ""
ifndef DEBUG
override CFLAGS += -D_FORTIFY_SOURCE=2
endif
LDFLAGS += -ldl -lrt -lm
endif
ifneq "$(findstring FreeBSD, $(shell uname))" ""
override CFLAGS += -pthread
LDFLAGS += -lpthread
endif
ifneq "$(findstring NetBSD, $(shell uname))" ""
override CFLAGS += -pthread
LDFLAGS += -lpthread
endif
ifneq "$(findstring OpenBSD, $(shell uname))" ""
override CFLAGS += -pthread
LDFLAGS += -lpthread
endif
COMM_HDR = include/alloc-inl.h include/config.h include/debug.h include/types.h
ifeq "$(shell echo '$(HASH)include <Python.h>@int main() {return 0; }' | tr @ '\n' | $(CC) $(CFLAGS) -x c - -o .test $(PYTHON_INCLUDE) $(LDFLAGS) $(PYTHON_LIB) 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
PYTHON_OK=1
PYFLAGS=-DUSE_PYTHON $(PYTHON_INCLUDE) $(LDFLAGS) $(PYTHON_LIB) -DPYTHON_VERSION="\"$(PYTHON_VERSION)\""
else
PYTHON_OK=0
PYFLAGS=
endif
ifdef NO_PYTHON
PYTHON_OK=0
PYFLAGS=
endif
IN_REPO=0
ifeq "$(shell command -v git >/dev/null && git status >/dev/null 2>&1 && echo 1 || echo 0)" "1"
IN_REPO=1
endif
ifeq "$(shell command -v svn >/dev/null && svn proplist . 2>/dev/null && echo 1 || echo 0)" "1"
IN_REPO=1
endif
ifeq "$(shell echo 'int main() { return 0;}' | $(CC) $(CFLAGS) -fsanitize=address -x c - -o .test2 2>/dev/null && echo 1 || echo 0 ; rm -f .test2 )" "1"
ASAN_CFLAGS=-fsanitize=address -fstack-protector-all -fno-omit-frame-pointer -DASAN_BUILD
ASAN_LDFLAGS=-fsanitize=address -fstack-protector-all -fno-omit-frame-pointer
endif
ifeq "$(shell echo '$(HASH)include <sys/ipc.h>@$(HASH)include <sys/shm.h>@int main() { int _id = shmget(IPC_PRIVATE, 65536, IPC_CREAT | IPC_EXCL | 0600); shmctl(_id, IPC_RMID, 0); return 0;}' | tr @ '\n' | $(CC) $(CFLAGS) -x c - -o .test2 2>/dev/null && echo 1 || echo 0 ; rm -f .test2 )" "1"
SHMAT_OK=1
else
SHMAT_OK=0
override CFLAGS+=-DUSEMMAP=1
LDFLAGS += -Wno-deprecated-declarations
endif
ifdef TEST_MMAP
SHMAT_OK=0
override CFLAGS += -DUSEMMAP=1
LDFLAGS += -Wno-deprecated-declarations
endif
.PHONY: all
all: test_x86 test_shm test_python ready $(PROGS) afl-as llvm gcc_plugin test_build all_done
.PHONY: llvm
llvm:
-$(MAKE) -j -f GNUmakefile.llvm
@test -e afl-cc || { echo "[-] Compiling afl-cc failed. You seem not to have a working compiler." ; exit 1; }
.PHONY: gcc_plugin
gcc_plugin:
-$(MAKE) -f GNUmakefile.gcc_plugin
.PHONY: man
man: $(MANPAGES)
.PHONY: test
test: tests
.PHONY: tests
tests: source-only
@cd test ; ./test-all.sh
@rm -f test/errors
.PHONY: performance-tests
performance-tests: performance-test
.PHONY: test-performance
test-performance: performance-test
.PHONY: performance-test
performance-test: source-only
@cd test ; ./test-performance.sh
# hint: make targets are also listed in the top level README.md
.PHONY: help
help:
@echo "HELP --- the following make targets exist:"
@echo "=========================================="
@echo "all: just the main afl++ binaries"
@echo "binary-only: everything for binary-only fuzzing: qemu_mode, unicorn_mode, libdislocator, libtokencap"
@echo "source-only: everything for source code fuzzing: gcc_plugin, libdislocator, libtokencap"
@echo "distrib: everything (for both binary-only and source code fuzzing)"
@echo "man: creates simple man pages from the help option of the programs"
@echo "install: installs everything you have compiled with the build option above"
@echo "clean: cleans everything compiled (not downloads when on a checkout)"
@echo "deepclean: cleans everything including downloads"
@echo "code-format: format the code, do this before you commit and send a PR please!"
@echo "tests: this runs the test framework. It is more catered for the developers, but if you run into problems this helps pinpointing the problem"
@echo "unit: perform unit tests (based on cmocka and GNU linker)"
@echo "document: creates afl-fuzz-document which will only do one run and save all manipulated inputs into out/queue/mutations"
@echo "help: shows these build options :-)"
@echo "=========================================="
@echo "Recommended: \"distrib\" or \"source-only\", then \"install\""
@echo
@echo Known build environment options:
@echo "=========================================="
@echo STATIC - compile AFL++ static
@echo ASAN_BUILD - compiles with memory sanitizer for debug purposes
@echo DEBUG - no optimization, -ggdb3, all warnings and -Werror
@echo PROFILING - compile afl-fuzz with profiling information
@echo INTROSPECTION - compile afl-fuzz with mutation introspection
@echo NO_PYTHON - disable python support
@echo NO_SPLICING - disables splicing mutation in afl-fuzz, not recommended for normal fuzzing
@echo AFL_NO_X86 - if compiling on non-intel/amd platforms
@echo NO_ARCH_OPT - builds afl++ without machine architecture optimizations
@echo "LLVM_CONFIG - if your distro doesn't use the standard name for llvm-config (e.g. Debian)"
@echo "=========================================="
@echo e.g.: make ASAN_BUILD=1
.PHONY: test_x86
ifndef AFL_NO_X86
test_x86:
@echo "[*] Checking for the default compiler cc..."
@type $(CC) >/dev/null || ( echo; echo "Oops, looks like there is no compiler '"$(CC)"' in your path."; echo; echo "Don't panic! You can restart with '"$(_)" CC=<yourCcompiler>'."; echo; exit 1 )
@echo "[*] Testing the PATH environment variable..."
@test "$${PATH}" != "$${PATH#.:}" && { echo "Please remove current directory '.' from PATH to avoid recursion of 'as', thanks!"; echo; exit 1; } || :
@echo "[*] Checking for the ability to compile x86 code..."
@echo 'main() { __asm__("xorb %al, %al"); }' | $(CC) $(CFLAGS) -w -x c - -o .test1 || ( echo; echo "Oops, looks like your compiler can't generate x86 code."; echo; echo "Don't panic! You can use the LLVM or QEMU mode, but see docs/INSTALL first."; echo "(To ignore this error, set AFL_NO_X86=1 and try again.)"; echo; exit 1 )
@rm -f .test1
else
test_x86:
@echo "[!] Note: skipping x86 compilation checks (AFL_NO_X86 set)."
endif
.PHONY: test_shm
ifeq "$(SHMAT_OK)" "1"
test_shm:
@echo "[+] shmat seems to be working."
@rm -f .test2
else
test_shm:
@echo "[-] shmat seems not to be working, switching to mmap implementation"
endif
.PHONY: test_python
ifeq "$(PYTHON_OK)" "1"
test_python:
@rm -f .test 2> /dev/null
@echo "[+] $(PYTHON_VERSION) support seems to be working."
else
test_python:
@echo "[-] You seem to need to install the package python3-dev, python2-dev or python-dev (and perhaps python[23]-apt), but it is optional so we continue"
endif
.PHONY: ready
ready:
@echo "[+] Everything seems to be working, ready to compile."
afl-as: src/afl-as.c include/afl-as.h $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) src/$@.c -o $@ $(LDFLAGS)
@ln -sf afl-as as
src/afl-performance.o : $(COMM_HDR) src/afl-performance.c include/hash.h
$(CC) $(CFLAGS) -Iinclude $(SPECIAL_PERFORMANCE) -O3 -fno-unroll-loops -c src/afl-performance.c -o src/afl-performance.o
src/afl-common.o : $(COMM_HDR) src/afl-common.c include/common.h
$(CC) $(CFLAGS) $(CFLAGS_FLTO) -c src/afl-common.c -o src/afl-common.o
src/afl-forkserver.o : $(COMM_HDR) src/afl-forkserver.c include/forkserver.h
$(CC) $(CFLAGS) $(CFLAGS_FLTO) -c src/afl-forkserver.c -o src/afl-forkserver.o
src/afl-sharedmem.o : $(COMM_HDR) src/afl-sharedmem.c include/sharedmem.h
$(CC) $(CFLAGS) $(CFLAGS_FLTO) -c src/afl-sharedmem.c -o src/afl-sharedmem.o
afl-fuzz: $(COMM_HDR) include/afl-fuzz.h $(AFL_FUZZ_FILES) src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o src/afl-performance.o | test_x86
$(CC) $(CFLAGS) $(COMPILE_STATIC) $(CFLAGS_FLTO) $(AFL_FUZZ_FILES) src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o src/afl-performance.o -o $@ $(PYFLAGS) $(LDFLAGS) -lm
afl-showmap: src/afl-showmap.c src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o src/afl-performance.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(COMPILE_STATIC) $(CFLAGS_FLTO) src/$@.c src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o src/afl-performance.o -o $@ $(LDFLAGS)
afl-tmin: src/afl-tmin.c src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o src/afl-performance.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(COMPILE_STATIC) $(CFLAGS_FLTO) src/$@.c src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o src/afl-performance.o -o $@ $(LDFLAGS)
afl-analyze: src/afl-analyze.c src/afl-common.o src/afl-sharedmem.o src/afl-performance.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(COMPILE_STATIC) $(CFLAGS_FLTO) src/$@.c src/afl-common.o src/afl-sharedmem.o src/afl-performance.o -o $@ $(LDFLAGS)
afl-gotcpu: src/afl-gotcpu.c src/afl-common.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(COMPILE_STATIC) $(CFLAGS_FLTO) src/$@.c src/afl-common.o -o $@ $(LDFLAGS)
.PHONY: document
document: afl-fuzz-document
# document all mutations and only do one run (use with only one input file!)
afl-fuzz-document: $(COMM_HDR) include/afl-fuzz.h $(AFL_FUZZ_FILES) src/afl-common.o src/afl-sharedmem.o src/afl-performance.o | test_x86
$(CC) -D_DEBUG=\"1\" -D_AFL_DOCUMENT_MUTATIONS $(CFLAGS) $(CFLAGS_FLTO) $(AFL_FUZZ_FILES) src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.c src/afl-performance.o -o afl-fuzz-document $(PYFLAGS) $(LDFLAGS)
test/unittests/unit_maybe_alloc.o : $(COMM_HDR) include/alloc-inl.h test/unittests/unit_maybe_alloc.c $(AFL_FUZZ_FILES)
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -c test/unittests/unit_maybe_alloc.c -o test/unittests/unit_maybe_alloc.o
unit_maybe_alloc: test/unittests/unit_maybe_alloc.o
@$(CC) $(CFLAGS) -Wl,--wrap=exit -Wl,--wrap=printf test/unittests/unit_maybe_alloc.o -o test/unittests/unit_maybe_alloc $(LDFLAGS) $(ASAN_LDFLAGS) -lcmocka
./test/unittests/unit_maybe_alloc
test/unittests/unit_hash.o : $(COMM_HDR) include/alloc-inl.h test/unittests/unit_hash.c $(AFL_FUZZ_FILES) src/afl-performance.o
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -c test/unittests/unit_hash.c -o test/unittests/unit_hash.o
unit_hash: test/unittests/unit_hash.o src/afl-performance.o
@$(CC) $(CFLAGS) -Wl,--wrap=exit -Wl,--wrap=printf $^ -o test/unittests/unit_hash $(LDFLAGS) $(ASAN_LDFLAGS) -lcmocka
./test/unittests/unit_hash
test/unittests/unit_rand.o : $(COMM_HDR) include/alloc-inl.h test/unittests/unit_rand.c $(AFL_FUZZ_FILES) src/afl-performance.o
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -c test/unittests/unit_rand.c -o test/unittests/unit_rand.o
unit_rand: test/unittests/unit_rand.o src/afl-common.o src/afl-performance.o
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -Wl,--wrap=exit -Wl,--wrap=printf $^ -o test/unittests/unit_rand $(LDFLAGS) $(ASAN_LDFLAGS) -lcmocka
./test/unittests/unit_rand
test/unittests/unit_list.o : $(COMM_HDR) include/list.h test/unittests/unit_list.c $(AFL_FUZZ_FILES)
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -c test/unittests/unit_list.c -o test/unittests/unit_list.o
unit_list: test/unittests/unit_list.o
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -Wl,--wrap=exit -Wl,--wrap=printf test/unittests/unit_list.o -o test/unittests/unit_list $(LDFLAGS) $(ASAN_LDFLAGS) -lcmocka
./test/unittests/unit_list
test/unittests/unit_preallocable.o : $(COMM_HDR) include/alloc-inl.h test/unittests/unit_preallocable.c $(AFL_FUZZ_FILES)
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -c test/unittests/unit_preallocable.c -o test/unittests/unit_preallocable.o
unit_preallocable: test/unittests/unit_preallocable.o
@$(CC) $(CFLAGS) $(ASAN_CFLAGS) -Wl,--wrap=exit -Wl,--wrap=printf test/unittests/unit_preallocable.o -o test/unittests/unit_preallocable $(LDFLAGS) $(ASAN_LDFLAGS) -lcmocka
./test/unittests/unit_preallocable
.PHONY: unit_clean
unit_clean:
@rm -f ./test/unittests/unit_preallocable ./test/unittests/unit_list ./test/unittests/unit_maybe_alloc test/unittests/*.o
.PHONY: unit
ifneq "$(shell uname)" "Darwin"
unit: unit_maybe_alloc unit_preallocable unit_list unit_clean unit_rand unit_hash
else
unit:
@echo [-] unit tests are skipped on Darwin \(lacks GNU linker feature --wrap\)
endif
.PHONY: code-format
code-format:
./.custom-format.py -i src/*.c
./.custom-format.py -i include/*.h
./.custom-format.py -i instrumentation/*.h
./.custom-format.py -i instrumentation/*.cc
./.custom-format.py -i instrumentation/*.c
@#./.custom-format.py -i custom_mutators/*/*.c* # destroys libfuzzer :-(
@#./.custom-format.py -i custom_mutators/*/*.h # destroys honggfuzz :-(
./.custom-format.py -i utils/*/*.c*
./.custom-format.py -i utils/*/*.h
./.custom-format.py -i test/*.c
./.custom-format.py -i qemu_mode/libcompcov/*.c
./.custom-format.py -i qemu_mode/libcompcov/*.cc
./.custom-format.py -i qemu_mode/libcompcov/*.h
./.custom-format.py -i qemu_mode/libqasan/*.c
./.custom-format.py -i qemu_mode/libqasan/*.h
./.custom-format.py -i *.h
./.custom-format.py -i *.c
.PHONY: test_build
ifndef AFL_NO_X86
test_build: afl-cc afl-gcc afl-as afl-showmap
@echo "[*] Testing the CC wrapper afl-cc and its instrumentation output..."
@unset AFL_MAP_SIZE AFL_USE_UBSAN AFL_USE_CFISAN AFL_USE_ASAN AFL_USE_MSAN; ASAN_OPTIONS=detect_leaks=0 AFL_INST_RATIO=100 AFL_PATH=. ./afl-cc test-instr.c -o test-instr 2>&1 || (echo "Oops, afl-cc failed"; exit 1 )
ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr0 ./test-instr < /dev/null
echo 1 | ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr1 ./test-instr
@rm -f test-instr
@cmp -s .test-instr0 .test-instr1; DR="$$?"; rm -f .test-instr0 .test-instr1; if [ "$$DR" = "0" ]; then echo; echo "Oops, the instrumentation of afl-cc does not seem to be behaving correctly!"; echo; echo "Please post to https://github.com/AFLplusplus/AFLplusplus/issues to troubleshoot the issue."; echo; exit 1; fi
@echo
@echo "[+] All right, the instrumentation of afl-cc seems to be working!"
# @echo "[*] Testing the CC wrapper afl-gcc and its instrumentation output..."
# @unset AFL_MAP_SIZE AFL_USE_UBSAN AFL_USE_CFISAN AFL_USE_ASAN AFL_USE_MSAN; AFL_CC=$(CC) ASAN_OPTIONS=detect_leaks=0 AFL_INST_RATIO=100 AFL_PATH=. ./afl-gcc test-instr.c -o test-instr 2>&1 || (echo "Oops, afl-gcc failed"; exit 1 )
# ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr0 ./test-instr < /dev/null
# echo 1 | ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr1 ./test-instr
# @rm -f test-instr
# @cmp -s .test-instr0 .test-instr1; DR="$$?"; rm -f .test-instr0 .test-instr1; if [ "$$DR" = "0" ]; then echo; echo "Oops, the instrumentation of afl-gcc does not seem to be behaving correctly!"; \
# gcc -v 2>&1 | grep -q -- --with-as= && ( echo; echo "Gcc is configured not to use an external assembler with the -B option."; echo "See docs/INSTALL.md section 5 how to build a -B enabled gcc." ) || \
# ( echo; echo "Please post to https://github.com/AFLplusplus/AFLplusplus/issues to troubleshoot the issue." ); echo; exit 0; fi
# @echo
# @echo "[+] All right, the instrumentation of afl-gcc seems to be working!"
else
test_build: afl-cc afl-as afl-showmap
@echo "[!] Note: skipping build tests (you may need to use LLVM or QEMU mode)."
endif
.PHONY: all_done
all_done: test_build
@test -e afl-cc && echo "[+] Main compiler 'afl-cc' successfully built!" || { echo "[-] Main compiler 'afl-cc' failed to build, set up a working build environment first!" ; exit 1 ; }
@test -e cmplog-instructions-pass.so && echo "[+] LLVM mode for 'afl-cc' successfully built!" || echo "[-] LLVM mode for 'afl-cc' failed to build, likely you either don't have llvm installed, or you need to set LLVM_CONFIG, to point to e.g. llvm-config-11. See instrumentation/README.llvm.md how to do this. Highly recommended!"
@test -e SanitizerCoverageLTO.so && echo "[+] LLVM LTO mode for 'afl-cc' successfully built!" || echo "[-] LLVM LTO mode for 'afl-cc' failed to build, this would need LLVM 11+, see instrumentation/README.lto.md how to build it"
@test -e afl-gcc-pass.so && echo "[+] gcc_plugin for 'afl-cc' successfully built!" || echo "[-] gcc_plugin for 'afl-cc' failed to build, unless you really need it that is fine - or read instrumentation/README.gcc_plugin.md how to build it"
@echo "[+] All done! Be sure to review the README.md - it's pretty short and useful."
@if [ "`uname`" = "Darwin" ]; then printf "\nWARNING: Fuzzing on MacOS X is slow because of the unusually high overhead of\nfork() on this OS. Consider using Linux or *BSD. You can also use VirtualBox\n(virtualbox.org) to put AFL inside a Linux or *BSD VM.\n\n"; fi
@! tty <&1 >/dev/null || printf "\033[0;30mNOTE: If you can read this, your terminal probably uses white background.\nThis will make the UI hard to read. See docs/status_screen.md for advice.\033[0m\n" 2>/dev/null
.NOTPARALLEL: clean all
.PHONY: clean
clean:
rm -f $(PROGS) libradamsa.so afl-fuzz-document afl-as as afl-g++ afl-clang afl-clang++ *.o src/*.o *~ a.out core core.[1-9][0-9]* *.stackdump .test .test1 .test2 test-instr .test-instr0 .test-instr1 afl-qemu-trace afl-gcc-fast afl-gcc-pass.so afl-g++-fast ld *.so *.8 test/unittests/*.o test/unittests/unit_maybe_alloc test/unittests/preallocable .afl-* afl-gcc afl-g++ afl-clang afl-clang++ test/unittests/unit_hash test/unittests/unit_rand
-$(MAKE) -f GNUmakefile.llvm clean
-$(MAKE) -f GNUmakefile.gcc_plugin clean
$(MAKE) -C utils/libdislocator clean
$(MAKE) -C utils/libtokencap clean
$(MAKE) -C utils/afl_network_proxy clean
$(MAKE) -C utils/socket_fuzzing clean
$(MAKE) -C utils/argv_fuzzing clean
$(MAKE) -C qemu_mode/unsigaction clean
$(MAKE) -C qemu_mode/libcompcov clean
$(MAKE) -C qemu_mode/libqasan clean
ifeq "$(IN_REPO)" "1"
test -e qemu_mode/qemuafl/Makefile && $(MAKE) -C qemu_mode/qemuafl clean || true
test -e unicorn_mode/unicornafl/Makefile && $(MAKE) -C unicorn_mode/unicornafl clean || true
else
rm -rf qemu_mode/qemuafl
rm -rf unicorn_mode/unicornafl
endif
.PHONY: deepclean
deepclean: clean
rm -rf unicorn_mode/unicornafl
rm -rf qemu_mode/qemuafl
# NEVER EVER ACTIVATE THAT!!!!! git reset --hard >/dev/null 2>&1 || true
.PHONY: distrib
distrib: all
-$(MAKE) -j -f GNUmakefile.llvm
-$(MAKE) -f GNUmakefile.gcc_plugin
$(MAKE) -C utils/libdislocator
$(MAKE) -C utils/libtokencap
-$(MAKE) -C utils/aflpp_driver
$(MAKE) -C utils/afl_network_proxy
$(MAKE) -C utils/socket_fuzzing
$(MAKE) -C utils/argv_fuzzing
-cd qemu_mode && sh ./build_qemu_support.sh
-cd unicorn_mode && unset CFLAGS && sh ./build_unicorn_support.sh
.PHONY: binary-only
binary-only: test_shm test_python ready $(PROGS)
$(MAKE) -C utils/libdislocator
$(MAKE) -C utils/libtokencap
$(MAKE) -C utils/afl_network_proxy
$(MAKE) -C utils/socket_fuzzing
$(MAKE) -C utils/argv_fuzzing
-cd qemu_mode && sh ./build_qemu_support.sh
-cd unicorn_mode && unset CFLAGS && sh ./build_unicorn_support.sh
.PHONY: source-only
source-only: all
-$(MAKE) -j -f GNUmakefile.llvm
-$(MAKE) -f GNUmakefile.gcc_plugin
$(MAKE) -C utils/libdislocator
$(MAKE) -C utils/libtokencap
-$(MAKE) -C utils/aflpp_driver
%.8: %
@echo .TH $* 8 $(BUILD_DATE) "afl++" > $@
@echo .SH NAME >> $@
@echo .B $* >> $@
@echo >> $@
@echo .SH SYNOPSIS >> $@
@./$* -h 2>&1 | head -n 3 | tail -n 1 | sed 's/^\.\///' >> $@
@echo >> $@
@echo .SH OPTIONS >> $@
@echo .nf >> $@
@./$* -hh 2>&1 | tail -n +4 >> $@
@echo >> $@
@echo .SH AUTHOR >> $@
@echo "afl++ was written by Michal \"lcamtuf\" Zalewski and is maintained by Marc \"van Hauser\" Heuse <mh@mh-sec.de>, Heiko \"hexcoder-\" Eissfeldt <heiko.eissfeldt@hexco.de>, Andrea Fioraldi <andreafioraldi@gmail.com> and Dominik Maier <domenukk@gmail.com>" >> $@
@echo The homepage of afl++ is: https://github.com/AFLplusplus/AFLplusplus >> $@
@echo >> $@
@echo .SH LICENSE >> $@
@echo Apache License Version 2.0, January 2004 >> $@
.PHONY: install
install: all $(MANPAGES)
@install -d -m 755 $${DESTDIR}$(BIN_PATH) $${DESTDIR}$(HELPER_PATH) $${DESTDIR}$(DOC_PATH) $${DESTDIR}$(MISC_PATH)
@rm -f $${DESTDIR}$(BIN_PATH)/afl-plot.sh
@rm -f $${DESTDIR}$(BIN_PATH)/afl-as
@rm -f $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt-32.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt-64.o $${DESTDIR}$(HELPER_PATH)/afl-gcc-rt.o
install -m 755 $(PROGS) $(SH_PROGS) $${DESTDIR}$(BIN_PATH)
@if [ -f afl-qemu-trace ]; then install -m 755 afl-qemu-trace $${DESTDIR}$(BIN_PATH); fi
@if [ -f libdislocator.so ]; then set -e; install -m 755 libdislocator.so $${DESTDIR}$(HELPER_PATH); fi
@if [ -f libtokencap.so ]; then set -e; install -m 755 libtokencap.so $${DESTDIR}$(HELPER_PATH); fi
@if [ -f libcompcov.so ]; then set -e; install -m 755 libcompcov.so $${DESTDIR}$(HELPER_PATH); fi
@if [ -f libqasan.so ]; then set -e; install -m 755 libqasan.so $${DESTDIR}$(HELPER_PATH); fi
@if [ -f afl-fuzz-document ]; then set -e; install -m 755 afl-fuzz-document $${DESTDIR}$(BIN_PATH); fi
@if [ -f socketfuzz32.so -o -f socketfuzz64.so ]; then $(MAKE) -C utils/socket_fuzzing install; fi
@if [ -f argvfuzz32.so -o -f argvfuzz64.so ]; then $(MAKE) -C utils/argv_fuzzing install; fi
@if [ -f utils/afl_network_proxy/afl-network-server ]; then $(MAKE) -C utils/afl_network_proxy install; fi
@if [ -f utils/aflpp_driver/libAFLDriver.a ]; then set -e; install -m 644 utils/aflpp_driver/libAFLDriver.a $${DESTDIR}$(HELPER_PATH); fi
@if [ -f utils/aflpp_driver/libAFLQemuDriver.a ]; then set -e; install -m 644 utils/aflpp_driver/libAFLQemuDriver.a $${DESTDIR}$(HELPER_PATH); fi
-$(MAKE) -f GNUmakefile.llvm install
-$(MAKE) -f GNUmakefile.gcc_plugin install
ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-gcc
ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-g++
ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang
ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang++
@mkdir -m 0755 -p ${DESTDIR}$(MAN_PATH)
install -m0644 *.8 ${DESTDIR}$(MAN_PATH)
install -m 755 afl-as $${DESTDIR}$(HELPER_PATH)
ln -sf afl-as $${DESTDIR}$(HELPER_PATH)/as
install -m 644 docs/*.md $${DESTDIR}$(DOC_PATH)
cp -r testcases/ $${DESTDIR}$(MISC_PATH)
cp -r dictionaries/ $${DESTDIR}$(MISC_PATH)

185
GNUmakefile.gcc_plugin Normal file
View File

@ -0,0 +1,185 @@
#
# american fuzzy lop++ - GCC plugin instrumentation
# -----------------------------------------------
#
# Written by Austin Seipp <aseipp@pobox.com> and
# Laszlo Szekeres <lszekeres@google.com> and
# Michal Zalewski and
# Heiko Eißfeldt <heiko@hexco.de>
#
# GCC integration design is based on the LLVM design, which comes
# from Laszlo Szekeres.
#
# Copyright 2015 Google Inc. All rights reserved.
# Copyright 2019-2020 AFLplusplus Project. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#TEST_MMAP=1
PREFIX ?= /usr/local
HELPER_PATH ?= $(PREFIX)/lib/afl
BIN_PATH ?= $(PREFIX)/bin
DOC_PATH ?= $(PREFIX)/share/doc/afl
MAN_PATH ?= $(PREFIX)/share/man/man8
VERSION = $(shell grep '^$(HASH)define VERSION ' ./config.h | cut -d '"' -f2)
CFLAGS ?= -O3 -g -funroll-loops -D_FORTIFY_SOURCE=2
CFLAGS_SAFE := -Wall -Iinclude -Wno-pointer-sign \
-DAFL_PATH=\"$(HELPER_PATH)\" -DBIN_PATH=\"$(BIN_PATH)\" \
-DGCC_VERSION=\"$(GCCVER)\" -DGCC_BINDIR=\"$(GCCBINDIR)\" \
-Wno-unused-function
override CFLAGS += $(CFLAGS_SAFE)
CXXFLAGS ?= -O3 -g -funroll-loops -D_FORTIFY_SOURCE=2
CXXEFLAGS := $(CXXFLAGS) -Wall -std=c++11
CC ?= gcc
CXX ?= g++
ifeq "clang" "$(CC)"
CC = gcc
CXX = g++
endif
ifeq "clang++" "$(CXX)"
CC = gcc
CXX = g++
endif
ifeq "$(findstring Foundation,$(shell $(CC) --version))" ""
CC = gcc
CXX = g++
endif
PLUGIN_BASE = "$(shell $(CC) -print-file-name=plugin)"
PLUGIN_FLAGS = -fPIC -fno-rtti -I$(PLUGIN_BASE)/include -I$(PLUGIN_BASE)
HASH=\#
GCCVER = $(shell $(CC) --version 2>/dev/null | awk 'NR == 1 {print $$NF}')
GCCBINDIR = $(shell dirname `command -v $(CC)` 2>/dev/null )
ifeq "$(shell echo '$(HASH)include <sys/ipc.h>@$(HASH)include <sys/shm.h>@int main() { int _id = shmget(IPC_PRIVATE, 65536, IPC_CREAT | IPC_EXCL | 0600); shmctl(_id, IPC_RMID, 0); return 0;}' | tr @ '\n' | $(CC) -x c - -o .test2 2>/dev/null && echo 1 || echo 0 ; rm -f .test2 )" "1"
SHMAT_OK=1
else
SHMAT_OK=0
override CFLAGS_SAFE += -DUSEMMAP=1
endif
ifeq "$(TEST_MMAP)" "1"
SHMAT_OK=0
override CFLAGS_SAFE += -DUSEMMAP=1
endif
ifneq "$(shell uname -s)" "Haiku"
ifneq "$(shell uname -s)" "OpenBSD"
LDFLAGS += -lrt
endif
else
CFLAGS_SAFE += -DUSEMMAP=1
endif
ifeq "$(shell uname -s)" "OpenBSD"
CC = egcc
CXX = eg++
PLUGIN_FLAGS += -I/usr/local/include
endif
ifeq "$(shell uname -s)" "DragonFly"
PLUGIN_FLAGS += -I/usr/local/include
endif
ifeq "$(shell uname -s)" "SunOS"
PLUGIN_FLAGS += -I/usr/include/gmp
endif
PROGS = ./afl-gcc-pass.so
.PHONY: all
all: test_shm test_deps $(PROGS) test_build all_done
.PHONY: test_shm
ifeq "$(SHMAT_OK)" "1"
test_shm:
@echo "[+] shmat seems to be working."
@rm -f .test2
else
test_shm:
@echo "[-] shmat seems not to be working, switching to mmap implementation"
endif
.PHONY: test_deps
test_deps:
@echo "[*] Checking for working '$(CC)'..."
@command -v $(CC) >/dev/null 2>&1 || ( echo "[-] Oops, can't find '$(CC)'. Make sure that it's in your \$$PATH (or set \$$CC and \$$CXX)."; exit 1 )
# @echo "[*] Checking for gcc for plugin support..."
# @$(CC) -v 2>&1 | grep -q -- --enable-plugin || ( echo "[-] Oops, this gcc has not been configured with plugin support."; exit 1 )
@echo "[*] Checking for gcc plugin development header files..."
@test -d `$(CC) -print-file-name=plugin`/include || ( echo "[-] Oops, can't find gcc header files. Be sure to install 'gcc-X-plugin-dev'."; exit 1 )
@echo "[*] Checking for './afl-showmap'..."
@test -f ./afl-showmap || ( echo "[-] Oops, can't find './afl-showmap'. Be sure to compile AFL first."; exit 1 )
@echo "[+] All set and ready to build."
afl-common.o: ./src/afl-common.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ $(LDFLAGS)
./afl-gcc-pass.so: instrumentation/afl-gcc-pass.so.cc | test_deps
$(CXX) $(CXXEFLAGS) $(PLUGIN_FLAGS) -shared $< -o $@
ln -sf afl-cc afl-gcc-fast
ln -sf afl-cc afl-g++-fast
ln -sf afl-cc.8 afl-gcc-fast.8
ln -sf afl-cc.8 afl-g++-fast.8
.PHONY: test_build
test_build: $(PROGS)
@echo "[*] Testing the CC wrapper and instrumentation output..."
unset AFL_USE_ASAN AFL_USE_MSAN; ASAN_OPTIONS=detect_leaks=0 AFL_QUIET=1 AFL_INST_RATIO=100 AFL_PATH=. AFL_CC=$(CC) ./afl-gcc-fast $(CFLAGS) $(CPPFLAGS) ./test-instr.c -o test-instr $(LDFLAGS)
ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr0 ./test-instr </dev/null
echo 1 | ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr1 ./test-instr
@rm -f test-instr
@cmp -s .test-instr0 .test-instr1; DR="$$?"; rm -f .test-instr0 .test-instr1; if [ "$$DR" = "0" ]; then echo; echo "Oops, the instrumentation does not seem to be behaving correctly!"; echo; echo "Please post to https://github.com/AFLplusplus/AFLplusplus/issues to troubleshoot the issue."; echo; exit 1; fi
@echo "[+] All right, the instrumentation seems to be working!"
.PHONY: all_done
all_done: test_build
@echo "[+] All done! You can now use './afl-gcc-fast' to compile programs."
.NOTPARALLEL: clean
%.8: %
@echo .TH $* 8 `date "+%Y-%m-%d"` "afl++" > ./$@
@echo .SH NAME >> ./$@
@echo .B $* >> ./$@
@echo >> ./$@
@echo .SH SYNOPSIS >> ./$@
@./$* -h 2>&1 | head -n 3 | tail -n 1 | sed 's/^\.\///' >> ./$@
@echo >> ./$@
@echo .SH OPTIONS >> ./$@
@echo .nf >> ./$@
@./$* -h 2>&1 | tail -n +4 >> ./$@
@echo >> ./$@
@echo .SH AUTHOR >> ./$@
@echo "afl++ was written by Michal \"lcamtuf\" Zalewski and is maintained by Marc \"van Hauser\" Heuse <mh@mh-sec.de>, Heiko \"hexcoder-\" Eissfeldt <heiko.eissfeldt@hexco.de>, Andrea Fioraldi <andreafioraldi@gmail.com> and Dominik Maier <domenukk@gmail.com>" >> ./$@
@echo The homepage of afl++ is: https://github.com/AFLplusplus/AFLplusplus >> ./$@
@echo >> ./$@
@echo .SH LICENSE >> ./$@
@echo Apache License Version 2.0, January 2004 >> ./$@
ln -sf afl-cc.8 ./afl-g++-fast.8
.PHONY: install
install: all
ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-gcc-fast
ln -sf afl-c++ $${DESTDIR}$(BIN_PATH)/afl-g++-fast
ln -sf afl-compiler-rt.o $${DESTDIR}$(HELPER_PATH)/afl-gcc-rt.o
install -m 755 ./afl-gcc-pass.so $${DESTDIR}$(HELPER_PATH)
install -m 644 -T instrumentation/README.gcc_plugin.md $${DESTDIR}$(DOC_PATH)/README.gcc_plugin.md
.PHONY: clean
clean:
rm -f *.o *.so *~ a.out core core.[1-9][0-9]* test-instr .test-instr0 .test-instr1 .test2
rm -f $(PROGS) afl-common.o ./afl-g++-fast ./afl-g*-fast.8 instrumentation/*.o

522
GNUmakefile.llvm Normal file
View File

@ -0,0 +1,522 @@
# american fuzzy lop++ - LLVM instrumentation
# -----------------------------------------
#
# Written by Laszlo Szekeres <lszekeres@google.com> and
# Michal Zalewski
#
# LLVM integration design comes from Laszlo Szekeres.
#
# Copyright 2015, 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# For Heiko:
#TEST_MMAP=1
HASH=\#
PREFIX ?= /usr/local
HELPER_PATH ?= $(PREFIX)/lib/afl
BIN_PATH ?= $(PREFIX)/bin
DOC_PATH ?= $(PREFIX)/share/doc/afl
MISC_PATH ?= $(PREFIX)/share/afl
MAN_PATH ?= $(PREFIX)/share/man/man8
BUILD_DATE ?= $(shell date -u -d "@$(SOURCE_DATE_EPOCH)" "+%Y-%m-%d" 2>/dev/null || date -u -r "$(SOURCE_DATE_EPOCH)" "+%Y-%m-%d" 2>/dev/null || date -u "+%Y-%m-%d")
VERSION = $(shell grep '^$(HASH)define VERSION ' ./config.h | cut -d '"' -f2)
ifeq "$(shell uname)" "OpenBSD"
LLVM_CONFIG ?= $(BIN_PATH)/llvm-config
HAS_OPT = $(shell test -x $(BIN_PATH)/opt && echo 0 || echo 1)
ifeq "$(HAS_OPT)" "1"
$(warning llvm_mode needs a complete llvm installation (versions 3.4 up to 12) -> e.g. "pkg_add llvm-7.0.1p9")
endif
else
LLVM_CONFIG ?= llvm-config
endif
LLVMVER = $(shell $(LLVM_CONFIG) --version 2>/dev/null | sed 's/git//' | sed 's/svn//' )
LLVM_MAJOR = $(shell $(LLVM_CONFIG) --version 2>/dev/null | sed 's/\..*//' )
LLVM_MINOR = $(shell $(LLVM_CONFIG) --version 2>/dev/null | sed 's/.*\.//' | sed 's/git//' | sed 's/svn//' | sed 's/ .*//' )
LLVM_UNSUPPORTED = $(shell $(LLVM_CONFIG) --version 2>/dev/null | egrep -q '^3\.[0-3]|^[0-2]\.' && echo 1 || echo 0 )
LLVM_TOO_NEW = $(shell $(LLVM_CONFIG) --version 2>/dev/null | egrep -q '^1[3-9]' && echo 1 || echo 0 )
LLVM_NEW_API = $(shell $(LLVM_CONFIG) --version 2>/dev/null | egrep -q '^1[0-9]' && echo 1 || echo 0 )
LLVM_10_OK = $(shell $(LLVM_CONFIG) --version 2>/dev/null | egrep -q '^1[1-9]|^10\.[1-9]|^10\.0.[1-9]' && echo 1 || echo 0 )
LLVM_HAVE_LTO = $(shell $(LLVM_CONFIG) --version 2>/dev/null | egrep -q '^1[1-9]' && echo 1 || echo 0 )
LLVM_BINDIR = $(shell $(LLVM_CONFIG) --bindir 2>/dev/null)
LLVM_LIBDIR = $(shell $(LLVM_CONFIG) --libdir 2>/dev/null)
LLVM_STDCXX = gnu++11
LLVM_APPLE_XCODE = $(shell clang -v 2>&1 | grep -q Apple && echo 1 || echo 0)
LLVM_LTO = 0
ifeq "$(LLVMVER)" ""
$(warning [!] llvm_mode needs llvm-config, which was not found)
endif
ifeq "$(LLVM_UNSUPPORTED)" "1"
$(error llvm_mode only supports llvm from version 3.4 onwards)
endif
ifeq "$(LLVM_TOO_NEW)" "1"
$(warning you are using an in-development llvm version - this might break llvm_mode!)
endif
LLVM_TOO_OLD=1
ifeq "$(LLVM_MAJOR)" "9"
$(info [+] llvm_mode detected llvm 9, enabling neverZero implementation)
LLVM_TOO_OLD=0
endif
ifeq "$(LLVM_NEW_API)" "1"
$(info [+] llvm_mode detected llvm 10+, enabling neverZero implementation and c++14)
LLVM_STDCXX = c++14
LLVM_TOO_OLD=0
endif
ifeq "$(LLVM_TOO_OLD)" "1"
$(info [!] llvm_mode detected an old version of llvm, upgrade to at least 9 or preferable 11!)
$(shell sleep 1)
endif
ifeq "$(LLVM_HAVE_LTO)" "1"
$(info [+] llvm_mode detected llvm 11+, enabling afl-lto LTO implementation)
LLVM_LTO = 1
#TEST_MMAP = 1
endif
ifeq "$(LLVM_LTO)" "0"
$(info [+] llvm_mode detected llvm < 11, afl-lto LTO will not be build.)
endif
ifeq "$(LLVM_APPLE_XCODE)" "1"
$(warning llvm_mode will not compile with Xcode clang...)
endif
# We were using llvm-config --bindir to get the location of clang, but
# this seems to be busted on some distros, so using the one in $PATH is
# probably better.
CC = $(LLVM_BINDIR)/clang
CXX = $(LLVM_BINDIR)/clang++
# llvm-config --bindir may not providing a valid path, so ...
ifeq "$(shell test -e $(CC) || echo 1 )" "1"
# however we must ensure that this is not a "CC=gcc make"
ifeq "$(shell command -v $(CC) 2> /dev/null)" ""
# we do not have a valid CC variable so we try alternatives
ifeq "$(shell test -e '$(BIN_DIR)/clang' && echo 1)" "1"
# we found one in the local install directory, lets use these
CC = $(BIN_DIR)/clang
else
# hope for the best
$(warning we have trouble finding clang - llvm-config is not helping us)
CC = clang
endif
endif
endif
# llvm-config --bindir may not providing a valid path, so ...
ifeq "$(shell test -e $(CXX) || echo 1 )" "1"
# however we must ensure that this is not a "CXX=g++ make"
ifeq "$(shell command -v $(CXX) 2> /dev/null)" ""
# we do not have a valid CXX variable so we try alternatives
ifeq "$(shell test -e '$(BIN_DIR)/clang++' && echo 1)" "1"
# we found one in the local install directory, lets use these
CXX = $(BIN_DIR)/clang++
else
# hope for the best
$(warning we have trouble finding clang++ - llvm-config is not helping us)
CXX = clang++
endif
endif
endif
# sanity check.
# Are versions of clang --version and llvm-config --version equal?
CLANGVER = $(shell $(CC) --version | sed -E -ne '/^.*version\ (1?[0-9]\.[0-9]\.[0-9]).*/s//\1/p')
# I disable this because it does not make sense with what we did before (marc)
# We did exactly set these 26 lines above with these values, and it would break
# "CC=gcc make" etc. usages
ifeq "$(findstring clang, $(shell $(CC) --version 2>/dev/null))" ""
CC_SAVE := $(LLVM_BINDIR)/clang
else
CC_SAVE := $(CC)
endif
ifeq "$(findstring clang, $(shell $(CXX) --version 2>/dev/null))" ""
CXX_SAVE := $(LLVM_BINDIR)/clang++
else
CXX_SAVE := $(CXX)
endif
CLANG_BIN := $(CC_SAVE)
CLANGPP_BIN := $(CXX_SAVE)
ifeq "$(CC_SAVE)" "$(LLVM_BINDIR)/clang"
USE_BINDIR = 1
else
ifeq "$(CXX_SAVE)" "$(LLVM_BINDIR)/clang++"
USE_BINDIR = 1
else
USE_BINDIR = 0
endif
endif
# On old platform we cannot compile with clang because std++ libraries are too
# old. For these we need to use gcc/g++, so if we find REAL_CC and REAL_CXX
# variable we override the compiler variables here
ifneq "$(REAL_CC)" ""
CC = $(REAL_CC)
endif
ifneq "$(REAL_CXX)" ""
CXX = $(REAL_CXX)
endif
#
# Now it can happen that CC points to clang - but there is no clang on the
# system. Then we fall back to cc
#
ifeq "$(shell command -v $(CC) 2>/dev/null)" ""
CC = cc
endif
ifeq "$(shell command -v $(CXX) 2>/dev/null)" ""
CXX = c++
endif
# After we set CC/CXX we can start makefile magic tests
#ifeq "$(shell echo 'int main() {return 0; }' | $(CC) -x c - -march=native -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
# CFLAGS_OPT = -march=native
#endif
ifeq "$(shell echo 'int main() {return 0; }' | $(CLANG_BIN) -x c - -flto=full -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
AFL_CLANG_FLTO ?= -flto=full
else
ifeq "$(shell echo 'int main() {return 0; }' | $(CLANG_BIN) -x c - -flto=thin -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
AFL_CLANG_FLTO ?= -flto=thin
else
ifeq "$(shell echo 'int main() {return 0; }' | $(CLANG_BIN) -x c - -flto -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
AFL_CLANG_FLTO ?= -flto
endif
endif
endif
ifeq "$(LLVM_LTO)" "1"
ifneq "$(AFL_CLANG_FLTO)" ""
ifeq "$(AFL_REAL_LD)" ""
ifneq "$(shell readlink $(LLVM_BINDIR)/ld.lld 2>&1)" ""
AFL_REAL_LD = $(LLVM_BINDIR)/ld.lld
else
$(warning ld.lld not found, cannot enable LTO mode)
LLVM_LTO = 0
endif
endif
else
$(warning clang option -flto is not working - maybe LLVMgold.so not found - cannot enable LTO mode)
LLVM_LTO = 0
endif
endif
AFL_CLANG_FUSELD=
ifeq "$(LLVM_LTO)" "1"
ifeq "$(shell echo 'int main() {return 0; }' | $(CLANG_BIN) -x c - -fuse-ld=`command -v ld` -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
AFL_CLANG_FUSELD=1
ifeq "$(shell echo 'int main() {return 0; }' | $(CLANG_BIN) -x c - -fuse-ld=ld.lld --ld-path=$(LLVM_BINDIR)/ld.lld -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
AFL_CLANG_LDPATH=1
endif
else
$(warning -fuse-ld is not working, cannot enable LTO mode)
LLVM_LTO = 0
endif
endif
ifeq "$(shell echo 'int main() {return 0; }' | $(CLANG_BIN) -x c - -fdebug-prefix-map=$(CURDIR)=llvm_mode -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
AFL_CLANG_DEBUG_PREFIX = -fdebug-prefix-map="$(CURDIR)=llvm_mode"
else
AFL_CLANG_DEBUG_PREFIX =
endif
CFLAGS ?= -O3 -funroll-loops -fPIC -D_FORTIFY_SOURCE=2
CFLAGS_SAFE := -Wall -g -Wno-cast-qual -Wno-variadic-macros -Wno-pointer-sign -I ./include/ -I ./instrumentation/ \
-DAFL_PATH=\"$(HELPER_PATH)\" -DBIN_PATH=\"$(BIN_PATH)\" \
-DLLVM_BINDIR=\"$(LLVM_BINDIR)\" -DVERSION=\"$(VERSION)\" \
-DLLVM_LIBDIR=\"$(LLVM_LIBDIR)\" -DLLVM_VERSION=\"$(LLVMVER)\" \
-Wno-deprecated -DAFL_CLANG_FLTO=\"$(AFL_CLANG_FLTO)\" \
-DAFL_REAL_LD=\"$(AFL_REAL_LD)\" \
-DAFL_CLANG_LDPATH=\"$(AFL_CLANG_LDPATH)\" \
-DAFL_CLANG_FUSELD=\"$(AFL_CLANG_FUSELD)\" \
-DCLANG_BIN=\"$(CLANG_BIN)\" -DCLANGPP_BIN=\"$(CLANGPP_BIN)\" -DUSE_BINDIR=$(USE_BINDIR) -Wno-unused-function \
$(AFL_CLANG_DEBUG_PREFIX)
override CFLAGS += $(CFLAGS_SAFE)
ifdef AFL_TRACE_PC
$(info Compile option AFL_TRACE_PC is deprecated, just set AFL_LLVM_INSTRUMENT=PCGUARD to activate when compiling targets )
endif
CXXFLAGS ?= -O3 -funroll-loops -fPIC -D_FORTIFY_SOURCE=2
override CXXFLAGS += -Wall -g -I ./include/ \
-DVERSION=\"$(VERSION)\" -Wno-variadic-macros \
-DLLVM_MINOR=$(LLVM_MINOR) -DLLVM_MAJOR=$(LLVM_MAJOR)
ifneq "$(shell $(LLVM_CONFIG) --includedir) 2> /dev/null" ""
CLANG_CFL = -I$(shell $(LLVM_CONFIG) --includedir)
endif
ifneq "$(LLVM_CONFIG)" ""
CLANG_CFL += -I$(shell dirname $(LLVM_CONFIG))/../include
endif
CLANG_CPPFL = `$(LLVM_CONFIG) --cxxflags` -fno-rtti -fPIC $(CXXFLAGS) -Wno-deprecated-declarations
CLANG_LFL = `$(LLVM_CONFIG) --ldflags` $(LDFLAGS)
# User teor2345 reports that this is required to make things work on MacOS X.
ifeq "$(shell uname)" "Darwin"
CLANG_LFL += -Wl,-flat_namespace -Wl,-undefined,suppress
else
CLANG_CPPFL += -Wl,-znodelete
endif
ifeq "$(shell uname)" "OpenBSD"
CLANG_LFL += `$(LLVM_CONFIG) --libdir`/libLLVM.so
CLANG_CPPFL += -mno-retpoline
CFLAGS += -mno-retpoline
# Needed for unwind symbols
LDFLAGS += -lc++abi -lpthread
endif
ifeq "$(shell echo '$(HASH)include <sys/ipc.h>@$(HASH)include <sys/shm.h>@int main() { int _id = shmget(IPC_PRIVATE, 65536, IPC_CREAT | IPC_EXCL | 0600); shmctl(_id, IPC_RMID, 0); return 0;}' | tr @ '\n' | $(CC) -x c - -o .test2 2>/dev/null && echo 1 || echo 0 ; rm -f .test2 )" "1"
SHMAT_OK=1
else
SHMAT_OK=0
CFLAGS_SAFE += -DUSEMMAP=1
LDFLAGS += -Wno-deprecated-declarations
endif
ifeq "$(TEST_MMAP)" "1"
SHMAT_OK=0
CFLAGS_SAFE += -DUSEMMAP=1
LDFLAGS += -Wno-deprecated-declarations
endif
PROGS_ALWAYS = ./afl-cc ./afl-compiler-rt.o ./afl-compiler-rt-32.o ./afl-compiler-rt-64.o
PROGS = $(PROGS_ALWAYS) ./afl-llvm-pass.so ./SanitizerCoveragePCGUARD.so ./split-compares-pass.so ./split-switches-pass.so ./cmplog-routines-pass.so ./cmplog-instructions-pass.so ./afl-llvm-dict2file.so ./compare-transform-pass.so ./libLLVMInsTrim.so ./afl-ld-lto ./afl-llvm-lto-instrumentlist.so ./afl-llvm-lto-instrumentation.so ./SanitizerCoverageLTO.so
# If prerequisites are not given, warn, do not build anything, and exit with code 0
ifeq "$(LLVMVER)" ""
NO_BUILD = 1
endif
ifneq "$(LLVM_UNSUPPORTED)$(LLVM_APPLE_XCODE)" "00"
NO_BUILD = 1
endif
ifeq "$(NO_BUILD)" "1"
TARGETS = test_shm $(PROGS_ALWAYS) afl-cc.8
else
TARGETS = test_shm test_deps $(PROGS) afl-cc.8 test_build all_done
endif
LLVM_MIN_4_0_1 = $(shell awk 'function tonum(ver, a) {split(ver,a,"."); return a[1]*1000000+a[2]*1000+a[3]} BEGIN { exit tonum(ARGV[1]) >= tonum(ARGV[2]) }' $(LLVMVER) 4.0.1; echo $$?)
.PHONY: all
all: $(TARGETS)
.PHONY: test_shm
ifeq "$(SHMAT_OK)" "1"
test_shm:
@echo "[+] shmat seems to be working."
@rm -f .test2
else
test_shm:
@echo "[-] shmat seems not to be working, switching to mmap implementation"
endif
.PHONY: no_build
no_build:
@printf "%b\\n" "\\033[0;31mPrerequisites are not met, skipping build llvm_mode\\033[0m"
.PHONY: test_deps
test_deps:
@echo "[*] Checking for working 'llvm-config'..."
ifneq "$(LLVM_APPLE_XCODE)" "1"
@type $(LLVM_CONFIG) >/dev/null 2>&1 || ( echo "[-] Oops, can't find 'llvm-config'. Install clang or set \$$LLVM_CONFIG or \$$PATH beforehand."; echo " (Sometimes, the binary will be named llvm-config-3.5 or something like that.)"; exit 1 )
endif
@echo "[*] Checking for working '$(CC)'..."
@type $(CC) >/dev/null 2>&1 || ( echo "[-] Oops, can't find '$(CC)'. Make sure that it's in your \$$PATH (or set \$$CC and \$$CXX)."; exit 1 )
@echo "[*] Checking for matching versions of '$(CC)' and '$(LLVM_CONFIG)'"
ifneq "$(CLANGVER)" "$(LLVMVER)"
@echo "[!] WARNING: we have llvm-config version $(LLVMVER) and a clang version $(CLANGVER)"
else
@echo "[*] We have llvm-config version $(LLVMVER) with a clang version $(CLANGVER), good."
endif
@echo "[*] Checking for './afl-showmap'..."
@test -f ./afl-showmap || ( echo "[-] Oops, can't find './afl-showmap'. Be sure to compile AFL first."; exit 1 )
@echo "[+] All set and ready to build."
instrumentation/afl-common.o: ./src/afl-common.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@ $(LDFLAGS)
./afl-cc: src/afl-cc.c instrumentation/afl-common.o
$(CC) $(CLANG_CFL) $(CFLAGS) $(CPPFLAGS) $< instrumentation/afl-common.o -o $@ -DLLVM_MINOR=$(LLVM_MINOR) -DLLVM_MAJOR=$(LLVM_MAJOR) $(LDFLAGS) -DCFLAGS_OPT=\"$(CFLAGS_OPT)\" -lm
@ln -sf afl-cc ./afl-c++
@ln -sf afl-cc ./afl-gcc
@ln -sf afl-cc ./afl-g++
@ln -sf afl-cc ./afl-clang
@ln -sf afl-cc ./afl-clang++
@ln -sf afl-cc ./afl-clang-fast
@ln -sf afl-cc ./afl-clang-fast++
ifneq "$(AFL_CLANG_FLTO)" ""
ifeq "$(LLVM_LTO)" "1"
@ln -sf afl-cc ./afl-clang-lto
@ln -sf afl-cc ./afl-clang-lto++
@ln -sf afl-cc ./afl-lto
@ln -sf afl-cc ./afl-lto++
endif
endif
instrumentation/afl-llvm-common.o: instrumentation/afl-llvm-common.cc instrumentation/afl-llvm-common.h
$(CXX) $(CFLAGS) $(CPPFLAGS) `$(LLVM_CONFIG) --cxxflags` -fno-rtti -fPIC -std=$(LLVM_STDCXX) -c $< -o $@
./libLLVMInsTrim.so: instrumentation/LLVMInsTrim.so.cc instrumentation/MarkNodes.cc instrumentation/afl-llvm-common.o | test_deps
-$(CXX) $(CLANG_CPPFL) -DLLVMInsTrim_EXPORTS -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< instrumentation/MarkNodes.cc -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
./afl-llvm-pass.so: instrumentation/afl-llvm-pass.so.cc instrumentation/afl-llvm-common.o | test_deps
ifeq "$(LLVM_MIN_4_0_1)" "0"
$(info [!] N-gram branch coverage instrumentation is not available for llvm version $(LLVMVER))
endif
$(CXX) $(CLANG_CPPFL) -DLLVMInsTrim_EXPORTS -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
./SanitizerCoveragePCGUARD.so: instrumentation/SanitizerCoveragePCGUARD.so.cc instrumentation/afl-llvm-common.o | test_deps
ifeq "$(LLVM_10_OK)" "1"
-$(CXX) $(CLANG_CPPFL) -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
endif
./afl-llvm-lto-instrumentlist.so: instrumentation/afl-llvm-lto-instrumentlist.so.cc instrumentation/afl-llvm-common.o
ifeq "$(LLVM_LTO)" "1"
$(CXX) $(CLANG_CPPFL) -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
endif
./afl-ld-lto: src/afl-ld-lto.c
ifeq "$(LLVM_LTO)" "1"
$(CC) $(CFLAGS) $(CPPFLAGS) $< -o $@
endif
./SanitizerCoverageLTO.so: instrumentation/SanitizerCoverageLTO.so.cc
ifeq "$(LLVM_LTO)" "1"
$(CXX) $(CLANG_CPPFL) -Wno-writable-strings -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
endif
./afl-llvm-lto-instrumentation.so: instrumentation/afl-llvm-lto-instrumentation.so.cc instrumentation/afl-llvm-common.o
ifeq "$(LLVM_LTO)" "1"
$(CXX) $(CLANG_CPPFL) -Wno-writable-strings -fno-rtti -fPIC -std=$(LLVM_STDCXX) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
$(CLANG_BIN) $(CFLAGS_SAFE) $(CPPFLAGS) -Wno-unused-result -O0 $(AFL_CLANG_FLTO) -fPIC -c instrumentation/afl-llvm-rt-lto.o.c -o ./afl-llvm-rt-lto.o
@$(CLANG_BIN) $(CFLAGS_SAFE) $(CPPFLAGS) -Wno-unused-result -O0 $(AFL_CLANG_FLTO) -m64 -fPIC -c instrumentation/afl-llvm-rt-lto.o.c -o ./afl-llvm-rt-lto-64.o 2>/dev/null; if [ "$$?" = "0" ]; then : ; fi
@$(CLANG_BIN) $(CFLAGS_SAFE) $(CPPFLAGS) -Wno-unused-result -O0 $(AFL_CLANG_FLTO) -m32 -fPIC -c instrumentation/afl-llvm-rt-lto.o.c -o ./afl-llvm-rt-lto-32.o 2>/dev/null; if [ "$$?" = "0" ]; then : ; fi
endif
# laf
./split-switches-pass.so: instrumentation/split-switches-pass.so.cc instrumentation/afl-llvm-common.o | test_deps
$(CXX) $(CLANG_CPPFL) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
./compare-transform-pass.so: instrumentation/compare-transform-pass.so.cc instrumentation/afl-llvm-common.o | test_deps
$(CXX) $(CLANG_CPPFL) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
./split-compares-pass.so: instrumentation/split-compares-pass.so.cc instrumentation/afl-llvm-common.o | test_deps
$(CXX) $(CLANG_CPPFL) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
# /laf
./cmplog-routines-pass.so: instrumentation/cmplog-routines-pass.cc instrumentation/afl-llvm-common.o | test_deps
$(CXX) $(CLANG_CPPFL) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
./cmplog-instructions-pass.so: instrumentation/cmplog-instructions-pass.cc instrumentation/afl-llvm-common.o | test_deps
$(CXX) $(CLANG_CPPFL) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
afl-llvm-dict2file.so: instrumentation/afl-llvm-dict2file.so.cc instrumentation/afl-llvm-common.o | test_deps
$(CXX) $(CLANG_CPPFL) -shared $< -o $@ $(CLANG_LFL) instrumentation/afl-llvm-common.o
.PHONY: document
document:
$(CLANG_BIN) -D_AFL_DOCUMENT_MUTATIONS $(CFLAGS_SAFE) $(CPPFLAGS) $(CLANG_CFL) -O3 -Wno-unused-result -fPIC -c instrumentation/afl-compiler-rt.o.c -o ./afl-compiler-rt.o
@$(CLANG_BIN) -D_AFL_DOCUMENT_MUTATIONS $(CFLAGS_SAFE) $(CPPFLAGS) $(CLANG_CFL) -O3 -Wno-unused-result -m32 -fPIC -c instrumentation/afl-compiler-rt.o.c -o ./afl-compiler-rt-32.o 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; else echo "failed (that's fine)"; fi
@$(CLANG_BIN) -D_AFL_DOCUMENT_MUTATIONS $(CFLAGS_SAFE) $(CPPFLAGS) $(CLANG_CFL) -O3 -Wno-unused-result -m64 -fPIC -c instrumentation/afl-compiler-rt.o.c -o ./afl-compiler-rt-64.o 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; else echo "failed (that's fine)"; fi
./afl-compiler-rt.o: instrumentation/afl-compiler-rt.o.c
$(CC) $(CLANG_CFL) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -fPIC -c $< -o $@
./afl-compiler-rt-32.o: instrumentation/afl-compiler-rt.o.c
@printf "[*] Building 32-bit variant of the runtime (-m32)... "
@$(CC) $(CLANG_CFL) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m32 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; ln -sf afl-compiler-rt-32.o afl-llvm-rt-32.o; else echo "failed (that's fine)"; fi
./afl-compiler-rt-64.o: instrumentation/afl-compiler-rt.o.c
@printf "[*] Building 64-bit variant of the runtime (-m64)... "
@$(CC) $(CLANG_CFL) $(CFLAGS_SAFE) $(CPPFLAGS) -O3 -Wno-unused-result -m64 -fPIC -c $< -o $@ 2>/dev/null; if [ "$$?" = "0" ]; then echo "success!"; ln -sf afl-compiler-rt-64.o afl-llvm-rt-64.o; else echo "failed (that's fine)"; fi
.PHONY: test_build
test_build: $(PROGS)
@echo "[*] Testing the CC wrapper and instrumentation output..."
unset AFL_USE_ASAN AFL_USE_MSAN AFL_INST_RATIO; ASAN_OPTIONS=detect_leaks=0 AFL_QUIET=1 AFL_PATH=. AFL_LLVM_LAF_ALL=1 ./afl-cc $(CFLAGS) $(CPPFLAGS) ./test-instr.c -o test-instr $(LDFLAGS)
ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr0 ./test-instr < /dev/null
echo 1 | ASAN_OPTIONS=detect_leaks=0 ./afl-showmap -m none -q -o .test-instr1 ./test-instr
@rm -f test-instr
@cmp -s .test-instr0 .test-instr1; DR="$$?"; rm -f .test-instr0 .test-instr1; if [ "$$DR" = "0" ]; then echo; echo "Oops, the instrumentation does not seem to be behaving correctly!"; echo; echo "Please post to https://github.com/AFLplusplus/AFLplusplus/issues to troubleshoot the issue."; echo; exit 1; fi
@echo "[+] All right, the instrumentation seems to be working!"
.PHONY: all_done
all_done: test_build
@echo "[+] All done! You can now use './afl-cc' to compile programs."
.NOTPARALLEL: clean
.PHONY: install
install: all
@install -d -m 755 $${DESTDIR}$(BIN_PATH) $${DESTDIR}$(HELPER_PATH) $${DESTDIR}$(DOC_PATH) $${DESTDIR}$(MISC_PATH)
@if [ -f ./afl-cc ]; then set -e; install -m 755 ./afl-cc $${DESTDIR}$(BIN_PATH); ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-c++; fi
@rm -f $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt*.o $${DESTDIR}$(HELPER_PATH)/afl-gcc-rt*.o
@if [ -f ./afl-compiler-rt.o ]; then set -e; install -m 755 ./afl-compiler-rt.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt.o ;fi
@if [ -f ./afl-lto ]; then set -e; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-lto; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-lto++; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-lto; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-lto++; install -m 755 ./afl-llvm-lto-instrumentation.so ./afl-llvm-rt-lto*.o ./afl-llvm-lto-instrumentlist.so $${DESTDIR}$(HELPER_PATH); fi
@if [ -f ./afl-ld-lto ]; then set -e; install -m 755 ./afl-ld-lto $${DESTDIR}$(BIN_PATH); fi
@if [ -f ./afl-compiler-rt-32.o ]; then set -e; install -m 755 ./afl-compiler-rt-32.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt-32.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt-32.o ;fi
@if [ -f ./afl-compiler-rt-64.o ]; then set -e; install -m 755 ./afl-compiler-rt-64.o $${DESTDIR}$(HELPER_PATH); ln -sf afl-compiler-rt-64.o $${DESTDIR}$(HELPER_PATH)/afl-llvm-rt-64.o ; fi
@if [ -f ./compare-transform-pass.so ]; then set -e; install -m 755 ./*.so $${DESTDIR}$(HELPER_PATH); fi
@if [ -f ./compare-transform-pass.so ]; then set -e; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-fast ; ln -sf ./afl-c++ $${DESTDIR}$(BIN_PATH)/afl-clang-fast++ ; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang ; ln -sf ./afl-c++ $${DESTDIR}$(BIN_PATH)/afl-clang++ ; fi
@if [ -f ./SanitizerCoverageLTO.so ]; then set -e; ln -sf afl-cc $${DESTDIR}$(BIN_PATH)/afl-clang-lto ; ln -sf ./afl-c++ $${DESTDIR}$(BIN_PATH)/afl-clang-lto++ ; fi
set -e; install -m 644 ./dynamic_list.txt $${DESTDIR}$(HELPER_PATH)
install -m 644 instrumentation/README.*.md $${DESTDIR}$(DOC_PATH)/
%.8: %
@echo .TH $* 8 $(BUILD_DATE) "afl++" > ./$@
@echo .SH NAME >> ./$@
@printf "%s" ".B $* \- " >> ./$@
@./$* -h 2>&1 | head -n 1 | sed -e "s/$$(printf '\e')[^m]*m//g" >> ./$@
@echo .B $* >> ./$@
@echo >> ./$@
@echo .SH SYNOPSIS >> ./$@
@./$* -h 2>&1 | head -n 3 | tail -n 1 | sed 's/^\.\///' >> ./$@
@echo >> ./$@
@echo .SH OPTIONS >> ./$@
@echo .nf >> ./$@
@./$* -h 2>&1 | tail -n +4 >> ./$@
@echo >> ./$@
@echo .SH AUTHOR >> ./$@
@echo "afl++ was written by Michal \"lcamtuf\" Zalewski and is maintained by Marc \"van Hauser\" Heuse <mh@mh-sec.de>, Heiko \"hexcoder-\" Eissfeldt <heiko.eissfeldt@hexco.de>, Andrea Fioraldi <andreafioraldi@gmail.com> and Dominik Maier <domenukk@gmail.com>" >> ./$@
@echo The homepage of afl++ is: https://github.com/AFLplusplus/AFLplusplus >> ./$@
@echo >> ./$@
@echo .SH LICENSE >> ./$@
@echo Apache License Version 2.0, January 2004 >> ./$@
@ln -sf afl-cc.8 ./afl-c++.8
ifneq "$(AFL_CLANG_FLTO)" ""
ifeq "$(LLVM_LTO)" "1"
@ln -sf afl-cc.8 ./afl-clang-lto.8
@ln -sf afl-cc.8 ./afl-clang-lto++.8
@ln -sf afl-cc.8 ./afl-lto.8
@ln -sf afl-cc.8 ./afl-lto++.8
endif
endif
.PHONY: clean
clean:
rm -f *.o *.so *~ a.out core core.[1-9][0-9]* .test2 test-instr .test-instr0 .test-instr1 *.dwo
rm -f $(PROGS) afl-common.o ./afl-c++ ./afl-lto ./afl-lto++ ./afl-clang-lto* ./afl-clang-fast* ./afl-clang*.8 ./ld ./afl-ld ./afl-llvm-rt*.o instrumentation/*.o

459
Makefile
View File

@ -1,447 +1,42 @@
#
# american fuzzy lop++ - makefile
# -----------------------------
#
# Originally written by Michal Zalewski
#
# Copyright 2013, 2014, 2015, 2016, 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
all:
@echo trying to use GNU make...
@gmake all || echo please install GNUmake
# For Heiko:
#TEST_MMAP=1
# the hash character is treated differently in different make versions
# so use a variable for '#'
HASH=\#
source-only:
@gmake source-only
PREFIX ?= /usr/local
BIN_PATH = $(PREFIX)/bin
HELPER_PATH = $(PREFIX)/lib/afl
DOC_PATH = $(PREFIX)/share/doc/afl
MISC_PATH = $(PREFIX)/share/afl
MAN_PATH = $(PREFIX)/man/man8
binary-only:
@gmake binary-only
PROGNAME = afl
VERSION = $(shell grep '^$(HASH)define VERSION ' ../config.h | cut -d '"' -f2)
distrib:
@gmake distrib
# PROGS intentionally omit afl-as, which gets installed elsewhere.
man:
@gmake man
PROGS = afl-gcc afl-fuzz afl-showmap afl-tmin afl-gotcpu afl-analyze
SH_PROGS = afl-plot afl-cmin afl-cmin.bash afl-whatsup afl-system-config
MANPAGES=$(foreach p, $(PROGS) $(SH_PROGS), $(p).8) afl-as.8
install:
@gmake install
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) -x c - -flto=full -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
CFLAGS_FLTO ?= -flto=full
else
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) -x c - -flto=thin -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
CFLAGS_FLTO ?= -flto=thin
else
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) -x c - -flto -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
CFLAGS_FLTO ?= -flto
endif
endif
endif
ifeq "$(shell echo 'int main() {return 0; }' | $(CC) -x c - -march=native -o .test 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
CFLAGS_OPT = -march=native
endif
ifneq "$(shell uname -m)" "x86_64"
ifneq "$(shell uname -m)" "i386"
ifneq "$(shell uname -m)" "amd64"
ifneq "$(shell uname -m)" "i86pc"
AFL_NO_X86=1
endif
endif
endif
endif
CFLAGS ?= -O3 -funroll-loops $(CFLAGS_OPT)
override CFLAGS += -Wall -g -Wno-pointer-sign -I include/ \
-DAFL_PATH=\"$(HELPER_PATH)\" -DBIN_PATH=\"$(BIN_PATH)\" \
-DDOC_PATH=\"$(DOC_PATH)\" -Wno-unused-function -fcommon
AFL_FUZZ_FILES = $(wildcard src/afl-fuzz*.c)
ifneq "$(shell which python3m)" ""
ifneq "$(shell which python3m-config)" ""
PYTHON_INCLUDE ?= $(shell python3m-config --includes)
PYTHON_VERSION ?= $(strip $(shell python3m --version 2>&1))
# Starting with python3.8, we need to pass the `embed` flag. Earier versions didn't know this flag.
ifeq "$(shell python3m-config --embed --libs 2>/dev/null | grep -q lpython && echo 1 )" "1"
PYTHON_LIB ?= $(shell python3m-config --libs --embed)
else
PYTHON_LIB ?= $(shell python3m-config --ldflags)
endif
endif
endif
ifneq "$(shell which python3)" ""
ifneq "$(shell which python3-config)" ""
PYTHON_INCLUDE ?= $(shell python3-config --includes)
PYTHON_VERSION ?= $(strip $(shell python3 --version 2>&1))
# Starting with python3.8, we need to pass the `embed` flag. Earier versions didn't know this flag.
ifeq "$(shell python3-config --embed --libs 2>/dev/null | grep -q lpython && echo 1 )" "1"
PYTHON_LIB ?= $(shell python3-config --libs --embed)
else
PYTHON_LIB ?= $(shell python3-config --ldflags)
endif
endif
endif
ifneq "$(shell which python)" ""
ifneq "$(shell which python-config)" ""
PYTHON_INCLUDE ?= $(shell python-config --includes)
PYTHON_LIB ?= $(shell python-config --ldflags)
PYTHON_VERSION ?= $(strip $(shell python --version 2>&1))
endif
endif
ifdef SOURCE_DATE_EPOCH
BUILD_DATE ?= $(shell date -u -d "@$(SOURCE_DATE_EPOCH)" "+%Y-%m-%d" 2>/dev/null || date -u -r "$(SOURCE_DATE_EPOCH)" "+%Y-%m-%d" 2>/dev/null || date -u "+%Y-%m-%d")
else
BUILD_DATE ?= $(shell date "+%Y-%m-%d")
endif
ifneq "$(filter Linux GNU%,$(shell uname))" ""
LDFLAGS += -ldl
endif
ifneq "$(findstring FreeBSD, $(shell uname))" ""
CFLAGS += -pthread
LDFLAGS += -lpthread
endif
ifneq "$(findstring NetBSD, $(shell uname))" ""
CFLAGS += -pthread
LDFLAGS += -lpthread
endif
ifeq "$(findstring clang, $(shell $(CC) --version 2>/dev/null))" ""
TEST_CC = afl-gcc
else
TEST_CC = afl-clang
endif
COMM_HDR = include/alloc-inl.h include/config.h include/debug.h include/types.h
ifeq "$(shell echo '$(HASH)include <Python.h>@int main() {return 0; }' | tr @ '\n' | $(CC) -x c - -o .test $(PYTHON_INCLUDE) $(LDFLAGS) $(PYTHON_LIB) 2>/dev/null && echo 1 || echo 0 ; rm -f .test )" "1"
PYTHON_OK=1
PYFLAGS=-DUSE_PYTHON $(PYTHON_INCLUDE) $(LDFLAGS) $(PYTHON_LIB) -DPYTHON_VERSION="\"$(PYTHON_VERSION)\""
else
PYTHON_OK=0
PYFLAGS=
endif
ifdef STATIC
$(info Compiling static version of binaries)
# Disable python for static compilation to simplify things
PYTHON_OK=0
PYFLAGS=
CFLAGS += -static
LDFLAGS += -lm -lrt -lpthread -lz -lutil
endif
ifeq "$(shell echo '$(HASH)include <sys/ipc.h>@$(HASH)include <sys/shm.h>@int main() { int _id = shmget(IPC_PRIVATE, 65536, IPC_CREAT | IPC_EXCL | 0600); shmctl(_id, IPC_RMID, 0); return 0;}' | tr @ '\n' | $(CC) -x c - -o .test2 2>/dev/null && echo 1 || echo 0 ; rm -f .test2 )" "1"
SHMAT_OK=1
else
SHMAT_OK=0
CFLAGS+=-DUSEMMAP=1
LDFLAGS+=-Wno-deprecated-declarations -lrt
endif
ifeq "$(TEST_MMAP)" "1"
SHMAT_OK=0
CFLAGS+=-DUSEMMAP=1
LDFLAGS+=-Wno-deprecated-declarations -lrt
endif
ifdef ASAN_BUILD
CFLAGS+=-fsanitize=address
LDFLAGS+=-fsanitize=address
endif
all: test_x86 test_shm test_python ready $(PROGS) afl-as test_build all_done
man: $(MANPAGES)
-$(MAKE) -C llvm_mode
-$(MAKE) -C gcc_plugin
tests: source-only
@cd test ; ./test.sh
@rm -f test/errors
performance-tests: performance-test
test-performance: performance-test
performance-test: source-only
@cd test ; ./test-performance.sh
help:
@echo "HELP --- the following make targets exist:"
@echo "=========================================="
@echo "all: just the main afl++ binaries"
@echo "binary-only: everything for binary-only fuzzing: qemu_mode, unicorn_mode, libdislocator, libtokencap, radamsa"
@echo "source-only: everything for source code fuzzing: llvm_mode, gcc_plugin, libdislocator, libtokencap, radamsa"
@echo "distrib: everything (for both binary-only and source code fuzzing)"
@echo "man: creates simple man pages from the help option of the programs"
@echo "install: installs everything you have compiled with the build option above"
@echo "clean: cleans everything. for qemu_mode it means it deletes all downloads as well"
@echo "code-format: format the code, do this before you commit and send a PR please!"
@echo "tests: this runs the test framework. It is more catered for the developers, but if you run into problems this helps pinpointing the problem"
@echo "document: creates afl-fuzz-document which will only do one run and save all manipulated inputs into out/queue/mutations"
@echo "help: shows these build options :-)"
@echo "=========================================="
@echo "Recommended: \"distrib\" or \"source-only\", then \"install\""
@echo
@echo Known build environment options:
@echo "=========================================="
@echo STATIC - compile AFL++ static
@echo ASAN_BUILD - compiles with memory sanitizer for debug purposes
@echo AFL_NO_X86 - if compiling on non-intel/amd platforms
@echo "=========================================="
@echo e.g.: make ASAN_BUILD=1
ifndef AFL_NO_X86
test_x86:
@echo "[*] Checking for the default compiler cc..."
@which $(CC) >/dev/null || ( echo; echo "Oops, looks like there is no compiler '"$(CC)"' in your path."; echo; echo "Don't panic! You can restart with '"$(_)" CC=<yourCcompiler>'."; echo; exit 1 )
@echo "[*] Checking for the ability to compile x86 code..."
@echo 'main() { __asm__("xorb %al, %al"); }' | $(CC) -w -x c - -o .test1 || ( echo; echo "Oops, looks like your compiler can't generate x86 code."; echo; echo "Don't panic! You can use the LLVM or QEMU mode, but see docs/INSTALL first."; echo "(To ignore this error, set AFL_NO_X86=1 and try again.)"; echo; exit 1 )
@rm -f .test1
else
test_x86:
@echo "[!] Note: skipping x86 compilation checks (AFL_NO_X86 set)."
endif
ifeq "$(SHMAT_OK)" "1"
test_shm:
@echo "[+] shmat seems to be working."
@rm -f .test2
else
test_shm:
@echo "[-] shmat seems not to be working, switching to mmap implementation"
endif
ifeq "$(PYTHON_OK)" "1"
test_python:
@rm -f .test 2> /dev/null
@echo "[+] $(PYTHON_VERSION) support seems to be working."
else
test_python:
@echo "[-] You seem to need to install the package python3-dev or python2-dev (and perhaps python[23]-apt), but it is optional so we continue"
endif
ready:
@echo "[+] Everything seems to be working, ready to compile."
afl-gcc: src/afl-gcc.c $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) src/$@.c -o $@ $(LDFLAGS)
set -e; for i in afl-g++ afl-clang afl-clang++; do ln -sf afl-gcc $$i; done
afl-as: src/afl-as.c include/afl-as.h $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) src/$@.c -o $@ $(LDFLAGS)
ln -sf afl-as as
src/afl-common.o : $(COMM_HDR) src/afl-common.c include/common.h
$(CC) $(CFLAGS) $(CFLAGS_FLTO) -c src/afl-common.c -o src/afl-common.o
src/afl-forkserver.o : $(COMM_HDR) src/afl-forkserver.c include/forkserver.h
$(CC) $(CFLAGS) $(CFLAGS_FLTO) -c src/afl-forkserver.c -o src/afl-forkserver.o
src/afl-sharedmem.o : $(COMM_HDR) src/afl-sharedmem.c include/sharedmem.h
$(CC) $(CFLAGS) $(CFLAGS_FLTO) -c src/afl-sharedmem.c -o src/afl-sharedmem.o
radamsa: src/third_party/libradamsa/libradamsa.so
cp src/third_party/libradamsa/libradamsa.so .
src/third_party/libradamsa/libradamsa.so: src/third_party/libradamsa/libradamsa.c src/third_party/libradamsa/radamsa.h
$(MAKE) -C src/third_party/libradamsa/ CFLAGS="$(CFLAGS)"
afl-fuzz: $(COMM_HDR) include/afl-fuzz.h $(AFL_FUZZ_FILES) src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o | test_x86
$(CC) $(CFLAGS) $(CFLAGS_FLTO) $(AFL_FUZZ_FILES) src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o -o $@ $(PYFLAGS) $(LDFLAGS)
afl-showmap: src/afl-showmap.c src/afl-common.o src/afl-sharedmem.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(CFLAGS_FLTO) src/$@.c src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o -o $@ $(LDFLAGS)
afl-tmin: src/afl-tmin.c src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(CFLAGS_FLTO) src/$@.c src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o -o $@ $(LDFLAGS)
afl-analyze: src/afl-analyze.c src/afl-common.o src/afl-sharedmem.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(CFLAGS_FLTO) src/$@.c src/afl-common.o src/afl-sharedmem.o -o $@ $(LDFLAGS)
afl-gotcpu: src/afl-gotcpu.c $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) src/$@.c -o $@ $(LDFLAGS)
# document all mutations and only do one run (use with only one input file!)
document: include/afl-fuzz.h $(AFL_FUZZ_FILES) src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o $(COMM_HDR) | test_x86
$(CC) $(CFLAGS) $(AFL_FUZZ_FILES) -D_AFL_DOCUMENT_MUTATIONS src/afl-common.o src/afl-sharedmem.o src/afl-forkserver.o -o afl-fuzz-document $(LDFLAGS) $(PYFLAGS)
document:
@gmake document
deepclean:
@gmake deepclean
code-format:
./.custom-format.py -i src/*.c
./.custom-format.py -i include/*.h
./.custom-format.py -i libdislocator/*.c
./.custom-format.py -i libtokencap/*.c
./.custom-format.py -i llvm_mode/*.c
./.custom-format.py -i llvm_mode/*.h
./.custom-format.py -i llvm_mode/*.cc
./.custom-format.py -i gcc_plugin/*.c
#./.custom-format.py -i gcc_plugin/*.h
./.custom-format.py -i gcc_plugin/*.cc
./.custom-format.py -i examples/*/*.c
./.custom-format.py -i examples/*/*.h
./.custom-format.py -i qemu_mode/patches/*.h
./.custom-format.py -i qemu_mode/libcompcov/*.c
./.custom-format.py -i qemu_mode/libcompcov/*.cc
./.custom-format.py -i qemu_mode/libcompcov/*.h
./.custom-format.py -i qbdi_mode/*.c
./.custom-format.py -i qbdi_mode/*.cpp
./.custom-format.py -i *.h
./.custom-format.py -i *.c
@gmake code-format
help:
@gmake help
ifndef AFL_NO_X86
tests:
@gmake tests
test_build: afl-gcc afl-as afl-showmap
@echo "[*] Testing the CC wrapper and instrumentation output..."
@unset AFL_USE_ASAN AFL_USE_MSAN AFL_CC; AFL_DEBUG=1 AFL_INST_RATIO=100 AFL_PATH=. ./$(TEST_CC) $(CFLAGS) test-instr.c -o test-instr $(LDFLAGS) 2>&1 | grep 'afl-as' >/dev/null || (echo "Oops, afl-as did not get called from "$(TEST_CC)". This is normally achieved by "$(CC)" honoring the -B option."; exit 1 )
./afl-showmap -m none -q -o .test-instr0 ./test-instr < /dev/null
echo 1 | ./afl-showmap -m none -q -o .test-instr1 ./test-instr
@rm -f test-instr
@cmp -s .test-instr0 .test-instr1; DR="$$?"; rm -f .test-instr0 .test-instr1; if [ "$$DR" = "0" ]; then echo; echo "Oops, the instrumentation does not seem to be behaving correctly!"; echo; echo "Please post to https://github.com/vanhauser-thc/AFLplusplus/issues to troubleshoot the issue."; echo; exit 1; fi
@echo "[+] All right, the instrumentation seems to be working!"
unit:
@gmake unit
else
test_build: afl-gcc afl-as afl-showmap
@echo "[!] Note: skipping build tests (you may need to use LLVM or QEMU mode)."
endif
all_done: test_build
@if [ ! "`which clang 2>/dev/null`" = "" ]; then echo "[+] LLVM users: see llvm_mode/README.md for a faster alternative to afl-gcc."; fi
@echo "[+] All done! Be sure to review the README.md - it's pretty short and useful."
@if [ "`uname`" = "Darwin" ]; then printf "\nWARNING: Fuzzing on MacOS X is slow because of the unusually high overhead of\nfork() on this OS. Consider using Linux or *BSD. You can also use VirtualBox\n(virtualbox.org) to put AFL inside a Linux or *BSD VM.\n\n"; fi
@! tty <&1 >/dev/null || printf "\033[0;30mNOTE: If you can read this, your terminal probably uses white background.\nThis will make the UI hard to read. See docs/status_screen.md for advice.\033[0m\n" 2>/dev/null
.NOTPARALLEL: clean
unit_clean:
@gmake unit_clean
clean:
rm -f $(PROGS) libradamsa.so afl-fuzz-document afl-as as afl-g++ afl-clang afl-clang++ *.o src/*.o *~ a.out core core.[1-9][0-9]* *.stackdump .test .test1 .test2 test-instr .test-instr0 .test-instr1 qemu_mode/qemu-3.1.1.tar.xz afl-qemu-trace afl-gcc-fast afl-gcc-pass.so afl-gcc-rt.o afl-g++-fast *.so *.8
rm -rf out_dir qemu_mode/qemu-3.1.1 *.dSYM */*.dSYM
-$(MAKE) -C llvm_mode clean
-$(MAKE) -C gcc_plugin clean
$(MAKE) -C libdislocator clean
$(MAKE) -C libtokencap clean
$(MAKE) -C examples/socket_fuzzing clean
$(MAKE) -C examples/argv_fuzzing clean
$(MAKE) -C qemu_mode/unsigaction clean
$(MAKE) -C qemu_mode/libcompcov clean
$(MAKE) -C src/third_party/libradamsa/ clean
-rm -rf unicorn_mode/unicornafl
distrib: all radamsa
-$(MAKE) -C llvm_mode
-$(MAKE) -C gcc_plugin
$(MAKE) -C libdislocator
$(MAKE) -C libtokencap
$(MAKE) -C examples/socket_fuzzing
$(MAKE) -C examples/argv_fuzzing
cd qemu_mode && sh ./build_qemu_support.sh
cd unicorn_mode && sh ./build_unicorn_support.sh
binary-only: all radamsa
$(MAKE) -C libdislocator
$(MAKE) -C libtokencap
$(MAKE) -C examples/socket_fuzzing
$(MAKE) -C examples/argv_fuzzing
cd qemu_mode && sh ./build_qemu_support.sh
cd unicorn_mode && sh ./build_unicorn_support.sh
source-only: all radamsa
-$(MAKE) -C llvm_mode
-$(MAKE) -C gcc_plugin
$(MAKE) -C libdislocator
$(MAKE) -C libtokencap
%.8: %
@echo .TH $* 8 $(BUILD_DATE) "afl++" > $@
@echo .SH NAME >> $@
@echo .B $* >> $@
@echo >> $@
@echo .SH SYNOPSIS >> $@
@./$* -h 2>&1 | head -n 3 | tail -n 1 | sed 's/^\.\///' >> $@
@echo >> $@
@echo .SH OPTIONS >> $@
@echo .nf >> $@
@./$* -h 2>&1 | tail -n +4 >> $@
@echo >> $@
@echo .SH AUTHOR >> $@
@echo "afl++ was written by Michal \"lcamtuf\" Zalewski and is maintained by Marc \"van Hauser\" Heuse <mh@mh-sec.de>, Heiko \"hexcoder-\" Eissfeldt <heiko.eissfeldt@hexco.de> and Andrea Fioraldi <andreafioraldi@gmail.com>" >> $@
@echo The homepage of afl++ is: https://github.com/vanhauser-thc/AFLplusplus >> $@
@echo >> $@
@echo .SH LICENSE >> $@
@echo Apache License Version 2.0, January 2004 >> $@
install: all $(MANPAGES)
install -d -m 755 $${DESTDIR}$(BIN_PATH) $${DESTDIR}$(HELPER_PATH) $${DESTDIR}$(DOC_PATH) $${DESTDIR}$(MISC_PATH)
rm -f $${DESTDIR}$(BIN_PATH)/afl-plot.sh
install -m 755 $(PROGS) $(SH_PROGS) $${DESTDIR}$(BIN_PATH)
rm -f $${DESTDIR}$(BIN_PATH)/afl-as
if [ -f afl-qemu-trace ]; then install -m 755 afl-qemu-trace $${DESTDIR}$(BIN_PATH); fi
if [ -f afl-gcc-fast ]; then set e; install -m 755 afl-gcc-fast $${DESTDIR}$(BIN_PATH); ln -sf afl-gcc-fast $${DESTDIR}$(BIN_PATH)/afl-g++-fast; install -m 755 afl-gcc-pass.so afl-gcc-rt.o $${DESTDIR}$(HELPER_PATH); fi
ifndef AFL_TRACE_PC
if [ -f afl-clang-fast -a -f libLLVMInsTrim.so -a -f afl-llvm-rt.o ]; then set -e; install -m 755 afl-clang-fast $${DESTDIR}$(BIN_PATH); ln -sf afl-clang-fast $${DESTDIR}$(BIN_PATH)/afl-clang-fast++; install -m 755 libLLVMInsTrim.so afl-llvm-pass.so afl-llvm-rt.o $${DESTDIR}$(HELPER_PATH); fi
else
if [ -f afl-clang-fast -a -f afl-llvm-rt.o ]; then set -e; install -m 755 afl-clang-fast $${DESTDIR}$(BIN_PATH); ln -sf afl-clang-fast $${DESTDIR}$(BIN_PATH)/afl-clang-fast++; install -m 755 afl-llvm-rt.o $${DESTDIR}$(HELPER_PATH); fi
endif
if [ -f afl-llvm-rt-32.o ]; then set -e; install -m 755 afl-llvm-rt-32.o $${DESTDIR}$(HELPER_PATH); fi
if [ -f afl-llvm-rt-64.o ]; then set -e; install -m 755 afl-llvm-rt-64.o $${DESTDIR}$(HELPER_PATH); fi
if [ -f compare-transform-pass.so ]; then set -e; install -m 755 compare-transform-pass.so $${DESTDIR}$(HELPER_PATH); fi
if [ -f split-compares-pass.so ]; then set -e; install -m 755 split-compares-pass.so $${DESTDIR}$(HELPER_PATH); fi
if [ -f split-switches-pass.so ]; then set -e; install -m 755 split-switches-pass.so $${DESTDIR}$(HELPER_PATH); fi
if [ -f libdislocator.so ]; then set -e; install -m 755 libdislocator.so $${DESTDIR}$(HELPER_PATH); fi
if [ -f libtokencap.so ]; then set -e; install -m 755 libtokencap.so $${DESTDIR}$(HELPER_PATH); fi
if [ -f libcompcov.so ]; then set -e; install -m 755 libcompcov.so $${DESTDIR}$(HELPER_PATH); fi
if [ -f libradamsa.so ]; then set -e; install -m 755 libradamsa.so $${DESTDIR}$(HELPER_PATH); fi
if [ -f afl-fuzz-document ]; then set -e; install -m 755 afl-fuzz-document $${DESTDIR}$(BIN_PATH); fi
$(MAKE) -C examples/socket_fuzzing install
$(MAKE) -C examples/argv_fuzzing install
set -e; ln -sf afl-gcc $${DESTDIR}$(BIN_PATH)/afl-g++
set -e; if [ -f afl-clang-fast ] ; then ln -sf afl-clang-fast $${DESTDIR}$(BIN_PATH)/afl-clang ; ln -sf afl-clang-fast $${DESTDIR}$(BIN_PATH)/afl-clang++ ; else ln -sf afl-gcc $${DESTDIR}$(BIN_PATH)/afl-clang ; ln -sf afl-gcc $${DESTDIR}$(BIN_PATH)/afl-clang++; fi
mkdir -m 0755 -p ${DESTDIR}$(MAN_PATH)
install -m0644 *.8 ${DESTDIR}$(MAN_PATH)
install -m 755 afl-as $${DESTDIR}$(HELPER_PATH)
ln -sf afl-as $${DESTDIR}$(HELPER_PATH)/as
install -m 644 docs/*.md $${DESTDIR}$(DOC_PATH)
cp -r testcases/ $${DESTDIR}$(MISC_PATH)
cp -r dictionaries/ $${DESTDIR}$(MISC_PATH)
@gmake clean

1171
README.md

File diff suppressed because it is too large Load Diff

97
TODO.md
View File

@ -1,92 +1,31 @@
# TODO list for AFL++
## Roadmap 2.61
Makefile:
- -march=native -Ofast -flto=full (especially for afl-fuzz)
llvm_mode:
- using lto + opt to instrument at link time, and using a sat solver to
select basic block IDs that do not result in collisions
(Solution for "The far away future", see bottom of file)
qemu_mode:
- ensure redqueen implementation works fine
- ensure no issues in persistent mode
## Roadmap 3.00+
- AFL_MAP_SIZE for qemu_mode and unicorn_mode
- CPU affinity for many cores? There seems to be an issue > 96 cores
- afl-plot to support multiple plot_data
- afl_custom_fuzz_splice_optin()
- afl_custom_splice()
- intel-pt tracer
## Further down the road
afl-fuzz:
- sync_fuzzers(): only masters sync from all, slaves only sync from master
(@andrea: be careful, often people run all slaves)
- ascii_only mode
gcc_plugin:
- laf-intel
- better instrumentation
- setting min_len/max_len/start_offset/end_offset limits for mutation output
qemu_mode:
- update to 4.x (probably this will be skipped :( )
- instrim for QEMU mode via static analysis (with r2pipe? or angr?)
Idea: The static analyzer outputs a map in which each edge that must be
skipped is marked with 1. QEMU loads it at startup in the parent process.
- rename qemu specific envs to AFL_QEMU (AFL_ENTRYPOINT, AFL_CODE_START/END, AFL_COMPCOV_LEVEL?)
- add AFL_QEMU_EXITPOINT (maybe multiple?)
- non colliding instrumentation
- rename qemu specific envs to AFL_QEMU (AFL_ENTRYPOINT, AFL_CODE_START/END,
AFL_COMPCOV_LEVEL?)
- add AFL_QEMU_EXITPOINT (maybe multiple?), maybe pointless as we have
persistent mode
- add/implement AFL_QEMU_INST_LIBLIST and AFL_QEMU_NOINST_PROGRAM
- add/implement AFL_QEMU_INST_REGIONS as a list of _START/_END addresses
custom_mutators:
- rip what Superion is doing into custom mutators for js, php, etc.
- uniform python and custom mutators API
## Ideas
## The far away future:
Problem: Average targets (tiff, jpeg, unrar) go through 1500 edges.
At afl's default map that means ~16 collisions and ~3 wrappings.
- Solution #1: increase map size.
=> speed loss is bad. last resort solution
every +1 decreases fuzzing speed by ~10% and halfs the collisions
birthday paradox predicts collisions at this # of edges:
| mapsize | collisions |
| :-----: | :--------: |
| 2^16 | 302 |
| 2^17 | 427 |
| 2^18 | 603 |
| 2^19 | 853 |
| 2^20 | 1207 |
| 2^21 | 1706 |
| 2^22 | 2412 |
| 2^23 | 3411 |
| 2^24 | 4823 |
Increasing the map is an easy solution but also not a good one.
- Solution #2: use dynamic map size and collision free basic block IDs
=> This works and is the selected solution
This only works in llvm_mode and llvm >= 9 though
A potential good future solution. Heiko/hexcoder follows this up
- Solution #3: write instruction pointers to a big shared map
=> Tested and it is a dead end
512kb/1MB shared map and the instrumented code writes the instruction
pointer into the map. Map must be big enough but could be command line
controlled.
Good: complete coverage information, nothing is lost. choice of analysis
impacts speed, but this can be decided by user options
Neutral: a little bit slower but no loss of coverage
Bad: completely changes how afl uses the map and the scheduling.
Overall another very good solution, Marc Heuse/vanHauser follows this up
- LTO/sancov: write current edge to prev_loc and use that information when
using cmplog or __sanitizer_cov_trace_cmp*. maybe we can deduct by follow
up edge numbers that both following cmp paths have been found and then
disable working on this edge id -> cmplog_intelligence branch

109
afl-cmin
View File

@ -1,4 +1,6 @@
#!/usr/bin/env sh
export AFL_QUIET=1
export ASAN_OPTIONS=detect_leaks=0
THISPATH=`dirname ${0}`
export PATH="${THISPATH}:$PATH"
awk -f - -- ${@+"$@"} <<'EOF'
@ -23,7 +25,7 @@ awk -f - -- ${@+"$@"} <<'EOF'
# ln
# cp
# pwd
# which
# type
# cd
# find
# stat
@ -111,13 +113,16 @@ function usage() {
" -C - keep crashing inputs, reject everything else\n" \
" -e - solve for edge coverage only, ignore hit counts\n" \
"\n" \
"For additional tips, please consult docs/README.md\n" \
"For additional tips, please consult README.md\n" \
"\n" \
"Environment variables used:\n" \
"AFL_ALLOW_TMP: allow unsafe use of input/output directories under {/var}/tmp\n" \
"AFL_CRASH_EXITCODE: optional child exit code to be interpreted as crash\n" \
"AFL_FORKSRV_INIT_TMOUT: time the fuzzer waits for the target to come up, initially\n" \
"AFL_KEEP_TRACES: leave the temporary <out_dir>/.traces directory\n" \
"AFL_PATH: path for the afl-showmap binary\n" \
"AFL_SKIP_BIN_CHECK: skip check for target binary\n" \
"AFL_ALLOW_TMP: allow unsafe use of input/output directories under {/var}/tmp\n"
"AFL_KILL_SIGNAL: Signal ID delivered to child processes on timeout, etc. (default: SIGKILL)\n"
"AFL_PATH: path for the afl-showmap binary if not found anywhere else\n" \
"AFL_SKIP_BIN_CHECK: skip check for target binary\n"
exit 1
}
@ -130,6 +135,8 @@ BEGIN {
# defaults
extra_par = ""
AFL_CMIN_CRASHES_ONLY = ""
# process options
Opterr = 1 # default is to diagnose
Optind = 1 # skip ARGV[0]
@ -166,7 +173,7 @@ BEGIN {
continue
} else
if (_go_c == "C") {
ENVIRON["AFL_CMIN_CRASHES_ONLY"] = 1
AFL_CMIN_CRASHES_ONLY = "AFL_CMIN_CRASHES_ONLY=1 "
continue
} else
if (_go_c == "e") {
@ -176,14 +183,12 @@ BEGIN {
if (_go_c == "Q") {
if (qemu_mode) { print "Option "_go_c" is only allowed once" > "/dev/stderr"}
extra_par = extra_par " -Q"
if ( !mem_limit_given ) mem_limit = "250"
qemu_mode = 1
continue
} else
if (_go_c == "U") {
if (unicorn_mode) { print "Option "_go_c" is only allowed once" > "/dev/stderr"}
extra_par = extra_par " -U"
if ( !mem_limit_given ) mem_limit = "250"
unicorn_mode = 1
continue
} else
@ -193,7 +198,7 @@ BEGIN {
usage()
} # while options
if (!mem_limit) mem_limit = 200
if (!mem_limit) mem_limit = "none"
if (!timeout) timeout = "none"
# get program args
@ -262,7 +267,7 @@ BEGIN {
if (target_bin && !exists_and_is_executable(target_bin)) {
"which "target_bin" 2>/dev/null" | getline tnew
"command -v "target_bin" 2>/dev/null" | getline tnew
if (!tnew || !exists_and_is_executable(tnew)) {
print "[-] Error: binary '"target_bin"' not found or not executable." > "/dev/stderr"
exit 1
@ -307,14 +312,18 @@ BEGIN {
close( stdin_file )
}
if (!ENVIRON["AFL_PATH"]) {
if (0 == system("test -f afl-cmin")) {
# First we look in PATH
if (0 == system("command -v afl-showmap >/dev/null 2>&1")) {
"command -v afl-showmap 2>/dev/null" | getline showmap
} else {
# then we look in the current directory
if (0 == system("test -x ./afl-showmap")) {
showmap = "./afl-showmap"
} else {
"which afl-showmap 2>/dev/null" | getline showmap
if (ENVIRON["AFL_PATH"]) {
showmap = ENVIRON["AFL_PATH"] "/afl-showmap"
}
}
} else {
showmap = ENVIRON["AFL_PATH"] "/afl-showmap"
}
if (!showmap || 0 != system("test -x "showmap )) {
@ -334,7 +343,7 @@ BEGIN {
stat_format = "-f '%z %N'" # *BSD, MacOS
}
cmdline = "cd "in_dir" && find . \\( ! -name . -a -type d -prune \\) -o -type f -exec stat "stat_format" \\{\\} \\; | sort -k1n -k2r"
cmdline = "ls "in_dir" | (cd "in_dir" && xargs stat "stat_format") | sort -k1n -k2r"
cmdline = "ls "in_dir" | (cd "in_dir" && xargs stat "stat_format" 2>/dev/null) | sort -k1n -k2r"
while (cmdline | getline) {
sub(/^[0-9]+ (\.\/)?/,"",$0)
infilesSmallToBig[i++] = $0
@ -346,7 +355,7 @@ BEGIN {
# Make sure that we're not dealing with a directory.
if (0 == system("test -d "in_dir"/"first_file)) {
print "[-] Error: The input directory contains subdirectories - please fix." > "/dev/stderr"
print "[-] Error: The input directory is empty or contains subdirectories - please fix." > "/dev/stderr"
exit 1
}
@ -356,33 +365,35 @@ BEGIN {
cp_tool = "cp"
}
# Make sure that we can actually get anything out of afl-showmap before we
# waste too much time.
if (!ENVIRON["AFL_SKIP_BIN_CHECK"]) {
# Make sure that we can actually get anything out of afl-showmap before we
# waste too much time.
print "[*] Testing the target binary..."
print "[*] Testing the target binary..."
if (!stdin_file) {
system( "AFL_CMIN_ALLOW_ANY=1 \""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"/.run_test\" -Z "extra_par" -- \""target_bin"\" "prog_args_string" <\""in_dir"/"first_file"\"")
} else {
system("cp "in_dir"/"first_file" "stdin_file)
system( "AFL_CMIN_ALLOW_ANY=1 \""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"/.run_test\" -Z "extra_par" -A \""stdin_file"\" -- \""target_bin"\" "prog_args_string" </dev/null")
}
first_count = 0
runtest = trace_dir"/.run_test"
while ((getline < runtest) > 0) {
++first_count
}
if (first_count) {
print "[+] OK, "first_count" tuples recorded."
} else {
print "[-] Error: no instrumentation output detected (perhaps crash or timeout)." > "/dev/stderr"
if (!ENVIRON["AFL_KEEP_TRACES"]) {
system("rm -rf "trace_dir" 2>/dev/null")
if (!stdin_file) {
system( "AFL_CMIN_ALLOW_ANY=1 "AFL_CMIN_CRASHES_ONLY"\""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"/.run_test\" -Z "extra_par" -- \""target_bin"\" "prog_args_string" <\""in_dir"/"first_file"\"")
} else {
system("cp "in_dir"/"first_file" "stdin_file)
system( "AFL_CMIN_ALLOW_ANY=1 "AFL_CMIN_CRASHES_ONLY"\""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"/.run_test\" -Z "extra_par" -A \""stdin_file"\" -- \""target_bin"\" "prog_args_string" </dev/null")
}
first_count = 0
runtest = trace_dir"/.run_test"
while ((getline < runtest) > 0) {
++first_count
}
if (first_count) {
print "[+] OK, "first_count" tuples recorded."
} else {
print "[-] Error: no instrumentation output detected (perhaps crash or timeout)." > "/dev/stderr"
if (!ENVIRON["AFL_KEEP_TRACES"]) {
system("rm -rf "trace_dir" 2>/dev/null")
}
exit 1
}
exit 1
}
# Let's roll!
@ -396,10 +407,22 @@ BEGIN {
cur = 0;
if (!stdin_file) {
print " Processing "in_count" files (forkserver mode)..."
system( "AFL_CMIN_ALLOW_ANY=1 \""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"\" -Z "extra_par" -i \""in_dir"\" -- \""target_bin"\" "prog_args_string)
# print AFL_CMIN_CRASHES_ONLY"\""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"\" -Z "extra_par" -i \""in_dir"\" -- \""target_bin"\" "prog_args_string
retval = system( AFL_CMIN_CRASHES_ONLY"\""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"\" -Z "extra_par" -i \""in_dir"\" -- \""target_bin"\" "prog_args_string)
} else {
print " Processing "in_count" files (forkserver mode)..."
system( "AFL_CMIN_ALLOW_ANY=1 \""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"\" -Z "extra_par" -i \""in_dir"\" -- \""target_bin"\" "prog_args_string" </dev/null")
# print AFL_CMIN_CRASHES_ONLY"\""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"\" -Z "extra_par" -i \""in_dir"\" -A \""stdin_file"\" -- \""target_bin"\" "prog_args_string" </dev/null"
retval = system( AFL_CMIN_CRASHES_ONLY"\""showmap"\" -m "mem_limit" -t "timeout" -o \""trace_dir"\" -Z "extra_par" -i \""in_dir"\" -A \""stdin_file"\" -- \""target_bin"\" "prog_args_string" </dev/null")
}
if (retval && !AFL_CMIN_CRASHES_ONLY) {
print "[!] Exit code "retval" != 0 received from afl-showmap, terminating..."
if (!ENVIRON["AFL_KEEP_TRACES"]) {
system("rm -rf "trace_dir" 2>/dev/null")
system("rmdir "out_dir)
}
exit retval
}
#######################################################

View File

@ -45,12 +45,14 @@ echo
# Process command-line options...
MEM_LIMIT=200
MEM_LIMIT=none
TIMEOUT=none
unset IN_DIR OUT_DIR STDIN_FILE EXTRA_PAR MEM_LIMIT_GIVEN \
AFL_CMIN_CRASHES_ONLY AFL_CMIN_ALLOW_ANY QEMU_MODE UNICORN_MODE
export AFL_QUIET=1
while getopts "+i:o:f:m:t:eQUCh" opt; do
case "$opt" in
@ -83,12 +85,10 @@ while getopts "+i:o:f:m:t:eQUCh" opt; do
;;
"Q")
EXTRA_PAR="$EXTRA_PAR -Q"
test "$MEM_LIMIT_GIVEN" = "" && MEM_LIMIT=250
QEMU_MODE=1
;;
"U")
EXTRA_PAR="$EXTRA_PAR -U"
test "$MEM_LIMIT_GIVEN" = "" && MEM_LIMIT=250
UNICORN_MODE=1
;;
"?")
@ -126,13 +126,12 @@ Minimization settings:
-C - keep crashing inputs, reject everything else
-e - solve for edge coverage only, ignore hit counts
For additional tips, please consult docs/README.md.
For additional tips, please consult README.md.
Environment variables used:
AFL_KEEP_TRACES: leave the temporary <out_dir>\.traces directory
AFL_PATH: path for the afl-showmap binary
AFL_PATH: last resort location to find the afl-showmap binary
AFL_SKIP_BIN_CHECK: skip check for target binary
AFL_ALLOW_TMP: allow unsafe use of input/output directories under {/var}/tmp
_EOF_
exit 1
fi
@ -140,29 +139,29 @@ fi
# Do a sanity check to discourage the use of /tmp, since we can't really
# handle this safely from a shell script.
if [ "$AFL_ALLOW_TMP" = "" ]; then
echo "$IN_DIR" | grep -qE '^(/var)?/tmp/'
T1="$?"
echo "$TARGET_BIN" | grep -qE '^(/var)?/tmp/'
T2="$?"
echo "$OUT_DIR" | grep -qE '^(/var)?/tmp/'
T3="$?"
echo "$STDIN_FILE" | grep -qE '^(/var)?/tmp/'
T4="$?"
echo "$PWD" | grep -qE '^(/var)?/tmp/'
T5="$?"
if [ "$T1" = "0" -o "$T2" = "0" -o "$T3" = "0" -o "$T4" = "0" -o "$T5" = "0" ]; then
echo "[-] Error: do not use this script in /tmp or /var/tmp." 1>&2
exit 1
fi
fi
#if [ "$AFL_ALLOW_TMP" = "" ]; then
#
# echo "$IN_DIR" | grep -qE '^(/var)?/tmp/'
# T1="$?"
#
# echo "$TARGET_BIN" | grep -qE '^(/var)?/tmp/'
# T2="$?"
#
# echo "$OUT_DIR" | grep -qE '^(/var)?/tmp/'
# T3="$?"
#
# echo "$STDIN_FILE" | grep -qE '^(/var)?/tmp/'
# T4="$?"
#
# echo "$PWD" | grep -qE '^(/var)?/tmp/'
# T5="$?"
#
# if [ "$T1" = "0" -o "$T2" = "0" -o "$T3" = "0" -o "$T4" = "0" -o "$T5" = "0" ]; then
# echo "[-] Error: do not use this script in /tmp or /var/tmp." 1>&2
# exit 1
# fi
#
#fi
# If @@ is specified, but there's no -f, let's come up with a temporary input
# file name.
@ -243,10 +242,21 @@ if [ ! "$STDIN_FILE" = "" ]; then
touch "$STDIN_FILE" || exit 1
fi
if [ "$AFL_PATH" = "" ]; then
SHOWMAP="${0%/afl-cmin}/afl-showmap"
SHOWMAP=`command -v afl-showmap 2>/dev/null`
if [ -z "$SHOWMAP" ]; then
TMP="${0%/afl-cmin.bash}/afl-showmap"
if [ -x "$TMP" ]; then
SHOWMAP=$TMP
fi
fi
if [ -z "$SHOWMAP" -a -x "./afl-showmap" ]; then
SHOWMAP="./afl-showmap"
else
SHOWMAP="$AFL_PATH/afl-showmap"
if [ -n "$AFL_PATH" ]; then
SHOWMAP="$AFL_PATH/afl-showmap"
fi
fi
if [ ! -x "$SHOWMAP" ]; then

View File

@ -15,6 +15,10 @@
# http://www.apache.org/licenses/LICENSE-2.0
#
get_abs_path() {
echo $(cd "`dirname "$1"`" && pwd)/"`basename "$1"`"
}
echo "progress plotting utility for afl-fuzz by Michal Zalewski"
echo
@ -31,44 +35,53 @@ an empty directory where this tool can write the resulting plots to.
The program will put index.html and three PNG images in the output directory;
you should be able to view it with any web browser of your choice.
Environment variables used:
AFL_ALLOW_TMP: allow /var/tmp or /tmp for input and output directories
_EOF_
exit 1
fi
if [ "$AFL_ALLOW_TMP" = "" ]; then
inputdir=`get_abs_path "$1"`
outputdir=`get_abs_path "$2"`
echo "$1" | grep -qE '^(/var)?/tmp/'
T1="$?"
#if [ "$AFL_ALLOW_TMP" = "" ]; then
#
# echo "$inputdir" | grep -qE '^(/var)?/tmp/'
# T1="$?"
#
# echo "$outputdir" | grep -qE '^(/var)?/tmp/'
# T2="$?"
#
# if [ "$T1" = "0" -o "$T2" = "0" ]; then
#
# echo "[-] Error: this script shouldn't be used with shared /tmp directories." 1>&2
# exit 1
#
# fi
#
#fi
echo "$2" | grep -qE '^(/var)?/tmp/'
T2="$?"
if [ "$T1" = "0" -o "$T2" = "0" ]; then
echo "[-] Error: this script shouldn't be used with shared /tmp directories." 1>&2
exit 1
fi
fi
if [ ! -f "$1/plot_data" ]; then
if [ ! -f "$inputdir/plot_data" ]; then
echo "[-] Error: input directory is not valid (missing 'plot_data')." 1>&2
exit 1
fi
BANNER="`cat "$1/fuzzer_stats" | grep '^afl_banner ' | cut -d: -f2- | cut -b2-`"
LINES=`cat "$inputdir/plot_data" | wc -l`
if [ "$LINES" -lt 3 ]; then
echo "[-] Error: plot_data carries too little data, let it run longer." 1>&2
exit 1
fi
BANNER="`cat "$inputdir/fuzzer_stats" 2> /dev/null | grep '^afl_banner ' | cut -d: -f2- | cut -b2-`"
test "$BANNER" = "" && BANNER="(none)"
GNUPLOT=`which gnuplot 2>/dev/null`
GNUPLOT=`command -v gnuplot 2>/dev/null`
if [ "$GNUPLOT" = "" ]; then
@ -77,17 +90,17 @@ if [ "$GNUPLOT" = "" ]; then
fi
mkdir "$2" 2>/dev/null
mkdir "$outputdir" 2>/dev/null
if [ ! -d "$2" ]; then
if [ ! -d "$outputdir" ]; then
echo "[-] Error: unable to create the output directory - pick another location." 1>&2
exit 1
fi
rm -f "$2/high_freq.png" "$2/low_freq.png" "$2/exec_speed.png"
mv -f "$2/index.html" "$2/index.html.orig" 2>/dev/null
rm -f "$outputdir/high_freq.png" "$outputdir/low_freq.png" "$outputdir/exec_speed.png" "$outputdir/edges.png"
mv -f "$outputdir/index.html" "$outputdir/index.html.orig" 2>/dev/null
echo "[*] Generating plots..."
@ -96,7 +109,7 @@ echo "[*] Generating plots..."
cat <<_EOF_
set terminal png truecolor enhanced size 1000,300 butt
set output '$2/high_freq.png'
set output '$outputdir/high_freq.png'
set xdata time
set timefmt '%s'
@ -114,31 +127,42 @@ set key outside
set autoscale xfixmin
set autoscale xfixmax
plot '$1/plot_data' using 1:4 with filledcurve x1 title 'total paths' linecolor rgb '#000000' fillstyle transparent solid 0.2 noborder, \\
set xlabel "all times in UTC" font "small"
set ytics auto
plot '$inputdir/plot_data' using 1:4 with filledcurve x1 title 'total paths' linecolor rgb '#000000' fillstyle transparent solid 0.2 noborder, \\
'' using 1:3 with filledcurve x1 title 'current path' linecolor rgb '#f0f0f0' fillstyle transparent solid 0.5 noborder, \\
'' using 1:5 with lines title 'pending paths' linecolor rgb '#0090ff' linewidth 3, \\
'' using 1:6 with lines title 'pending favs' linecolor rgb '#c00080' linewidth 3, \\
'' using 1:2 with lines title 'cycles done' linecolor rgb '#c000f0' linewidth 3
set terminal png truecolor enhanced size 1000,200 butt
set output '$2/low_freq.png'
set output '$outputdir/low_freq.png'
plot '$1/plot_data' using 1:8 with filledcurve x1 title '' linecolor rgb '#c00080' fillstyle transparent solid 0.2 noborder, \\
set ytics 1
plot '$inputdir/plot_data' using 1:8 with filledcurve x1 title '' linecolor rgb '#c00080' fillstyle transparent solid 0.2 noborder, \\
'' using 1:8 with lines title ' uniq crashes' linecolor rgb '#c00080' linewidth 3, \\
'' using 1:9 with lines title 'uniq hangs' linecolor rgb '#c000f0' linewidth 3, \\
'' using 1:10 with lines title 'levels' linecolor rgb '#0090ff' linewidth 3
set terminal png truecolor enhanced size 1000,200 butt
set output '$2/exec_speed.png'
set output '$outputdir/exec_speed.png'
plot '$1/plot_data' using 1:11 with filledcurve x1 title '' linecolor rgb '#0090ff' fillstyle transparent solid 0.2 noborder, \\
'$1/plot_data' using 1:11 with lines title ' execs/sec' linecolor rgb '#0090ff' linewidth 3 smooth bezier;
set ytics auto
plot '$inputdir/plot_data' using 1:11 with filledcurve x1 title '' linecolor rgb '#0090ff' fillstyle transparent solid 0.2 noborder, \\
'$inputdir/plot_data' using 1:11 with lines title ' execs/sec' linecolor rgb '#0090ff' linewidth 3 smooth bezier;
set terminal png truecolor enhanced size 1000,300 butt
set output '$outputdir/edges.png'
set ytics auto
plot '$inputdir/plot_data' using 1:13 with lines title ' edges' linecolor rgb '#0090ff' linewidth 3
_EOF_
) | gnuplot
if [ ! -s "$2/exec_speed.png" ]; then
if [ ! -s "$outputdir/exec_speed.png" ]; then
echo "[-] Error: something went wrong! Perhaps you have an ancient version of gnuplot?" 1>&2
exit 1
@ -147,13 +171,14 @@ fi
echo "[*] Generating index.html..."
cat >"$2/index.html" <<_EOF_
cat >"$outputdir/index.html" <<_EOF_
<table style="font-family: 'Trebuchet MS', 'Tahoma', 'Arial', 'Helvetica'">
<tr><td style="width: 18ex"><b>Banner:</b></td><td>$BANNER</td></tr>
<tr><td><b>Directory:</b></td><td>$1</td></tr>
<tr><td><b>Directory:</b></td><td>$inputdir</td></tr>
<tr><td><b>Generated on:</b></td><td>`date`</td></tr>
</table>
<p>
<img src="edges.png" width=1000 height=300>
<img src="high_freq.png" width=1000 height=300><p>
<img src="low_freq.png" width=1000 height=200><p>
<img src="exec_speed.png" width=1000 height=200>
@ -164,8 +189,8 @@ _EOF_
# served by Apache or other HTTP daemon. Since the plots aren't horribly
# sensitive, this seems like a reasonable trade-off.
chmod 755 "$2"
chmod 644 "$2/high_freq.png" "$2/low_freq.png" "$2/exec_speed.png" "$2/index.html"
chmod 755 "$outputdir"
chmod 644 "$outputdir/high_freq.png" "$outputdir/low_freq.png" "$outputdir/exec_speed.png" "$outputdir/edges.png" "$outputdir/index.html"
echo "[+] All done - enjoy your charts!"

View File

@ -1,5 +1,5 @@
#!/bin/sh
test "$1" = "-h" && {
test "$1" = "-h" -o "$1" = "-hh" && {
echo 'afl-system-config by Marc Heuse <mh@mh-sec.de>'
echo
echo $0
@ -34,6 +34,7 @@ if [ "$PLATFORM" = "Linux" ] ; then
test -e /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor && echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
test -e /sys/devices/system/cpu/intel_pstate/no_turbo && echo 0 > /sys/devices/system/cpu/intel_pstate/no_turbo
test -e /sys/devices/system/cpu/cpufreq/boost && echo 1 > /sys/devices/system/cpu/cpufreq/boost
test -e /sys/devices/system/cpu/intel_pstate/max_perf_pct && echo 100 > /sys/devices/system/cpu/intel_pstate/max_perf_pct
} > /dev/null
echo Settings applied.
dmesg | egrep -q 'nospectre_v2|spectre_v2=off' || {
@ -48,6 +49,12 @@ if [ "$PLATFORM" = "FreeBSD" ] ; then
sysctl kern.elf64.aslr.enable=0
} > /dev/null
echo Settings applied.
cat <<EOF
In order to suppress core file generation during fuzzing it is recommended to set
me:\\
:coredumpsize=0:
in the ~/.login_conf file for the user used for fuzzing.
EOF
echo It is recommended to boot the kernel with lots of security off - if you are running a machine that is in a secured network - so set this:
echo ' sysctl hw.ibrs_disable=1'
echo 'Setting kern.pmap.pg_ps_enabled=0 into /boot/loader.conf might be helpful too.'
@ -58,6 +65,17 @@ if [ "$PLATFORM" = "OpenBSD" ] ; then
echo 'System security features cannot be disabled on OpenBSD.'
DONE=1
fi
if [ "$PLATFORM" = "DragonFly" ] ; then
#/sbin/sysctl kern.corefile=/dev/null
#echo Settings applied.
cat <<EOF
In order to suppress core file generation during fuzzing it is recommended to set
me:\\
:coredumpsize=0:
in the ~/.login_conf file for the user used for fuzzing.
EOF
DONE=1
fi
if [ "$PLATFORM" = "NetBSD" ] ; then
{
#echo It is recommended to enable unprivileged users to set cpu affinity
@ -79,5 +97,14 @@ if [ "$PLATFORM" = "Darwin" ] ; then
fi
DONE=1
fi
if [ "$PLATFORM" = "Haiku" ] ; then
SETTINGS=~/config/settings/system/debug_server/settings
[ -r ${SETTINGS} ] && grep -qE "default_action\s+kill" ${SETTINGS} && { echo "Nothing to do"; } || { \
echo We change the debug_server default_action from user to silently kill; \
[ ! -r ${SETTINGS} ] && echo "default_action kill" >${SETTINGS} || { mv ${SETTINGS} s.tmp; sed -e "s/default_action\s\s*user/default_action kill/" s.tmp > ${SETTINGS}; rm s.tmp; }; \
echo Settings applied.; \
}
DONE=1
fi
test -z "$DONE" && echo Error: Unknown platform: $PLATFORM
test -z "$AFL_TMPDIR" && echo Also use AFL_TMPDIR and point it to a tmpfs for the input file caching
exit 0

View File

@ -20,7 +20,7 @@
echo "$0 status check tool for afl-fuzz by Michal Zalewski"
echo
test "$1" = "-h" && {
test "$1" = "-h" -o "$1" = "-hh" && {
echo $0 [-s] output_directory
echo
echo Options:
@ -61,6 +61,13 @@ if [ -d queue ]; then
fi
RED=`tput setaf 9 1 1`
GREEN=`tput setaf 2 1 1`
BLUE=`tput setaf 4 1 1`
YELLOW=`tput setaf 11 1 1`
NC=`tput sgr0`
RESET="$NC"
CUR_TIME=`date +%s`
TMP=`mktemp -t .afl-whatsup-XXXXXXXX` || TMP=`mktemp -p /data/local/tmp .afl-whatsup-XXXXXXXX` || TMP=`mktemp -p /data/local/tmp .afl-whatsup-XXXXXXXX` || exit 1
@ -75,6 +82,12 @@ TOTAL_CRASHES=0
TOTAL_PFAV=0
TOTAL_PENDING=0
# Time since last path / crash / hang, formatted as string
FMT_TIME="0 days 0 hours"
FMT_PATH="${RED}none seen yet${NC}"
FMT_CRASH="none seen yet"
FMT_HANG="none seen yet"
if [ "$SUMMARY_ONLY" = "" ]; then
echo "Individual fuzzers"
@ -83,6 +96,38 @@ if [ "$SUMMARY_ONLY" = "" ]; then
fi
fmt_duration()
{
DUR_STRING=
if [ $1 -le 0 ]; then
return 1
fi
local duration=$((CUR_TIME - $1))
local days=$((duration / 60 / 60 / 24))
local hours=$(((duration / 60 / 60) % 24))
local minutes=$(((duration / 60) % 60))
local seconds=$((duration % 60))
if [ $duration -le 0 ]; then
DUR_STRING="0 seconds"
elif [ $duration -eq 1 ]; then
DUR_STRING="1 second"
elif [ $days -gt 0 ]; then
DUR_STRING="$days days, $hours hours"
elif [ $hours -gt 0 ]; then
DUR_STRING="$hours hours, $minutes minutes"
elif [ $minutes -gt 0 ]; then
DUR_STRING="$minutes minutes, $seconds seconds"
else
DUR_STRING="$seconds seconds"
fi
}
FIRST=true
TOTAL_WCOP=
TOTAL_LAST_PATH=0
for i in `find . -maxdepth 2 -iname fuzzer_stats | sort`; do
sed 's/^command_line.*$/_skip:1/;s/[ ]*:[ ]*/="/;s/$/"/' "$i" >"$TMP"
@ -92,9 +137,15 @@ for i in `find . -maxdepth 2 -iname fuzzer_stats | sort`; do
RUN_DAYS=$((RUN_UNIX / 60 / 60 / 24))
RUN_HRS=$(((RUN_UNIX / 60 / 60) % 24))
test -n "$cycles_wo_finds" && {
test -z "$FIRST" && TOTAL_WCOP="${TOTAL_WCOP}/"
TOTAL_WCOP="${TOTAL_WCOP}${cycles_wo_finds}"
FIRST=
}
if [ "$SUMMARY_ONLY" = "" ]; then
echo ">>> $afl_banner ($RUN_DAYS days, $RUN_HRS hrs) <<<"
echo ">>> $afl_banner ($RUN_DAYS days, $RUN_HRS hrs) fuzzer PID: $fuzzer_pid <<<"
echo
fi
@ -115,7 +166,8 @@ for i in `find . -maxdepth 2 -iname fuzzer_stats | sort`; do
ALIVE_CNT=$((ALIVE_CNT + 1))
EXEC_SEC=$((execs_done / RUN_UNIX))
EXEC_SEC=0
test -z "$RUN_UNIX" -o "$RUN_UNIX" = 0 || EXEC_SEC=$((execs_done / RUN_UNIX))
PATH_PERC=$((cur_path * 100 / paths_total))
TOTAL_TIME=$((TOTAL_TIME + RUN_UNIX))
@ -125,8 +177,43 @@ for i in `find . -maxdepth 2 -iname fuzzer_stats | sort`; do
TOTAL_PENDING=$((TOTAL_PENDING + pending_total))
TOTAL_PFAV=$((TOTAL_PFAV + pending_favs))
if [ "$last_path" -gt "$TOTAL_LAST_PATH" ]; then
TOTAL_LAST_PATH=$last_path
fi
if [ "$SUMMARY_ONLY" = "" ]; then
# Warnings in red
TIMEOUT_PERC=$((exec_timeout * 100 / execs_done))
if [ $TIMEOUT_PERC -ge 10 ]; then
echo " ${RED}timeout_ratio $TIMEOUT_PERC%${NC}"
fi
if [ $EXEC_SEC -eq 0 ]; then
echo " ${YELLOW}no data yet, 0 execs/sec${NC}"
elif [ $EXEC_SEC -lt 100 ]; then
echo " ${RED}slow execution, $EXEC_SEC execs/sec${NC}"
fi
fmt_duration $last_path && FMT_PATH=$DUR_STRING
fmt_duration $last_crash && FMT_CRASH=$DUR_STRING
fmt_duration $last_hang && FMT_HANG=$DUR_STRING
FMT_CWOP="not available"
test -n "$cycles_wo_finds" && {
test "$cycles_wo_finds" = 0 && FMT_CWOP="$cycles_wo_finds"
test "$cycles_wo_finds" -gt 10 && FMT_CWOP="${YELLOW}$cycles_wo_finds${NC}"
test "$cycles_wo_finds" -gt 50 && FMT_CWOP="${RED}$cycles_wo_finds${NC}"
}
echo " last_path : $FMT_PATH"
echo " last_crash : $FMT_CRASH"
echo " last_hang : $FMT_HANG"
echo " cycles_wo_finds : $FMT_CWOP"
CPU_USAGE=$(ps aux | grep $fuzzer_pid | grep -v grep | awk '{print $3}')
MEM_USAGE=$(ps aux | grep $fuzzer_pid | grep -v grep | awk '{print $4}')
echo " cpu usage $CPU_USAGE%, memory usage $MEM_USAGE%"
echo " cycle $((cycles_done + 1)), lifetime speed $EXEC_SEC execs/sec, path $cur_path/$paths_total (${PATH_PERC}%)"
if [ "$unique_crashes" = "0" ]; then
@ -141,11 +228,28 @@ for i in `find . -maxdepth 2 -iname fuzzer_stats | sort`; do
done
# Formatting for total time, time since last path, crash, and hang
fmt_duration $((CUR_TIME - TOTAL_TIME)) && FMT_TIME=$DUR_STRING
# Formatting for total execution
FMT_EXECS="0 millions"
EXECS_MILLION=$((TOTAL_EXECS / 1000 / 1000))
EXECS_THOUSAND=$((TOTAL_EXECS / 1000 % 1000))
if [ $EXECS_MILLION -gt 9 ]; then
FMT_EXECS="$EXECS_MILLION millions"
elif [ $EXECS_MILLION -gt 0 ]; then
FMT_EXECS="$EXECS_MILLION millions, $EXECS_THOUSAND thousands"
else
FMT_EXECS="$EXECS_THOUSAND thousands"
fi
rm -f "$TMP"
TOTAL_DAYS=$((TOTAL_TIME / 60 / 60 / 24))
TOTAL_HRS=$(((TOTAL_TIME / 60 / 60) % 24))
test -z "$TOTAL_WCOP" && TOTAL_WCOP="not available"
fmt_duration $TOTAL_LAST_PATH && TOTAL_LAST_PATH=$DUR_STRING
test "$TOTAL_TIME" = "0" && TOTAL_TIME=1
echo "Summary stats"
@ -157,9 +261,12 @@ if [ ! "$DEAD_CNT" = "0" ]; then
echo " Dead or remote : $DEAD_CNT (excluded from stats)"
fi
echo " Total run time : $TOTAL_DAYS days, $TOTAL_HRS hours"
echo " Total execs : $((TOTAL_EXECS / 1000 / 1000)) million"
echo " Total run time : $FMT_TIME"
echo " Total execs : $FMT_EXECS"
echo " Cumulative speed : $TOTAL_EPS execs/sec"
if [ "$ALIVE_CNT" -gt "0" ]; then
echo " Average speed : $((TOTAL_EPS / ALIVE_CNT)) execs/sec"
fi
echo " Pending paths : $TOTAL_PFAV faves, $TOTAL_PENDING total"
if [ "$ALIVE_CNT" -gt "1" ]; then
@ -167,6 +274,8 @@ if [ "$ALIVE_CNT" -gt "1" ]; then
fi
echo " Crashes found : $TOTAL_CRASHES locally unique"
echo "Cycles without finds : $TOTAL_WCOP"
echo " Time without finds : $TOTAL_LAST_PATH"
echo
exit 0

View File

@ -28,9 +28,9 @@ if not os.getenv("AFL_INST_LIBS"):
os.environ["AFL_CODE_END"] = "0x%x" % (pe.OPTIONAL_HEADER.ImageBase + pe.OPTIONAL_HEADER.BaseOfCode + pe.OPTIONAL_HEADER.SizeOfCode)
if pe.FILE_HEADER.Machine == pefile.MACHINE_TYPE["IMAGE_FILE_MACHINE_AMD64"] or pe.FILE_HEADER.Machine == pefile.MACHINE_TYPE["IMAGE_FILE_MACHINE_IA64"]:
os.environ["LD_PRELOAD"] = os.path.join(my_dir, "qemu_mode/unsigaction/unsigaction64.so")
os.environ["QEMU_SET_ENV"] = "LD_PRELOAD=" + os.path.join(my_dir, "qemu_mode/unsigaction/unsigaction64.so") + ",WINEARCH=win64"
else:
os.environ["LD_PRELOAD"] = os.path.join(my_dir, "qemu_mode/unsigaction/unsigaction32.so")
os.environ["QEMU_SET_ENV"] = "LD_PRELOAD=" + os.path.join(my_dir, "qemu_mode/unsigaction/unsigaction32.so") + ",WINEARCH=win32"
if os.getenv("WINECOV_QEMU_PATH"):
qemu_path = os.getenv("WINECOV_QEMU_PATH")
@ -68,7 +68,12 @@ else:
argv = sys.argv[1:]
for i in range(len(argv)):
if ".cur_input" in argv[i]:
argv[i] = subprocess.run([os.path.join(os.path.dirname(wine_path), "winepath"), "--windows", argv[i]], universal_newlines=True, stdout=subprocess.PIPE).stdout
# Get the Wine translated path using the winepath tool
arg_translated = subprocess.run([os.path.join(os.path.dirname(wine_path), "winepath"), "--windows", argv[i]], universal_newlines=True, stdout=subprocess.PIPE).stdout
# Remove the spurious LF at the end of the path
if len(arg_translated) > 0 and arg_translated[-1] == '\n':
arg_translated = arg_translated[:-1]
argv[i] = arg_translated
break
print("[afl-wine-trace] exec:", " ".join([qemu_path, wine_path] + argv))

115
custom_mutators/Android.bp Normal file
View File

@ -0,0 +1,115 @@
cc_library_shared {
name: "libfuzzer-mutator",
vendor_available: true,
host_supported: true,
cflags: [
"-g",
"-O0",
"-funroll-loops",
"-fPIC",
"-fpermissive",
"-std=c++11",
],
srcs: [
"libfuzzer/FuzzerCrossOver.cpp",
"libfuzzer/FuzzerDataFlowTrace.cpp",
"libfuzzer/FuzzerDriver.cpp",
"libfuzzer/FuzzerExtFunctionsDlsym.cpp",
"libfuzzer/FuzzerExtFunctionsWeak.cpp",
"libfuzzer/FuzzerExtFunctionsWindows.cpp",
"libfuzzer/FuzzerExtraCounters.cpp",
"libfuzzer/FuzzerFork.cpp",
"libfuzzer/FuzzerIO.cpp",
"libfuzzer/FuzzerIOPosix.cpp",
"libfuzzer/FuzzerIOWindows.cpp",
"libfuzzer/FuzzerLoop.cpp",
"libfuzzer/FuzzerMerge.cpp",
"libfuzzer/FuzzerMutate.cpp",
"libfuzzer/FuzzerSHA1.cpp",
"libfuzzer/FuzzerTracePC.cpp",
"libfuzzer/FuzzerUtil.cpp",
"libfuzzer/FuzzerUtilDarwin.cpp",
"libfuzzer/FuzzerUtilFuchsia.cpp",
"libfuzzer/FuzzerUtilLinux.cpp",
"libfuzzer/FuzzerUtilPosix.cpp",
"libfuzzer/FuzzerUtilWindows.cpp",
"libfuzzer/libfuzzer.cpp",
],
header_libs: [
"libafl_headers",
],
}
/*cc_library_shared {
name: "honggfuzz-mutator",
vendor_available: true,
host_supported: true,
cflags: [
"-g",
"-O0",
"-funroll-loops",
"-fPIC",
"-Wl,-Bsymbolic",
],
srcs: [
"honggfuzz/honggfuzz.c",
"honggfuzz/mangle.c",
// "../src/afl-perfomance.c",
],
header_libs: [
"libafl_headers",
],
}*/
cc_library_shared {
name: "radamsa-mutator",
vendor_available: true,
host_supported: true,
cflags: [
"-g",
"-O0",
"-funroll-loops",
"-fPIC",
],
srcs: [
"radamsa/libradamsa.c",
"radamsa/radamsa-mutator.c",
],
header_libs: [
"libafl_headers",
],
}
cc_library_shared {
name: "symcc-mutator",
vendor_available: true,
host_supported: true,
cflags: [
"-g",
"-O0",
"-funroll-loops",
"-fPIC",
],
srcs: [
"symcc/symcc.c",
],
header_libs: [
"libafl_headers",
],
}
subdirs = [
"libprotobuf-mutator-example",
]

48
custom_mutators/README.md Normal file
View File

@ -0,0 +1,48 @@
# Custom Mutators
Custom mutators enhance and alter the mutation strategies of afl++.
For further information and documentation on how to write your own, read [the docs](../docs/custom_mutators.md).
## The afl++ Grammar Mutator
If you use git to clone afl++, then the following will incorporate our
excellent grammar custom mutator:
```sh
git submodule update --init
```
Read the README in the [Grammar-Mutator] repository on how to use it.
[Grammar-Mutator]: https://github.com/AFLplusplus/Grammar-Mutator
## Production-Ready Custom Mutators
This directory holds ready to use custom mutators.
Just type "make" in the individual subdirectories.
Use with e.g.
`AFL_CUSTOM_MUTATOR_LIBRARY=custom_mutators/radamsa/radamsa-mutator.so afl-fuzz ....`
and add `AFL_CUSTOM_MUTATOR_ONLY=1` if you only want to use the custom mutator.
Multiple custom mutators can be used by separating their paths with `:` in the environment variable.
## 3rd Party Custom Mutators
### Superion Mutators
Adrian Tiron ported the Superion grammar fuzzer to afl++, it is WIP and
requires cmake (among other things):
[https://github.com/adrian-rt/superion-mutator](https://github.com/adrian-rt/superion-mutator)
### libprotobuf Mutators
There are two WIP protobuf projects, that require work to be working though:
transforms protobuf raw:
https://github.com/bruce30262/libprotobuf-mutator_fuzzing_learning/tree/master/4_libprotobuf_aflpp_custom_mutator
has a transform function you need to fill for your protobuf format, however
needs to be ported to the updated afl++ custom mutator API (not much work):
https://github.com/thebabush/afl-libprotobuf-mutator

View File

@ -0,0 +1 @@
b3c4fcf

View File

@ -0,0 +1,6 @@
# Grammar-Mutator
This is just a stub directory that will clone the real grammar mutator
directory.
Execute `./build_grammar_mutator.sh` to set everything up.

View File

@ -0,0 +1,140 @@
#!/bin/sh
#
# american fuzzy lop++ - unicorn mode build script
# ------------------------------------------------
#
# Originally written by Nathan Voss <njvoss99@gmail.com>
#
# Adapted from code by Andrew Griffiths <agriffiths@google.com> and
# Michal Zalewski
#
# Adapted for AFLplusplus by Dominik Maier <mail@dmnk.co>
#
# CompareCoverage and NeverZero counters by Andrea Fioraldi
# <andreafioraldi@gmail.com>
#
# Copyright 2017 Battelle Memorial Institute. All rights reserved.
# Copyright 2019-2020 AFLplusplus Project. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# This script downloads, patches, and builds a version of Unicorn with
# minor tweaks to allow Unicorn-emulated binaries to be run under
# afl-fuzz.
#
# The modifications reside in patches/*. The standalone Unicorn library
# will be written to /usr/lib/libunicornafl.so, and the Python bindings
# will be installed system-wide.
#
# You must make sure that Unicorn Engine is not already installed before
# running this script. If it is, please uninstall it first.
GRAMMAR_VERSION="$(cat ./GRAMMAR_VERSION)"
GRAMMAR_REPO="https://github.com/AFLplusplus/grammar-mutator"
echo "================================================="
echo "Grammar Mutator build script"
echo "================================================="
echo
echo "[*] Performing basic sanity checks..."
PLT=`uname -s`
if [ ! -f "../../config.h" ]; then
echo "[-] Error: key files not found - wrong working directory?"
exit 1
fi
PYTHONBIN=`command -v python3 || command -v python || command -v python2 || echo python3`
MAKECMD=make
TARCMD=tar
if [ "$PLT" = "Darwin" ]; then
CORES=`sysctl -n hw.ncpu`
TARCMD=tar
fi
if [ "$PLT" = "FreeBSD" ]; then
MAKECMD=gmake
CORES=`sysctl -n hw.ncpu`
TARCMD=gtar
fi
if [ "$PLT" = "NetBSD" ] || [ "$PLT" = "OpenBSD" ]; then
MAKECMD=gmake
CORES=`sysctl -n hw.ncpu`
TARCMD=gtar
fi
PREREQ_NOTFOUND=
for i in git $MAKECMD $TARCMD; do
T=`command -v "$i" 2>/dev/null`
if [ "$T" = "" ]; then
echo "[-] Error: '$i' not found. Run 'sudo apt-get install $i' or similar."
PREREQ_NOTFOUND=1
fi
done
if echo "$CC" | grep -qF /afl-; then
echo "[-] Error: do not use afl-gcc or afl-clang to compile this tool."
PREREQ_NOTFOUND=1
fi
if [ "$PREREQ_NOTFOUND" = "1" ]; then
exit 1
fi
echo "[+] All checks passed!"
echo "[*] Making sure grammar mutator is checked out"
git status 1>/dev/null 2>/dev/null
if [ $? -eq 0 ]; then
echo "[*] initializing grammar mutator submodule"
git submodule init || exit 1
git submodule update ./grammar-mutator 2>/dev/null # ignore errors
else
echo "[*] cloning grammar mutator"
test -d grammar-mutator || {
CNT=1
while [ '!' -d grammar-mutator -a "$CNT" -lt 4 ]; do
echo "Trying to clone grammar-mutator (attempt $CNT/3)"
git clone "$GRAMMAR_REPO"
CNT=`expr "$CNT" + 1`
done
}
fi
test -d grammar-mutator || { echo "[-] not checked out, please install git or check your internet connection." ; exit 1 ; }
echo "[+] Got grammar mutator."
cd "grammar-mutator" || exit 1
echo "[*] Checking out $GRAMMAR_VERSION"
sh -c 'git stash && git stash drop' 1>/dev/null 2>/dev/null
git checkout "$GRAMMAR_VERSION" || exit 1
echo "[*] Downloading antlr..."
wget -c https://www.antlr.org/download/antlr-4.8-complete.jar
cd ..
echo
echo
echo "[+] All successfully prepared!"
echo "[!] To build for your grammar just do:"
echo " cd grammar-mutator"
echo " make GRAMMAR_FILE=/path/to/your/grammar"
echo "[+] You will find a JSON and RUBY grammar in grammar-mutator/grammars to play with."
echo

View File

@ -0,0 +1,50 @@
#!/bin/sh
##################################################
# AFL++ tool to update a git ref.
# Usage: ./<script>.sh <new commit hash>
# If no commit hash was provided, it'll take HEAD.
##################################################
TOOL="grammar mutator"
VERSION_FILE='./GRAMMAR_VERSION'
REPO_FOLDER='./grammar_mutator'
THIS_SCRIPT=`basename $0`
BRANCH="stable"
NEW_VERSION="$1"
if [ "$NEW_VERSION" = "-h" ]; then
echo "Internal script to update bound $TOOL version."
echo
echo "Usage: $THIS_SCRIPT <new commit hash>"
echo "If no commit hash is provided, will use HEAD."
echo "-h to show this help screen."
exit 1
fi
git submodule init && git submodule update ./grammar_mutator || exit 1
cd "$REPO_FOLDER" || exit 1
git fetch origin $BRANCH 1>/dev/null || exit 1
git stash 1>/dev/null 2>/dev/null
git stash drop 1>/dev/null 2>/dev/null
git checkout $BRANCH
if [ -z "$NEW_VERSION" ]; then
# No version provided, take HEAD.
NEW_VERSION=$(git rev-parse --short HEAD)
fi
if [ -z "$NEW_VERSION" ]; then
echo "Error getting version."
exit 1
fi
git checkout "$NEW_VERSION" || exit 1
cd ..
rm "$VERSION_FILE"
echo "$NEW_VERSION" > "$VERSION_FILE"
echo "Done. New $TOOL version is $NEW_VERSION."

View File

@ -0,0 +1,17 @@
CFLAGS = -O3 -funroll-loops -fPIC -Wl,-Bsymbolic
all: honggfuzz-mutator.so
honggfuzz-mutator.so: honggfuzz.c input.h mangle.c ../../src/afl-performance.c
$(CC) $(CFLAGS) -I../../include -I. -shared -o honggfuzz-mutator.so honggfuzz.c mangle.c ../../src/afl-performance.c
update:
@# seriously? --unlink is a dud option? sigh ...
rm -f mangle.c mangle.h honggfuzz.h
wget --unlink https://github.com/google/honggfuzz/raw/master/mangle.c
wget --unlink https://github.com/google/honggfuzz/raw/master/mangle.h
wget --unlink https://github.com/google/honggfuzz/raw/master/honggfuzz.h
clean:
rm -f *.o *~ *.so core

View File

@ -0,0 +1,12 @@
# custum mutator: honggfuzz mangle
this is the honggfuzz mutator in mangle.c as a custom mutator
module for afl++. It is the original mangle.c, mangle.h and honggfuzz.h
with a lot of mocking around it :-)
just type `make` to build
```AFL_CUSTOM_MUTATOR_LIBRARY=custom_mutators/honggfuzz/honggfuzz-mutator.so afl-fuzz ...```
> Original repository: https://github.com/google/honggfuzz
> Source commit: d0fbcb0373c32436b8fb922e6937da93b17291f5

View File

@ -0,0 +1,22 @@
#ifndef CUSTOM_MUTATOR_HELPERS
#define CUSTOM_MUTATOR_HELPERS
#include "config.h"
#include "types.h"
#include "afl-fuzz.h"
#include <stdlib.h>
#define INITIAL_GROWTH_SIZE (64)
/* Use in a struct: creates a name_buf and a name_size variable. */
#define BUF_VAR(type, name) \
type * name##_buf; \
size_t name##_size;
/* this filles in `&structptr->something_buf, &structptr->something_size`. */
#define BUF_PARAMS(struct, name) \
(void **)&struct->name##_buf, &struct->name##_size
#undef INITIAL_GROWTH_SIZE
#endif

View File

@ -0,0 +1,144 @@
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "custom_mutator_helpers.h"
#include "mangle.h"
#define NUMBER_OF_MUTATIONS 5
uint8_t * queue_input;
size_t queue_input_size;
afl_state_t * afl_struct;
run_t run;
honggfuzz_t global;
struct _dynfile_t dynfile;
typedef struct my_mutator {
afl_state_t *afl;
run_t * run;
u8 * mutator_buf;
unsigned int seed;
unsigned int extras_cnt, a_extras_cnt;
} my_mutator_t;
my_mutator_t *afl_custom_init(afl_state_t *afl, unsigned int seed) {
my_mutator_t *data = calloc(1, sizeof(my_mutator_t));
if (!data) {
perror("afl_custom_init alloc");
return NULL;
}
if ((data->mutator_buf = malloc(MAX_FILE)) == NULL) {
free(data);
perror("mutator_buf alloc");
return NULL;
}
run.dynfile = &dynfile;
run.global = &global;
data->afl = afl;
data->seed = seed;
data->run = &run;
afl_struct = afl;
run.global->mutate.maxInputSz = MAX_FILE;
run.global->mutate.mutationsPerRun = NUMBER_OF_MUTATIONS;
run.mutationsPerRun = NUMBER_OF_MUTATIONS;
run.global->timing.lastCovUpdate = 6;
// global->feedback.cmpFeedback
// global->feedback.cmpFeedbackMap
return data;
}
/* When a new queue entry is added we check if there are new dictionary
entries to add to honggfuzz structure */
void afl_custom_queue_new_entry(my_mutator_t * data,
const uint8_t *filename_new_queue,
const uint8_t *filename_orig_queue) {
if (run.global->mutate.dictionaryCnt >= 1024) return;
while (data->extras_cnt < data->afl->extras_cnt &&
run.global->mutate.dictionaryCnt < 1024) {
memcpy(run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].val,
data->afl->extras[data->extras_cnt].data,
data->afl->extras[data->extras_cnt].len);
run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].len =
data->afl->extras[data->extras_cnt].len;
run.global->mutate.dictionaryCnt++;
data->extras_cnt++;
}
while (data->a_extras_cnt < data->afl->a_extras_cnt &&
run.global->mutate.dictionaryCnt < 1024) {
memcpy(run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].val,
data->afl->a_extras[data->a_extras_cnt].data,
data->afl->a_extras[data->a_extras_cnt].len);
run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].len =
data->afl->a_extras[data->a_extras_cnt].len;
run.global->mutate.dictionaryCnt++;
data->a_extras_cnt++;
}
}
/* we could set only_printable if is_ascii is set ... let's see
uint8_t afl_custom_queue_get(void *data, const uint8_t *filename) {
//run.global->cfg.only_printable = ...
}
*/
/* here we run the honggfuzz mutator, which is really good */
size_t afl_custom_fuzz(my_mutator_t *data, uint8_t *buf, size_t buf_size,
u8 **out_buf, uint8_t *add_buf, size_t add_buf_size,
size_t max_size) {
/* set everything up, costly ... :( */
memcpy(data->mutator_buf, buf, buf_size);
queue_input = data->mutator_buf;
run.dynfile->data = data->mutator_buf;
queue_input_size = buf_size;
run.dynfile->size = buf_size;
*out_buf = data->mutator_buf;
/* the mutation */
mangle_mangleContent(&run, NUMBER_OF_MUTATIONS);
/* return size of mutated data */
return run.dynfile->size;
}
/**
* Deinitialize everything
*
* @param data The data ptr from afl_custom_init
*/
void afl_custom_deinit(my_mutator_t *data) {
free(data->mutator_buf);
free(data);
}

View File

@ -0,0 +1,386 @@
/*
*
* honggfuzz - core structures and macros
* -----------------------------------------
*
* Author: Robert Swiecki <swiecki@google.com>
*
* Copyright 2010-2018 by Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
#ifndef _HF_HONGGFUZZ_H_
#define _HF_HONGGFUZZ_H_
#include <dirent.h>
#include <inttypes.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <sys/types.h>
#include <time.h>
#include "libhfcommon/util.h"
#define PROG_NAME "honggfuzz"
#define PROG_VERSION "2.4"
/* Name of the template which will be replaced with the proper name of the file */
#define _HF_FILE_PLACEHOLDER "___FILE___"
/* Default name of the report created with some architectures */
#define _HF_REPORT_FILE "HONGGFUZZ.REPORT.TXT"
/* Default stack-size of created threads. */
#define _HF_PTHREAD_STACKSIZE (1024ULL * 1024ULL * 2ULL) /* 2MB */
/* Name of envvar which indicates sequential number of fuzzer */
#define _HF_THREAD_NO_ENV "HFUZZ_THREAD_NO"
/* Name of envvar which indicates that the netDriver should be used */
#define _HF_THREAD_NETDRIVER_ENV "HFUZZ_USE_NETDRIVER"
/* Name of envvar which indicates honggfuzz's log level in use */
#define _HF_LOG_LEVEL_ENV "HFUZZ_LOG_LEVEL"
/* Number of crash verifier iterations before tag crash as stable */
#define _HF_VERIFIER_ITER 5
/* Size (in bytes) for report data to be stored in stack before written to file */
#define _HF_REPORT_SIZE 32768
/* Perf bitmap size */
#define _HF_PERF_BITMAP_SIZE_16M (1024U * 1024U * 16U)
#define _HF_PERF_BITMAP_BITSZ_MASK 0x7FFFFFFULL
/* Maximum number of PC guards (=trace-pc-guard) we support */
#define _HF_PC_GUARD_MAX (1024ULL * 1024ULL * 64ULL)
/* Maximum size of the input file in bytes (1 MiB) */
#define _HF_INPUT_MAX_SIZE (1024ULL * 1024ULL)
/* Default maximum size of produced inputs */
#define _HF_INPUT_DEFAULT_SIZE (1024ULL * 8)
/* Per-thread bitmap */
#define _HF_PERTHREAD_BITMAP_FD 1018
/* FD used to report back used int/str constants from the fuzzed process */
#define _HF_CMP_BITMAP_FD 1019
/* FD used to log inside the child process */
#define _HF_LOG_FD 1020
/* FD used to represent the input file */
#define _HF_INPUT_FD 1021
/* FD used to pass coverage feedback from the fuzzed process */
#define _HF_COV_BITMAP_FD 1022
#define _HF_BITMAP_FD _HF_COV_BITMAP_FD /* Old name for _HF_COV_BITMAP_FD */
/* FD used to pass data to a persistent process */
#define _HF_PERSISTENT_FD 1023
/* Input file as a string */
#define _HF_INPUT_FILE_PATH "/dev/fd/" HF_XSTR(_HF_INPUT_FD)
/* Maximum number of supported execve() args */
#define _HF_ARGS_MAX 2048
/* Message indicating that the fuzzed process is ready for new data */
static const uint8_t HFReadyTag = 'R';
/* Maximum number of active fuzzing threads */
#define _HF_THREAD_MAX 1024U
/* Persistent-binary signature - if found within file, it means it's a persistent mode binary */
#define _HF_PERSISTENT_SIG "\x01_LIBHFUZZ_PERSISTENT_BINARY_SIGNATURE_\x02\xFF"
/* HF NetDriver signature - if found within file, it means it's a NetDriver-based binary */
#define _HF_NETDRIVER_SIG "\x01_LIBHFUZZ_NETDRIVER_BINARY_SIGNATURE_\x02\xFF"
/* printf() nonmonetary separator. According to MacOSX's man it's supported there as well */
#define _HF_NONMON_SEP "'"
typedef enum {
_HF_DYNFILE_NONE = 0x0,
_HF_DYNFILE_INSTR_COUNT = 0x1,
_HF_DYNFILE_BRANCH_COUNT = 0x2,
_HF_DYNFILE_BTS_EDGE = 0x10,
_HF_DYNFILE_IPT_BLOCK = 0x20,
_HF_DYNFILE_SOFT = 0x40,
} dynFileMethod_t;
typedef struct {
uint64_t cpuInstrCnt;
uint64_t cpuBranchCnt;
uint64_t bbCnt;
uint64_t newBBCnt;
uint64_t softCntPc;
uint64_t softCntEdge;
uint64_t softCntCmp;
} hwcnt_t;
typedef enum {
_HF_STATE_UNSET = 0,
_HF_STATE_STATIC,
_HF_STATE_DYNAMIC_DRY_RUN,
_HF_STATE_DYNAMIC_MAIN,
_HF_STATE_DYNAMIC_MINIMIZE,
} fuzzState_t;
typedef enum {
HF_MAYBE = -1,
HF_NO = 0,
HF_YES = 1,
} tristate_t;
struct _dynfile_t {
size_t size;
uint64_t cov[4];
size_t idx;
int fd;
uint64_t timeExecUSecs;
char path[PATH_MAX];
struct _dynfile_t* src;
uint32_t refs;
uint8_t* data;
TAILQ_ENTRY(_dynfile_t) pointers;
};
typedef struct _dynfile_t dynfile_t;
struct strings_t {
size_t len;
TAILQ_ENTRY(strings_t) pointers;
char s[];
};
typedef struct {
uint8_t pcGuardMap[_HF_PC_GUARD_MAX];
uint8_t bbMapPc[_HF_PERF_BITMAP_SIZE_16M];
uint32_t bbMapCmp[_HF_PERF_BITMAP_SIZE_16M];
uint64_t pidNewPC[_HF_THREAD_MAX];
uint64_t pidNewEdge[_HF_THREAD_MAX];
uint64_t pidNewCmp[_HF_THREAD_MAX];
uint64_t guardNb;
uint64_t pidTotalPC[_HF_THREAD_MAX];
uint64_t pidTotalEdge[_HF_THREAD_MAX];
uint64_t pidTotalCmp[_HF_THREAD_MAX];
} feedback_t;
typedef struct {
uint32_t cnt;
struct {
uint8_t val[32];
uint32_t len;
} valArr[1024 * 16];
} cmpfeedback_t;
typedef struct {
struct {
size_t threadsMax;
size_t threadsFinished;
uint32_t threadsActiveCnt;
pthread_t mainThread;
pid_t mainPid;
pthread_t threads[_HF_THREAD_MAX];
} threads;
struct {
const char* inputDir;
const char* outputDir;
DIR* inputDirPtr;
size_t fileCnt;
size_t testedFileCnt;
const char* fileExtn;
size_t maxFileSz;
size_t newUnitsAdded;
char workDir[PATH_MAX];
const char* crashDir;
const char* covDirNew;
bool saveUnique;
bool saveSmaller;
size_t dynfileqMaxSz;
size_t dynfileqCnt;
dynfile_t* dynfileqCurrent;
dynfile_t* dynfileq2Current;
TAILQ_HEAD(dyns_t, _dynfile_t) dynfileq;
bool exportFeedback;
} io;
struct {
int argc;
const char* const* cmdline;
bool nullifyStdio;
bool fuzzStdin;
const char* externalCommand;
const char* postExternalCommand;
const char* feedbackMutateCommand;
bool netDriver;
bool persistent;
uint64_t asLimit;
uint64_t rssLimit;
uint64_t dataLimit;
uint64_t coreLimit;
uint64_t stackLimit;
bool clearEnv;
char* env_ptrs[128];
char env_vals[128][4096];
sigset_t waitSigSet;
} exe;
struct {
time_t timeStart;
time_t runEndTime;
time_t tmOut;
time_t lastCovUpdate;
int64_t timeOfLongestUnitUSecs;
bool tmoutVTALRM;
} timing;
struct {
struct {
uint8_t val[256];
size_t len;
} dictionary[1024];
size_t dictionaryCnt;
const char* dictionaryFile;
size_t mutationsMax;
unsigned mutationsPerRun;
size_t maxInputSz;
} mutate;
struct {
bool useScreen;
char cmdline_txt[65];
int64_t lastDisplayUSecs;
} display;
struct {
bool useVerifier;
bool exitUponCrash;
const char* reportFile;
size_t dynFileIterExpire;
bool only_printable;
bool minimize;
bool switchingToFDM;
} cfg;
struct {
bool enable;
bool del_report;
} sanitizer;
struct {
fuzzState_t state;
feedback_t* covFeedbackMap;
int covFeedbackFd;
cmpfeedback_t* cmpFeedbackMap;
int cmpFeedbackFd;
bool cmpFeedback;
const char* blocklistFile;
uint64_t* blocklist;
size_t blocklistCnt;
bool skipFeedbackOnTimeout;
uint64_t maxCov[4];
dynFileMethod_t dynFileMethod;
hwcnt_t hwCnts;
} feedback;
struct {
size_t mutationsCnt;
size_t crashesCnt;
size_t uniqueCrashesCnt;
size_t verifiedCrashesCnt;
size_t blCrashesCnt;
size_t timeoutedCnt;
} cnts;
struct {
bool enabled;
int serverSocket;
int clientSocket;
} socketFuzzer;
struct {
pthread_rwlock_t dynfileq;
pthread_mutex_t feedback;
pthread_mutex_t report;
pthread_mutex_t state;
pthread_mutex_t input;
pthread_mutex_t timing;
} mutex;
/* For the Linux code */
struct {
int exeFd;
uint64_t dynamicCutOffAddr;
bool disableRandomization;
void* ignoreAddr;
const char* symsBlFile;
char** symsBl;
size_t symsBlCnt;
const char* symsWlFile;
char** symsWl;
size_t symsWlCnt;
uintptr_t cloneFlags;
tristate_t useNetNs;
bool kernelOnly;
bool useClone;
} arch_linux;
/* For the NetBSD code */
struct {
void* ignoreAddr;
const char* symsBlFile;
char** symsBl;
size_t symsBlCnt;
const char* symsWlFile;
char** symsWl;
size_t symsWlCnt;
} arch_netbsd;
} honggfuzz_t;
typedef enum {
_HF_RS_UNKNOWN = 0,
_HF_RS_WAITING_FOR_INITIAL_READY = 1,
_HF_RS_WAITING_FOR_READY = 2,
_HF_RS_SEND_DATA = 3,
} runState_t;
typedef struct {
honggfuzz_t* global;
pid_t pid;
int64_t timeStartedUSecs;
char crashFileName[PATH_MAX];
uint64_t pc;
uint64_t backtrace;
uint64_t access;
int exception;
char report[_HF_REPORT_SIZE];
bool mainWorker;
unsigned mutationsPerRun;
dynfile_t* dynfile;
bool staticFileTryMore;
uint32_t fuzzNo;
int persistentSock;
runState_t runState;
bool tmOutSignaled;
char* args[_HF_ARGS_MAX + 1];
int perThreadCovFeedbackFd;
unsigned triesLeft;
dynfile_t* current;
#if !defined(_HF_ARCH_DARWIN)
timer_t timerId;
#endif // !defined(_HF_ARCH_DARWIN)
hwcnt_t hwCnts;
struct {
/* For Linux code */
uint8_t* perfMmapBuf;
uint8_t* perfMmapAux;
int cpuInstrFd;
int cpuBranchFd;
int cpuIptBtsFd;
} arch_linux;
} run_t;
#endif

View File

@ -0,0 +1,106 @@
#ifndef _HG_INPUT_
#define _HG_INPUT_
#include <stdarg.h>
#ifdef __clang__
#include <stdatomic.h>
#endif
#include <stdbool.h>
#include <stdint.h>
#include <time.h>
#include "honggfuzz.h"
#include "afl-fuzz.h"
/*
* Go-style defer scoped implementation
*
* If compiled with clang, use: -fblocks -lBlocksRuntime
*
* Example of use:
*
* {
* int fd = open(fname, O_RDONLY);
* if (fd == -1) {
* error(....);
* return;
* }
* defer { close(fd); };
* ssize_t sz = read(fd, buf, sizeof(buf));
* ...
* ...
* }
*
*/
#define __STRMERGE(a, b) a##b
#define _STRMERGE(a, b) __STRMERGE(a, b)
#ifdef __clang__
#if __has_extension(blocks)
static void __attribute__((unused)) __clang_cleanup_func(void (^*dfunc)(void)) {
(*dfunc)();
}
#define defer \
void (^_STRMERGE(__defer_f_, __COUNTER__))(void) \
__attribute__((cleanup(__clang_cleanup_func))) __attribute__((unused)) = ^
#else /* __has_extension(blocks) */
#define defer UNIMPLEMENTED - NO - SUPPORT - FOR - BLOCKS - IN - YOUR - CLANG - ENABLED
#endif /* __has_extension(blocks) */
#else /* !__clang__, e.g.: gcc */
#define __block
#define _DEFER(a, count) \
auto void _STRMERGE(__defer_f_, count)(void* _defer_arg __attribute__((unused))); \
int _STRMERGE(__defer_var_, count) __attribute__((cleanup(_STRMERGE(__defer_f_, count)))) \
__attribute__((unused)); \
void _STRMERGE(__defer_f_, count)(void* _defer_arg __attribute__((unused)))
#define defer _DEFER(a, __COUNTER__)
#endif /* ifdef __clang__ */
#define HF_MIN(x, y) (x <= y ? x : y)
#define HF_MAX(x, y) (x >= y ? x : y)
#define ATOMIC_GET
#define ARRAYSIZE(x) (sizeof(x) / sizeof(*x))
#define HF_ATTR_UNUSED __attribute__((unused))
#define util_Malloc(x) malloc(x)
extern uint8_t * queue_input;
extern size_t queue_input_size;
extern afl_state_t * afl_struct;
inline void wmb() { }
inline void LOG_F(const char *format, ...) { }
static inline uint64_t util_rndGet(uint64_t min, uint64_t max) {
return min + rand_below(afl_struct, max - min + 1);
}
static inline uint64_t util_rnd64() { return rand_below(afl_struct, 1 << 30); }
static inline const uint8_t* input_getRandomInputAsBuf(run_t* run, size_t* len) {
*len = queue_input_size;
run->dynfile->data = queue_input;
run->dynfile->size = queue_input_size;
return queue_input;
}
static inline void input_setSize(run_t* run, size_t sz) {
run->dynfile->size = sz;
}
static inline void util_turnToPrintable(uint8_t* buf, size_t sz) {
for (size_t i = 0; i < sz; i++)
buf[i] = buf[i] % 95 + 32;
}
static inline void util_rndBuf(uint8_t* buf, size_t sz) {
if (sz == 0) return;
for (size_t i = 0; i < sz; i++)
buf[i] = (uint8_t)rand_below(afl_struct, 256);
}
static inline uint8_t util_rndPrintable() {
return 32 + rand_below(afl_struct, 127 - 32);
}
static inline void util_rndBufPrintable(uint8_t* buf, size_t sz) {
for (size_t i = 0; i < sz; i++)
buf[i] = util_rndPrintable();
}
#endif

View File

@ -0,0 +1,3 @@
#ifndef LOG_E
#define LOG_E LOG_F
#endif

View File

@ -0,0 +1 @@
common.h

View File

@ -0,0 +1 @@
common.h

View File

@ -0,0 +1,907 @@
/*
*
* honggfuzz - run->dynfile->datafer mangling routines
* -----------------------------------------
*
* Author:
* Robert Swiecki <swiecki@google.com>
*
* Copyright 2010-2018 by Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
#include "mangle.h"
#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include "input.h"
#include "libhfcommon/common.h"
#include "libhfcommon/log.h"
#include "libhfcommon/util.h"
static inline size_t mangle_LenLeft(run_t* run, size_t off) {
if (off >= run->dynfile->size) {
LOG_F("Offset is too large: off:%zu >= len:%zu", off, run->dynfile->size);
}
return (run->dynfile->size - off - 1);
}
/*
* Get a random value <1:max>, but prefer smaller ones
* Based on an idea by https://twitter.com/gamozolabs
*/
static inline size_t mangle_getLen(size_t max) {
if (max > _HF_INPUT_MAX_SIZE) {
LOG_F("max (%zu) > _HF_INPUT_MAX_SIZE (%zu)", max, (size_t)_HF_INPUT_MAX_SIZE);
}
if (max == 0) {
LOG_F("max == 0");
}
if (max == 1) {
return 1;
}
/* Give 50% chance the the uniform distribution */
if (util_rnd64() & 1) {
return (size_t)util_rndGet(1, max);
}
/* effectively exprand() */
return (size_t)util_rndGet(1, util_rndGet(1, max));
}
/* Prefer smaller values here, so use mangle_getLen() */
static inline size_t mangle_getOffSet(run_t* run) {
return mangle_getLen(run->dynfile->size) - 1;
}
/* Offset which can be equal to the file size */
static inline size_t mangle_getOffSetPlus1(run_t* run) {
size_t reqlen = HF_MIN(run->dynfile->size + 1, _HF_INPUT_MAX_SIZE);
return mangle_getLen(reqlen) - 1;
}
static inline void mangle_Move(run_t* run, size_t off_from, size_t off_to, size_t len) {
if (off_from >= run->dynfile->size) {
return;
}
if (off_to >= run->dynfile->size) {
return;
}
if (off_from == off_to) {
return;
}
size_t len_from = run->dynfile->size - off_from;
len = HF_MIN(len, len_from);
size_t len_to = run->dynfile->size - off_to;
len = HF_MIN(len, len_to);
memmove(&run->dynfile->data[off_to], &run->dynfile->data[off_from], len);
}
static inline void mangle_Overwrite(
run_t* run, size_t off, const uint8_t* src, size_t len, bool printable) {
if (len == 0) {
return;
}
size_t maxToCopy = run->dynfile->size - off;
if (len > maxToCopy) {
len = maxToCopy;
}
memmove(&run->dynfile->data[off], src, len);
if (printable) {
util_turnToPrintable(&run->dynfile->data[off], len);
}
}
static inline size_t mangle_Inflate(run_t* run, size_t off, size_t len, bool printable) {
if (run->dynfile->size >= run->global->mutate.maxInputSz) {
return 0;
}
if (len > (run->global->mutate.maxInputSz - run->dynfile->size)) {
len = run->global->mutate.maxInputSz - run->dynfile->size;
}
input_setSize(run, run->dynfile->size + len);
mangle_Move(run, off, off + len, run->dynfile->size);
if (printable) {
memset(&run->dynfile->data[off], ' ', len);
}
return len;
}
static inline void mangle_Insert(
run_t* run, size_t off, const uint8_t* val, size_t len, bool printable) {
len = mangle_Inflate(run, off, len, printable);
mangle_Overwrite(run, off, val, len, printable);
}
static inline void mangle_UseValue(run_t* run, const uint8_t* val, size_t len, bool printable) {
if (util_rnd64() & 1) {
mangle_Overwrite(run, mangle_getOffSet(run), val, len, printable);
} else {
mangle_Insert(run, mangle_getOffSetPlus1(run), val, len, printable);
}
}
static inline void mangle_UseValueAt(
run_t* run, size_t off, const uint8_t* val, size_t len, bool printable) {
if (util_rnd64() & 1) {
mangle_Overwrite(run, off, val, len, printable);
} else {
mangle_Insert(run, off, val, len, printable);
}
}
static void mangle_MemSwap(run_t* run, bool printable HF_ATTR_UNUSED) {
/* No big deal if those two are overlapping */
size_t off1 = mangle_getOffSet(run);
size_t maxlen1 = run->dynfile->size - off1;
size_t off2 = mangle_getOffSet(run);
size_t maxlen2 = run->dynfile->size - off2;
size_t len = mangle_getLen(HF_MIN(maxlen1, maxlen2));
if (off1 == off2) {
return;
}
for (size_t i = 0; i < (len / 2); i++) {
/*
* First - from the head, next from the tail. Don't worry about layout of the overlapping
* part - there's no good solution to that, and it can be left somewhat scrambled,
* while still preserving the entropy
*/
const uint8_t tmp1 = run->dynfile->data[off2 + i];
run->dynfile->data[off2 + i] = run->dynfile->data[off1 + i];
run->dynfile->data[off1 + i] = tmp1;
const uint8_t tmp2 = run->dynfile->data[off2 + (len - 1) - i];
run->dynfile->data[off2 + (len - 1) - i] = run->dynfile->data[off1 + (len - 1) - i];
run->dynfile->data[off1 + (len - 1) - i] = tmp2;
}
}
static void mangle_MemCopy(run_t* run, bool printable HF_ATTR_UNUSED) {
size_t off = mangle_getOffSet(run);
size_t len = mangle_getLen(run->dynfile->size - off);
/* Use a temp buf, as Insert/Inflate can change source bytes */
uint8_t* tmpbuf = (uint8_t*)util_Malloc(len);
defer {
free(tmpbuf);
};
memmove(tmpbuf, &run->dynfile->data[off], len);
mangle_UseValue(run, tmpbuf, len, printable);
}
static void mangle_Bytes(run_t* run, bool printable) {
uint16_t buf;
if (printable) {
util_rndBufPrintable((uint8_t*)&buf, sizeof(buf));
} else {
buf = util_rnd64();
}
/* Overwrite with random 1-2-byte values */
size_t toCopy = util_rndGet(1, 2);
mangle_UseValue(run, (const uint8_t*)&buf, toCopy, printable);
}
static void mangle_ByteRepeat(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
size_t destOff = off + 1;
size_t maxSz = run->dynfile->size - destOff;
/* No space to repeat */
if (!maxSz) {
mangle_Bytes(run, printable);
return;
}
size_t len = mangle_getLen(maxSz);
if (util_rnd64() & 0x1) {
len = mangle_Inflate(run, destOff, len, printable);
}
memset(&run->dynfile->data[destOff], run->dynfile->data[off], len);
}
static void mangle_Bit(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
run->dynfile->data[off] ^= (uint8_t)(1U << util_rndGet(0, 7));
if (printable) {
util_turnToPrintable(&(run->dynfile->data[off]), 1);
}
}
static const struct {
const uint8_t val[8];
const size_t size;
} mangleMagicVals[] = {
/* 1B - No endianness */
{"\x00\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x01\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x02\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x03\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x04\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x05\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x06\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x07\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x08\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x09\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x0A\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x0B\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x0C\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x0D\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x0E\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x0F\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x10\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x20\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x40\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x7E\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x7F\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x80\x00\x00\x00\x00\x00\x00\x00", 1},
{"\x81\x00\x00\x00\x00\x00\x00\x00", 1},
{"\xC0\x00\x00\x00\x00\x00\x00\x00", 1},
{"\xFE\x00\x00\x00\x00\x00\x00\x00", 1},
{"\xFF\x00\x00\x00\x00\x00\x00\x00", 1},
/* 2B - NE */
{"\x00\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x01\x01\x00\x00\x00\x00\x00\x00", 2},
{"\x80\x80\x00\x00\x00\x00\x00\x00", 2},
{"\xFF\xFF\x00\x00\x00\x00\x00\x00", 2},
/* 2B - BE */
{"\x00\x01\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x02\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x03\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x04\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x05\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x06\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x07\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x08\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x09\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x0A\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x0B\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x0C\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x0D\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x0E\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x0F\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x10\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x20\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x40\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x7E\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x7F\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x80\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x81\x00\x00\x00\x00\x00\x00", 2},
{"\x00\xC0\x00\x00\x00\x00\x00\x00", 2},
{"\x00\xFE\x00\x00\x00\x00\x00\x00", 2},
{"\x00\xFF\x00\x00\x00\x00\x00\x00", 2},
{"\x7E\xFF\x00\x00\x00\x00\x00\x00", 2},
{"\x7F\xFF\x00\x00\x00\x00\x00\x00", 2},
{"\x80\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x80\x01\x00\x00\x00\x00\x00\x00", 2},
{"\xFF\xFE\x00\x00\x00\x00\x00\x00", 2},
/* 2B - LE */
{"\x00\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x01\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x02\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x03\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x04\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x05\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x06\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x07\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x08\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x09\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x0A\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x0B\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x0C\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x0D\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x0E\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x0F\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x10\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x20\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x40\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x7E\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x7F\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x80\x00\x00\x00\x00\x00\x00\x00", 2},
{"\x81\x00\x00\x00\x00\x00\x00\x00", 2},
{"\xC0\x00\x00\x00\x00\x00\x00\x00", 2},
{"\xFE\x00\x00\x00\x00\x00\x00\x00", 2},
{"\xFF\x00\x00\x00\x00\x00\x00\x00", 2},
{"\xFF\x7E\x00\x00\x00\x00\x00\x00", 2},
{"\xFF\x7F\x00\x00\x00\x00\x00\x00", 2},
{"\x00\x80\x00\x00\x00\x00\x00\x00", 2},
{"\x01\x80\x00\x00\x00\x00\x00\x00", 2},
{"\xFE\xFF\x00\x00\x00\x00\x00\x00", 2},
/* 4B - NE */
{"\x00\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x01\x01\x01\x01\x00\x00\x00\x00", 4},
{"\x80\x80\x80\x80\x00\x00\x00\x00", 4},
{"\xFF\xFF\xFF\xFF\x00\x00\x00\x00", 4},
/* 4B - BE */
{"\x00\x00\x00\x01\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x02\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x03\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x04\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x05\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x06\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x07\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x08\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x09\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x0A\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x0B\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x0C\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x0D\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x0E\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x0F\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x10\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x20\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x40\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x7E\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x7F\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x80\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x81\x00\x00\x00\x00", 4},
{"\x00\x00\x00\xC0\x00\x00\x00\x00", 4},
{"\x00\x00\x00\xFE\x00\x00\x00\x00", 4},
{"\x00\x00\x00\xFF\x00\x00\x00\x00", 4},
{"\x7E\xFF\xFF\xFF\x00\x00\x00\x00", 4},
{"\x7F\xFF\xFF\xFF\x00\x00\x00\x00", 4},
{"\x80\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x80\x00\x00\x01\x00\x00\x00\x00", 4},
{"\xFF\xFF\xFF\xFE\x00\x00\x00\x00", 4},
/* 4B - LE */
{"\x00\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x01\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x02\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x03\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x04\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x05\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x06\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x07\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x08\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x09\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x0A\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x0B\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x0C\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x0D\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x0E\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x0F\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x10\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x20\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x40\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x7E\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x7F\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x80\x00\x00\x00\x00\x00\x00\x00", 4},
{"\x81\x00\x00\x00\x00\x00\x00\x00", 4},
{"\xC0\x00\x00\x00\x00\x00\x00\x00", 4},
{"\xFE\x00\x00\x00\x00\x00\x00\x00", 4},
{"\xFF\x00\x00\x00\x00\x00\x00\x00", 4},
{"\xFF\xFF\xFF\x7E\x00\x00\x00\x00", 4},
{"\xFF\xFF\xFF\x7F\x00\x00\x00\x00", 4},
{"\x00\x00\x00\x80\x00\x00\x00\x00", 4},
{"\x01\x00\x00\x80\x00\x00\x00\x00", 4},
{"\xFE\xFF\xFF\xFF\x00\x00\x00\x00", 4},
/* 8B - NE */
{"\x00\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x01\x01\x01\x01\x01\x01\x01\x01", 8},
{"\x80\x80\x80\x80\x80\x80\x80\x80", 8},
{"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 8},
/* 8B - BE */
{"\x00\x00\x00\x00\x00\x00\x00\x01", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x02", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x03", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x04", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x05", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x06", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x07", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x08", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x09", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x0A", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x0B", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x0C", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x0D", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x0E", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x0F", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x10", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x20", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x40", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x7E", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x7F", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x80", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x81", 8},
{"\x00\x00\x00\x00\x00\x00\x00\xC0", 8},
{"\x00\x00\x00\x00\x00\x00\x00\xFE", 8},
{"\x00\x00\x00\x00\x00\x00\x00\xFF", 8},
{"\x7E\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 8},
{"\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 8},
{"\x80\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x80\x00\x00\x00\x00\x00\x00\x01", 8},
{"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE", 8},
/* 8B - LE */
{"\x00\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x01\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x02\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x03\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x04\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x05\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x06\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x07\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x08\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x09\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x0A\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x0B\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x0C\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x0D\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x0E\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x0F\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x10\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x20\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x40\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x7E\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x7F\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x80\x00\x00\x00\x00\x00\x00\x00", 8},
{"\x81\x00\x00\x00\x00\x00\x00\x00", 8},
{"\xC0\x00\x00\x00\x00\x00\x00\x00", 8},
{"\xFE\x00\x00\x00\x00\x00\x00\x00", 8},
{"\xFF\x00\x00\x00\x00\x00\x00\x00", 8},
{"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7E", 8},
{"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", 8},
{"\x00\x00\x00\x00\x00\x00\x00\x80", 8},
{"\x01\x00\x00\x00\x00\x00\x00\x80", 8},
{"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF", 8},
};
static void mangle_Magic(run_t* run, bool printable) {
uint64_t choice = util_rndGet(0, ARRAYSIZE(mangleMagicVals) - 1);
mangle_UseValue(run, mangleMagicVals[choice].val, mangleMagicVals[choice].size, printable);
}
static void mangle_StaticDict(run_t* run, bool printable) {
if (run->global->mutate.dictionaryCnt == 0) {
mangle_Bytes(run, printable);
return;
}
uint64_t choice = util_rndGet(0, run->global->mutate.dictionaryCnt - 1);
mangle_UseValue(run, run->global->mutate.dictionary[choice].val,
run->global->mutate.dictionary[choice].len, printable);
}
static inline const uint8_t* mangle_FeedbackDict(run_t* run, size_t* len) {
if (!run->global->feedback.cmpFeedback) {
return NULL;
}
cmpfeedback_t* cmpf = run->global->feedback.cmpFeedbackMap;
uint32_t cnt = ATOMIC_GET(cmpf->cnt);
if (cnt == 0) {
return NULL;
}
if (cnt > ARRAYSIZE(cmpf->valArr)) {
cnt = ARRAYSIZE(cmpf->valArr);
}
uint32_t choice = util_rndGet(0, cnt - 1);
*len = (size_t)ATOMIC_GET(cmpf->valArr[choice].len);
if (*len == 0) {
return NULL;
}
return cmpf->valArr[choice].val;
}
static void mangle_ConstFeedbackDict(run_t* run, bool printable) {
size_t len;
const uint8_t* val = mangle_FeedbackDict(run, &len);
if (val == NULL) {
mangle_Bytes(run, printable);
return;
}
mangle_UseValue(run, val, len, printable);
}
static void mangle_MemSet(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
size_t len = mangle_getLen(run->dynfile->size - off);
int val = printable ? (int)util_rndPrintable() : (int)util_rndGet(0, UINT8_MAX);
if (util_rnd64() & 1) {
len = mangle_Inflate(run, off, len, printable);
}
memset(&run->dynfile->data[off], val, len);
}
static void mangle_MemClr(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
size_t len = mangle_getLen(run->dynfile->size - off);
int val = printable ? ' ' : 0;
if (util_rnd64() & 1) {
len = mangle_Inflate(run, off, len, printable);
}
memset(&run->dynfile->data[off], val, len);
}
static void mangle_RandomBuf(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
size_t len = mangle_getLen(run->dynfile->size - off);
if (util_rnd64() & 1) {
len = mangle_Inflate(run, off, len, printable);
}
if (printable) {
util_rndBufPrintable(&run->dynfile->data[off], len);
} else {
util_rndBuf(&run->dynfile->data[off], len);
}
}
static inline void mangle_AddSubWithRange(
run_t* run, size_t off, size_t varLen, uint64_t range, bool printable) {
int64_t delta = (int64_t)util_rndGet(0, range * 2) - (int64_t)range;
switch (varLen) {
case 1: {
run->dynfile->data[off] += delta;
break;
}
case 2: {
int16_t val;
memcpy(&val, &run->dynfile->data[off], sizeof(val));
if (util_rnd64() & 0x1) {
val += delta;
} else {
/* Foreign endianess */
val = __builtin_bswap16(val);
val += delta;
val = __builtin_bswap16(val);
}
mangle_Overwrite(run, off, (uint8_t*)&val, varLen, printable);
break;
}
case 4: {
int32_t val;
memcpy(&val, &run->dynfile->data[off], sizeof(val));
if (util_rnd64() & 0x1) {
val += delta;
} else {
/* Foreign endianess */
val = __builtin_bswap32(val);
val += delta;
val = __builtin_bswap32(val);
}
mangle_Overwrite(run, off, (uint8_t*)&val, varLen, printable);
break;
}
case 8: {
int64_t val;
memcpy(&val, &run->dynfile->data[off], sizeof(val));
if (util_rnd64() & 0x1) {
val += delta;
} else {
/* Foreign endianess */
val = __builtin_bswap64(val);
val += delta;
val = __builtin_bswap64(val);
}
mangle_Overwrite(run, off, (uint8_t*)&val, varLen, printable);
break;
}
default: {
LOG_F("Unknown variable length size: %zu", varLen);
}
}
}
static void mangle_AddSub(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
/* 1,2,4,8 */
size_t varLen = 1U << util_rndGet(0, 3);
if ((run->dynfile->size - off) < varLen) {
varLen = 1;
}
uint64_t range;
switch (varLen) {
case 1:
range = 16;
break;
case 2:
range = 4096;
break;
case 4:
range = 1048576;
break;
case 8:
range = 268435456;
break;
default:
LOG_F("Invalid operand size: %zu", varLen);
}
mangle_AddSubWithRange(run, off, varLen, range, printable);
}
static void mangle_IncByte(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
if (printable) {
run->dynfile->data[off] = (run->dynfile->data[off] - 32 + 1) % 95 + 32;
} else {
run->dynfile->data[off] += (uint8_t)1UL;
}
}
static void mangle_DecByte(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
if (printable) {
run->dynfile->data[off] = (run->dynfile->data[off] - 32 + 94) % 95 + 32;
} else {
run->dynfile->data[off] -= (uint8_t)1UL;
}
}
static void mangle_NegByte(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
if (printable) {
run->dynfile->data[off] = 94 - (run->dynfile->data[off] - 32) + 32;
} else {
run->dynfile->data[off] = ~(run->dynfile->data[off]);
}
}
static void mangle_Expand(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
size_t len;
if (util_rnd64() % 16) {
len = mangle_getLen(HF_MIN(16, run->global->mutate.maxInputSz - off));
} else {
len = mangle_getLen(run->global->mutate.maxInputSz - off);
}
mangle_Inflate(run, off, len, printable);
}
static void mangle_Shrink(run_t* run, bool printable HF_ATTR_UNUSED) {
if (run->dynfile->size <= 2U) {
return;
}
size_t off_start = mangle_getOffSet(run);
size_t len = mangle_LenLeft(run, off_start);
if (len == 0) {
return;
}
if (util_rnd64() % 16) {
len = mangle_getLen(HF_MIN(16, len));
} else {
len = mangle_getLen(len);
}
size_t off_end = off_start + len;
size_t len_to_move = run->dynfile->size - off_end;
mangle_Move(run, off_end, off_start, len_to_move);
input_setSize(run, run->dynfile->size - len);
}
static void mangle_ASCIINum(run_t* run, bool printable) {
size_t len = util_rndGet(2, 8);
char buf[20];
snprintf(buf, sizeof(buf), "%-19" PRId64, (int64_t)util_rnd64());
mangle_UseValue(run, (const uint8_t*)buf, len, printable);
}
static void mangle_ASCIINumChange(run_t* run, bool printable) {
size_t off = mangle_getOffSet(run);
/* Find a digit */
for (; off < run->dynfile->size; off++) {
if (isdigit(run->dynfile->data[off])) {
break;
}
}
size_t left = run->dynfile->size - off;
if (left == 0) {
return;
}
size_t len = 0;
uint64_t val = 0;
/* 20 is maximum lenght of a string representing a 64-bit unsigned value */
for (len = 0; (len < 20) && (len < left); len++) {
char c = run->dynfile->data[off + len];
if (!isdigit(c)) {
break;
}
val *= 10;
val += (c - '0');
}
switch (util_rndGet(0, 7)) {
case 0:
val++;
break;
case 1:
val--;
break;
case 2:
val *= 2;
break;
case 3:
val /= 2;
break;
case 4:
val = util_rnd64();
break;
case 5:
val += util_rndGet(1, 256);
break;
case 6:
val -= util_rndGet(1, 256);
break;
case 7:
val = ~(val);
break;
default:
LOG_F("Invalid choice");
};
char buf[20];
snprintf(buf, sizeof(buf), "%-19" PRIu64, val);
mangle_UseValueAt(run, off, (const uint8_t*)buf, len, printable);
}
static void mangle_Splice(run_t* run, bool printable) {
if (run->global->feedback.dynFileMethod == _HF_DYNFILE_NONE) {
mangle_Bytes(run, printable);
return;
}
size_t sz = 0;
const uint8_t* buf = input_getRandomInputAsBuf(run, &sz);
if (!buf) {
LOG_E("input_getRandomInputAsBuf() returned no input");
mangle_Bytes(run, printable);
return;
}
if (!sz) {
mangle_Bytes(run, printable);
return;
}
size_t remoteOff = mangle_getLen(sz) - 1;
size_t len = mangle_getLen(sz - remoteOff);
mangle_UseValue(run, &buf[remoteOff], len, printable);
}
static void mangle_Resize(run_t* run, bool printable) {
ssize_t oldsz = run->dynfile->size;
ssize_t newsz = 0;
uint64_t choice = util_rndGet(0, 32);
switch (choice) {
case 0: /* Set new size arbitrarily */
newsz = (ssize_t)util_rndGet(1, run->global->mutate.maxInputSz);
break;
case 1 ... 4: /* Increase size by a small value */
newsz = oldsz + (ssize_t)util_rndGet(0, 8);
break;
case 5: /* Increase size by a larger value */
newsz = oldsz + (ssize_t)util_rndGet(9, 128);
break;
case 6 ... 9: /* Decrease size by a small value */
newsz = oldsz - (ssize_t)util_rndGet(0, 8);
break;
case 10: /* Decrease size by a larger value */
newsz = oldsz - (ssize_t)util_rndGet(9, 128);
break;
case 11 ... 32: /* Do nothing */
newsz = oldsz;
break;
default:
LOG_F("Illegal value from util_rndGet: %" PRIu64, choice);
break;
}
if (newsz < 1) {
newsz = 1;
}
if (newsz > (ssize_t)run->global->mutate.maxInputSz) {
newsz = run->global->mutate.maxInputSz;
}
input_setSize(run, (size_t)newsz);
if (newsz > oldsz) {
if (printable) {
memset(&run->dynfile->data[oldsz], ' ', newsz - oldsz);
}
}
}
void mangle_mangleContent(run_t* run, int speed_factor) {
static void (*const mangleFuncs[])(run_t * run, bool printable) = {
mangle_Shrink,
mangle_Expand,
mangle_Bit,
mangle_IncByte,
mangle_DecByte,
mangle_NegByte,
mangle_AddSub,
mangle_MemSet,
mangle_MemClr,
mangle_MemSwap,
mangle_MemCopy,
mangle_Bytes,
mangle_ASCIINum,
mangle_ASCIINumChange,
mangle_ByteRepeat,
mangle_Magic,
mangle_StaticDict,
mangle_ConstFeedbackDict,
mangle_RandomBuf,
mangle_Splice,
};
if (run->mutationsPerRun == 0U) {
return;
}
if (run->dynfile->size == 0U) {
mangle_Resize(run, /* printable= */ run->global->cfg.only_printable);
}
uint64_t changesCnt = run->global->mutate.mutationsPerRun;
if (speed_factor < 5) {
changesCnt = util_rndGet(1, run->global->mutate.mutationsPerRun);
} else if (speed_factor < 10) {
changesCnt = run->global->mutate.mutationsPerRun;
} else {
changesCnt = HF_MIN(speed_factor, 10);
changesCnt = HF_MAX(changesCnt, (run->global->mutate.mutationsPerRun * 5));
}
/* If last coverage acquisition was more than 5 secs ago, use splicing more frequently */
if ((time(NULL) - ATOMIC_GET(run->global->timing.lastCovUpdate)) > 5) {
if (util_rnd64() & 0x1) {
mangle_Splice(run, run->global->cfg.only_printable);
}
}
for (uint64_t x = 0; x < changesCnt; x++) {
if (run->global->feedback.cmpFeedback && (util_rnd64() & 0x1)) {
/*
* mangle_ConstFeedbackDict() is quite powerful if the dynamic feedback dictionary
* exists. If so, give it 50% chance of being used among all mangling functions.
*/
mangle_ConstFeedbackDict(run, /* printable= */ run->global->cfg.only_printable);
} else {
uint64_t choice = util_rndGet(0, ARRAYSIZE(mangleFuncs) - 1);
mangleFuncs[choice](run, /* printable= */ run->global->cfg.only_printable);
}
}
wmb();
}

View File

@ -0,0 +1,31 @@
/*
*
* honggfuzz - buffer mangling routines
* -----------------------------------------
*
* Author: Robert Swiecki <swiecki@google.com>
*
* Copyright 2010-2018 by Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
#ifndef _HF_MANGLE_H_
#define _HF_MANGLE_H_
#include "honggfuzz.h"
extern void mangle_mangleContent(run_t* run, int speed_factor);
#endif

View File

@ -0,0 +1,35 @@
//===- FuzzerBuiltins.h - Internal header for builtins ----------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Wrapper functions and macros around builtin functions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_BUILTINS_H
#define LLVM_FUZZER_BUILTINS_H
#include "FuzzerPlatform.h"
#if !LIBFUZZER_MSVC
#include <cstdint>
#define GET_CALLER_PC() __builtin_return_address(0)
namespace fuzzer {
inline uint8_t Bswap(uint8_t x) { return x; }
inline uint16_t Bswap(uint16_t x) { return __builtin_bswap16(x); }
inline uint32_t Bswap(uint32_t x) { return __builtin_bswap32(x); }
inline uint64_t Bswap(uint64_t x) { return __builtin_bswap64(x); }
inline uint32_t Clzll(unsigned long long X) { return __builtin_clzll(X); }
inline uint32_t Clz(unsigned long long X) { return __builtin_clz(X); }
inline int Popcountll(unsigned long long X) { return __builtin_popcountll(X); }
} // namespace fuzzer
#endif // !LIBFUZZER_MSVC
#endif // LLVM_FUZZER_BUILTINS_H

View File

@ -0,0 +1,72 @@
//===- FuzzerBuiltinsMSVC.h - Internal header for builtins ------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Wrapper functions and macros that use intrinsics instead of builtin functions
// which cannot be compiled by MSVC.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_BUILTINS_MSVC_H
#define LLVM_FUZZER_BUILTINS_MSVC_H
#include "FuzzerPlatform.h"
#if LIBFUZZER_MSVC
#include <intrin.h>
#include <cstdint>
#include <cstdlib>
// __builtin_return_address() cannot be compiled with MSVC. Use the equivalent
// from <intrin.h>
#define GET_CALLER_PC() _ReturnAddress()
namespace fuzzer {
inline uint8_t Bswap(uint8_t x) { return x; }
// Use alternatives to __builtin functions from <stdlib.h> and <intrin.h> on
// Windows since the builtins are not supported by MSVC.
inline uint16_t Bswap(uint16_t x) { return _byteswap_ushort(x); }
inline uint32_t Bswap(uint32_t x) { return _byteswap_ulong(x); }
inline uint64_t Bswap(uint64_t x) { return _byteswap_uint64(x); }
// The functions below were mostly copied from
// compiler-rt/lib/builtins/int_lib.h which defines the __builtin functions used
// outside of Windows.
inline uint32_t Clzll(uint64_t X) {
unsigned long LeadZeroIdx = 0;
#if !defined(_M_ARM) && !defined(_M_X64)
// Scan the high 32 bits.
if (_BitScanReverse(&LeadZeroIdx, static_cast<unsigned long>(X >> 32)))
return static_cast<int>(63 - (LeadZeroIdx + 32)); // Create a bit offset from the MSB.
// Scan the low 32 bits.
if (_BitScanReverse(&LeadZeroIdx, static_cast<unsigned long>(X)))
return static_cast<int>(63 - LeadZeroIdx);
#else
if (_BitScanReverse64(&LeadZeroIdx, X)) return 63 - LeadZeroIdx;
#endif
return 64;
}
inline uint32_t Clz(uint32_t X) {
unsigned long LeadZeroIdx = 0;
if (_BitScanReverse(&LeadZeroIdx, X)) return 31 - LeadZeroIdx;
return 32;
}
inline int Popcountll(unsigned long long X) {
#if !defined(_M_ARM) && !defined(_M_X64)
return __popcnt(X) + __popcnt(X >> 32);
#else
return __popcnt64(X);
#endif
}
} // namespace fuzzer
#endif // LIBFUZER_MSVC
#endif // LLVM_FUZZER_BUILTINS_MSVC_H

View File

@ -0,0 +1,178 @@
//===- FuzzerCommand.h - Interface representing a process -------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// FuzzerCommand represents a command to run in a subprocess. It allows callers
// to manage command line arguments and output and error streams.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_COMMAND_H
#define LLVM_FUZZER_COMMAND_H
#include "FuzzerDefs.h"
#include "FuzzerIO.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
namespace fuzzer {
class Command final {
public:
// This command line flag is used to indicate that the remaining command line
// is immutable, meaning this flag effectively marks the end of the mutable
// argument list.
static inline const char *ignoreRemainingArgs() {
return "-ignore_remaining_args=1";
}
Command() : CombinedOutAndErr(false) {}
explicit Command(const Vector<std::string> &ArgsToAdd)
: Args(ArgsToAdd), CombinedOutAndErr(false) {}
explicit Command(const Command &Other)
: Args(Other.Args), CombinedOutAndErr(Other.CombinedOutAndErr),
OutputFile(Other.OutputFile) {}
Command &operator=(const Command &Other) {
Args = Other.Args;
CombinedOutAndErr = Other.CombinedOutAndErr;
OutputFile = Other.OutputFile;
return *this;
}
~Command() {}
// Returns true if the given Arg is present in Args. Only checks up to
// "-ignore_remaining_args=1".
bool hasArgument(const std::string &Arg) const {
auto i = endMutableArgs();
return std::find(Args.begin(), i, Arg) != i;
}
// Gets all of the current command line arguments, **including** those after
// "-ignore-remaining-args=1".
const Vector<std::string> &getArguments() const { return Args; }
// Adds the given argument before "-ignore_remaining_args=1", or at the end
// if that flag isn't present.
void addArgument(const std::string &Arg) {
Args.insert(endMutableArgs(), Arg);
}
// Adds all given arguments before "-ignore_remaining_args=1", or at the end
// if that flag isn't present.
void addArguments(const Vector<std::string> &ArgsToAdd) {
Args.insert(endMutableArgs(), ArgsToAdd.begin(), ArgsToAdd.end());
}
// Removes the given argument from the command argument list. Ignores any
// occurrences after "-ignore_remaining_args=1", if present.
void removeArgument(const std::string &Arg) {
auto i = endMutableArgs();
Args.erase(std::remove(Args.begin(), i, Arg), i);
}
// Like hasArgument, but checks for "-[Flag]=...".
bool hasFlag(const std::string &Flag) const {
std::string Arg("-" + Flag + "=");
auto IsMatch = [&](const std::string &Other) {
return Arg.compare(0, std::string::npos, Other, 0, Arg.length()) == 0;
};
return std::any_of(Args.begin(), endMutableArgs(), IsMatch);
}
// Returns the value of the first instance of a given flag, or an empty string
// if the flag isn't present. Ignores any occurrences after
// "-ignore_remaining_args=1", if present.
std::string getFlagValue(const std::string &Flag) const {
std::string Arg("-" + Flag + "=");
auto IsMatch = [&](const std::string &Other) {
return Arg.compare(0, std::string::npos, Other, 0, Arg.length()) == 0;
};
auto i = endMutableArgs();
auto j = std::find_if(Args.begin(), i, IsMatch);
std::string result;
if (j != i) {
result = j->substr(Arg.length());
}
return result;
}
// Like AddArgument, but adds "-[Flag]=[Value]".
void addFlag(const std::string &Flag, const std::string &Value) {
addArgument("-" + Flag + "=" + Value);
}
// Like RemoveArgument, but removes "-[Flag]=...".
void removeFlag(const std::string &Flag) {
std::string Arg("-" + Flag + "=");
auto IsMatch = [&](const std::string &Other) {
return Arg.compare(0, std::string::npos, Other, 0, Arg.length()) == 0;
};
auto i = endMutableArgs();
Args.erase(std::remove_if(Args.begin(), i, IsMatch), i);
}
// Returns whether the command's stdout is being written to an output file.
bool hasOutputFile() const { return !OutputFile.empty(); }
// Returns the currently set output file.
const std::string &getOutputFile() const { return OutputFile; }
// Configures the command to redirect its output to the name file.
void setOutputFile(const std::string &FileName) { OutputFile = FileName; }
// Returns whether the command's stderr is redirected to stdout.
bool isOutAndErrCombined() const { return CombinedOutAndErr; }
// Sets whether to redirect the command's stderr to its stdout.
void combineOutAndErr(bool combine = true) { CombinedOutAndErr = combine; }
// Returns a string representation of the command. On many systems this will
// be the equivalent command line.
std::string toString() const {
std::stringstream SS;
for (auto arg : getArguments())
SS << arg << " ";
if (hasOutputFile())
SS << ">" << getOutputFile() << " ";
if (isOutAndErrCombined())
SS << "2>&1 ";
std::string result = SS.str();
if (!result.empty())
result = result.substr(0, result.length() - 1);
return result;
}
private:
Command(Command &&Other) = delete;
Command &operator=(Command &&Other) = delete;
Vector<std::string>::iterator endMutableArgs() {
return std::find(Args.begin(), Args.end(), ignoreRemainingArgs());
}
Vector<std::string>::const_iterator endMutableArgs() const {
return std::find(Args.begin(), Args.end(), ignoreRemainingArgs());
}
// The command arguments. Args[0] is the command name.
Vector<std::string> Args;
// True indicates stderr is redirected to stdout.
bool CombinedOutAndErr;
// If not empty, stdout is redirected to the named file.
std::string OutputFile;
};
} // namespace fuzzer
#endif // LLVM_FUZZER_COMMAND_H

View File

@ -0,0 +1,581 @@
//===- FuzzerCorpus.h - Internal header for the Fuzzer ----------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::InputCorpus
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_CORPUS
#define LLVM_FUZZER_CORPUS
#include "FuzzerDataFlowTrace.h"
#include "FuzzerDefs.h"
#include "FuzzerIO.h"
#include "FuzzerRandom.h"
#include "FuzzerSHA1.h"
#include "FuzzerTracePC.h"
#include <algorithm>
#include <chrono>
#include <numeric>
#include <random>
#include <unordered_set>
namespace fuzzer {
struct InputInfo {
Unit U; // The actual input data.
std::chrono::microseconds TimeOfUnit;
uint8_t Sha1[kSHA1NumBytes]; // Checksum.
// Number of features that this input has and no smaller input has.
size_t NumFeatures = 0;
size_t Tmp = 0; // Used by ValidateFeatureSet.
// Stats.
size_t NumExecutedMutations = 0;
size_t NumSuccessfullMutations = 0;
bool NeverReduce = false;
bool MayDeleteFile = false;
bool Reduced = false;
bool HasFocusFunction = false;
Vector<uint32_t> UniqFeatureSet;
Vector<uint8_t> DataFlowTraceForFocusFunction;
// Power schedule.
bool NeedsEnergyUpdate = false;
double Energy = 0.0;
size_t SumIncidence = 0;
Vector<std::pair<uint32_t, uint16_t>> FeatureFreqs;
// Delete feature Idx and its frequency from FeatureFreqs.
bool DeleteFeatureFreq(uint32_t Idx) {
if (FeatureFreqs.empty())
return false;
// Binary search over local feature frequencies sorted by index.
auto Lower = std::lower_bound(FeatureFreqs.begin(), FeatureFreqs.end(),
std::pair<uint32_t, uint16_t>(Idx, 0));
if (Lower != FeatureFreqs.end() && Lower->first == Idx) {
FeatureFreqs.erase(Lower);
return true;
}
return false;
}
// Assign more energy to a high-entropy seed, i.e., that reveals more
// information about the globally rare features in the neighborhood of the
// seed. Since we do not know the entropy of a seed that has never been
// executed we assign fresh seeds maximum entropy and let II->Energy approach
// the true entropy from above. If ScalePerExecTime is true, the computed
// entropy is scaled based on how fast this input executes compared to the
// average execution time of inputs. The faster an input executes, the more
// energy gets assigned to the input.
void UpdateEnergy(size_t GlobalNumberOfFeatures, bool ScalePerExecTime,
std::chrono::microseconds AverageUnitExecutionTime) {
Energy = 0.0;
SumIncidence = 0;
// Apply add-one smoothing to locally discovered features.
for (auto F : FeatureFreqs) {
size_t LocalIncidence = F.second + 1;
Energy -= LocalIncidence * logl(LocalIncidence);
SumIncidence += LocalIncidence;
}
// Apply add-one smoothing to locally undiscovered features.
// PreciseEnergy -= 0; // since logl(1.0) == 0)
SumIncidence += (GlobalNumberOfFeatures - FeatureFreqs.size());
// Add a single locally abundant feature apply add-one smoothing.
size_t AbdIncidence = NumExecutedMutations + 1;
Energy -= AbdIncidence * logl(AbdIncidence);
SumIncidence += AbdIncidence;
// Normalize.
if (SumIncidence != 0)
Energy = (Energy / SumIncidence) + logl(SumIncidence);
if (ScalePerExecTime) {
// Scaling to favor inputs with lower execution time.
uint32_t PerfScore = 100;
if (TimeOfUnit.count() > AverageUnitExecutionTime.count() * 10)
PerfScore = 10;
else if (TimeOfUnit.count() > AverageUnitExecutionTime.count() * 4)
PerfScore = 25;
else if (TimeOfUnit.count() > AverageUnitExecutionTime.count() * 2)
PerfScore = 50;
else if (TimeOfUnit.count() * 3 > AverageUnitExecutionTime.count() * 4)
PerfScore = 75;
else if (TimeOfUnit.count() * 4 < AverageUnitExecutionTime.count())
PerfScore = 300;
else if (TimeOfUnit.count() * 3 < AverageUnitExecutionTime.count())
PerfScore = 200;
else if (TimeOfUnit.count() * 2 < AverageUnitExecutionTime.count())
PerfScore = 150;
Energy *= PerfScore;
}
}
// Increment the frequency of the feature Idx.
void UpdateFeatureFrequency(uint32_t Idx) {
NeedsEnergyUpdate = true;
// The local feature frequencies is an ordered vector of pairs.
// If there are no local feature frequencies, push_back preserves order.
// Set the feature frequency for feature Idx32 to 1.
if (FeatureFreqs.empty()) {
FeatureFreqs.push_back(std::pair<uint32_t, uint16_t>(Idx, 1));
return;
}
// Binary search over local feature frequencies sorted by index.
auto Lower = std::lower_bound(FeatureFreqs.begin(), FeatureFreqs.end(),
std::pair<uint32_t, uint16_t>(Idx, 0));
// If feature Idx32 already exists, increment its frequency.
// Otherwise, insert a new pair right after the next lower index.
if (Lower != FeatureFreqs.end() && Lower->first == Idx) {
Lower->second++;
} else {
FeatureFreqs.insert(Lower, std::pair<uint32_t, uint16_t>(Idx, 1));
}
}
};
struct EntropicOptions {
bool Enabled;
size_t NumberOfRarestFeatures;
size_t FeatureFrequencyThreshold;
bool ScalePerExecTime;
};
class InputCorpus {
static const uint32_t kFeatureSetSize = 1 << 21;
static const uint8_t kMaxMutationFactor = 20;
static const size_t kSparseEnergyUpdates = 100;
size_t NumExecutedMutations = 0;
EntropicOptions Entropic;
public:
InputCorpus(const std::string &OutputCorpus, EntropicOptions Entropic)
: Entropic(Entropic), OutputCorpus(OutputCorpus) {
memset(InputSizesPerFeature, 0, sizeof(InputSizesPerFeature));
memset(SmallestElementPerFeature, 0, sizeof(SmallestElementPerFeature));
}
~InputCorpus() {
for (auto II : Inputs)
delete II;
}
size_t size() const { return Inputs.size(); }
size_t SizeInBytes() const {
size_t Res = 0;
for (auto II : Inputs)
Res += II->U.size();
return Res;
}
size_t NumActiveUnits() const {
size_t Res = 0;
for (auto II : Inputs)
Res += !II->U.empty();
return Res;
}
size_t MaxInputSize() const {
size_t Res = 0;
for (auto II : Inputs)
Res = std::max(Res, II->U.size());
return Res;
}
void IncrementNumExecutedMutations() { NumExecutedMutations++; }
size_t NumInputsThatTouchFocusFunction() {
return std::count_if(Inputs.begin(), Inputs.end(), [](const InputInfo *II) {
return II->HasFocusFunction;
});
}
size_t NumInputsWithDataFlowTrace() {
return std::count_if(Inputs.begin(), Inputs.end(), [](const InputInfo *II) {
return !II->DataFlowTraceForFocusFunction.empty();
});
}
bool empty() const { return Inputs.empty(); }
const Unit &operator[] (size_t Idx) const { return Inputs[Idx]->U; }
InputInfo *AddToCorpus(const Unit &U, size_t NumFeatures, bool MayDeleteFile,
bool HasFocusFunction, bool NeverReduce,
std::chrono::microseconds TimeOfUnit,
const Vector<uint32_t> &FeatureSet,
const DataFlowTrace &DFT, const InputInfo *BaseII) {
assert(!U.empty());
if (FeatureDebug)
Printf("ADD_TO_CORPUS %zd NF %zd\n", Inputs.size(), NumFeatures);
Inputs.push_back(new InputInfo());
InputInfo &II = *Inputs.back();
II.U = U;
II.NumFeatures = NumFeatures;
II.NeverReduce = NeverReduce;
II.TimeOfUnit = TimeOfUnit;
II.MayDeleteFile = MayDeleteFile;
II.UniqFeatureSet = FeatureSet;
II.HasFocusFunction = HasFocusFunction;
// Assign maximal energy to the new seed.
II.Energy = RareFeatures.empty() ? 1.0 : log(RareFeatures.size());
II.SumIncidence = RareFeatures.size();
II.NeedsEnergyUpdate = false;
std::sort(II.UniqFeatureSet.begin(), II.UniqFeatureSet.end());
ComputeSHA1(U.data(), U.size(), II.Sha1);
auto Sha1Str = Sha1ToString(II.Sha1);
Hashes.insert(Sha1Str);
if (HasFocusFunction)
if (auto V = DFT.Get(Sha1Str))
II.DataFlowTraceForFocusFunction = *V;
// This is a gross heuristic.
// Ideally, when we add an element to a corpus we need to know its DFT.
// But if we don't, we'll use the DFT of its base input.
if (II.DataFlowTraceForFocusFunction.empty() && BaseII)
II.DataFlowTraceForFocusFunction = BaseII->DataFlowTraceForFocusFunction;
DistributionNeedsUpdate = true;
PrintCorpus();
// ValidateFeatureSet();
return &II;
}
// Debug-only
void PrintUnit(const Unit &U) {
if (!FeatureDebug) return;
for (uint8_t C : U) {
if (C != 'F' && C != 'U' && C != 'Z')
C = '.';
Printf("%c", C);
}
}
// Debug-only
void PrintFeatureSet(const Vector<uint32_t> &FeatureSet) {
if (!FeatureDebug) return;
Printf("{");
for (uint32_t Feature: FeatureSet)
Printf("%u,", Feature);
Printf("}");
}
// Debug-only
void PrintCorpus() {
if (!FeatureDebug) return;
Printf("======= CORPUS:\n");
int i = 0;
for (auto II : Inputs) {
if (std::find(II->U.begin(), II->U.end(), 'F') != II->U.end()) {
Printf("[%2d] ", i);
Printf("%s sz=%zd ", Sha1ToString(II->Sha1).c_str(), II->U.size());
PrintUnit(II->U);
Printf(" ");
PrintFeatureSet(II->UniqFeatureSet);
Printf("\n");
}
i++;
}
}
void Replace(InputInfo *II, const Unit &U) {
assert(II->U.size() > U.size());
Hashes.erase(Sha1ToString(II->Sha1));
DeleteFile(*II);
ComputeSHA1(U.data(), U.size(), II->Sha1);
Hashes.insert(Sha1ToString(II->Sha1));
II->U = U;
II->Reduced = true;
DistributionNeedsUpdate = true;
}
bool HasUnit(const Unit &U) { return Hashes.count(Hash(U)); }
bool HasUnit(const std::string &H) { return Hashes.count(H); }
InputInfo &ChooseUnitToMutate(Random &Rand) {
InputInfo &II = *Inputs[ChooseUnitIdxToMutate(Rand)];
assert(!II.U.empty());
return II;
}
InputInfo &ChooseUnitToCrossOverWith(Random &Rand, bool UniformDist) {
if (!UniformDist) {
return ChooseUnitToMutate(Rand);
}
InputInfo &II = *Inputs[Rand(Inputs.size())];
assert(!II.U.empty());
return II;
}
// Returns an index of random unit from the corpus to mutate.
size_t ChooseUnitIdxToMutate(Random &Rand) {
UpdateCorpusDistribution(Rand);
size_t Idx = static_cast<size_t>(CorpusDistribution(Rand));
assert(Idx < Inputs.size());
return Idx;
}
void PrintStats() {
for (size_t i = 0; i < Inputs.size(); i++) {
const auto &II = *Inputs[i];
Printf(" [% 3zd %s] sz: % 5zd runs: % 5zd succ: % 5zd focus: %d\n", i,
Sha1ToString(II.Sha1).c_str(), II.U.size(),
II.NumExecutedMutations, II.NumSuccessfullMutations, II.HasFocusFunction);
}
}
void PrintFeatureSet() {
for (size_t i = 0; i < kFeatureSetSize; i++) {
if(size_t Sz = GetFeature(i))
Printf("[%zd: id %zd sz%zd] ", i, SmallestElementPerFeature[i], Sz);
}
Printf("\n\t");
for (size_t i = 0; i < Inputs.size(); i++)
if (size_t N = Inputs[i]->NumFeatures)
Printf(" %zd=>%zd ", i, N);
Printf("\n");
}
void DeleteFile(const InputInfo &II) {
if (!OutputCorpus.empty() && II.MayDeleteFile)
RemoveFile(DirPlusFile(OutputCorpus, Sha1ToString(II.Sha1)));
}
void DeleteInput(size_t Idx) {
InputInfo &II = *Inputs[Idx];
DeleteFile(II);
Unit().swap(II.U);
II.Energy = 0.0;
II.NeedsEnergyUpdate = false;
DistributionNeedsUpdate = true;
if (FeatureDebug)
Printf("EVICTED %zd\n", Idx);
}
void AddRareFeature(uint32_t Idx) {
// Maintain *at least* TopXRarestFeatures many rare features
// and all features with a frequency below ConsideredRare.
// Remove all other features.
while (RareFeatures.size() > Entropic.NumberOfRarestFeatures &&
FreqOfMostAbundantRareFeature > Entropic.FeatureFrequencyThreshold) {
// Find most and second most abbundant feature.
uint32_t MostAbundantRareFeatureIndices[2] = {RareFeatures[0],
RareFeatures[0]};
size_t Delete = 0;
for (size_t i = 0; i < RareFeatures.size(); i++) {
uint32_t Idx2 = RareFeatures[i];
if (GlobalFeatureFreqs[Idx2] >=
GlobalFeatureFreqs[MostAbundantRareFeatureIndices[0]]) {
MostAbundantRareFeatureIndices[1] = MostAbundantRareFeatureIndices[0];
MostAbundantRareFeatureIndices[0] = Idx2;
Delete = i;
}
}
// Remove most abundant rare feature.
RareFeatures[Delete] = RareFeatures.back();
RareFeatures.pop_back();
for (auto II : Inputs) {
if (II->DeleteFeatureFreq(MostAbundantRareFeatureIndices[0]))
II->NeedsEnergyUpdate = true;
}
// Set 2nd most abundant as the new most abundant feature count.
FreqOfMostAbundantRareFeature =
GlobalFeatureFreqs[MostAbundantRareFeatureIndices[1]];
}
// Add rare feature, handle collisions, and update energy.
RareFeatures.push_back(Idx);
GlobalFeatureFreqs[Idx] = 0;
for (auto II : Inputs) {
II->DeleteFeatureFreq(Idx);
// Apply add-one smoothing to this locally undiscovered feature.
// Zero energy seeds will never be fuzzed and remain zero energy.
if (II->Energy > 0.0) {
II->SumIncidence += 1;
II->Energy += logl(II->SumIncidence) / II->SumIncidence;
}
}
DistributionNeedsUpdate = true;
}
bool AddFeature(size_t Idx, uint32_t NewSize, bool Shrink) {
assert(NewSize);
Idx = Idx % kFeatureSetSize;
uint32_t OldSize = GetFeature(Idx);
if (OldSize == 0 || (Shrink && OldSize > NewSize)) {
if (OldSize > 0) {
size_t OldIdx = SmallestElementPerFeature[Idx];
InputInfo &II = *Inputs[OldIdx];
assert(II.NumFeatures > 0);
II.NumFeatures--;
if (II.NumFeatures == 0)
DeleteInput(OldIdx);
} else {
NumAddedFeatures++;
if (Entropic.Enabled)
AddRareFeature((uint32_t)Idx);
}
NumUpdatedFeatures++;
if (FeatureDebug)
Printf("ADD FEATURE %zd sz %d\n", Idx, NewSize);
SmallestElementPerFeature[Idx] = Inputs.size();
InputSizesPerFeature[Idx] = NewSize;
return true;
}
return false;
}
// Increment frequency of feature Idx globally and locally.
void UpdateFeatureFrequency(InputInfo *II, size_t Idx) {
uint32_t Idx32 = Idx % kFeatureSetSize;
// Saturated increment.
if (GlobalFeatureFreqs[Idx32] == 0xFFFF)
return;
uint16_t Freq = GlobalFeatureFreqs[Idx32]++;
// Skip if abundant.
if (Freq > FreqOfMostAbundantRareFeature ||
std::find(RareFeatures.begin(), RareFeatures.end(), Idx32) ==
RareFeatures.end())
return;
// Update global frequencies.
if (Freq == FreqOfMostAbundantRareFeature)
FreqOfMostAbundantRareFeature++;
// Update local frequencies.
if (II)
II->UpdateFeatureFrequency(Idx32);
}
size_t NumFeatures() const { return NumAddedFeatures; }
size_t NumFeatureUpdates() const { return NumUpdatedFeatures; }
private:
static const bool FeatureDebug = false;
size_t GetFeature(size_t Idx) const { return InputSizesPerFeature[Idx]; }
void ValidateFeatureSet() {
if (FeatureDebug)
PrintFeatureSet();
for (size_t Idx = 0; Idx < kFeatureSetSize; Idx++)
if (GetFeature(Idx))
Inputs[SmallestElementPerFeature[Idx]]->Tmp++;
for (auto II: Inputs) {
if (II->Tmp != II->NumFeatures)
Printf("ZZZ %zd %zd\n", II->Tmp, II->NumFeatures);
assert(II->Tmp == II->NumFeatures);
II->Tmp = 0;
}
}
// Updates the probability distribution for the units in the corpus.
// Must be called whenever the corpus or unit weights are changed.
//
// Hypothesis: inputs that maximize information about globally rare features
// are interesting.
void UpdateCorpusDistribution(Random &Rand) {
// Skip update if no seeds or rare features were added/deleted.
// Sparse updates for local change of feature frequencies,
// i.e., randomly do not skip.
if (!DistributionNeedsUpdate &&
(!Entropic.Enabled || Rand(kSparseEnergyUpdates)))
return;
DistributionNeedsUpdate = false;
size_t N = Inputs.size();
assert(N);
Intervals.resize(N + 1);
Weights.resize(N);
std::iota(Intervals.begin(), Intervals.end(), 0);
std::chrono::microseconds AverageUnitExecutionTime(0);
for (auto II : Inputs) {
AverageUnitExecutionTime += II->TimeOfUnit;
}
AverageUnitExecutionTime /= N;
bool VanillaSchedule = true;
if (Entropic.Enabled) {
for (auto II : Inputs) {
if (II->NeedsEnergyUpdate && II->Energy != 0.0) {
II->NeedsEnergyUpdate = false;
II->UpdateEnergy(RareFeatures.size(), Entropic.ScalePerExecTime,
AverageUnitExecutionTime);
}
}
for (size_t i = 0; i < N; i++) {
if (Inputs[i]->NumFeatures == 0) {
// If the seed doesn't represent any features, assign zero energy.
Weights[i] = 0.;
} else if (Inputs[i]->NumExecutedMutations / kMaxMutationFactor >
NumExecutedMutations / Inputs.size()) {
// If the seed was fuzzed a lot more than average, assign zero energy.
Weights[i] = 0.;
} else {
// Otherwise, simply assign the computed energy.
Weights[i] = Inputs[i]->Energy;
}
// If energy for all seeds is zero, fall back to vanilla schedule.
if (Weights[i] > 0.0)
VanillaSchedule = false;
}
}
if (VanillaSchedule) {
for (size_t i = 0; i < N; i++)
Weights[i] = Inputs[i]->NumFeatures
? (i + 1) * (Inputs[i]->HasFocusFunction ? 1000 : 1)
: 0.;
}
if (FeatureDebug) {
for (size_t i = 0; i < N; i++)
Printf("%zd ", Inputs[i]->NumFeatures);
Printf("SCORE\n");
for (size_t i = 0; i < N; i++)
Printf("%f ", Weights[i]);
Printf("Weights\n");
}
CorpusDistribution = std::piecewise_constant_distribution<double>(
Intervals.begin(), Intervals.end(), Weights.begin());
}
std::piecewise_constant_distribution<double> CorpusDistribution;
Vector<double> Intervals;
Vector<double> Weights;
std::unordered_set<std::string> Hashes;
Vector<InputInfo*> Inputs;
size_t NumAddedFeatures = 0;
size_t NumUpdatedFeatures = 0;
uint32_t InputSizesPerFeature[kFeatureSetSize];
uint32_t SmallestElementPerFeature[kFeatureSetSize];
bool DistributionNeedsUpdate = true;
uint16_t FreqOfMostAbundantRareFeature = 0;
uint16_t GlobalFeatureFreqs[kFeatureSetSize] = {};
Vector<uint32_t> RareFeatures;
std::string OutputCorpus;
};
} // namespace fuzzer
#endif // LLVM_FUZZER_CORPUS

View File

@ -0,0 +1,60 @@
//===- FuzzerCrossOver.cpp - Cross over two test inputs -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Cross over test inputs.
//===----------------------------------------------------------------------===//
#include "FuzzerDefs.h"
#include "FuzzerMutate.h"
#include "FuzzerRandom.h"
#include <cstring>
namespace fuzzer {
// Cross Data1 and Data2, store the result (up to MaxOutSize bytes) in Out.
size_t MutationDispatcher::CrossOver(const uint8_t *Data1, size_t Size1,
const uint8_t *Data2, size_t Size2,
uint8_t *Out, size_t MaxOutSize) {
assert(Size1 || Size2);
MaxOutSize = Rand(MaxOutSize) + 1;
size_t OutPos = 0;
size_t Pos1 = 0;
size_t Pos2 = 0;
size_t * InPos = &Pos1;
size_t InSize = Size1;
const uint8_t *Data = Data1;
bool CurrentlyUsingFirstData = true;
while (OutPos < MaxOutSize && (Pos1 < Size1 || Pos2 < Size2)) {
// Merge a part of Data into Out.
size_t OutSizeLeft = MaxOutSize - OutPos;
if (*InPos < InSize) {
size_t InSizeLeft = InSize - *InPos;
size_t MaxExtraSize = std::min(OutSizeLeft, InSizeLeft);
size_t ExtraSize = Rand(MaxExtraSize) + 1;
memcpy(Out + OutPos, Data + *InPos, ExtraSize);
OutPos += ExtraSize;
(*InPos) += ExtraSize;
}
// Use the other input data on the next iteration.
InPos = CurrentlyUsingFirstData ? &Pos2 : &Pos1;
InSize = CurrentlyUsingFirstData ? Size2 : Size1;
Data = CurrentlyUsingFirstData ? Data2 : Data1;
CurrentlyUsingFirstData = !CurrentlyUsingFirstData;
}
return OutPos;
}
} // namespace fuzzer

View File

@ -0,0 +1,344 @@
//===- FuzzerDataFlowTrace.cpp - DataFlowTrace ---*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::DataFlowTrace
//===----------------------------------------------------------------------===//
#include "FuzzerDataFlowTrace.h"
#include "FuzzerCommand.h"
#include "FuzzerIO.h"
#include "FuzzerRandom.h"
#include "FuzzerSHA1.h"
#include "FuzzerUtil.h"
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace fuzzer {
static const char *kFunctionsTxt = "functions.txt";
bool BlockCoverage::AppendCoverage(const std::string &S) {
std::stringstream SS(S);
return AppendCoverage(SS);
}
// Coverage lines have this form:
// CN X Y Z T
// where N is the number of the function, T is the total number of instrumented
// BBs, and X,Y,Z, if present, are the indecies of covered BB.
// BB #0, which is the entry block, is not explicitly listed.
bool BlockCoverage::AppendCoverage(std::istream &IN) {
std::string L;
while (std::getline(IN, L, '\n')) {
if (L.empty()) continue;
std::stringstream SS(L.c_str() + 1);
size_t FunctionId = 0;
SS >> FunctionId;
if (L[0] == 'F') {
FunctionsWithDFT.insert(FunctionId);
continue;
}
if (L[0] != 'C') continue;
Vector<uint32_t> CoveredBlocks;
while (true) {
uint32_t BB = 0;
SS >> BB;
if (!SS) break;
CoveredBlocks.push_back(BB);
}
if (CoveredBlocks.empty()) return false;
uint32_t NumBlocks = CoveredBlocks.back();
CoveredBlocks.pop_back();
for (auto BB : CoveredBlocks)
if (BB >= NumBlocks) return false;
auto It = Functions.find(FunctionId);
auto &Counters =
It == Functions.end()
? Functions.insert({FunctionId, Vector<uint32_t>(NumBlocks)})
.first->second
: It->second;
if (Counters.size() != NumBlocks) return false; // wrong number of blocks.
Counters[0]++;
for (auto BB : CoveredBlocks)
Counters[BB]++;
}
return true;
}
// Assign weights to each function.
// General principles:
// * any uncovered function gets weight 0.
// * a function with lots of uncovered blocks gets bigger weight.
// * a function with a less frequently executed code gets bigger weight.
Vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {
Vector<double> Res(NumFunctions);
for (auto It : Functions) {
auto FunctionID = It.first;
auto Counters = It.second;
assert(FunctionID < NumFunctions);
auto &Weight = Res[FunctionID];
// Give higher weight if the function has a DFT.
Weight = FunctionsWithDFT.count(FunctionID) ? 1000. : 1;
// Give higher weight to functions with less frequently seen basic blocks.
Weight /= SmallestNonZeroCounter(Counters);
// Give higher weight to functions with the most uncovered basic blocks.
Weight *= NumberOfUncoveredBlocks(Counters) + 1;
}
return Res;
}
void DataFlowTrace::ReadCoverage(const std::string &DirPath) {
Vector<SizedFile> Files;
GetSizedFilesFromDir(DirPath, &Files);
for (auto &SF : Files) {
auto Name = Basename(SF.File);
if (Name == kFunctionsTxt) continue;
if (!CorporaHashes.count(Name)) continue;
std::ifstream IF(SF.File);
Coverage.AppendCoverage(IF);
}
}
static void DFTStringAppendToVector(Vector<uint8_t> * DFT,
const std::string &DFTString) {
assert(DFT->size() == DFTString.size());
for (size_t I = 0, Len = DFT->size(); I < Len; I++)
(*DFT)[I] = DFTString[I] == '1';
}
// converts a string of '0' and '1' into a Vector<uint8_t>
static Vector<uint8_t> DFTStringToVector(const std::string &DFTString) {
Vector<uint8_t> DFT(DFTString.size());
DFTStringAppendToVector(&DFT, DFTString);
return DFT;
}
static bool ParseError(const char *Err, const std::string &Line) {
Printf("DataFlowTrace: parse error: %s: Line: %s\n", Err, Line.c_str());
return false;
}
// TODO(metzman): replace std::string with std::string_view for
// better performance. Need to figure our how to use string_view on Windows.
static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
std::string *DFTString) {
if (!Line.empty() && Line[0] != 'F') return false; // Ignore coverage.
size_t SpacePos = Line.find(' ');
if (SpacePos == std::string::npos)
return ParseError("no space in the trace line", Line);
if (Line.empty() || Line[0] != 'F')
return ParseError("the trace line doesn't start with 'F'", Line);
*FunctionNum = std::atol(Line.c_str() + 1);
const char *Beg = Line.c_str() + SpacePos + 1;
const char *End = Line.c_str() + Line.size();
assert(Beg < End);
size_t Len = End - Beg;
for (size_t I = 0; I < Len; I++) {
if (Beg[I] != '0' && Beg[I] != '1')
return ParseError("the trace should contain only 0 or 1", Line);
}
*DFTString = Beg;
return true;
}
bool DataFlowTrace::Init(const std::string &DirPath, std::string *FocusFunction,
Vector<SizedFile> &CorporaFiles, Random &Rand) {
if (DirPath.empty()) return false;
Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
Vector<SizedFile> Files;
GetSizedFilesFromDir(DirPath, &Files);
std::string L;
size_t FocusFuncIdx = SIZE_MAX;
Vector<std::string> FunctionNames;
// Collect the hashes of the corpus files.
for (auto &SF : CorporaFiles)
CorporaHashes.insert(Hash(FileToVector(SF.File)));
// Read functions.txt
std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
size_t NumFunctions = 0;
while (std::getline(IF, L, '\n')) {
FunctionNames.push_back(L);
NumFunctions++;
if (*FocusFunction == L) FocusFuncIdx = NumFunctions - 1;
}
if (!NumFunctions) return false;
if (*FocusFunction == "auto") {
// AUTOFOCUS works like this:
// * reads the coverage data from the DFT files.
// * assigns weights to functions based on coverage.
// * chooses a random function according to the weights.
ReadCoverage(DirPath);
auto Weights = Coverage.FunctionWeights(NumFunctions);
Vector<double> Intervals(NumFunctions + 1);
std::iota(Intervals.begin(), Intervals.end(), 0);
auto Distribution = std::piecewise_constant_distribution<double>(
Intervals.begin(), Intervals.end(), Weights.begin());
FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
*FocusFunction = FunctionNames[FocusFuncIdx];
assert(FocusFuncIdx < NumFunctions);
Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
FunctionNames[FocusFuncIdx].c_str());
for (size_t i = 0; i < NumFunctions; i++) {
if (!Weights[i]) continue;
Printf(" [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
Weights[i], Coverage.GetNumberOfBlocks(i),
Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
FunctionNames[i].c_str());
}
}
if (FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
return false;
// Read traces.
size_t NumTraceFiles = 0;
size_t NumTracesWithFocusFunction = 0;
for (auto &SF : Files) {
auto Name = Basename(SF.File);
if (Name == kFunctionsTxt) continue;
if (!CorporaHashes.count(Name)) continue; // not in the corpus.
NumTraceFiles++;
// Printf("=== %s\n", Name.c_str());
std::ifstream IF2(SF.File);
while (std::getline(IF2, L, '\n')) {
size_t FunctionNum = 0;
std::string DFTString;
if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
FunctionNum == FocusFuncIdx) {
NumTracesWithFocusFunction++;
if (FunctionNum >= NumFunctions)
return ParseError("N is greater than the number of functions", L);
Traces[Name] = DFTStringToVector(DFTString);
// Print just a few small traces.
if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)
Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());
break; // No need to parse the following lines.
}
}
}
Printf(
"INFO: DataFlowTrace: %zd trace files, %zd functions, "
"%zd traces with focus function\n",
NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
return NumTraceFiles > 0;
}
int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
const Vector<SizedFile> &CorporaFiles) {
Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
if (CorporaFiles.empty()) {
Printf("ERROR: can't collect data flow without corpus provided.");
return 1;
}
static char DFSanEnv[] = "DFSAN_OPTIONS=warn_unimplemented=0";
putenv(DFSanEnv);
MkDir(DirPath);
for (auto &F : CorporaFiles) {
// For every input F we need to collect the data flow and the coverage.
// Data flow collection may fail if we request too many DFSan tags at once.
// So, we start from requesting all tags in range [0,Size) and if that fails
// we then request tags in [0,Size/2) and [Size/2, Size), and so on.
// Function number => DFT.
auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
// std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
// std::unordered_set<std::string> Cov;
Command Cmd;
Cmd.addArgument(DFTBinary);
Cmd.addArgument(F.File);
Cmd.addArgument(OutPath);
Printf("CMD: %s\n", Cmd.toString().c_str());
ExecuteCommand(Cmd);
}
// Write functions.txt if it's currently empty or doesn't exist.
auto FunctionsTxtPath = DirPlusFile(DirPath, kFunctionsTxt);
if (FileToString(FunctionsTxtPath).empty()) {
Command Cmd;
Cmd.addArgument(DFTBinary);
Cmd.setOutputFile(FunctionsTxtPath);
ExecuteCommand(Cmd);
}
return 0;
}
} // namespace fuzzer

View File

@ -0,0 +1,135 @@
//===- FuzzerDataFlowTrace.h - Internal header for the Fuzzer ---*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::DataFlowTrace; reads and handles a data-flow trace.
//
// A data flow trace is generated by e.g. dataflow/DataFlow.cpp
// and is stored on disk in a separate directory.
//
// The trace dir contains a file 'functions.txt' which lists function names,
// oner per line, e.g.
// ==> functions.txt <==
// Func2
// LLVMFuzzerTestOneInput
// Func1
//
// All other files in the dir are the traces, see dataflow/DataFlow.cpp.
// The name of the file is sha1 of the input used to generate the trace.
//
// Current status:
// the data is parsed and the summary is printed, but the data is not yet
// used in any other way.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_DATA_FLOW_TRACE
#define LLVM_FUZZER_DATA_FLOW_TRACE
#include "FuzzerDefs.h"
#include "FuzzerIO.h"
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <string>
namespace fuzzer {
int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
const Vector<SizedFile> &CorporaFiles);
class BlockCoverage {
public:
bool AppendCoverage(std::istream &IN);
bool AppendCoverage(const std::string &S);
size_t NumCoveredFunctions() const { return Functions.size(); }
uint32_t GetCounter(size_t FunctionId, size_t BasicBlockId) {
auto It = Functions.find(FunctionId);
if (It == Functions.end()) return 0;
const auto &Counters = It->second;
if (BasicBlockId < Counters.size())
return Counters[BasicBlockId];
return 0;
}
uint32_t GetNumberOfBlocks(size_t FunctionId) {
auto It = Functions.find(FunctionId);
if (It == Functions.end()) return 0;
const auto &Counters = It->second;
return Counters.size();
}
uint32_t GetNumberOfCoveredBlocks(size_t FunctionId) {
auto It = Functions.find(FunctionId);
if (It == Functions.end()) return 0;
const auto &Counters = It->second;
uint32_t Result = 0;
for (auto Cnt: Counters)
if (Cnt)
Result++;
return Result;
}
Vector<double> FunctionWeights(size_t NumFunctions) const;
void clear() { Functions.clear(); }
private:
typedef Vector<uint32_t> CoverageVector;
uint32_t NumberOfCoveredBlocks(const CoverageVector &Counters) const {
uint32_t Res = 0;
for (auto Cnt : Counters)
if (Cnt)
Res++;
return Res;
}
uint32_t NumberOfUncoveredBlocks(const CoverageVector &Counters) const {
return Counters.size() - NumberOfCoveredBlocks(Counters);
}
uint32_t SmallestNonZeroCounter(const CoverageVector &Counters) const {
assert(!Counters.empty());
uint32_t Res = Counters[0];
for (auto Cnt : Counters)
if (Cnt)
Res = Min(Res, Cnt);
assert(Res);
return Res;
}
// Function ID => vector of counters.
// Each counter represents how many input files trigger the given basic block.
std::unordered_map<size_t, CoverageVector> Functions;
// Functions that have DFT entry.
std::unordered_set<size_t> FunctionsWithDFT;
};
class DataFlowTrace {
public:
void ReadCoverage(const std::string &DirPath);
bool Init(const std::string &DirPath, std::string *FocusFunction,
Vector<SizedFile> &CorporaFiles, Random &Rand);
void Clear() { Traces.clear(); }
const Vector<uint8_t> *Get(const std::string &InputSha1) const {
auto It = Traces.find(InputSha1);
if (It != Traces.end())
return &It->second;
return nullptr;
}
private:
// Input's sha1 => DFT for the FocusFunction.
std::unordered_map<std::string, Vector<uint8_t> > Traces;
BlockCoverage Coverage;
std::unordered_set<std::string> CorporaHashes;
};
} // namespace fuzzer
#endif // LLVM_FUZZER_DATA_FLOW_TRACE

View File

@ -0,0 +1,75 @@
//===- FuzzerDefs.h - Internal header for the Fuzzer ------------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Basic definitions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_DEFS_H
#define LLVM_FUZZER_DEFS_H
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <set>
#include <string>
#include <vector>
namespace fuzzer {
template <class T> T Min(T a, T b) { return a < b ? a : b; }
template <class T> T Max(T a, T b) { return a > b ? a : b; }
class Random;
class Dictionary;
class DictionaryEntry;
class MutationDispatcher;
struct FuzzingOptions;
class InputCorpus;
struct InputInfo;
struct ExternalFunctions;
// Global interface to functions that may or may not be available.
extern ExternalFunctions *EF;
// We are using a custom allocator to give a different symbol name to STL
// containers in order to avoid ODR violations.
template<typename T>
class fuzzer_allocator: public std::allocator<T> {
public:
fuzzer_allocator() = default;
template<class U>
explicit fuzzer_allocator(const fuzzer_allocator<U>&) {}
template<class Other>
struct rebind { typedef fuzzer_allocator<Other> other; };
};
template<typename T>
using Vector = std::vector<T, fuzzer_allocator<T>>;
template<typename T>
using Set = std::set<T, std::less<T>, fuzzer_allocator<T>>;
typedef Vector<uint8_t> Unit;
typedef Vector<Unit> UnitVector;
typedef int (*UserCallback)(const uint8_t *Data, size_t Size);
int FuzzerDriver(int *argc, char ***argv, UserCallback Callback);
uint8_t *ExtraCountersBegin();
uint8_t *ExtraCountersEnd();
void ClearExtraCounters();
extern bool RunningUserCallback;
} // namespace fuzzer
#endif // LLVM_FUZZER_DEFS_H

View File

@ -0,0 +1,118 @@
//===- FuzzerDictionary.h - Internal header for the Fuzzer ------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::Dictionary
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_DICTIONARY_H
#define LLVM_FUZZER_DICTIONARY_H
#include "FuzzerDefs.h"
#include "FuzzerIO.h"
#include "FuzzerUtil.h"
#include <algorithm>
#include <limits>
namespace fuzzer {
// A simple POD sized array of bytes.
template <size_t kMaxSizeT> class FixedWord {
public:
static const size_t kMaxSize = kMaxSizeT;
FixedWord() {}
FixedWord(const uint8_t *B, uint8_t S) { Set(B, S); }
void Set(const uint8_t *B, uint8_t S) {
assert(S <= kMaxSize);
memcpy(Data, B, S);
Size = S;
}
bool operator==(const FixedWord<kMaxSize> &w) const {
return Size == w.Size && 0 == memcmp(Data, w.Data, Size);
}
static size_t GetMaxSize() { return kMaxSize; }
const uint8_t *data() const { return Data; }
uint8_t size() const { return Size; }
private:
uint8_t Size = 0;
uint8_t Data[kMaxSize];
};
typedef FixedWord<64> Word;
class DictionaryEntry {
public:
DictionaryEntry() {}
explicit DictionaryEntry(Word W) : W(W) {}
DictionaryEntry(Word W, size_t PositionHint) : W(W), PositionHint(PositionHint) {}
const Word &GetW() const { return W; }
bool HasPositionHint() const { return PositionHint != std::numeric_limits<size_t>::max(); }
size_t GetPositionHint() const {
assert(HasPositionHint());
return PositionHint;
}
void IncUseCount() { UseCount++; }
void IncSuccessCount() { SuccessCount++; }
size_t GetUseCount() const { return UseCount; }
size_t GetSuccessCount() const {return SuccessCount; }
void Print(const char *PrintAfter = "\n") {
PrintASCII(W.data(), W.size());
if (HasPositionHint())
Printf("@%zd", GetPositionHint());
Printf("%s", PrintAfter);
}
private:
Word W;
size_t PositionHint = std::numeric_limits<size_t>::max();
size_t UseCount = 0;
size_t SuccessCount = 0;
};
class Dictionary {
public:
static const size_t kMaxDictSize = 1 << 14;
bool ContainsWord(const Word &W) const {
return std::any_of(begin(), end(), [&](const DictionaryEntry &DE) {
return DE.GetW() == W;
});
}
const DictionaryEntry *begin() const { return &DE[0]; }
const DictionaryEntry *end() const { return begin() + Size; }
DictionaryEntry & operator[] (size_t Idx) {
assert(Idx < Size);
return DE[Idx];
}
void push_back(const DictionaryEntry &DE) {
if (Size < kMaxDictSize)
this->DE[Size++] = DE;
}
void clear() { Size = 0; }
bool empty() const { return Size == 0; }
size_t size() const { return Size; }
private:
DictionaryEntry DE[kMaxDictSize];
size_t Size = 0;
};
// Parses one dictionary entry.
// If successful, write the enty to Unit and returns true,
// otherwise returns false.
bool ParseOneDictionaryEntry(const std::string &Str, Unit *U);
// Parses the dictionary file, fills Units, returns true iff all lines
// were parsed successfully.
bool ParseDictionaryFile(const std::string &Text, Vector<Unit> *Units);
} // namespace fuzzer
#endif // LLVM_FUZZER_DICTIONARY_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,50 @@
//===- FuzzerExtFunctions.def - External functions --------------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// This defines the external function pointers that
// ``fuzzer::ExternalFunctions`` should contain and try to initialize. The
// EXT_FUNC macro must be defined at the point of inclusion. The signature of
// the macro is:
//
// EXT_FUNC(<name>, <return_type>, <function_signature>, <warn_if_missing>)
//===----------------------------------------------------------------------===//
// Optional user functions
EXT_FUNC(LLVMFuzzerInitialize, int, (int *argc, char ***argv), false);
EXT_FUNC(LLVMFuzzerCustomMutator, size_t,
(uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed),
false);
EXT_FUNC(LLVMFuzzerCustomCrossOver, size_t,
(const uint8_t *Data1, size_t Size1,
const uint8_t *Data2, size_t Size2,
uint8_t *Out, size_t MaxOutSize, unsigned int Seed),
false);
// Sanitizer functions
EXT_FUNC(__lsan_enable, void, (), false);
EXT_FUNC(__lsan_disable, void, (), false);
EXT_FUNC(__lsan_do_recoverable_leak_check, int, (), false);
EXT_FUNC(__sanitizer_acquire_crash_state, int, (), true);
EXT_FUNC(__sanitizer_install_malloc_and_free_hooks, int,
(void (*malloc_hook)(const volatile void *, size_t),
void (*free_hook)(const volatile void *)),
false);
EXT_FUNC(__sanitizer_log_write, void, (const char *buf, size_t len), false);
EXT_FUNC(__sanitizer_purge_allocator, void, (), false);
EXT_FUNC(__sanitizer_print_memory_profile, void, (size_t, size_t), false);
EXT_FUNC(__sanitizer_print_stack_trace, void, (), true);
EXT_FUNC(__sanitizer_symbolize_pc, void,
(void *, const char *fmt, char *out_buf, size_t out_buf_size), false);
EXT_FUNC(__sanitizer_get_module_and_offset_for_pc, int,
(void *pc, char *module_path,
size_t module_path_len,void **pc_offset), false);
EXT_FUNC(__sanitizer_set_death_callback, void, (void (*)(void)), true);
EXT_FUNC(__sanitizer_set_report_fd, void, (void*), false);
EXT_FUNC(__msan_scoped_disable_interceptor_checks, void, (), false);
EXT_FUNC(__msan_scoped_enable_interceptor_checks, void, (), false);
EXT_FUNC(__msan_unpoison, void, (const volatile void *, size_t size), false);
EXT_FUNC(__msan_unpoison_param, void, (size_t n), false);

View File

@ -0,0 +1,34 @@
//===- FuzzerExtFunctions.h - Interface to external functions ---*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Defines an interface to (possibly optional) functions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_EXT_FUNCTIONS_H
#define LLVM_FUZZER_EXT_FUNCTIONS_H
#include <stddef.h>
#include <stdint.h>
namespace fuzzer {
struct ExternalFunctions {
// Initialize function pointers. Functions that are not available will be set
// to nullptr. Do not call this constructor before ``main()`` has been
// entered.
ExternalFunctions();
#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
RETURN_TYPE(*NAME) FUNC_SIG = nullptr
#include "FuzzerExtFunctions.def"
#undef EXT_FUNC
};
} // namespace fuzzer
#endif

View File

@ -0,0 +1,60 @@
//===- FuzzerExtFunctionsDlsym.cpp - Interface to external functions ------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Implementation for operating systems that support dlsym(). We only use it on
// Apple platforms for now. We don't use this approach on Linux because it
// requires that clients of LibFuzzer pass ``--export-dynamic`` to the linker.
// That is a complication we don't wish to expose to clients right now.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_APPLE
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
#include <dlfcn.h>
using namespace fuzzer;
template <typename T>
static T GetFnPtr(const char *FnName, bool WarnIfMissing) {
dlerror(); // Clear any previous errors.
void *Fn = dlsym(RTLD_DEFAULT, FnName);
if (Fn == nullptr) {
if (WarnIfMissing) {
const char *ErrorMsg = dlerror();
Printf("WARNING: Failed to find function \"%s\".", FnName);
if (ErrorMsg) Printf(" Reason %s.", ErrorMsg);
Printf("\n");
}
}
return reinterpret_cast<T>(Fn);
}
namespace fuzzer {
ExternalFunctions::ExternalFunctions() {
\
#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
this->NAME = GetFnPtr<decltype(ExternalFunctions::NAME)>(#NAME, WARN)
#include "FuzzerExtFunctions.def"
#undef EXT_FUNC
}
} // namespace fuzzer
#endif // LIBFUZZER_APPLE

View File

@ -0,0 +1,63 @@
//===- FuzzerExtFunctionsWeak.cpp - Interface to external functions -------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Implementation for Linux. This relies on the linker's support for weak
// symbols. We don't use this approach on Apple platforms because it requires
// clients of LibFuzzer to pass ``-U _<symbol_name>`` to the linker to allow
// weak symbols to be undefined. That is a complication we don't want to expose
// to clients right now.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_LINUX || LIBFUZZER_NETBSD || LIBFUZZER_FUCHSIA || \
LIBFUZZER_FREEBSD || LIBFUZZER_OPENBSD || LIBFUZZER_EMSCRIPTEN
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
extern "C" {
// Declare these symbols as weak to allow them to be optionally defined.
#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
__attribute__((weak, visibility("default"))) RETURN_TYPE NAME FUNC_SIG
#include "FuzzerExtFunctions.def"
#undef EXT_FUNC
}
using namespace fuzzer;
static void CheckFnPtr(void *FnPtr, const char *FnName, bool WarnIfMissing) {
if (FnPtr == nullptr && WarnIfMissing) {
Printf("WARNING: Failed to find function \"%s\".\n", FnName);
}
}
namespace fuzzer {
ExternalFunctions::ExternalFunctions() {
\
#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
this->NAME = ::NAME; \
CheckFnPtr(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(::NAME)), \
#NAME, WARN);
#include "FuzzerExtFunctions.def"
#undef EXT_FUNC
}
} // namespace fuzzer
#endif

View File

@ -0,0 +1,95 @@
//=== FuzzerExtWindows.cpp - Interface to external functions --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Implementation of FuzzerExtFunctions for Windows. Uses alternatename when
// compiled with MSVC. Uses weak aliases when compiled with clang. Unfortunately
// the method each compiler supports is not supported by the other.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_WINDOWS
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
using namespace fuzzer;
// Intermediate macro to ensure the parameter is expanded before stringified.
#define STRINGIFY_(A) #A
#define STRINGIFY(A) STRINGIFY_(A)
#if LIBFUZZER_MSVC
// Copied from compiler-rt/lib/sanitizer_common/sanitizer_win_defs.h
#if defined(_M_IX86) || defined(__i386__)
#define WIN_SYM_PREFIX "_"
#else
#define WIN_SYM_PREFIX
#endif
// Declare external functions as having alternativenames, so that we can
// determine if they are not defined.
#define EXTERNAL_FUNC(Name, Default) \
__pragma( \
comment(linker, "/alternatename:" WIN_SYM_PREFIX STRINGIFY( \
Name) "=" WIN_SYM_PREFIX STRINGIFY(Default)))
#else
// Declare external functions as weak to allow them to default to a
// specified function if not defined explicitly. We must use weak symbols
// because clang's support for alternatename is not 100%, see
// https://bugs.llvm.org/show_bug.cgi?id=40218 for more details.
#define EXTERNAL_FUNC(Name, Default) \
__attribute__((weak, alias(STRINGIFY(Default))))
#endif // LIBFUZZER_MSVC
extern "C" {
\
#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
RETURN_TYPE NAME##Def FUNC_SIG { \
\
Printf("ERROR: Function \"%s\" not defined.\n", #NAME); \
exit(1); \
\
} \
EXTERNAL_FUNC(NAME, NAME##Def) RETURN_TYPE NAME FUNC_SIG
#include "FuzzerExtFunctions.def"
#undef EXT_FUNC
}
template <typename T>
static T *GetFnPtr(T *Fun, T *FunDef, const char *FnName, bool WarnIfMissing) {
if (Fun == FunDef) {
if (WarnIfMissing)
Printf("WARNING: Failed to find function \"%s\".\n", FnName);
return nullptr;
}
return Fun;
}
namespace fuzzer {
ExternalFunctions::ExternalFunctions() {
\
#define EXT_FUNC(NAME, RETURN_TYPE, FUNC_SIG, WARN) \
this->NAME = GetFnPtr<decltype(::NAME)>(::NAME, ::NAME##Def, #NAME, WARN);
#include "FuzzerExtFunctions.def"
#undef EXT_FUNC
}
} // namespace fuzzer
#endif // LIBFUZZER_WINDOWS

View File

@ -0,0 +1,71 @@
//===- FuzzerExtraCounters.cpp - Extra coverage counters ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Extra coverage counters defined by user code.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#include <cstdint>
#if LIBFUZZER_LINUX || LIBFUZZER_NETBSD || LIBFUZZER_FREEBSD || \
LIBFUZZER_OPENBSD || LIBFUZZER_FUCHSIA || LIBFUZZER_EMSCRIPTEN
__attribute__((weak)) extern uint8_t __start___libfuzzer_extra_counters;
__attribute__((weak)) extern uint8_t __stop___libfuzzer_extra_counters;
namespace fuzzer {
uint8_t *ExtraCountersBegin() {
return &__start___libfuzzer_extra_counters;
}
uint8_t *ExtraCountersEnd() {
return &__stop___libfuzzer_extra_counters;
}
ATTRIBUTE_NO_SANITIZE_ALL
void ClearExtraCounters() { // hand-written memset, don't asan-ify.
uintptr_t *Beg = reinterpret_cast<uintptr_t *>(ExtraCountersBegin());
uintptr_t *End = reinterpret_cast<uintptr_t *>(ExtraCountersEnd());
for (; Beg < End; Beg++) {
*Beg = 0;
__asm__ __volatile__("" : : : "memory");
}
}
} // namespace fuzzer
#else
// TODO: implement for other platforms.
namespace fuzzer {
uint8_t *ExtraCountersBegin() {
return nullptr;
}
uint8_t *ExtraCountersEnd() {
return nullptr;
}
void ClearExtraCounters() {
}
} // namespace fuzzer
#endif

View File

@ -0,0 +1,198 @@
//===- FuzzerFlags.def - Run-time flags -------------------------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Flags. FUZZER_FLAG_INT/FUZZER_FLAG_STRING macros should be defined at the
// point of inclusion. We are not using any flag parsing library for better
// portability and independence.
//===----------------------------------------------------------------------===//
FUZZER_FLAG_INT(verbosity, 1, "Verbosity level.")
FUZZER_FLAG_UNSIGNED(seed, 0, "Random seed. If 0, seed is generated.")
FUZZER_FLAG_INT(runs, -1,
"Number of individual test runs (-1 for infinite runs).")
FUZZER_FLAG_INT(max_len, 0, "Maximum length of the test input. "
"If 0, libFuzzer tries to guess a good value based on the corpus "
"and reports it. ")
FUZZER_FLAG_INT(len_control, 100, "Try generating small inputs first, "
"then try larger inputs over time. Specifies the rate at which the length "
"limit is increased (smaller == faster). If 0, immediately try inputs with "
"size up to max_len. Default value is 0, if LLVMFuzzerCustomMutator is used.")
FUZZER_FLAG_STRING(seed_inputs, "A comma-separated list of input files "
"to use as an additional seed corpus. Alternatively, an \"@\" followed by "
"the name of a file containing the comma-separated list.")
FUZZER_FLAG_INT(keep_seed, 0, "If 1, keep seed inputs in the corpus even if "
"they do not produce new coverage. When used with |reduce_inputs==1|, the "
"seed inputs will never be reduced. This option can be useful when seeds are"
"not properly formed for the fuzz target but still have useful snippets.")
FUZZER_FLAG_INT(cross_over, 1, "If 1, cross over inputs.")
FUZZER_FLAG_INT(cross_over_uniform_dist, 0, "Experimental. If 1, use a "
"uniform probability distribution when choosing inputs to cross over with. "
"Some of the inputs in the corpus may never get chosen for mutation "
"depending on the input mutation scheduling policy. With this flag, all "
"inputs, regardless of the input mutation scheduling policy, can be chosen "
"as an input to cross over with. This can be particularly useful with "
"|keep_seed==1|; all the initial seed inputs, even though they do not "
"increase coverage because they are not properly formed, will still be "
"chosen as an input to cross over with.")
FUZZER_FLAG_INT(mutate_depth, 5,
"Apply this number of consecutive mutations to each input.")
FUZZER_FLAG_INT(reduce_depth, 0, "Experimental/internal. "
"Reduce depth if mutations lose unique features")
FUZZER_FLAG_INT(shuffle, 1, "Shuffle inputs at startup")
FUZZER_FLAG_INT(prefer_small, 1,
"If 1, always prefer smaller inputs during the corpus shuffle.")
FUZZER_FLAG_INT(
timeout, 1200,
"Timeout in seconds (if positive). "
"If one unit runs more than this number of seconds the process will abort.")
FUZZER_FLAG_INT(error_exitcode, 77, "When libFuzzer itself reports a bug "
"this exit code will be used.")
FUZZER_FLAG_INT(timeout_exitcode, 70, "When libFuzzer reports a timeout "
"this exit code will be used.")
FUZZER_FLAG_INT(max_total_time, 0, "If positive, indicates the maximal total "
"time in seconds to run the fuzzer.")
FUZZER_FLAG_INT(help, 0, "Print help.")
FUZZER_FLAG_INT(fork, 0, "Experimental mode where fuzzing happens "
"in a subprocess")
FUZZER_FLAG_INT(ignore_timeouts, 1, "Ignore timeouts in fork mode")
FUZZER_FLAG_INT(ignore_ooms, 1, "Ignore OOMs in fork mode")
FUZZER_FLAG_INT(ignore_crashes, 0, "Ignore crashes in fork mode")
FUZZER_FLAG_INT(merge, 0, "If 1, the 2-nd, 3-rd, etc corpora will be "
"merged into the 1-st corpus. Only interesting units will be taken. "
"This flag can be used to minimize a corpus.")
FUZZER_FLAG_STRING(stop_file, "Stop fuzzing ASAP if this file exists")
FUZZER_FLAG_STRING(merge_inner, "internal flag")
FUZZER_FLAG_STRING(merge_control_file,
"Specify a control file used for the merge process. "
"If a merge process gets killed it tries to leave this file "
"in a state suitable for resuming the merge. "
"By default a temporary file will be used."
"The same file can be used for multistep merge process.")
FUZZER_FLAG_INT(minimize_crash, 0, "If 1, minimizes the provided"
" crash input. Use with -runs=N or -max_total_time=N to limit "
"the number attempts."
" Use with -exact_artifact_path to specify the output."
" Combine with ASAN_OPTIONS=dedup_token_length=3 (or similar) to ensure that"
" the minimized input triggers the same crash."
)
FUZZER_FLAG_INT(cleanse_crash, 0, "If 1, tries to cleanse the provided"
" crash input to make it contain fewer original bytes."
" Use with -exact_artifact_path to specify the output."
)
FUZZER_FLAG_INT(minimize_crash_internal_step, 0, "internal flag")
FUZZER_FLAG_STRING(features_dir, "internal flag. Used to dump feature sets on disk."
"Every time a new input is added to the corpus, a corresponding file in the features_dir"
" is created containing the unique features of that input."
" Features are stored in binary format.")
FUZZER_FLAG_STRING(mutation_graph_file, "Saves a graph (in DOT format) to"
" mutation_graph_file. The graph contains a vertex for each input that has"
" unique coverage; directed edges are provided between parents and children"
" where the child has unique coverage, and are recorded with the type of"
" mutation that caused the child.")
FUZZER_FLAG_INT(use_counters, 1, "Use coverage counters")
FUZZER_FLAG_INT(use_memmem, 1,
"Use hints from intercepting memmem, strstr, etc")
FUZZER_FLAG_INT(use_value_profile, 0,
"Experimental. Use value profile to guide fuzzing.")
FUZZER_FLAG_INT(use_cmp, 1, "Use CMP traces to guide mutations")
FUZZER_FLAG_INT(shrink, 0, "Experimental. Try to shrink corpus inputs.")
FUZZER_FLAG_INT(reduce_inputs, 1,
"Try to reduce the size of inputs while preserving their full feature sets")
FUZZER_FLAG_UNSIGNED(jobs, 0, "Number of jobs to run. If jobs >= 1 we spawn"
" this number of jobs in separate worker processes"
" with stdout/stderr redirected to fuzz-JOB.log.")
FUZZER_FLAG_UNSIGNED(workers, 0,
"Number of simultaneous worker processes to run the jobs."
" If zero, \"min(jobs,NumberOfCpuCores()/2)\" is used.")
FUZZER_FLAG_INT(reload, 1,
"Reload the main corpus every <N> seconds to get new units"
" discovered by other processes. If 0, disabled")
FUZZER_FLAG_INT(report_slow_units, 10,
"Report slowest units if they run for more than this number of seconds.")
FUZZER_FLAG_INT(only_ascii, 0,
"If 1, generate only ASCII (isprint+isspace) inputs.")
FUZZER_FLAG_STRING(dict, "Experimental. Use the dictionary file.")
FUZZER_FLAG_STRING(artifact_prefix, "Write fuzzing artifacts (crash, "
"timeout, or slow inputs) as "
"$(artifact_prefix)file")
FUZZER_FLAG_STRING(exact_artifact_path,
"Write the single artifact on failure (crash, timeout) "
"as $(exact_artifact_path). This overrides -artifact_prefix "
"and will not use checksum in the file name. Do not "
"use the same path for several parallel processes.")
FUZZER_FLAG_INT(print_pcs, 0, "If 1, print out newly covered PCs.")
FUZZER_FLAG_INT(print_funcs, 2, "If >=1, print out at most this number of "
"newly covered functions.")
FUZZER_FLAG_INT(print_final_stats, 0, "If 1, print statistics at exit.")
FUZZER_FLAG_INT(print_corpus_stats, 0,
"If 1, print statistics on corpus elements at exit.")
FUZZER_FLAG_INT(print_coverage, 0, "If 1, print coverage information as text"
" at exit.")
FUZZER_FLAG_INT(dump_coverage, 0, "Deprecated.")
FUZZER_FLAG_INT(handle_segv, 1, "If 1, try to intercept SIGSEGV.")
FUZZER_FLAG_INT(handle_bus, 1, "If 1, try to intercept SIGBUS.")
FUZZER_FLAG_INT(handle_abrt, 1, "If 1, try to intercept SIGABRT.")
FUZZER_FLAG_INT(handle_ill, 1, "If 1, try to intercept SIGILL.")
FUZZER_FLAG_INT(handle_fpe, 1, "If 1, try to intercept SIGFPE.")
FUZZER_FLAG_INT(handle_int, 1, "If 1, try to intercept SIGINT.")
FUZZER_FLAG_INT(handle_term, 1, "If 1, try to intercept SIGTERM.")
FUZZER_FLAG_INT(handle_xfsz, 1, "If 1, try to intercept SIGXFSZ.")
FUZZER_FLAG_INT(handle_usr1, 1, "If 1, try to intercept SIGUSR1.")
FUZZER_FLAG_INT(handle_usr2, 1, "If 1, try to intercept SIGUSR2.")
FUZZER_FLAG_INT(close_fd_mask, 0, "If 1, close stdout at startup; "
"if 2, close stderr; if 3, close both. "
"Be careful, this will also close e.g. stderr of asan.")
FUZZER_FLAG_INT(detect_leaks, 1, "If 1, and if LeakSanitizer is enabled "
"try to detect memory leaks during fuzzing (i.e. not only at shut down).")
FUZZER_FLAG_INT(purge_allocator_interval, 1, "Purge allocator caches and "
"quarantines every <N> seconds. When rss_limit_mb is specified (>0), "
"purging starts when RSS exceeds 50% of rss_limit_mb. Pass "
"purge_allocator_interval=-1 to disable this functionality.")
FUZZER_FLAG_INT(trace_malloc, 0, "If >= 1 will print all mallocs/frees. "
"If >= 2 will also print stack traces.")
FUZZER_FLAG_INT(rss_limit_mb, 2048, "If non-zero, the fuzzer will exit upon"
"reaching this limit of RSS memory usage.")
FUZZER_FLAG_INT(malloc_limit_mb, 0, "If non-zero, the fuzzer will exit "
"if the target tries to allocate this number of Mb with one malloc call. "
"If zero (default) same limit as rss_limit_mb is applied.")
FUZZER_FLAG_STRING(exit_on_src_pos, "Exit if a newly found PC originates"
" from the given source location. Example: -exit_on_src_pos=foo.cc:123. "
"Used primarily for testing libFuzzer itself.")
FUZZER_FLAG_STRING(exit_on_item, "Exit if an item with a given sha1 sum"
" was added to the corpus. "
"Used primarily for testing libFuzzer itself.")
FUZZER_FLAG_INT(ignore_remaining_args, 0, "If 1, ignore all arguments passed "
"after this one. Useful for fuzzers that need to do their own "
"argument parsing.")
FUZZER_FLAG_STRING(focus_function, "Experimental. "
"Fuzzing will focus on inputs that trigger calls to this function. "
"If -focus_function=auto and -data_flow_trace is used, libFuzzer "
"will choose the focus functions automatically. Disables -entropic when "
"specified.")
FUZZER_FLAG_INT(entropic, 1, "Enables entropic power schedule.")
FUZZER_FLAG_INT(entropic_feature_frequency_threshold, 0xFF, "Experimental. If "
"entropic is enabled, all features which are observed less often than "
"the specified value are considered as rare.")
FUZZER_FLAG_INT(entropic_number_of_rarest_features, 100, "Experimental. If "
"entropic is enabled, we keep track of the frequencies only for the "
"Top-X least abundant features (union features that are considered as "
"rare).")
FUZZER_FLAG_INT(entropic_scale_per_exec_time, 0, "Experimental. If 1, "
"the Entropic power schedule gets scaled based on the input execution "
"time. Inputs with lower execution time get scheduled more (up to 30x). "
"Note that, if 1, fuzzer stops from being deterministic even if a "
"non-zero random seed is given.")
FUZZER_FLAG_INT(analyze_dict, 0, "Experimental")
FUZZER_DEPRECATED_FLAG(use_clang_coverage)
FUZZER_FLAG_STRING(data_flow_trace, "Experimental: use the data flow trace")
FUZZER_FLAG_STRING(collect_data_flow,
"Experimental: collect the data flow trace")
FUZZER_FLAG_INT(create_missing_dirs, 0, "Automatically attempt to create "
"directories for arguments that would normally expect them to already "
"exist (i.e. artifact_prefix, exact_artifact_path, features_dir, corpus)")

View File

@ -0,0 +1,501 @@
//===- FuzzerFork.cpp - run fuzzing in separate subprocesses --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Spawn and orchestrate separate fuzzing processes.
//===----------------------------------------------------------------------===//
#include "FuzzerCommand.h"
#include "FuzzerFork.h"
#include "FuzzerIO.h"
#include "FuzzerInternal.h"
#include "FuzzerMerge.h"
#include "FuzzerSHA1.h"
#include "FuzzerTracePC.h"
#include "FuzzerUtil.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <fstream>
#include <memory>
#include <mutex>
#include <queue>
#include <sstream>
#include <thread>
namespace fuzzer {
struct Stats {
size_t number_of_executed_units = 0;
size_t peak_rss_mb = 0;
size_t average_exec_per_sec = 0;
};
static Stats ParseFinalStatsFromLog(const std::string &LogPath) {
std::ifstream In(LogPath);
std::string Line;
Stats Res;
struct {
const char *Name;
size_t * Var;
} NameVarPairs[] = {
{"stat::number_of_executed_units:", &Res.number_of_executed_units},
{"stat::peak_rss_mb:", &Res.peak_rss_mb},
{"stat::average_exec_per_sec:", &Res.average_exec_per_sec},
{nullptr, nullptr},
};
while (std::getline(In, Line, '\n')) {
if (Line.find("stat::") != 0) continue;
std::istringstream ISS(Line);
std::string Name;
size_t Val;
ISS >> Name >> Val;
for (size_t i = 0; NameVarPairs[i].Name; i++)
if (Name == NameVarPairs[i].Name) *NameVarPairs[i].Var = Val;
}
return Res;
}
struct FuzzJob {
// Inputs.
Command Cmd;
std::string CorpusDir;
std::string FeaturesDir;
std::string LogPath;
std::string SeedListPath;
std::string CFPath;
size_t JobId;
int DftTimeInSeconds = 0;
// Fuzzing Outputs.
int ExitCode;
~FuzzJob() {
RemoveFile(CFPath);
RemoveFile(LogPath);
RemoveFile(SeedListPath);
RmDirRecursive(CorpusDir);
RmDirRecursive(FeaturesDir);
}
};
struct GlobalEnv {
Vector<std::string> Args;
Vector<std::string> CorpusDirs;
std::string MainCorpusDir;
std::string TempDir;
std::string DFTDir;
std::string DataFlowBinary;
Set<uint32_t> Features, Cov;
Set<std::string> FilesWithDFT;
Vector<std::string> Files;
Random * Rand;
std::chrono::system_clock::time_point ProcessStartTime;
int Verbosity = 0;
size_t NumTimeouts = 0;
size_t NumOOMs = 0;
size_t NumCrashes = 0;
size_t NumRuns = 0;
std::string StopFile() {
return DirPlusFile(TempDir, "STOP");
}
size_t secondsSinceProcessStartUp() const {
return std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now() - ProcessStartTime)
.count();
}
FuzzJob *CreateNewJob(size_t JobId) {
Command Cmd(Args);
Cmd.removeFlag("fork");
Cmd.removeFlag("runs");
Cmd.removeFlag("collect_data_flow");
for (auto &C : CorpusDirs) // Remove all corpora from the args.
Cmd.removeArgument(C);
Cmd.addFlag("reload", "0"); // working in an isolated dir, no reload.
Cmd.addFlag("print_final_stats", "1");
Cmd.addFlag("print_funcs", "0"); // no need to spend time symbolizing.
Cmd.addFlag("max_total_time", std::to_string(std::min((size_t)300, JobId)));
Cmd.addFlag("stop_file", StopFile());
if (!DataFlowBinary.empty()) {
Cmd.addFlag("data_flow_trace", DFTDir);
if (!Cmd.hasFlag("focus_function")) Cmd.addFlag("focus_function", "auto");
}
auto Job = new FuzzJob;
std::string Seeds;
if (size_t CorpusSubsetSize =
std::min(Files.size(), (size_t)sqrt(Files.size() + 2))) {
auto Time1 = std::chrono::system_clock::now();
for (size_t i = 0; i < CorpusSubsetSize; i++) {
auto &SF = Files[Rand->SkewTowardsLast(Files.size())];
Seeds += (Seeds.empty() ? "" : ",") + SF;
CollectDFT(SF);
}
auto Time2 = std::chrono::system_clock::now();
Job->DftTimeInSeconds = duration_cast<seconds>(Time2 - Time1).count();
}
if (!Seeds.empty()) {
Job->SeedListPath =
DirPlusFile(TempDir, std::to_string(JobId) + ".seeds");
WriteToFile(Seeds, Job->SeedListPath);
Cmd.addFlag("seed_inputs", "@" + Job->SeedListPath);
}
Job->LogPath = DirPlusFile(TempDir, std::to_string(JobId) + ".log");
Job->CorpusDir = DirPlusFile(TempDir, "C" + std::to_string(JobId));
Job->FeaturesDir = DirPlusFile(TempDir, "F" + std::to_string(JobId));
Job->CFPath = DirPlusFile(TempDir, std::to_string(JobId) + ".merge");
Job->JobId = JobId;
Cmd.addArgument(Job->CorpusDir);
Cmd.addFlag("features_dir", Job->FeaturesDir);
for (auto &D : {Job->CorpusDir, Job->FeaturesDir}) {
RmDirRecursive(D);
MkDir(D);
}
Cmd.setOutputFile(Job->LogPath);
Cmd.combineOutAndErr();
Job->Cmd = Cmd;
if (Verbosity >= 2)
Printf("Job %zd/%p Created: %s\n", JobId, Job,
Job->Cmd.toString().c_str());
// Start from very short runs and gradually increase them.
return Job;
}
void RunOneMergeJob(FuzzJob *Job) {
auto Stats = ParseFinalStatsFromLog(Job->LogPath);
NumRuns += Stats.number_of_executed_units;
Vector<SizedFile> TempFiles, MergeCandidates;
// Read all newly created inputs and their feature sets.
// Choose only those inputs that have new features.
GetSizedFilesFromDir(Job->CorpusDir, &TempFiles);
std::sort(TempFiles.begin(), TempFiles.end());
for (auto &F : TempFiles) {
auto FeatureFile = F.File;
FeatureFile.replace(0, Job->CorpusDir.size(), Job->FeaturesDir);
auto FeatureBytes = FileToVector(FeatureFile, 0, false);
assert((FeatureBytes.size() % sizeof(uint32_t)) == 0);
Vector<uint32_t> NewFeatures(FeatureBytes.size() / sizeof(uint32_t));
memcpy(NewFeatures.data(), FeatureBytes.data(), FeatureBytes.size());
for (auto Ft : NewFeatures) {
if (!Features.count(Ft)) {
MergeCandidates.push_back(F);
break;
}
}
}
// if (!FilesToAdd.empty() || Job->ExitCode != 0)
Printf(
"#%zd: cov: %zd ft: %zd corp: %zd exec/s %zd "
"oom/timeout/crash: %zd/%zd/%zd time: %zds job: %zd dft_time: %d\n",
NumRuns, Cov.size(), Features.size(), Files.size(),
Stats.average_exec_per_sec, NumOOMs, NumTimeouts, NumCrashes,
secondsSinceProcessStartUp(), Job->JobId, Job->DftTimeInSeconds);
if (MergeCandidates.empty()) return;
Vector<std::string> FilesToAdd;
Set<uint32_t> NewFeatures, NewCov;
CrashResistantMerge(Args, {}, MergeCandidates, &FilesToAdd, Features,
&NewFeatures, Cov, &NewCov, Job->CFPath, false);
for (auto &Path : FilesToAdd) {
auto U = FileToVector(Path);
auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
WriteToFile(U, NewPath);
Files.push_back(NewPath);
}
Features.insert(NewFeatures.begin(), NewFeatures.end());
Cov.insert(NewCov.begin(), NewCov.end());
for (auto Idx : NewCov)
if (auto *TE = TPC.PCTableEntryByIdx(Idx))
if (TPC.PcIsFuncEntry(TE))
PrintPC(" NEW_FUNC: %p %F %L\n", "",
TPC.GetNextInstructionPc(TE->PC));
}
void CollectDFT(const std::string &InputPath) {
if (DataFlowBinary.empty()) return;
if (!FilesWithDFT.insert(InputPath).second) return;
Command Cmd(Args);
Cmd.removeFlag("fork");
Cmd.removeFlag("runs");
Cmd.addFlag("data_flow_trace", DFTDir);
Cmd.addArgument(InputPath);
for (auto &C : CorpusDirs) // Remove all corpora from the args.
Cmd.removeArgument(C);
Cmd.setOutputFile(DirPlusFile(TempDir, "dft.log"));
Cmd.combineOutAndErr();
// Printf("CollectDFT: %s\n", Cmd.toString().c_str());
ExecuteCommand(Cmd);
}
};
struct JobQueue {
std::queue<FuzzJob *> Qu;
std::mutex Mu;
std::condition_variable Cv;
void Push(FuzzJob *Job) {
{
std::lock_guard<std::mutex> Lock(Mu);
Qu.push(Job);
}
Cv.notify_one();
}
FuzzJob *Pop() {
std::unique_lock<std::mutex> Lk(Mu);
// std::lock_guard<std::mutex> Lock(Mu);
Cv.wait(Lk, [&] { return !Qu.empty(); });
assert(!Qu.empty());
auto Job = Qu.front();
Qu.pop();
return Job;
}
};
void WorkerThread(JobQueue *FuzzQ, JobQueue *MergeQ) {
while (auto Job = FuzzQ->Pop()) {
// Printf("WorkerThread: job %p\n", Job);
Job->ExitCode = ExecuteCommand(Job->Cmd);
MergeQ->Push(Job);
}
}
// This is just a skeleton of an experimental -fork=1 feature.
void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
const Vector<std::string> &Args,
const Vector<std::string> &CorpusDirs, int NumJobs) {
Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs);
GlobalEnv Env;
Env.Args = Args;
Env.CorpusDirs = CorpusDirs;
Env.Rand = &Rand;
Env.Verbosity = Options.Verbosity;
Env.ProcessStartTime = std::chrono::system_clock::now();
Env.DataFlowBinary = Options.CollectDataFlow;
Vector<SizedFile> SeedFiles;
for (auto &Dir : CorpusDirs)
GetSizedFilesFromDir(Dir, &SeedFiles);
std::sort(SeedFiles.begin(), SeedFiles.end());
Env.TempDir = TempPath("FuzzWithFork", ".dir");
Env.DFTDir = DirPlusFile(Env.TempDir, "DFT");
RmDirRecursive(Env.TempDir); // in case there is a leftover from old runs.
MkDir(Env.TempDir);
MkDir(Env.DFTDir);
if (CorpusDirs.empty())
MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
else
Env.MainCorpusDir = CorpusDirs[0];
if (Options.KeepSeed) {
for (auto &File : SeedFiles)
Env.Files.push_back(File.File);
} else {
auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, {}, &Env.Features,
{}, &Env.Cov, CFPath, false);
RemoveFile(CFPath);
}
Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs,
Env.Files.size(), Env.TempDir.c_str());
int ExitCode = 0;
JobQueue FuzzQ, MergeQ;
auto StopJobs = [&]() {
for (int i = 0; i < NumJobs; i++)
FuzzQ.Push(nullptr);
MergeQ.Push(nullptr);
WriteToFile(Unit({1}), Env.StopFile());
};
size_t JobId = 1;
Vector<std::thread> Threads;
for (int t = 0; t < NumJobs; t++) {
Threads.push_back(std::thread(WorkerThread, &FuzzQ, &MergeQ));
FuzzQ.Push(Env.CreateNewJob(JobId++));
}
while (true) {
std::unique_ptr<FuzzJob> Job(MergeQ.Pop());
if (!Job) break;
ExitCode = Job->ExitCode;
if (ExitCode == Options.InterruptExitCode) {
Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
StopJobs();
break;
}
Fuzzer::MaybeExitGracefully();
Env.RunOneMergeJob(Job.get());
// Continue if our crash is one of the ignorred ones.
if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
Env.NumTimeouts++;
else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
Env.NumOOMs++;
else if (ExitCode != 0) {
Env.NumCrashes++;
if (Options.IgnoreCrashes) {
std::ifstream In(Job->LogPath);
std::string Line;
while (std::getline(In, Line, '\n'))
if (Line.find("ERROR:") != Line.npos ||
Line.find("runtime error:") != Line.npos)
Printf("%s\n", Line.c_str());
} else {
// And exit if we don't ignore this crash.
Printf("INFO: log from the inner process:\n%s",
FileToString(Job->LogPath).c_str());
StopJobs();
break;
}
}
// Stop if we are over the time budget.
// This is not precise, since other threads are still running
// and we will wait while joining them.
// We also don't stop instantly: other jobs need to finish.
if (Options.MaxTotalTimeSec > 0 &&
Env.secondsSinceProcessStartUp() >= (size_t)Options.MaxTotalTimeSec) {
Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
Env.secondsSinceProcessStartUp());
StopJobs();
break;
}
if (Env.NumRuns >= Options.MaxNumberOfRuns) {
Printf("INFO: fuzzed for %zd iterations, wrapping up soon\n",
Env.NumRuns);
StopJobs();
break;
}
FuzzQ.Push(Env.CreateNewJob(JobId++));
}
for (auto &T : Threads)
T.join();
// The workers have terminated. Don't try to remove the directory before they
// terminate to avoid a race condition preventing cleanup on Windows.
RmDirRecursive(Env.TempDir);
// Use the exit code from the last child process.
Printf("INFO: exiting: %d time: %zds\n", ExitCode,
Env.secondsSinceProcessStartUp());
exit(ExitCode);
}
} // namespace fuzzer

View File

@ -0,0 +1,24 @@
//===- FuzzerFork.h - run fuzzing in sub-processes --------------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_FORK_H
#define LLVM_FUZZER_FORK_H
#include "FuzzerDefs.h"
#include "FuzzerOptions.h"
#include "FuzzerRandom.h"
#include <string>
namespace fuzzer {
void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
const Vector<std::string> &Args,
const Vector<std::string> &CorpusDirs, int NumJobs);
} // namespace fuzzer
#endif // LLVM_FUZZER_FORK_H

View File

@ -0,0 +1,255 @@
//===- FuzzerIO.cpp - IO utils. -------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// IO functions.
//===----------------------------------------------------------------------===//
#include "FuzzerDefs.h"
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
#include "FuzzerUtil.h"
#include <algorithm>
#include <cstdarg>
#include <fstream>
#include <iterator>
#include <sys/stat.h>
#include <sys/types.h>
namespace fuzzer {
static FILE *OutputFile = stderr;
long GetEpoch(const std::string &Path) {
struct stat St;
if (stat(Path.c_str(), &St)) return 0; // Can't stat, be conservative.
return St.st_mtime;
}
Unit FileToVector(const std::string &Path, size_t MaxSize, bool ExitOnError) {
std::ifstream T(Path, std::ios::binary);
if (ExitOnError && !T) {
Printf("No such directory: %s; exiting\n", Path.c_str());
exit(1);
}
T.seekg(0, T.end);
auto EndPos = T.tellg();
if (EndPos < 0) return {};
size_t FileLen = EndPos;
if (MaxSize) FileLen = std::min(FileLen, MaxSize);
T.seekg(0, T.beg);
Unit Res(FileLen);
T.read(reinterpret_cast<char *>(Res.data()), FileLen);
return Res;
}
std::string FileToString(const std::string &Path) {
std::ifstream T(Path, std::ios::binary);
return std::string((std::istreambuf_iterator<char>(T)),
std::istreambuf_iterator<char>());
}
void CopyFileToErr(const std::string &Path) {
Printf("%s", FileToString(Path).c_str());
}
void WriteToFile(const Unit &U, const std::string &Path) {
WriteToFile(U.data(), U.size(), Path);
}
void WriteToFile(const std::string &Data, const std::string &Path) {
WriteToFile(reinterpret_cast<const uint8_t *>(Data.c_str()), Data.size(),
Path);
}
void WriteToFile(const uint8_t *Data, size_t Size, const std::string &Path) {
return;
// Use raw C interface because this function may be called from a sig handler.
FILE *Out = fopen(Path.c_str(), "wb");
if (!Out) return;
fwrite(Data, sizeof(Data[0]), Size, Out);
fclose(Out);
}
void AppendToFile(const std::string &Data, const std::string &Path) {
return;
AppendToFile(reinterpret_cast<const uint8_t *>(Data.data()), Data.size(),
Path);
}
void AppendToFile(const uint8_t *Data, size_t Size, const std::string &Path) {
return;
FILE *Out = fopen(Path.c_str(), "a");
if (!Out) return;
fwrite(Data, sizeof(Data[0]), Size, Out);
fclose(Out);
}
void ReadDirToVectorOfUnits(const char *Path, Vector<Unit> *V, long *Epoch,
size_t MaxSize, bool ExitOnError) {
long E = Epoch ? *Epoch : 0;
Vector<std::string> Files;
ListFilesInDirRecursive(Path, Epoch, &Files, /*TopDir*/ true);
size_t NumLoaded = 0;
for (size_t i = 0; i < Files.size(); i++) {
auto &X = Files[i];
if (Epoch && GetEpoch(X) < E) continue;
NumLoaded++;
if ((NumLoaded & (NumLoaded - 1)) == 0 && NumLoaded >= 1024)
Printf("Loaded %zd/%zd files from %s\n", NumLoaded, Files.size(), Path);
auto S = FileToVector(X, MaxSize, ExitOnError);
if (!S.empty()) V->push_back(S);
}
}
void GetSizedFilesFromDir(const std::string &Dir, Vector<SizedFile> *V) {
Vector<std::string> Files;
ListFilesInDirRecursive(Dir, 0, &Files, /*TopDir*/ true);
for (auto &File : Files)
if (size_t Size = FileSize(File)) V->push_back({File, Size});
}
std::string DirPlusFile(const std::string &DirPath,
const std::string &FileName) {
return DirPath + GetSeparator() + FileName;
}
void DupAndCloseStderr() {
int OutputFd = DuplicateFile(2);
if (OutputFd >= 0) {
FILE *NewOutputFile = OpenFile(OutputFd, "w");
if (NewOutputFile) {
OutputFile = NewOutputFile;
if (EF->__sanitizer_set_report_fd)
EF->__sanitizer_set_report_fd(
reinterpret_cast<void *>(GetHandleFromFd(OutputFd)));
DiscardOutput(2);
}
}
}
void CloseStdout() {
DiscardOutput(1);
}
void Printf(const char *Fmt, ...) {
va_list ap;
va_start(ap, Fmt);
vfprintf(OutputFile, Fmt, ap);
va_end(ap);
fflush(OutputFile);
}
void VPrintf(bool Verbose, const char *Fmt, ...) {
return;
if (!Verbose) return;
va_list ap;
va_start(ap, Fmt);
vfprintf(OutputFile, Fmt, ap);
va_end(ap);
fflush(OutputFile);
}
static bool MkDirRecursiveInner(const std::string &Leaf) {
// Prevent chance of potential infinite recursion
if (Leaf == ".") return true;
const std::string &Dir = DirName(Leaf);
if (IsDirectory(Dir)) {
MkDir(Leaf);
return IsDirectory(Leaf);
}
bool ret = MkDirRecursiveInner(Dir);
if (!ret) {
// Give up early if a previous MkDir failed
return ret;
}
MkDir(Leaf);
return IsDirectory(Leaf);
}
bool MkDirRecursive(const std::string &Dir) {
if (Dir.empty()) return false;
if (IsDirectory(Dir)) return true;
return MkDirRecursiveInner(Dir);
}
void RmDirRecursive(const std::string &Dir) {
IterateDirRecursive(
Dir, [](const std::string &Path) {},
[](const std::string &Path) { RmDir(Path); },
[](const std::string &Path) { RemoveFile(Path); });
}
std::string TempPath(const char *Prefix, const char *Extension) {
return DirPlusFile(TmpDir(), std::string("libFuzzerTemp.") + Prefix +
std::to_string(GetPid()) + Extension);
}
} // namespace fuzzer

View File

@ -0,0 +1,112 @@
//===- FuzzerIO.h - Internal header for IO utils ----------------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// IO interface.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_IO_H
#define LLVM_FUZZER_IO_H
#include "FuzzerDefs.h"
namespace fuzzer {
long GetEpoch(const std::string &Path);
Unit FileToVector(const std::string &Path, size_t MaxSize = 0,
bool ExitOnError = true);
std::string FileToString(const std::string &Path);
void CopyFileToErr(const std::string &Path);
void WriteToFile(const uint8_t *Data, size_t Size, const std::string &Path);
// Write Data.c_str() to the file without terminating null character.
void WriteToFile(const std::string &Data, const std::string &Path);
void WriteToFile(const Unit &U, const std::string &Path);
void AppendToFile(const uint8_t *Data, size_t Size, const std::string &Path);
void AppendToFile(const std::string &Data, const std::string &Path);
void ReadDirToVectorOfUnits(const char *Path, Vector<Unit> *V,
long *Epoch, size_t MaxSize, bool ExitOnError);
// Returns "Dir/FileName" or equivalent for the current OS.
std::string DirPlusFile(const std::string &DirPath,
const std::string &FileName);
// Returns the name of the dir, similar to the 'dirname' utility.
std::string DirName(const std::string &FileName);
// Returns path to a TmpDir.
std::string TmpDir();
std::string TempPath(const char *Prefix, const char *Extension);
bool IsInterestingCoverageFile(const std::string &FileName);
void DupAndCloseStderr();
void CloseStdout();
void Printf(const char *Fmt, ...);
void VPrintf(bool Verbose, const char *Fmt, ...);
// Print using raw syscalls, useful when printing at early init stages.
void RawPrint(const char *Str);
// Platform specific functions:
bool IsFile(const std::string &Path);
bool IsDirectory(const std::string &Path);
size_t FileSize(const std::string &Path);
void ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
Vector<std::string> *V, bool TopDir);
bool MkDirRecursive(const std::string &Dir);
void RmDirRecursive(const std::string &Dir);
// Iterate files and dirs inside Dir, recursively.
// Call DirPreCallback/DirPostCallback on dirs before/after
// calling FileCallback on files.
void IterateDirRecursive(const std::string &Dir,
void (*DirPreCallback)(const std::string &Dir),
void (*DirPostCallback)(const std::string &Dir),
void (*FileCallback)(const std::string &Dir));
struct SizedFile {
std::string File;
size_t Size;
bool operator<(const SizedFile &B) const { return Size < B.Size; }
};
void GetSizedFilesFromDir(const std::string &Dir, Vector<SizedFile> *V);
char GetSeparator();
bool IsSeparator(char C);
// Similar to the basename utility: returns the file name w/o the dir prefix.
std::string Basename(const std::string &Path);
FILE* OpenFile(int Fd, const char *Mode);
int CloseFile(int Fd);
int DuplicateFile(int Fd);
void RemoveFile(const std::string &Path);
void RenameFile(const std::string &OldPath, const std::string &NewPath);
intptr_t GetHandleFromFd(int fd);
void MkDir(const std::string &Path);
void RmDir(const std::string &Path);
const std::string &getDevNull();
} // namespace fuzzer
#endif // LLVM_FUZZER_IO_H

View File

@ -0,0 +1,223 @@
//===- FuzzerIOPosix.cpp - IO utils for Posix. ----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// IO functions implementation using Posix API.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_POSIX || LIBFUZZER_FUCHSIA
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
#include <cstdarg>
#include <cstdio>
#include <dirent.h>
#include <fstream>
#include <iterator>
#include <libgen.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
namespace fuzzer {
bool IsFile(const std::string &Path) {
struct stat St;
if (stat(Path.c_str(), &St)) return false;
return S_ISREG(St.st_mode);
}
bool IsDirectory(const std::string &Path) {
struct stat St;
if (stat(Path.c_str(), &St)) return false;
return S_ISDIR(St.st_mode);
}
size_t FileSize(const std::string &Path) {
struct stat St;
if (stat(Path.c_str(), &St)) return 0;
return St.st_size;
}
std::string Basename(const std::string &Path) {
size_t Pos = Path.rfind(GetSeparator());
if (Pos == std::string::npos) return Path;
assert(Pos < Path.size());
return Path.substr(Pos + 1);
}
void ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
Vector<std::string> *V, bool TopDir) {
auto E = GetEpoch(Dir);
if (Epoch)
if (E && *Epoch >= E) return;
DIR *D = opendir(Dir.c_str());
if (!D) {
Printf("%s: %s; exiting\n", strerror(errno), Dir.c_str());
exit(1);
}
while (auto E = readdir(D)) {
std::string Path = DirPlusFile(Dir, E->d_name);
if (E->d_type == DT_REG || E->d_type == DT_LNK ||
(E->d_type == DT_UNKNOWN && IsFile(Path)))
V->push_back(Path);
else if ((E->d_type == DT_DIR ||
(E->d_type == DT_UNKNOWN && IsDirectory(Path))) &&
*E->d_name != '.')
ListFilesInDirRecursive(Path, Epoch, V, false);
}
closedir(D);
if (Epoch && TopDir) *Epoch = E;
}
void IterateDirRecursive(const std::string &Dir,
void (*DirPreCallback)(const std::string &Dir),
void (*DirPostCallback)(const std::string &Dir),
void (*FileCallback)(const std::string &Dir)) {
DirPreCallback(Dir);
DIR *D = opendir(Dir.c_str());
if (!D) return;
while (auto E = readdir(D)) {
std::string Path = DirPlusFile(Dir, E->d_name);
if (E->d_type == DT_REG || E->d_type == DT_LNK ||
(E->d_type == DT_UNKNOWN && IsFile(Path)))
FileCallback(Path);
else if ((E->d_type == DT_DIR ||
(E->d_type == DT_UNKNOWN && IsDirectory(Path))) &&
*E->d_name != '.')
IterateDirRecursive(Path, DirPreCallback, DirPostCallback, FileCallback);
}
closedir(D);
DirPostCallback(Dir);
}
char GetSeparator() {
return '/';
}
bool IsSeparator(char C) {
return C == '/';
}
FILE *OpenFile(int Fd, const char *Mode) {
return fdopen(Fd, Mode);
}
int CloseFile(int fd) {
return close(fd);
}
int DuplicateFile(int Fd) {
return dup(Fd);
}
void RemoveFile(const std::string &Path) {
unlink(Path.c_str());
}
void RenameFile(const std::string &OldPath, const std::string &NewPath) {
rename(OldPath.c_str(), NewPath.c_str());
}
intptr_t GetHandleFromFd(int fd) {
return static_cast<intptr_t>(fd);
}
std::string DirName(const std::string &FileName) {
char *Tmp = new char[FileName.size() + 1];
memcpy(Tmp, FileName.c_str(), FileName.size() + 1);
std::string Res = dirname(Tmp);
delete[] Tmp;
return Res;
}
std::string TmpDir() {
if (auto Env = getenv("TMPDIR")) return Env;
return "/tmp";
}
bool IsInterestingCoverageFile(const std::string &FileName) {
if (FileName.find("compiler-rt/lib/") != std::string::npos)
return false; // sanitizer internal.
if (FileName.find("/usr/lib/") != std::string::npos) return false;
if (FileName.find("/usr/include/") != std::string::npos) return false;
if (FileName == "<null>") return false;
return true;
}
void RawPrint(const char *Str) {
write(2, Str, strlen(Str));
}
void MkDir(const std::string &Path) {
mkdir(Path.c_str(), 0700);
}
void RmDir(const std::string &Path) {
rmdir(Path.c_str());
}
const std::string &getDevNull() {
static const std::string devNull = "/dev/null";
return devNull;
}
} // namespace fuzzer
#endif // LIBFUZZER_POSIX

View File

@ -0,0 +1,513 @@
//===- FuzzerIOWindows.cpp - IO utils for Windows. ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// IO functions implementation for Windows.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_WINDOWS
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
#include <cstdarg>
#include <cstdio>
#include <fstream>
#include <io.h>
#include <iterator>
#include <sys/stat.h>
#include <sys/types.h>
#include <windows.h>
namespace fuzzer {
static bool IsFile(const std::string &Path, const DWORD &FileAttributes) {
if (FileAttributes & FILE_ATTRIBUTE_NORMAL) return true;
if (FileAttributes & FILE_ATTRIBUTE_DIRECTORY) return false;
HANDLE FileHandle(CreateFileA(Path.c_str(), 0, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0));
if (FileHandle == INVALID_HANDLE_VALUE) {
Printf("CreateFileA() failed for \"%s\" (Error code: %lu).\n", Path.c_str(),
GetLastError());
return false;
}
DWORD FileType = GetFileType(FileHandle);
if (FileType == FILE_TYPE_UNKNOWN) {
Printf("GetFileType() failed for \"%s\" (Error code: %lu).\n", Path.c_str(),
GetLastError());
CloseHandle(FileHandle);
return false;
}
if (FileType != FILE_TYPE_DISK) {
CloseHandle(FileHandle);
return false;
}
CloseHandle(FileHandle);
return true;
}
bool IsFile(const std::string &Path) {
DWORD Att = GetFileAttributesA(Path.c_str());
if (Att == INVALID_FILE_ATTRIBUTES) {
Printf("GetFileAttributesA() failed for \"%s\" (Error code: %lu).\n",
Path.c_str(), GetLastError());
return false;
}
return IsFile(Path, Att);
}
static bool IsDir(DWORD FileAttrs) {
if (FileAttrs == INVALID_FILE_ATTRIBUTES) return false;
return FileAttrs & FILE_ATTRIBUTE_DIRECTORY;
}
bool IsDirectory(const std::string &Path) {
DWORD Att = GetFileAttributesA(Path.c_str());
if (Att == INVALID_FILE_ATTRIBUTES) {
Printf("GetFileAttributesA() failed for \"%s\" (Error code: %lu).\n",
Path.c_str(), GetLastError());
return false;
}
return IsDir(Att);
}
std::string Basename(const std::string &Path) {
size_t Pos = Path.find_last_of("/\\");
if (Pos == std::string::npos) return Path;
assert(Pos < Path.size());
return Path.substr(Pos + 1);
}
size_t FileSize(const std::string &Path) {
WIN32_FILE_ATTRIBUTE_DATA attr;
if (!GetFileAttributesExA(Path.c_str(), GetFileExInfoStandard, &attr)) {
DWORD LastError = GetLastError();
if (LastError != ERROR_FILE_NOT_FOUND)
Printf("GetFileAttributesExA() failed for \"%s\" (Error code: %lu).\n",
Path.c_str(), LastError);
return 0;
}
ULARGE_INTEGER size;
size.HighPart = attr.nFileSizeHigh;
size.LowPart = attr.nFileSizeLow;
return size.QuadPart;
}
void ListFilesInDirRecursive(const std::string &Dir, long *Epoch,
Vector<std::string> *V, bool TopDir) {
auto E = GetEpoch(Dir);
if (Epoch)
if (E && *Epoch >= E) return;
std::string Path(Dir);
assert(!Path.empty());
if (Path.back() != '\\') Path.push_back('\\');
Path.push_back('*');
// Get the first directory entry.
WIN32_FIND_DATAA FindInfo;
HANDLE FindHandle(FindFirstFileA(Path.c_str(), &FindInfo));
if (FindHandle == INVALID_HANDLE_VALUE) {
if (GetLastError() == ERROR_FILE_NOT_FOUND) return;
Printf("No such file or directory: %s; exiting\n", Dir.c_str());
exit(1);
}
do {
std::string FileName = DirPlusFile(Dir, FindInfo.cFileName);
if (FindInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
size_t FilenameLen = strlen(FindInfo.cFileName);
if ((FilenameLen == 1 && FindInfo.cFileName[0] == '.') ||
(FilenameLen == 2 && FindInfo.cFileName[0] == '.' &&
FindInfo.cFileName[1] == '.'))
continue;
ListFilesInDirRecursive(FileName, Epoch, V, false);
} else if (IsFile(FileName, FindInfo.dwFileAttributes))
V->push_back(FileName);
} while (FindNextFileA(FindHandle, &FindInfo));
DWORD LastError = GetLastError();
if (LastError != ERROR_NO_MORE_FILES)
Printf("FindNextFileA failed (Error code: %lu).\n", LastError);
FindClose(FindHandle);
if (Epoch && TopDir) *Epoch = E;
}
void IterateDirRecursive(const std::string &Dir,
void (*DirPreCallback)(const std::string &Dir),
void (*DirPostCallback)(const std::string &Dir),
void (*FileCallback)(const std::string &Dir)) {
// TODO(metzman): Implement ListFilesInDirRecursive via this function.
DirPreCallback(Dir);
DWORD DirAttrs = GetFileAttributesA(Dir.c_str());
if (!IsDir(DirAttrs)) return;
std::string TargetDir(Dir);
assert(!TargetDir.empty());
if (TargetDir.back() != '\\') TargetDir.push_back('\\');
TargetDir.push_back('*');
WIN32_FIND_DATAA FindInfo;
// Find the directory's first file.
HANDLE FindHandle = FindFirstFileA(TargetDir.c_str(), &FindInfo);
if (FindHandle == INVALID_HANDLE_VALUE) {
DWORD LastError = GetLastError();
if (LastError != ERROR_FILE_NOT_FOUND) {
// If the directory isn't empty, then something abnormal is going on.
Printf("FindFirstFileA failed for %s (Error code: %lu).\n", Dir.c_str(),
LastError);
}
return;
}
do {
std::string Path = DirPlusFile(Dir, FindInfo.cFileName);
DWORD PathAttrs = FindInfo.dwFileAttributes;
if (IsDir(PathAttrs)) {
// Is Path the current directory (".") or the parent ("..")?
if (strcmp(FindInfo.cFileName, ".") == 0 ||
strcmp(FindInfo.cFileName, "..") == 0)
continue;
IterateDirRecursive(Path, DirPreCallback, DirPostCallback, FileCallback);
} else if (PathAttrs != INVALID_FILE_ATTRIBUTES) {
FileCallback(Path);
}
} while (FindNextFileA(FindHandle, &FindInfo));
DWORD LastError = GetLastError();
if (LastError != ERROR_NO_MORE_FILES)
Printf("FindNextFileA failed for %s (Error code: %lu).\n", Dir.c_str(),
LastError);
FindClose(FindHandle);
DirPostCallback(Dir);
}
char GetSeparator() {
return '\\';
}
FILE *OpenFile(int Fd, const char *Mode) {
return _fdopen(Fd, Mode);
}
int CloseFile(int Fd) {
return _close(Fd);
}
int DuplicateFile(int Fd) {
return _dup(Fd);
}
void RemoveFile(const std::string &Path) {
_unlink(Path.c_str());
}
void RenameFile(const std::string &OldPath, const std::string &NewPath) {
rename(OldPath.c_str(), NewPath.c_str());
}
intptr_t GetHandleFromFd(int fd) {
return _get_osfhandle(fd);
}
bool IsSeparator(char C) {
return C == '\\' || C == '/';
}
// Parse disk designators, like "C:\". If Relative == true, also accepts: "C:".
// Returns number of characters considered if successful.
static size_t ParseDrive(const std::string &FileName, const size_t Offset,
bool Relative = true) {
if (Offset + 1 >= FileName.size() || FileName[Offset + 1] != ':') return 0;
if (Offset + 2 >= FileName.size() || !IsSeparator(FileName[Offset + 2])) {
if (!Relative) // Accept relative path?
return 0;
else
return 2;
}
return 3;
}
// Parse a file name, like: SomeFile.txt
// Returns number of characters considered if successful.
static size_t ParseFileName(const std::string &FileName, const size_t Offset) {
size_t Pos = Offset;
const size_t End = FileName.size();
for (; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
;
return Pos - Offset;
}
// Parse a directory ending in separator, like: `SomeDir\`
// Returns number of characters considered if successful.
static size_t ParseDir(const std::string &FileName, const size_t Offset) {
size_t Pos = Offset;
const size_t End = FileName.size();
if (Pos >= End || IsSeparator(FileName[Pos])) return 0;
for (; Pos < End && !IsSeparator(FileName[Pos]); ++Pos)
;
if (Pos >= End) return 0;
++Pos; // Include separator.
return Pos - Offset;
}
// Parse a servername and share, like: `SomeServer\SomeShare\`
// Returns number of characters considered if successful.
static size_t ParseServerAndShare(const std::string &FileName,
const size_t Offset) {
size_t Pos = Offset, Res;
if (!(Res = ParseDir(FileName, Pos))) return 0;
Pos += Res;
if (!(Res = ParseDir(FileName, Pos))) return 0;
Pos += Res;
return Pos - Offset;
}
// Parse the given Ref string from the position Offset, to exactly match the
// given string Patt. Returns number of characters considered if successful.
static size_t ParseCustomString(const std::string &Ref, size_t Offset,
const char *Patt) {
size_t Len = strlen(Patt);
if (Offset + Len > Ref.size()) return 0;
return Ref.compare(Offset, Len, Patt) == 0 ? Len : 0;
}
// Parse a location, like:
// \\?\UNC\Server\Share\ \\?\C:\ \\Server\Share\ \ C:\ C:
// Returns number of characters considered if successful.
static size_t ParseLocation(const std::string &FileName) {
size_t Pos = 0, Res;
if ((Res = ParseCustomString(FileName, Pos, R"(\\?\)"))) {
Pos += Res;
if ((Res = ParseCustomString(FileName, Pos, R"(UNC\)"))) {
Pos += Res;
if ((Res = ParseServerAndShare(FileName, Pos))) return Pos + Res;
return 0;
}
if ((Res = ParseDrive(FileName, Pos, false))) return Pos + Res;
return 0;
}
if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
++Pos;
if (Pos < FileName.size() && IsSeparator(FileName[Pos])) {
++Pos;
if ((Res = ParseServerAndShare(FileName, Pos))) return Pos + Res;
return 0;
}
return Pos;
}
if ((Res = ParseDrive(FileName, Pos))) return Pos + Res;
return Pos;
}
std::string DirName(const std::string &FileName) {
size_t LocationLen = ParseLocation(FileName);
size_t DirLen = 0, Res;
while ((Res = ParseDir(FileName, LocationLen + DirLen)))
DirLen += Res;
size_t FileLen = ParseFileName(FileName, LocationLen + DirLen);
if (LocationLen + DirLen + FileLen != FileName.size()) {
Printf("DirName() failed for \"%s\", invalid path.\n", FileName.c_str());
exit(1);
}
if (DirLen) {
--DirLen; // Remove trailing separator.
if (!FileLen) { // Path ended in separator.
assert(DirLen);
// Remove file name from Dir.
while (DirLen && !IsSeparator(FileName[LocationLen + DirLen - 1]))
--DirLen;
if (DirLen) // Remove trailing separator.
--DirLen;
}
}
if (!LocationLen) { // Relative path.
if (!DirLen) return ".";
return std::string(".\\").append(FileName, 0, DirLen);
}
return FileName.substr(0, LocationLen + DirLen);
}
std::string TmpDir() {
std::string Tmp;
Tmp.resize(MAX_PATH + 1);
DWORD Size = GetTempPathA(Tmp.size(), &Tmp[0]);
if (Size == 0) {
Printf("Couldn't get Tmp path.\n");
exit(1);
}
Tmp.resize(Size);
return Tmp;
}
bool IsInterestingCoverageFile(const std::string &FileName) {
if (FileName.find("Program Files") != std::string::npos) return false;
if (FileName.find("compiler-rt\\lib\\") != std::string::npos)
return false; // sanitizer internal.
if (FileName == "<null>") return false;
return true;
}
void RawPrint(const char *Str) {
_write(2, Str, strlen(Str));
}
void MkDir(const std::string &Path) {
if (CreateDirectoryA(Path.c_str(), nullptr)) return;
Printf("CreateDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
GetLastError());
}
void RmDir(const std::string &Path) {
if (RemoveDirectoryA(Path.c_str())) return;
Printf("RemoveDirectoryA failed for %s (Error code: %lu).\n", Path.c_str(),
GetLastError());
}
const std::string &getDevNull() {
static const std::string devNull = "NUL";
return devNull;
}
} // namespace fuzzer
#endif // LIBFUZZER_WINDOWS

View File

@ -0,0 +1,290 @@
//===-- FuzzerInterceptors.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Intercept certain libc functions to aid fuzzing.
// Linked only when other RTs that define their own interceptors are not linked.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_LINUX
#define GET_CALLER_PC() __builtin_return_address(0)
#define PTR_TO_REAL(x) real_##x
#define REAL(x) __interception::PTR_TO_REAL(x)
#define FUNC_TYPE(x) x##_type
#define DEFINE_REAL(ret_type, func, ...) \
typedef ret_type (*FUNC_TYPE(func))(__VA_ARGS__); \
namespace __interception { \
\
FUNC_TYPE(func) PTR_TO_REAL(func); \
\
}
#include <cassert>
#include <cstdint>
#include <dlfcn.h> // for dlsym()
static void *getFuncAddr(const char *name, uintptr_t wrapper_addr) {
void *addr = dlsym(RTLD_NEXT, name);
if (!addr) {
// If the lookup using RTLD_NEXT failed, the sanitizer runtime library is
// later in the library search order than the DSO that we are trying to
// intercept, which means that we cannot intercept this function. We still
// want the address of the real definition, though, so look it up using
// RTLD_DEFAULT.
addr = dlsym(RTLD_DEFAULT, name);
// In case `name' is not loaded, dlsym ends up finding the actual wrapper.
// We don't want to intercept the wrapper and have it point to itself.
if (reinterpret_cast<uintptr_t>(addr) == wrapper_addr) addr = nullptr;
}
return addr;
}
static int FuzzerInited = 0;
static bool FuzzerInitIsRunning;
static void fuzzerInit();
static void ensureFuzzerInited() {
assert(!FuzzerInitIsRunning);
if (!FuzzerInited) { fuzzerInit(); }
}
static int internal_strcmp_strncmp(const char *s1, const char *s2, bool strncmp,
size_t n) {
size_t i = 0;
while (true) {
if (strncmp) {
if (i == n) break;
i++;
}
unsigned c1 = *s1;
unsigned c2 = *s2;
if (c1 != c2) return (c1 < c2) ? -1 : 1;
if (c1 == 0) break;
s1++;
s2++;
}
return 0;
}
static int internal_strncmp(const char *s1, const char *s2, size_t n) {
return internal_strcmp_strncmp(s1, s2, true, n);
}
static int internal_strcmp(const char *s1, const char *s2) {
return internal_strcmp_strncmp(s1, s2, false, 0);
}
static int internal_memcmp(const void *s1, const void *s2, size_t n) {
const uint8_t *t1 = static_cast<const uint8_t *>(s1);
const uint8_t *t2 = static_cast<const uint8_t *>(s2);
for (size_t i = 0; i < n; ++i, ++t1, ++t2)
if (*t1 != *t2) return *t1 < *t2 ? -1 : 1;
return 0;
}
static size_t internal_strlen(const char *s) {
size_t i = 0;
while (s[i])
i++;
return i;
}
static char *internal_strstr(const char *haystack, const char *needle) {
// This is O(N^2), but we are not using it in hot places.
size_t len1 = internal_strlen(haystack);
size_t len2 = internal_strlen(needle);
if (len1 < len2) return nullptr;
for (size_t pos = 0; pos <= len1 - len2; pos++) {
if (internal_memcmp(haystack + pos, needle, len2) == 0)
return const_cast<char *>(haystack) + pos;
}
return nullptr;
}
extern "C" {
// Weak hooks forward-declared to avoid dependency on
// <sanitizer/common_interface_defs.h>.
void __sanitizer_weak_hook_memcmp(void *called_pc, const void *s1,
const void *s2, size_t n, int result);
void __sanitizer_weak_hook_strncmp(void *called_pc, const char *s1,
const char *s2, size_t n, int result);
void __sanitizer_weak_hook_strncasecmp(void *called_pc, const char *s1,
const char *s2, size_t n, int result);
void __sanitizer_weak_hook_strcmp(void *called_pc, const char *s1,
const char *s2, int result);
void __sanitizer_weak_hook_strcasecmp(void *called_pc, const char *s1,
const char *s2, int result);
void __sanitizer_weak_hook_strstr(void *called_pc, const char *s1,
const char *s2, char *result);
void __sanitizer_weak_hook_strcasestr(void *called_pc, const char *s1,
const char *s2, char *result);
void __sanitizer_weak_hook_memmem(void *called_pc, const void *s1, size_t len1,
const void *s2, size_t len2, void *result);
DEFINE_REAL(int, bcmp, const void *, const void *, size_t)
DEFINE_REAL(int, memcmp, const void *, const void *, size_t)
DEFINE_REAL(int, strncmp, const char *, const char *, size_t)
DEFINE_REAL(int, strcmp, const char *, const char *)
DEFINE_REAL(int, strncasecmp, const char *, const char *, size_t)
DEFINE_REAL(int, strcasecmp, const char *, const char *)
DEFINE_REAL(char *, strstr, const char *, const char *)
DEFINE_REAL(char *, strcasestr, const char *, const char *)
DEFINE_REAL(void *, memmem, const void *, size_t, const void *, size_t)
ATTRIBUTE_INTERFACE int bcmp(const char *s1, const char *s2, size_t n) {
if (!FuzzerInited) return internal_memcmp(s1, s2, n);
int result = REAL(bcmp)(s1, s2, n);
__sanitizer_weak_hook_memcmp(GET_CALLER_PC(), s1, s2, n, result);
return result;
}
ATTRIBUTE_INTERFACE int memcmp(const void *s1, const void *s2, size_t n) {
if (!FuzzerInited) return internal_memcmp(s1, s2, n);
int result = REAL(memcmp)(s1, s2, n);
__sanitizer_weak_hook_memcmp(GET_CALLER_PC(), s1, s2, n, result);
return result;
}
ATTRIBUTE_INTERFACE int strncmp(const char *s1, const char *s2, size_t n) {
if (!FuzzerInited) return internal_strncmp(s1, s2, n);
int result = REAL(strncmp)(s1, s2, n);
__sanitizer_weak_hook_strncmp(GET_CALLER_PC(), s1, s2, n, result);
return result;
}
ATTRIBUTE_INTERFACE int strcmp(const char *s1, const char *s2) {
if (!FuzzerInited) return internal_strcmp(s1, s2);
int result = REAL(strcmp)(s1, s2);
__sanitizer_weak_hook_strcmp(GET_CALLER_PC(), s1, s2, result);
return result;
}
ATTRIBUTE_INTERFACE int strncasecmp(const char *s1, const char *s2, size_t n) {
ensureFuzzerInited();
int result = REAL(strncasecmp)(s1, s2, n);
__sanitizer_weak_hook_strncasecmp(GET_CALLER_PC(), s1, s2, n, result);
return result;
}
ATTRIBUTE_INTERFACE int strcasecmp(const char *s1, const char *s2) {
ensureFuzzerInited();
int result = REAL(strcasecmp)(s1, s2);
__sanitizer_weak_hook_strcasecmp(GET_CALLER_PC(), s1, s2, result);
return result;
}
ATTRIBUTE_INTERFACE char *strstr(const char *s1, const char *s2) {
if (!FuzzerInited) return internal_strstr(s1, s2);
char *result = REAL(strstr)(s1, s2);
__sanitizer_weak_hook_strstr(GET_CALLER_PC(), s1, s2, result);
return result;
}
ATTRIBUTE_INTERFACE char *strcasestr(const char *s1, const char *s2) {
ensureFuzzerInited();
char *result = REAL(strcasestr)(s1, s2);
__sanitizer_weak_hook_strcasestr(GET_CALLER_PC(), s1, s2, result);
return result;
}
ATTRIBUTE_INTERFACE
void *memmem(const void *s1, size_t len1, const void *s2, size_t len2) {
ensureFuzzerInited();
void *result = REAL(memmem)(s1, len1, s2, len2);
__sanitizer_weak_hook_memmem(GET_CALLER_PC(), s1, len1, s2, len2, result);
return result;
}
__attribute__((section(".preinit_array"),
used)) static void (*__local_fuzzer_preinit)(void) = fuzzerInit;
} // extern "C"
static void fuzzerInit() {
assert(!FuzzerInitIsRunning);
if (FuzzerInited) return;
FuzzerInitIsRunning = true;
REAL(bcmp) = reinterpret_cast<memcmp_type>(
getFuncAddr("bcmp", reinterpret_cast<uintptr_t>(&bcmp)));
REAL(memcmp) = reinterpret_cast<memcmp_type>(
getFuncAddr("memcmp", reinterpret_cast<uintptr_t>(&memcmp)));
REAL(strncmp) = reinterpret_cast<strncmp_type>(
getFuncAddr("strncmp", reinterpret_cast<uintptr_t>(&strncmp)));
REAL(strcmp) = reinterpret_cast<strcmp_type>(
getFuncAddr("strcmp", reinterpret_cast<uintptr_t>(&strcmp)));
REAL(strncasecmp) = reinterpret_cast<strncasecmp_type>(
getFuncAddr("strncasecmp", reinterpret_cast<uintptr_t>(&strncasecmp)));
REAL(strcasecmp) = reinterpret_cast<strcasecmp_type>(
getFuncAddr("strcasecmp", reinterpret_cast<uintptr_t>(&strcasecmp)));
REAL(strstr) = reinterpret_cast<strstr_type>(
getFuncAddr("strstr", reinterpret_cast<uintptr_t>(&strstr)));
REAL(strcasestr) = reinterpret_cast<strcasestr_type>(
getFuncAddr("strcasestr", reinterpret_cast<uintptr_t>(&strcasestr)));
REAL(memmem) = reinterpret_cast<memmem_type>(
getFuncAddr("memmem", reinterpret_cast<uintptr_t>(&memmem)));
FuzzerInitIsRunning = false;
FuzzerInited = 1;
}
#endif

View File

@ -0,0 +1,79 @@
//===- FuzzerInterface.h - Interface header for the Fuzzer ------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Define the interface between libFuzzer and the library being tested.
//===----------------------------------------------------------------------===//
// NOTE: the libFuzzer interface is thin and in the majority of cases
// you should not include this file into your target. In 95% of cases
// all you need is to define the following function in your file:
// extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);
// WARNING: keep the interface in C.
#ifndef LLVM_FUZZER_INTERFACE_H
#define LLVM_FUZZER_INTERFACE_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// Define FUZZER_INTERFACE_VISIBILITY to set default visibility in a way that
// doesn't break MSVC.
#if defined(_WIN32)
#define FUZZER_INTERFACE_VISIBILITY __declspec(dllexport)
#else
#define FUZZER_INTERFACE_VISIBILITY __attribute__((visibility("default")))
#endif
// Mandatory user-provided target function.
// Executes the code under test with [Data, Data+Size) as the input.
// libFuzzer will invoke this function *many* times with different inputs.
// Must return 0.
FUZZER_INTERFACE_VISIBILITY int
LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);
// Optional user-provided initialization function.
// If provided, this function will be called by libFuzzer once at startup.
// It may read and modify argc/argv.
// Must return 0.
FUZZER_INTERFACE_VISIBILITY int LLVMFuzzerInitialize(int *argc, char ***argv);
// Optional user-provided custom mutator.
// Mutates raw data in [Data, Data+Size) inplace.
// Returns the new size, which is not greater than MaxSize.
// Given the same Seed produces the same mutation.
FUZZER_INTERFACE_VISIBILITY size_t
LLVMFuzzerCustomMutator(uint8_t *Data, size_t Size, size_t MaxSize,
unsigned int Seed);
// Optional user-provided custom cross-over function.
// Combines pieces of Data1 & Data2 together into Out.
// Returns the new size, which is not greater than MaxOutSize.
// Should produce the same mutation given the same Seed.
FUZZER_INTERFACE_VISIBILITY size_t
LLVMFuzzerCustomCrossOver(const uint8_t *Data1, size_t Size1,
const uint8_t *Data2, size_t Size2, uint8_t *Out,
size_t MaxOutSize, unsigned int Seed);
// Experimental, may go away in future.
// libFuzzer-provided function to be used inside LLVMFuzzerCustomMutator.
// Mutates raw data in [Data, Data+Size) inplace.
// Returns the new size, which is not greater than MaxSize.
FUZZER_INTERFACE_VISIBILITY size_t
LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
#undef FUZZER_INTERFACE_VISIBILITY
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // LLVM_FUZZER_INTERFACE_H

View File

@ -0,0 +1,173 @@
//===- FuzzerInternal.h - Internal header for the Fuzzer --------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Define the main class fuzzer::Fuzzer and most functions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_INTERNAL_H
#define LLVM_FUZZER_INTERNAL_H
#include "FuzzerDataFlowTrace.h"
#include "FuzzerDefs.h"
#include "FuzzerExtFunctions.h"
#include "FuzzerInterface.h"
#include "FuzzerOptions.h"
#include "FuzzerSHA1.h"
#include "FuzzerValueBitMap.h"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <climits>
#include <cstdlib>
#include <string.h>
namespace fuzzer {
using namespace std::chrono;
class Fuzzer {
public:
Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
FuzzingOptions Options);
~Fuzzer();
void Loop(Vector<SizedFile> &CorporaFiles);
void ReadAndExecuteSeedCorpora(Vector<SizedFile> &CorporaFiles);
void MinimizeCrashLoop(const Unit &U);
void RereadOutputCorpus(size_t MaxSize);
size_t secondsSinceProcessStartUp() {
return duration_cast<seconds>(system_clock::now() - ProcessStartTime)
.count();
}
bool TimedOut() {
return Options.MaxTotalTimeSec > 0 &&
secondsSinceProcessStartUp() >
static_cast<size_t>(Options.MaxTotalTimeSec);
}
size_t execPerSec() {
size_t Seconds = secondsSinceProcessStartUp();
return Seconds ? TotalNumberOfRuns / Seconds : 0;
}
size_t getTotalNumberOfRuns() { return TotalNumberOfRuns; }
static void StaticAlarmCallback();
static void StaticCrashSignalCallback();
static void StaticExitCallback();
static void StaticInterruptCallback();
static void StaticFileSizeExceedCallback();
static void StaticGracefulExitCallback();
void ExecuteCallback(const uint8_t *Data, size_t Size);
bool RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile = false,
InputInfo *II = nullptr, bool ForceAddToCorpus = false,
bool *FoundUniqFeatures = nullptr);
// Merge Corpora[1:] into Corpora[0].
void Merge(const Vector<std::string> &Corpora);
void CrashResistantMergeInternalStep(const std::string &ControlFilePath);
MutationDispatcher &GetMD() { return MD; }
void PrintFinalStats();
void SetMaxInputLen(size_t MaxInputLen);
void SetMaxMutationLen(size_t MaxMutationLen);
void RssLimitCallback();
bool InFuzzingThread() const { return IsMyThread; }
size_t GetCurrentUnitInFuzzingThead(const uint8_t **Data) const;
void TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
bool DuringInitialCorpusExecution);
void HandleMalloc(size_t Size);
static void MaybeExitGracefully();
std::string WriteToOutputCorpus(const Unit &U);
private:
void AlarmCallback();
void CrashCallback();
void ExitCallback();
void CrashOnOverwrittenData();
void InterruptCallback();
void MutateAndTestOne();
void PurgeAllocator();
void ReportNewCoverage(InputInfo *II, const Unit &U);
void PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size);
void WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix);
void PrintStats(const char *Where, const char *End = "\n", size_t Units = 0,
size_t Features = 0);
void PrintStatusForNewUnit(const Unit &U, const char *Text);
void CheckExitOnSrcPosOrItem();
static void StaticDeathCallback();
void DumpCurrentUnit(const char *Prefix);
void DeathCallback();
void AllocateCurrentUnitData();
uint8_t *CurrentUnitData = nullptr;
std::atomic<size_t> CurrentUnitSize;
uint8_t BaseSha1[kSHA1NumBytes]; // Checksum of the base unit.
bool GracefulExitRequested = false;
size_t TotalNumberOfRuns = 0;
size_t NumberOfNewUnitsAdded = 0;
size_t LastCorpusUpdateRun = 0;
bool HasMoreMallocsThanFrees = false;
size_t NumberOfLeakDetectionAttempts = 0;
system_clock::time_point LastAllocatorPurgeAttemptTime = system_clock::now();
UserCallback CB;
InputCorpus &Corpus;
MutationDispatcher &MD;
FuzzingOptions Options;
DataFlowTrace DFT;
system_clock::time_point ProcessStartTime = system_clock::now();
system_clock::time_point UnitStartTime, UnitStopTime;
long TimeOfLongestUnitInSeconds = 0;
long EpochOfLastReadOfOutputCorpus = 0;
size_t MaxInputLen = 0;
size_t MaxMutationLen = 0;
size_t TmpMaxMutationLen = 0;
Vector<uint32_t> UniqFeatureSetTmp;
// Need to know our own thread.
static thread_local bool IsMyThread;
};
struct ScopedEnableMsanInterceptorChecks {
ScopedEnableMsanInterceptorChecks() {
if (EF->__msan_scoped_enable_interceptor_checks)
EF->__msan_scoped_enable_interceptor_checks();
}
~ScopedEnableMsanInterceptorChecks() {
if (EF->__msan_scoped_disable_interceptor_checks)
EF->__msan_scoped_disable_interceptor_checks();
}
};
struct ScopedDisableMsanInterceptorChecks {
ScopedDisableMsanInterceptorChecks() {
if (EF->__msan_scoped_disable_interceptor_checks)
EF->__msan_scoped_disable_interceptor_checks();
}
~ScopedDisableMsanInterceptorChecks() {
if (EF->__msan_scoped_enable_interceptor_checks)
EF->__msan_scoped_enable_interceptor_checks();
}
};
} // namespace fuzzer
#endif // LLVM_FUZZER_INTERNAL_H

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
//===- FuzzerMain.cpp - main() function and flags -------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// main() and flags.
//===----------------------------------------------------------------------===//
#include "FuzzerDefs.h"
#include "FuzzerPlatform.h"
extern "C" {
// This function should be defined by the user.
int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size);
} // extern "C"
ATTRIBUTE_INTERFACE int main(int argc, char **argv) {
return fuzzer::FuzzerDriver(&argc, &argv, LLVMFuzzerTestOneInput);
}

View File

@ -0,0 +1,485 @@
//===- FuzzerMerge.cpp - merging corpora ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Merging corpora.
//===----------------------------------------------------------------------===//
#include "FuzzerCommand.h"
#include "FuzzerMerge.h"
#include "FuzzerIO.h"
#include "FuzzerInternal.h"
#include "FuzzerTracePC.h"
#include "FuzzerUtil.h"
#include <fstream>
#include <iterator>
#include <set>
#include <sstream>
#include <unordered_set>
namespace fuzzer {
bool Merger::Parse(const std::string &Str, bool ParseCoverage) {
std::istringstream SS(Str);
return Parse(SS, ParseCoverage);
}
void Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) {
if (!Parse(IS, ParseCoverage)) {
Printf("MERGE: failed to parse the control file (unexpected error)\n");
exit(1);
}
}
// The control file example:
//
// 3 # The number of inputs
// 1 # The number of inputs in the first corpus, <= the previous number
// file0
// file1
// file2 # One file name per line.
// STARTED 0 123 # FileID, file size
// FT 0 1 4 6 8 # FileID COV1 COV2 ...
// COV 0 7 8 9 # FileID COV1 COV1
// STARTED 1 456 # If FT is missing, the input crashed while processing.
// STARTED 2 567
// FT 2 8 9
// COV 2 11 12
bool Merger::Parse(std::istream &IS, bool ParseCoverage) {
LastFailure.clear();
std::string Line;
// Parse NumFiles.
if (!std::getline(IS, Line, '\n')) return false;
std::istringstream L1(Line);
size_t NumFiles = 0;
L1 >> NumFiles;
if (NumFiles == 0 || NumFiles > 10000000) return false;
// Parse NumFilesInFirstCorpus.
if (!std::getline(IS, Line, '\n')) return false;
std::istringstream L2(Line);
NumFilesInFirstCorpus = NumFiles + 1;
L2 >> NumFilesInFirstCorpus;
if (NumFilesInFirstCorpus > NumFiles) return false;
// Parse file names.
Files.resize(NumFiles);
for (size_t i = 0; i < NumFiles; i++)
if (!std::getline(IS, Files[i].Name, '\n')) return false;
// Parse STARTED, FT, and COV lines.
size_t ExpectedStartMarker = 0;
const size_t kInvalidStartMarker = -1;
size_t LastSeenStartMarker = kInvalidStartMarker;
Vector<uint32_t> TmpFeatures;
Set<uint32_t> PCs;
while (std::getline(IS, Line, '\n')) {
std::istringstream ISS1(Line);
std::string Marker;
size_t N;
ISS1 >> Marker;
ISS1 >> N;
if (Marker == "STARTED") {
// STARTED FILE_ID FILE_SIZE
if (ExpectedStartMarker != N) return false;
ISS1 >> Files[ExpectedStartMarker].Size;
LastSeenStartMarker = ExpectedStartMarker;
assert(ExpectedStartMarker < Files.size());
ExpectedStartMarker++;
} else if (Marker == "FT") {
// FT FILE_ID COV1 COV2 COV3 ...
size_t CurrentFileIdx = N;
if (CurrentFileIdx != LastSeenStartMarker) return false;
LastSeenStartMarker = kInvalidStartMarker;
if (ParseCoverage) {
TmpFeatures.clear(); // use a vector from outer scope to avoid resizes.
while (ISS1 >> N)
TmpFeatures.push_back(N);
std::sort(TmpFeatures.begin(), TmpFeatures.end());
Files[CurrentFileIdx].Features = TmpFeatures;
}
} else if (Marker == "COV") {
size_t CurrentFileIdx = N;
if (ParseCoverage)
while (ISS1 >> N)
if (PCs.insert(N).second) Files[CurrentFileIdx].Cov.push_back(N);
} else {
return false;
}
}
if (LastSeenStartMarker != kInvalidStartMarker)
LastFailure = Files[LastSeenStartMarker].Name;
FirstNotProcessedFile = ExpectedStartMarker;
return true;
}
size_t Merger::ApproximateMemoryConsumption() const {
size_t Res = 0;
for (const auto &F : Files)
Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
return Res;
}
// Decides which files need to be merged (add those to NewFiles).
// Returns the number of new features added.
size_t Merger::Merge(const Set<uint32_t> &InitialFeatures,
Set<uint32_t> * NewFeatures,
const Set<uint32_t> &InitialCov, Set<uint32_t> *NewCov,
Vector<std::string> *NewFiles) {
NewFiles->clear();
assert(NumFilesInFirstCorpus <= Files.size());
Set<uint32_t> AllFeatures = InitialFeatures;
// What features are in the initial corpus?
for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
auto &Cur = Files[i].Features;
AllFeatures.insert(Cur.begin(), Cur.end());
}
// Remove all features that we already know from all other inputs.
for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
auto & Cur = Files[i].Features;
Vector<uint32_t> Tmp;
std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
Cur.swap(Tmp);
}
// Sort. Give preference to
// * smaller files
// * files with more features.
std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
[&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
if (a.Size != b.Size) return a.Size < b.Size;
return a.Features.size() > b.Features.size();
});
// One greedy pass: add the file's features to AllFeatures.
// If new features were added, add this file to NewFiles.
for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
auto &Cur = Files[i].Features;
// Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
// Files[i].Size, Cur.size());
bool FoundNewFeatures = false;
for (auto Fe : Cur) {
if (AllFeatures.insert(Fe).second) {
FoundNewFeatures = true;
NewFeatures->insert(Fe);
}
}
if (FoundNewFeatures) NewFiles->push_back(Files[i].Name);
for (auto Cov : Files[i].Cov)
if (InitialCov.find(Cov) == InitialCov.end()) NewCov->insert(Cov);
}
return NewFeatures->size();
}
Set<uint32_t> Merger::AllFeatures() const {
Set<uint32_t> S;
for (auto &File : Files)
S.insert(File.Features.begin(), File.Features.end());
return S;
}
// Inner process. May crash if the target crashes.
void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
Merger M;
std::ifstream IF(CFPath);
M.ParseOrExit(IF, false);
IF.close();
if (!M.LastFailure.empty())
Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
M.LastFailure.c_str());
Printf(
"MERGE-INNER: %zd total files;"
" %zd processed earlier; will process %zd files now\n",
M.Files.size(), M.FirstNotProcessedFile,
M.Files.size() - M.FirstNotProcessedFile);
std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
Set<size_t> AllFeatures;
auto PrintStatsWrapper = [this, &AllFeatures](const char *Where) {
this->PrintStats(Where, "\n", 0, AllFeatures.size());
};
Set<const TracePC::PCTableEntry *> AllPCs;
for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
Fuzzer::MaybeExitGracefully();
auto U = FileToVector(M.Files[i].Name);
if (U.size() > MaxInputLen) {
U.resize(MaxInputLen);
U.shrink_to_fit();
}
// Write the pre-run marker.
OF << "STARTED " << i << " " << U.size() << "\n";
OF.flush(); // Flush is important since Command::Execute may crash.
// Run.
TPC.ResetMaps();
ExecuteCallback(U.data(), U.size());
// Collect coverage. We are iterating over the files in this order:
// * First, files in the initial corpus ordered by size, smallest first.
// * Then, all other files, smallest first.
// So it makes no sense to record all features for all files, instead we
// only record features that were not seen before.
Set<size_t> UniqFeatures;
TPC.CollectFeatures([&](size_t Feature) {
if (AllFeatures.insert(Feature).second) UniqFeatures.insert(Feature);
});
TPC.UpdateObservedPCs();
// Show stats.
if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
PrintStatsWrapper("pulse ");
if (TotalNumberOfRuns == M.NumFilesInFirstCorpus)
PrintStatsWrapper("LOADED");
// Write the post-run marker and the coverage.
OF << "FT " << i;
for (size_t F : UniqFeatures)
OF << " " << F;
OF << "\n";
OF << "COV " << i;
TPC.ForEachObservedPC([&](const TracePC::PCTableEntry *TE) {
if (AllPCs.insert(TE).second) OF << " " << TPC.PCTableEntryIdx(TE);
});
OF << "\n";
OF.flush();
}
PrintStatsWrapper("DONE ");
}
static size_t WriteNewControlFile(const std::string & CFPath,
const Vector<SizedFile> & OldCorpus,
const Vector<SizedFile> & NewCorpus,
const Vector<MergeFileInfo> &KnownFiles) {
std::unordered_set<std::string> FilesToSkip;
for (auto &SF : KnownFiles)
FilesToSkip.insert(SF.Name);
Vector<std::string> FilesToUse;
auto MaybeUseFile = [=, &FilesToUse](std::string Name) {
if (FilesToSkip.find(Name) == FilesToSkip.end()) FilesToUse.push_back(Name);
};
for (auto &SF : OldCorpus)
MaybeUseFile(SF.File);
auto FilesToUseFromOldCorpus = FilesToUse.size();
for (auto &SF : NewCorpus)
MaybeUseFile(SF.File);
RemoveFile(CFPath);
std::ofstream ControlFile(CFPath);
ControlFile << FilesToUse.size() << "\n";
ControlFile << FilesToUseFromOldCorpus << "\n";
for (auto &FN : FilesToUse)
ControlFile << FN << "\n";
if (!ControlFile) {
Printf("MERGE-OUTER: failed to write to the control file: %s\n",
CFPath.c_str());
exit(1);
}
return FilesToUse.size();
}
// Outer process. Does not call the target code and thus should not fail.
void CrashResistantMerge(const Vector<std::string> &Args,
const Vector<SizedFile> & OldCorpus,
const Vector<SizedFile> & NewCorpus,
Vector<std::string> * NewFiles,
const Set<uint32_t> & InitialFeatures,
Set<uint32_t> * NewFeatures,
const Set<uint32_t> &InitialCov, Set<uint32_t> *NewCov,
const std::string &CFPath, bool V /*Verbose*/) {
if (NewCorpus.empty() && OldCorpus.empty()) return; // Nothing to merge.
size_t NumAttempts = 0;
Vector<MergeFileInfo> KnownFiles;
if (FileSize(CFPath)) {
VPrintf(V, "MERGE-OUTER: non-empty control file provided: '%s'\n",
CFPath.c_str());
Merger M;
std::ifstream IF(CFPath);
if (M.Parse(IF, /*ParseCoverage=*/true)) {
VPrintf(V,
"MERGE-OUTER: control file ok, %zd files total,"
" first not processed file %zd\n",
M.Files.size(), M.FirstNotProcessedFile);
if (!M.LastFailure.empty())
VPrintf(V,
"MERGE-OUTER: '%s' will be skipped as unlucky "
"(merge has stumbled on it the last time)\n",
M.LastFailure.c_str());
if (M.FirstNotProcessedFile >= M.Files.size()) {
// Merge has already been completed with the given merge control file.
if (M.Files.size() == OldCorpus.size() + NewCorpus.size()) {
VPrintf(
V,
"MERGE-OUTER: nothing to do, merge has been completed before\n");
exit(0);
}
// Number of input files likely changed, start merge from scratch, but
// reuse coverage information from the given merge control file.
VPrintf(
V,
"MERGE-OUTER: starting merge from scratch, but reusing coverage "
"information from the given control file\n");
KnownFiles = M.Files;
} else {
// There is a merge in progress, continue.
NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
}
} else {
VPrintf(V, "MERGE-OUTER: bad control file, will overwrite it\n");
}
}
if (!NumAttempts) {
// The supplied control file is empty or bad, create a fresh one.
VPrintf(V,
"MERGE-OUTER: "
"%zd files, %zd in the initial corpus, %zd processed earlier\n",
OldCorpus.size() + NewCorpus.size(), OldCorpus.size(),
KnownFiles.size());
NumAttempts = WriteNewControlFile(CFPath, OldCorpus, NewCorpus, KnownFiles);
}
// Execute the inner process until it passes.
// Every inner process should execute at least one input.
Command BaseCmd(Args);
BaseCmd.removeFlag("merge");
BaseCmd.removeFlag("fork");
BaseCmd.removeFlag("collect_data_flow");
for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
Fuzzer::MaybeExitGracefully();
VPrintf(V, "MERGE-OUTER: attempt %zd\n", Attempt);
Command Cmd(BaseCmd);
Cmd.addFlag("merge_control_file", CFPath);
Cmd.addFlag("merge_inner", "1");
if (!V) {
Cmd.setOutputFile(getDevNull());
Cmd.combineOutAndErr();
}
auto ExitCode = ExecuteCommand(Cmd);
if (!ExitCode) {
VPrintf(V, "MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt);
break;
}
}
// Read the control file and do the merge.
Merger M;
std::ifstream IF(CFPath);
IF.seekg(0, IF.end);
VPrintf(V, "MERGE-OUTER: the control file has %zd bytes\n",
(size_t)IF.tellg());
IF.seekg(0, IF.beg);
M.ParseOrExit(IF, true);
IF.close();
VPrintf(V,
"MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
M.Files.insert(M.Files.end(), KnownFiles.begin(), KnownFiles.end());
M.Merge(InitialFeatures, NewFeatures, InitialCov, NewCov, NewFiles);
VPrintf(V,
"MERGE-OUTER: %zd new files with %zd new features added; "
"%zd new coverage edges\n",
NewFiles->size(), NewFeatures->size(), NewCov->size());
}
} // namespace fuzzer

View File

@ -0,0 +1,87 @@
//===- FuzzerMerge.h - merging corpa ----------------------------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Merging Corpora.
//
// The task:
// Take the existing corpus (possibly empty) and merge new inputs into
// it so that only inputs with new coverage ('features') are added.
// The process should tolerate the crashes, OOMs, leaks, etc.
//
// Algorithm:
// The outer process collects the set of files and writes their names
// into a temporary "control" file, then repeatedly launches the inner
// process until all inputs are processed.
// The outer process does not actually execute the target code.
//
// The inner process reads the control file and sees a) list of all the inputs
// and b) the last processed input. Then it starts processing the inputs one
// by one. Before processing every input it writes one line to control file:
// STARTED INPUT_ID INPUT_SIZE
// After processing an input it writes the following lines:
// FT INPUT_ID Feature1 Feature2 Feature3 ...
// COV INPUT_ID Coverage1 Coverage2 Coverage3 ...
// If a crash happens while processing an input the last line in the control
// file will be "STARTED INPUT_ID" and so the next process will know
// where to resume.
//
// Once all inputs are processed by the inner process(es) the outer process
// reads the control files and does the merge based entirely on the contents
// of control file.
// It uses a single pass greedy algorithm choosing first the smallest inputs
// within the same size the inputs that have more new features.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_MERGE_H
#define LLVM_FUZZER_MERGE_H
#include "FuzzerDefs.h"
#include <istream>
#include <ostream>
#include <set>
#include <vector>
namespace fuzzer {
struct MergeFileInfo {
std::string Name;
size_t Size = 0;
Vector<uint32_t> Features, Cov;
};
struct Merger {
Vector<MergeFileInfo> Files;
size_t NumFilesInFirstCorpus = 0;
size_t FirstNotProcessedFile = 0;
std::string LastFailure;
bool Parse(std::istream &IS, bool ParseCoverage);
bool Parse(const std::string &Str, bool ParseCoverage);
void ParseOrExit(std::istream &IS, bool ParseCoverage);
size_t Merge(const Set<uint32_t> &InitialFeatures, Set<uint32_t> *NewFeatures,
const Set<uint32_t> &InitialCov, Set<uint32_t> *NewCov,
Vector<std::string> *NewFiles);
size_t ApproximateMemoryConsumption() const;
Set<uint32_t> AllFeatures() const;
};
void CrashResistantMerge(const Vector<std::string> &Args,
const Vector<SizedFile> &OldCorpus,
const Vector<SizedFile> &NewCorpus,
Vector<std::string> *NewFiles,
const Set<uint32_t> &InitialFeatures,
Set<uint32_t> *NewFeatures,
const Set<uint32_t> &InitialCov,
Set<uint32_t> *NewCov,
const std::string &CFPath,
bool Verbose);
} // namespace fuzzer
#endif // LLVM_FUZZER_MERGE_H

View File

@ -0,0 +1,747 @@
//===- FuzzerMutate.cpp - Mutate a test input -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Mutate a test input.
//===----------------------------------------------------------------------===//
#include "FuzzerDefs.h"
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
#include "FuzzerMutate.h"
#include "FuzzerOptions.h"
#include "FuzzerTracePC.h"
#include <random>
#include <chrono>
namespace fuzzer {
const size_t Dictionary::kMaxDictSize;
static const size_t kMaxMutationsToPrint = 10;
static void PrintASCII(const Word &W, const char *PrintAfter) {
PrintASCII(W.data(), W.size(), PrintAfter);
}
MutationDispatcher::MutationDispatcher(Random & Rand,
const FuzzingOptions &Options)
: Rand(Rand), Options(Options) {
DefaultMutators.insert(
DefaultMutators.begin(),
{
{&MutationDispatcher::Mutate_EraseBytes, "EraseBytes"},
{&MutationDispatcher::Mutate_InsertByte, "InsertByte"},
{&MutationDispatcher::Mutate_InsertRepeatedBytes,
"InsertRepeatedBytes"},
{&MutationDispatcher::Mutate_ChangeByte, "ChangeByte"},
{&MutationDispatcher::Mutate_ChangeBit, "ChangeBit"},
{&MutationDispatcher::Mutate_ShuffleBytes, "ShuffleBytes"},
{&MutationDispatcher::Mutate_ChangeASCIIInteger, "ChangeASCIIInt"},
{&MutationDispatcher::Mutate_ChangeBinaryInteger, "ChangeBinInt"},
{&MutationDispatcher::Mutate_CopyPart, "CopyPart"},
{&MutationDispatcher::Mutate_CrossOver, "CrossOver"},
{&MutationDispatcher::Mutate_AddWordFromManualDictionary,
"ManualDict"},
{&MutationDispatcher::Mutate_AddWordFromPersistentAutoDictionary,
"PersAutoDict"},
});
if (Options.UseCmp)
DefaultMutators.push_back(
{&MutationDispatcher::Mutate_AddWordFromTORC, "CMP"});
if (EF->LLVMFuzzerCustomMutator)
Mutators.push_back({&MutationDispatcher::Mutate_Custom, "Custom"});
else
Mutators = DefaultMutators;
if (EF->LLVMFuzzerCustomCrossOver)
Mutators.push_back(
{&MutationDispatcher::Mutate_CustomCrossOver, "CustomCrossOver"});
}
static char RandCh(Random &Rand) {
if (Rand.RandBool()) return Rand(256);
const char Special[] = "!*'();:@&=+$,/?%#[]012Az-`~.\xff\x00";
return Special[Rand(sizeof(Special) - 1)];
}
size_t MutationDispatcher::Mutate_Custom(uint8_t *Data, size_t Size,
size_t MaxSize) {
return EF->LLVMFuzzerCustomMutator(Data, Size, MaxSize, Rand.Rand());
}
size_t MutationDispatcher::Mutate_CustomCrossOver(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size == 0) return 0;
if (!CrossOverWith) return 0;
const Unit &Other = *CrossOverWith;
if (Other.empty()) return 0;
CustomCrossOverInPlaceHere.resize(MaxSize);
auto & U = CustomCrossOverInPlaceHere;
size_t NewSize = EF->LLVMFuzzerCustomCrossOver(
Data, Size, Other.data(), Other.size(), U.data(), U.size(), Rand.Rand());
if (!NewSize) return 0;
assert(NewSize <= MaxSize && "CustomCrossOver returned overisized unit");
memcpy(Data, U.data(), NewSize);
return NewSize;
}
size_t MutationDispatcher::Mutate_ShuffleBytes(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size > MaxSize || Size == 0) return 0;
size_t ShuffleAmount =
Rand(std::min(Size, (size_t)8)) + 1; // [1,8] and <= Size.
size_t ShuffleStart = Rand(Size - ShuffleAmount);
assert(ShuffleStart + ShuffleAmount <= Size);
unsigned num = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle(Data + ShuffleStart, Data + ShuffleStart + ShuffleAmount, std::default_random_engine(num));
//std::shuffle(Data + ShuffleStart, Data + ShuffleStart + ShuffleAmount, Rand);
return Size;
}
size_t MutationDispatcher::Mutate_EraseBytes(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size <= 1) return 0;
size_t N = Rand(Size / 2) + 1;
assert(N < Size);
size_t Idx = Rand(Size - N + 1);
// Erase Data[Idx:Idx+N].
memmove(Data + Idx, Data + Idx + N, Size - Idx - N);
// Printf("Erase: %zd %zd => %zd; Idx %zd\n", N, Size, Size - N, Idx);
return Size - N;
}
size_t MutationDispatcher::Mutate_InsertByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size >= MaxSize) return 0;
size_t Idx = Rand(Size + 1);
// Insert new value at Data[Idx].
memmove(Data + Idx + 1, Data + Idx, Size - Idx);
Data[Idx] = RandCh(Rand);
return Size + 1;
}
size_t MutationDispatcher::Mutate_InsertRepeatedBytes(uint8_t *Data,
size_t Size,
size_t MaxSize) {
const size_t kMinBytesToInsert = 3;
if (Size + kMinBytesToInsert >= MaxSize) return 0;
size_t MaxBytesToInsert = std::min(MaxSize - Size, (size_t)128);
size_t N = Rand(MaxBytesToInsert - kMinBytesToInsert + 1) + kMinBytesToInsert;
assert(Size + N <= MaxSize && N);
size_t Idx = Rand(Size + 1);
// Insert new values at Data[Idx].
memmove(Data + Idx + N, Data + Idx, Size - Idx);
// Give preference to 0x00 and 0xff.
uint8_t Byte = Rand.RandBool() ? Rand(256) : (Rand.RandBool() ? 0 : 255);
for (size_t i = 0; i < N; i++)
Data[Idx + i] = Byte;
return Size + N;
}
size_t MutationDispatcher::Mutate_ChangeByte(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size > MaxSize) return 0;
size_t Idx = Rand(Size);
Data[Idx] = RandCh(Rand);
return Size;
}
size_t MutationDispatcher::Mutate_ChangeBit(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size > MaxSize) return 0;
size_t Idx = Rand(Size);
Data[Idx] ^= 1 << Rand(8);
return Size;
}
size_t MutationDispatcher::Mutate_AddWordFromManualDictionary(uint8_t *Data,
size_t Size,
size_t MaxSize) {
return AddWordFromDictionary(ManualDictionary, Data, Size, MaxSize);
}
size_t MutationDispatcher::ApplyDictionaryEntry(uint8_t *Data, size_t Size,
size_t MaxSize,
DictionaryEntry &DE) {
const Word &W = DE.GetW();
bool UsePositionHint = DE.HasPositionHint() &&
DE.GetPositionHint() + W.size() < Size &&
Rand.RandBool();
if (Rand.RandBool()) { // Insert W.
if (Size + W.size() > MaxSize) return 0;
size_t Idx = UsePositionHint ? DE.GetPositionHint() : Rand(Size + 1);
memmove(Data + Idx + W.size(), Data + Idx, Size - Idx);
memcpy(Data + Idx, W.data(), W.size());
Size += W.size();
} else { // Overwrite some bytes with W.
if (W.size() > Size) return 0;
size_t Idx = UsePositionHint ? DE.GetPositionHint() : Rand(Size - W.size());
memcpy(Data + Idx, W.data(), W.size());
}
return Size;
}
// Somewhere in the past we have observed a comparison instructions
// with arguments Arg1 Arg2. This function tries to guess a dictionary
// entry that will satisfy that comparison.
// It first tries to find one of the arguments (possibly swapped) in the
// input and if it succeeds it creates a DE with a position hint.
// Otherwise it creates a DE with one of the arguments w/o a position hint.
DictionaryEntry MutationDispatcher::MakeDictionaryEntryFromCMP(
const void *Arg1, const void *Arg2, const void *Arg1Mutation,
const void *Arg2Mutation, size_t ArgSize, const uint8_t *Data,
size_t Size) {
bool HandleFirst = Rand.RandBool();
const void * ExistingBytes, *DesiredBytes;
Word W;
const uint8_t *End = Data + Size;
for (int Arg = 0; Arg < 2; Arg++) {
ExistingBytes = HandleFirst ? Arg1 : Arg2;
DesiredBytes = HandleFirst ? Arg2Mutation : Arg1Mutation;
HandleFirst = !HandleFirst;
W.Set(reinterpret_cast<const uint8_t *>(DesiredBytes), ArgSize);
const size_t kMaxNumPositions = 8;
size_t Positions[kMaxNumPositions];
size_t NumPositions = 0;
for (const uint8_t *Cur = Data;
Cur < End && NumPositions < kMaxNumPositions; Cur++) {
Cur =
(const uint8_t *)SearchMemory(Cur, End - Cur, ExistingBytes, ArgSize);
if (!Cur) break;
Positions[NumPositions++] = Cur - Data;
}
if (!NumPositions) continue;
return DictionaryEntry(W, Positions[Rand(NumPositions)]);
}
DictionaryEntry DE(W);
return DE;
}
template <class T>
DictionaryEntry MutationDispatcher::MakeDictionaryEntryFromCMP(
T Arg1, T Arg2, const uint8_t *Data, size_t Size) {
if (Rand.RandBool()) Arg1 = Bswap(Arg1);
if (Rand.RandBool()) Arg2 = Bswap(Arg2);
T Arg1Mutation = Arg1 + Rand(-1, 1);
T Arg2Mutation = Arg2 + Rand(-1, 1);
return MakeDictionaryEntryFromCMP(&Arg1, &Arg2, &Arg1Mutation, &Arg2Mutation,
sizeof(Arg1), Data, Size);
}
DictionaryEntry MutationDispatcher::MakeDictionaryEntryFromCMP(
const Word &Arg1, const Word &Arg2, const uint8_t *Data, size_t Size) {
return MakeDictionaryEntryFromCMP(Arg1.data(), Arg2.data(), Arg1.data(),
Arg2.data(), Arg1.size(), Data, Size);
}
size_t MutationDispatcher::Mutate_AddWordFromTORC(uint8_t *Data, size_t Size,
size_t MaxSize) {
Word W;
DictionaryEntry DE;
switch (Rand(4)) {
case 0: {
auto X = TPC.TORC8.Get(Rand.Rand());
DE = MakeDictionaryEntryFromCMP(X.A, X.B, Data, Size);
} break;
case 1: {
auto X = TPC.TORC4.Get(Rand.Rand());
if ((X.A >> 16) == 0 && (X.B >> 16) == 0 && Rand.RandBool())
DE = MakeDictionaryEntryFromCMP((uint16_t)X.A, (uint16_t)X.B, Data,
Size);
else
DE = MakeDictionaryEntryFromCMP(X.A, X.B, Data, Size);
} break;
case 2: {
auto X = TPC.TORCW.Get(Rand.Rand());
DE = MakeDictionaryEntryFromCMP(X.A, X.B, Data, Size);
} break;
case 3:
if (Options.UseMemmem) {
auto X = TPC.MMT.Get(Rand.Rand());
DE = DictionaryEntry(X);
}
break;
default:
assert(0);
}
if (!DE.GetW().size()) return 0;
Size = ApplyDictionaryEntry(Data, Size, MaxSize, DE);
if (!Size) return 0;
DictionaryEntry &DERef =
CmpDictionaryEntriesDeque[CmpDictionaryEntriesDequeIdx++ %
kCmpDictionaryEntriesDequeSize];
DERef = DE;
CurrentDictionaryEntrySequence.push_back(&DERef);
return Size;
}
size_t MutationDispatcher::Mutate_AddWordFromPersistentAutoDictionary(
uint8_t *Data, size_t Size, size_t MaxSize) {
return AddWordFromDictionary(PersistentAutoDictionary, Data, Size, MaxSize);
}
size_t MutationDispatcher::AddWordFromDictionary(Dictionary &D, uint8_t *Data,
size_t Size, size_t MaxSize) {
if (Size > MaxSize) return 0;
if (D.empty()) return 0;
DictionaryEntry &DE = D[Rand(D.size())];
Size = ApplyDictionaryEntry(Data, Size, MaxSize, DE);
if (!Size) return 0;
DE.IncUseCount();
CurrentDictionaryEntrySequence.push_back(&DE);
return Size;
}
// Overwrites part of To[0,ToSize) with a part of From[0,FromSize).
// Returns ToSize.
size_t MutationDispatcher::CopyPartOf(const uint8_t *From, size_t FromSize,
uint8_t *To, size_t ToSize) {
// Copy From[FromBeg, FromBeg + CopySize) into To[ToBeg, ToBeg + CopySize).
size_t ToBeg = Rand(ToSize);
size_t CopySize = Rand(ToSize - ToBeg) + 1;
assert(ToBeg + CopySize <= ToSize);
CopySize = std::min(CopySize, FromSize);
size_t FromBeg = Rand(FromSize - CopySize + 1);
assert(FromBeg + CopySize <= FromSize);
memmove(To + ToBeg, From + FromBeg, CopySize);
return ToSize;
}
// Inserts part of From[0,ToSize) into To.
// Returns new size of To on success or 0 on failure.
size_t MutationDispatcher::InsertPartOf(const uint8_t *From, size_t FromSize,
uint8_t *To, size_t ToSize,
size_t MaxToSize) {
if (ToSize >= MaxToSize) return 0;
size_t AvailableSpace = MaxToSize - ToSize;
size_t MaxCopySize = std::min(AvailableSpace, FromSize);
size_t CopySize = Rand(MaxCopySize) + 1;
size_t FromBeg = Rand(FromSize - CopySize + 1);
assert(FromBeg + CopySize <= FromSize);
size_t ToInsertPos = Rand(ToSize + 1);
assert(ToInsertPos + CopySize <= MaxToSize);
size_t TailSize = ToSize - ToInsertPos;
if (To == From) {
MutateInPlaceHere.resize(MaxToSize);
memcpy(MutateInPlaceHere.data(), From + FromBeg, CopySize);
memmove(To + ToInsertPos + CopySize, To + ToInsertPos, TailSize);
memmove(To + ToInsertPos, MutateInPlaceHere.data(), CopySize);
} else {
memmove(To + ToInsertPos + CopySize, To + ToInsertPos, TailSize);
memmove(To + ToInsertPos, From + FromBeg, CopySize);
}
return ToSize + CopySize;
}
size_t MutationDispatcher::Mutate_CopyPart(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size > MaxSize || Size == 0) return 0;
// If Size == MaxSize, `InsertPartOf(...)` will
// fail so there's no point using it in this case.
if (Size == MaxSize || Rand.RandBool())
return CopyPartOf(Data, Size, Data, Size);
else
return InsertPartOf(Data, Size, Data, Size, MaxSize);
}
size_t MutationDispatcher::Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size > MaxSize) return 0;
size_t B = Rand(Size);
while (B < Size && !isdigit(Data[B]))
B++;
if (B == Size) return 0;
size_t E = B;
while (E < Size && isdigit(Data[E]))
E++;
assert(B < E);
// now we have digits in [B, E).
// strtol and friends don't accept non-zero-teminated data, parse it manually.
uint64_t Val = Data[B] - '0';
for (size_t i = B + 1; i < E; i++)
Val = Val * 10 + Data[i] - '0';
// Mutate the integer value.
switch (Rand(5)) {
case 0:
Val++;
break;
case 1:
Val--;
break;
case 2:
Val /= 2;
break;
case 3:
Val *= 2;
break;
case 4:
Val = Rand(Val * Val);
break;
default:
assert(0);
}
// Just replace the bytes with the new ones, don't bother moving bytes.
for (size_t i = B; i < E; i++) {
size_t Idx = E + B - i - 1;
assert(Idx >= B && Idx < E);
Data[Idx] = (Val % 10) + '0';
Val /= 10;
}
return Size;
}
template <class T>
size_t ChangeBinaryInteger(uint8_t *Data, size_t Size, Random &Rand) {
if (Size < sizeof(T)) return 0;
size_t Off = Rand(Size - sizeof(T) + 1);
assert(Off + sizeof(T) <= Size);
T Val;
if (Off < 64 && !Rand(4)) {
Val = Size;
if (Rand.RandBool()) Val = Bswap(Val);
} else {
memcpy(&Val, Data + Off, sizeof(Val));
T Add = Rand(21);
Add -= 10;
if (Rand.RandBool())
Val = Bswap(T(Bswap(Val) + Add)); // Add assuming different endiannes.
else
Val = Val + Add; // Add assuming current endiannes.
if (Add == 0 || Rand.RandBool()) // Maybe negate.
Val = -Val;
}
memcpy(Data + Off, &Val, sizeof(Val));
return Size;
}
size_t MutationDispatcher::Mutate_ChangeBinaryInteger(uint8_t *Data,
size_t Size,
size_t MaxSize) {
if (Size > MaxSize) return 0;
switch (Rand(4)) {
case 3:
return ChangeBinaryInteger<uint64_t>(Data, Size, Rand);
case 2:
return ChangeBinaryInteger<uint32_t>(Data, Size, Rand);
case 1:
return ChangeBinaryInteger<uint16_t>(Data, Size, Rand);
case 0:
return ChangeBinaryInteger<uint8_t>(Data, Size, Rand);
default:
assert(0);
}
return 0;
}
size_t MutationDispatcher::Mutate_CrossOver(uint8_t *Data, size_t Size,
size_t MaxSize) {
if (Size > MaxSize) return 0;
if (Size == 0) return 0;
if (!CrossOverWith) return 0;
const Unit &O = *CrossOverWith;
if (O.empty()) return 0;
size_t NewSize = 0;
switch (Rand(3)) {
case 0:
MutateInPlaceHere.resize(MaxSize);
NewSize = CrossOver(Data, Size, O.data(), O.size(),
MutateInPlaceHere.data(), MaxSize);
memcpy(Data, MutateInPlaceHere.data(), NewSize);
break;
case 1:
NewSize = InsertPartOf(O.data(), O.size(), Data, Size, MaxSize);
if (!NewSize) NewSize = CopyPartOf(O.data(), O.size(), Data, Size);
break;
case 2:
NewSize = CopyPartOf(O.data(), O.size(), Data, Size);
break;
default:
assert(0);
}
assert(NewSize > 0 && "CrossOver returned empty unit");
assert(NewSize <= MaxSize && "CrossOver returned overisized unit");
return NewSize;
}
void MutationDispatcher::StartMutationSequence() {
CurrentMutatorSequence.clear();
CurrentDictionaryEntrySequence.clear();
}
// Copy successful dictionary entries to PersistentAutoDictionary.
void MutationDispatcher::RecordSuccessfulMutationSequence() {
for (auto DE : CurrentDictionaryEntrySequence) {
// PersistentAutoDictionary.AddWithSuccessCountOne(DE);
DE->IncSuccessCount();
assert(DE->GetW().size());
// Linear search is fine here as this happens seldom.
if (!PersistentAutoDictionary.ContainsWord(DE->GetW()))
PersistentAutoDictionary.push_back({DE->GetW(), 1});
}
}
void MutationDispatcher::PrintRecommendedDictionary() {
Vector<DictionaryEntry> V;
for (auto &DE : PersistentAutoDictionary)
if (!ManualDictionary.ContainsWord(DE.GetW())) V.push_back(DE);
if (V.empty()) return;
Printf("###### Recommended dictionary. ######\n");
for (auto &DE : V) {
assert(DE.GetW().size());
Printf("\"");
PrintASCII(DE.GetW(), "\"");
Printf(" # Uses: %zd\n", DE.GetUseCount());
}
Printf("###### End of recommended dictionary. ######\n");
}
const char *MutationDispatcher::WriteMutationSequence() {
static std::string buf;
buf = "";
for (size_t i = 0; i < CurrentMutatorSequence.size(); i++) {
buf = buf + " " + CurrentMutatorSequence[i].Name;
}
return buf.c_str();
}
void MutationDispatcher::PrintMutationSequence(bool Verbose) {
return;
Printf("MS: %zd ", CurrentMutatorSequence.size());
size_t EntriesToPrint =
Verbose ? CurrentMutatorSequence.size()
: std::min(kMaxMutationsToPrint, CurrentMutatorSequence.size());
for (size_t i = 0; i < EntriesToPrint; i++)
Printf("%s-", CurrentMutatorSequence[i].Name);
if (!CurrentDictionaryEntrySequence.empty()) {
Printf(" DE: ");
EntriesToPrint = Verbose ? CurrentDictionaryEntrySequence.size()
: std::min(kMaxMutationsToPrint,
CurrentDictionaryEntrySequence.size());
for (size_t i = 0; i < EntriesToPrint; i++) {
Printf("\"");
PrintASCII(CurrentDictionaryEntrySequence[i]->GetW(), "\"-");
}
}
}
std::string MutationDispatcher::MutationSequence() {
std::string MS;
for (auto M : CurrentMutatorSequence) {
MS += M.Name;
MS += "-";
}
return MS;
}
size_t MutationDispatcher::Mutate(uint8_t *Data, size_t Size, size_t MaxSize) {
return MutateImpl(Data, Size, MaxSize, Mutators);
}
size_t MutationDispatcher::DefaultMutate(uint8_t *Data, size_t Size,
size_t MaxSize) {
return MutateImpl(Data, Size, MaxSize, DefaultMutators);
}
// Mutates Data in place, returns new size.
size_t MutationDispatcher::MutateImpl(uint8_t *Data, size_t Size,
size_t MaxSize,
Vector<Mutator> &Mutators) {
assert(MaxSize > 0);
// Some mutations may fail (e.g. can't insert more bytes if Size == MaxSize),
// in which case they will return 0.
// Try several times before returning un-mutated data.
for (int Iter = 0; Iter < 100; Iter++) {
auto M = Mutators[Rand(Mutators.size())];
size_t NewSize = (this->*(M.Fn))(Data, Size, MaxSize);
if (NewSize && NewSize <= MaxSize) {
if (Options.OnlyASCII) ToASCII(Data, NewSize);
CurrentMutatorSequence.push_back(M);
return NewSize;
}
}
*Data = ' ';
return 1; // Fallback, should not happen frequently.
}
// Mask represents the set of Data bytes that are worth mutating.
size_t MutationDispatcher::MutateWithMask(uint8_t *Data, size_t Size,
size_t MaxSize,
const Vector<uint8_t> &Mask) {
size_t MaskedSize = std::min(Size, Mask.size());
// * Copy the worthy bytes into a temporary array T
// * Mutate T
// * Copy T back.
// This is totally unoptimized.
auto &T = MutateWithMaskTemp;
if (T.size() < Size) T.resize(Size);
size_t OneBits = 0;
for (size_t I = 0; I < MaskedSize; I++)
if (Mask[I]) T[OneBits++] = Data[I];
if (!OneBits) return 0;
assert(!T.empty());
size_t NewSize = Mutate(T.data(), OneBits, OneBits);
assert(NewSize <= OneBits);
(void)NewSize;
// Even if NewSize < OneBits we still use all OneBits bytes.
for (size_t I = 0, J = 0; I < MaskedSize; I++)
if (Mask[I]) Data[I] = T[J++];
return Size;
}
void MutationDispatcher::AddWordToManualDictionary(const Word &W) {
ManualDictionary.push_back({W, std::numeric_limits<size_t>::max()});
}
} // namespace fuzzer

View File

@ -0,0 +1,160 @@
//===- FuzzerMutate.h - Internal header for the Fuzzer ----------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::MutationDispatcher
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_MUTATE_H
#define LLVM_FUZZER_MUTATE_H
#include "FuzzerDefs.h"
#include "FuzzerDictionary.h"
#include "FuzzerOptions.h"
#include "FuzzerRandom.h"
namespace fuzzer {
class MutationDispatcher {
public:
MutationDispatcher(Random &Rand, const FuzzingOptions &Options);
~MutationDispatcher() {}
/// Indicate that we are about to start a new sequence of mutations.
void StartMutationSequence();
/// Print the current sequence of mutations. Only prints the full sequence
/// when Verbose is true.
const char *WriteMutationSequence();
void PrintMutationSequence(bool Verbose = true);
/// Return the current sequence of mutations.
std::string MutationSequence();
/// Indicate that the current sequence of mutations was successful.
void RecordSuccessfulMutationSequence();
/// Mutates data by invoking user-provided mutator.
size_t Mutate_Custom(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by invoking user-provided crossover.
size_t Mutate_CustomCrossOver(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by shuffling bytes.
size_t Mutate_ShuffleBytes(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by erasing bytes.
size_t Mutate_EraseBytes(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by inserting a byte.
size_t Mutate_InsertByte(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by inserting several repeated bytes.
size_t Mutate_InsertRepeatedBytes(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by chanding one byte.
size_t Mutate_ChangeByte(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by chanding one bit.
size_t Mutate_ChangeBit(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by copying/inserting a part of data into a different place.
size_t Mutate_CopyPart(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by adding a word from the manual dictionary.
size_t Mutate_AddWordFromManualDictionary(uint8_t *Data, size_t Size,
size_t MaxSize);
/// Mutates data by adding a word from the TORC.
size_t Mutate_AddWordFromTORC(uint8_t *Data, size_t Size, size_t MaxSize);
/// Mutates data by adding a word from the persistent automatic dictionary.
size_t Mutate_AddWordFromPersistentAutoDictionary(uint8_t *Data, size_t Size,
size_t MaxSize);
/// Tries to find an ASCII integer in Data, changes it to another ASCII int.
size_t Mutate_ChangeASCIIInteger(uint8_t *Data, size_t Size, size_t MaxSize);
/// Change a 1-, 2-, 4-, or 8-byte integer in interesting ways.
size_t Mutate_ChangeBinaryInteger(uint8_t *Data, size_t Size, size_t MaxSize);
/// CrossOver Data with CrossOverWith.
size_t Mutate_CrossOver(uint8_t *Data, size_t Size, size_t MaxSize);
/// Applies one of the configured mutations.
/// Returns the new size of data which could be up to MaxSize.
size_t Mutate(uint8_t *Data, size_t Size, size_t MaxSize);
/// Applies one of the configured mutations to the bytes of Data
/// that have '1' in Mask.
/// Mask.size() should be >= Size.
size_t MutateWithMask(uint8_t *Data, size_t Size, size_t MaxSize,
const Vector<uint8_t> &Mask);
/// Applies one of the default mutations. Provided as a service
/// to mutation authors.
size_t DefaultMutate(uint8_t *Data, size_t Size, size_t MaxSize);
/// Creates a cross-over of two pieces of Data, returns its size.
size_t CrossOver(const uint8_t *Data1, size_t Size1, const uint8_t *Data2,
size_t Size2, uint8_t *Out, size_t MaxOutSize);
void AddWordToManualDictionary(const Word &W);
void PrintRecommendedDictionary();
void SetCrossOverWith(const Unit *U) { CrossOverWith = U; }
Random &GetRand() { return Rand; }
private:
struct Mutator {
size_t (MutationDispatcher::*Fn)(uint8_t *Data, size_t Size, size_t Max);
const char *Name;
};
size_t AddWordFromDictionary(Dictionary &D, uint8_t *Data, size_t Size,
size_t MaxSize);
size_t MutateImpl(uint8_t *Data, size_t Size, size_t MaxSize,
Vector<Mutator> &Mutators);
size_t InsertPartOf(const uint8_t *From, size_t FromSize, uint8_t *To,
size_t ToSize, size_t MaxToSize);
size_t CopyPartOf(const uint8_t *From, size_t FromSize, uint8_t *To,
size_t ToSize);
size_t ApplyDictionaryEntry(uint8_t *Data, size_t Size, size_t MaxSize,
DictionaryEntry &DE);
template <class T>
DictionaryEntry MakeDictionaryEntryFromCMP(T Arg1, T Arg2,
const uint8_t *Data, size_t Size);
DictionaryEntry MakeDictionaryEntryFromCMP(const Word &Arg1, const Word &Arg2,
const uint8_t *Data, size_t Size);
DictionaryEntry MakeDictionaryEntryFromCMP(const void *Arg1, const void *Arg2,
const void *Arg1Mutation,
const void *Arg2Mutation,
size_t ArgSize,
const uint8_t *Data, size_t Size);
Random &Rand;
const FuzzingOptions Options;
// Dictionary provided by the user via -dict=DICT_FILE.
Dictionary ManualDictionary;
// Temporary dictionary modified by the fuzzer itself,
// recreated periodically.
Dictionary TempAutoDictionary;
// Persistent dictionary modified by the fuzzer, consists of
// entries that led to successful discoveries in the past mutations.
Dictionary PersistentAutoDictionary;
Vector<DictionaryEntry *> CurrentDictionaryEntrySequence;
static const size_t kCmpDictionaryEntriesDequeSize = 16;
DictionaryEntry CmpDictionaryEntriesDeque[kCmpDictionaryEntriesDequeSize];
size_t CmpDictionaryEntriesDequeIdx = 0;
const Unit *CrossOverWith = nullptr;
Vector<uint8_t> MutateInPlaceHere;
Vector<uint8_t> MutateWithMaskTemp;
// CustomCrossOver needs its own buffer as a custom implementation may call
// LLVMFuzzerMutate, which in turn may resize MutateInPlaceHere.
Vector<uint8_t> CustomCrossOverInPlaceHere;
Vector<Mutator> Mutators;
Vector<Mutator> DefaultMutators;
Vector<Mutator> CurrentMutatorSequence;
};
} // namespace fuzzer
#endif // LLVM_FUZZER_MUTATE_H

View File

@ -0,0 +1,90 @@
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::FuzzingOptions
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_OPTIONS_H
#define LLVM_FUZZER_OPTIONS_H
#include "FuzzerDefs.h"
namespace fuzzer {
struct FuzzingOptions {
int Verbosity = 1;
size_t MaxLen = 0;
size_t LenControl = 1000;
bool KeepSeed = false;
int UnitTimeoutSec = 300;
int TimeoutExitCode = 70;
int OOMExitCode = 71;
int InterruptExitCode = 72;
int ErrorExitCode = 77;
bool IgnoreTimeouts = true;
bool IgnoreOOMs = true;
bool IgnoreCrashes = false;
int MaxTotalTimeSec = 0;
int RssLimitMb = 0;
int MallocLimitMb = 0;
bool DoCrossOver = true;
bool CrossOverUniformDist = false;
int MutateDepth = 5;
bool ReduceDepth = false;
bool UseCounters = false;
bool UseMemmem = true;
bool UseCmp = false;
int UseValueProfile = false;
bool Shrink = false;
bool ReduceInputs = false;
int ReloadIntervalSec = 1;
bool ShuffleAtStartUp = true;
bool PreferSmall = true;
size_t MaxNumberOfRuns = -1L;
int ReportSlowUnits = 10;
bool OnlyASCII = false;
bool Entropic = true;
size_t EntropicFeatureFrequencyThreshold = 0xFF;
size_t EntropicNumberOfRarestFeatures = 100;
bool EntropicScalePerExecTime = false;
std::string OutputCorpus;
std::string ArtifactPrefix = "./";
std::string ExactArtifactPath;
std::string ExitOnSrcPos;
std::string ExitOnItem;
std::string FocusFunction;
std::string DataFlowTrace;
std::string CollectDataFlow;
std::string FeaturesDir;
std::string MutationGraphFile;
std::string StopFile;
bool SaveArtifacts = true;
bool PrintNEW = true; // Print a status line when new units are found;
bool PrintNewCovPcs = false;
int PrintNewCovFuncs = 0;
bool PrintFinalStats = false;
bool PrintCorpusStats = false;
bool PrintCoverage = false;
bool DumpCoverage = false;
bool DetectLeaks = true;
int PurgeAllocatorIntervalSec = 1;
int TraceMalloc = 0;
bool HandleAbrt = false;
bool HandleAlrm = false;
bool HandleBus = false;
bool HandleFpe = false;
bool HandleIll = false;
bool HandleInt = false;
bool HandleSegv = false;
bool HandleTerm = false;
bool HandleXfsz = false;
bool HandleUsr1 = false;
bool HandleUsr2 = false;
};
} // namespace fuzzer
#endif // LLVM_FUZZER_OPTIONS_H

View File

@ -0,0 +1,163 @@
//===-- FuzzerPlatform.h --------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Common platform macros.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_PLATFORM_H
#define LLVM_FUZZER_PLATFORM_H
// Platform detection.
#ifdef __linux__
#define LIBFUZZER_APPLE 0
#define LIBFUZZER_FUCHSIA 0
#define LIBFUZZER_LINUX 1
#define LIBFUZZER_NETBSD 0
#define LIBFUZZER_FREEBSD 0
#define LIBFUZZER_OPENBSD 0
#define LIBFUZZER_WINDOWS 0
#define LIBFUZZER_EMSCRIPTEN 0
#elif __APPLE__
#define LIBFUZZER_APPLE 1
#define LIBFUZZER_FUCHSIA 0
#define LIBFUZZER_LINUX 0
#define LIBFUZZER_NETBSD 0
#define LIBFUZZER_FREEBSD 0
#define LIBFUZZER_OPENBSD 0
#define LIBFUZZER_WINDOWS 0
#define LIBFUZZER_EMSCRIPTEN 0
#elif __NetBSD__
#define LIBFUZZER_APPLE 0
#define LIBFUZZER_FUCHSIA 0
#define LIBFUZZER_LINUX 0
#define LIBFUZZER_NETBSD 1
#define LIBFUZZER_FREEBSD 0
#define LIBFUZZER_OPENBSD 0
#define LIBFUZZER_WINDOWS 0
#define LIBFUZZER_EMSCRIPTEN 0
#elif __FreeBSD__
#define LIBFUZZER_APPLE 0
#define LIBFUZZER_FUCHSIA 0
#define LIBFUZZER_LINUX 0
#define LIBFUZZER_NETBSD 0
#define LIBFUZZER_FREEBSD 1
#define LIBFUZZER_OPENBSD 0
#define LIBFUZZER_WINDOWS 0
#define LIBFUZZER_EMSCRIPTEN 0
#elif __OpenBSD__
#define LIBFUZZER_APPLE 0
#define LIBFUZZER_FUCHSIA 0
#define LIBFUZZER_LINUX 0
#define LIBFUZZER_NETBSD 0
#define LIBFUZZER_FREEBSD 0
#define LIBFUZZER_OPENBSD 1
#define LIBFUZZER_WINDOWS 0
#define LIBFUZZER_EMSCRIPTEN 0
#elif _WIN32
#define LIBFUZZER_APPLE 0
#define LIBFUZZER_FUCHSIA 0
#define LIBFUZZER_LINUX 0
#define LIBFUZZER_NETBSD 0
#define LIBFUZZER_FREEBSD 0
#define LIBFUZZER_OPENBSD 0
#define LIBFUZZER_WINDOWS 1
#define LIBFUZZER_EMSCRIPTEN 0
#elif __Fuchsia__
#define LIBFUZZER_APPLE 0
#define LIBFUZZER_FUCHSIA 1
#define LIBFUZZER_LINUX 0
#define LIBFUZZER_NETBSD 0
#define LIBFUZZER_FREEBSD 0
#define LIBFUZZER_OPENBSD 0
#define LIBFUZZER_WINDOWS 0
#define LIBFUZZER_EMSCRIPTEN 0
#elif __EMSCRIPTEN__
#define LIBFUZZER_APPLE 0
#define LIBFUZZER_FUCHSIA 0
#define LIBFUZZER_LINUX 0
#define LIBFUZZER_NETBSD 0
#define LIBFUZZER_FREEBSD 0
#define LIBFUZZER_OPENBSD 0
#define LIBFUZZER_WINDOWS 0
#define LIBFUZZER_EMSCRIPTEN 1
#else
#error "Support for your platform has not been implemented"
#endif
#if defined(_MSC_VER) && !defined(__clang__)
// MSVC compiler is being used.
#define LIBFUZZER_MSVC 1
#else
#define LIBFUZZER_MSVC 0
#endif
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#define LIBFUZZER_POSIX \
(LIBFUZZER_APPLE || LIBFUZZER_LINUX || LIBFUZZER_NETBSD || \
LIBFUZZER_FREEBSD || LIBFUZZER_OPENBSD || LIBFUZZER_EMSCRIPTEN)
#ifdef __x86_64
#if __has_attribute(target)
#define ATTRIBUTE_TARGET_POPCNT __attribute__((target("popcnt")))
#else
#define ATTRIBUTE_TARGET_POPCNT
#endif
#else
#define ATTRIBUTE_TARGET_POPCNT
#endif
#ifdef __clang__ // avoid gcc warning.
#if __has_attribute(no_sanitize)
#define ATTRIBUTE_NO_SANITIZE_MEMORY __attribute__((no_sanitize("memory")))
#else
#define ATTRIBUTE_NO_SANITIZE_MEMORY
#endif
#define ALWAYS_INLINE __attribute__((always_inline))
#else
#define ATTRIBUTE_NO_SANITIZE_MEMORY
#define ALWAYS_INLINE
#endif // __clang__
#if LIBFUZZER_WINDOWS
#define ATTRIBUTE_NO_SANITIZE_ADDRESS
#else
#define ATTRIBUTE_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
#endif
#if LIBFUZZER_WINDOWS
#define ATTRIBUTE_ALIGNED(X) __declspec(align(X))
#define ATTRIBUTE_INTERFACE __declspec(dllexport)
// This is used for __sancov_lowest_stack which is needed for
// -fsanitize-coverage=stack-depth. That feature is not yet available on
// Windows, so make the symbol static to avoid linking errors.
#define ATTRIBUTES_INTERFACE_TLS_INITIAL_EXEC static
#define ATTRIBUTE_NOINLINE __declspec(noinline)
#else
#define ATTRIBUTE_ALIGNED(X) __attribute__((aligned(X)))
#define ATTRIBUTE_INTERFACE __attribute__((visibility("default")))
#define ATTRIBUTES_INTERFACE_TLS_INITIAL_EXEC \
ATTRIBUTE_INTERFACE __attribute__((tls_model("initial-exec"))) thread_local
#define ATTRIBUTE_NOINLINE __attribute__((noinline))
#endif
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
#define ATTRIBUTE_NO_SANITIZE_ALL ATTRIBUTE_NO_SANITIZE_ADDRESS
#elif __has_feature(memory_sanitizer)
#define ATTRIBUTE_NO_SANITIZE_ALL ATTRIBUTE_NO_SANITIZE_MEMORY
#else
#define ATTRIBUTE_NO_SANITIZE_ALL
#endif
#else
#define ATTRIBUTE_NO_SANITIZE_ALL
#endif
#endif // LLVM_FUZZER_PLATFORM_H

View File

@ -0,0 +1,38 @@
//===- FuzzerRandom.h - Internal header for the Fuzzer ----------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::Random
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_RANDOM_H
#define LLVM_FUZZER_RANDOM_H
#include <random>
namespace fuzzer {
class Random : public std::minstd_rand {
public:
explicit Random(unsigned int seed) : std::minstd_rand(seed) {}
result_type operator()() { return this->std::minstd_rand::operator()(); }
size_t Rand() { return this->operator()(); }
size_t RandBool() { return Rand() % 2; }
size_t SkewTowardsLast(size_t n) {
size_t T = this->operator()(n * n);
size_t Res = sqrt(T);
return Res;
}
size_t operator()(size_t n) { return n ? Rand() % n : 0; }
intptr_t operator()(intptr_t From, intptr_t To) {
assert(From < To);
intptr_t RangeSize = To - From + 1;
return operator()(RangeSize) + From;
}
};
} // namespace fuzzer
#endif // LLVM_FUZZER_RANDOM_H

View File

@ -0,0 +1,269 @@
//===- FuzzerSHA1.h - Private copy of the SHA1 implementation ---*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// This code is taken from public domain
// (http://oauth.googlecode.com/svn/code/c/liboauth/src/sha1.c)
// and modified by adding anonymous namespace, adding an interface
// function fuzzer::ComputeSHA1() and removing unnecessary code.
//
// lib/Fuzzer can not use SHA1 implementation from openssl because
// openssl may not be available and because we may be fuzzing openssl itself.
// For the same reason we do not want to depend on SHA1 from LLVM tree.
//===----------------------------------------------------------------------===//
#include "FuzzerSHA1.h"
#include "FuzzerDefs.h"
#include "FuzzerPlatform.h"
/* This code is public-domain - it is based on libcrypt
* placed in the public domain by Wei Dai and other contributors.
*/
#include <iomanip>
#include <sstream>
#include <stdint.h>
#include <string.h>
namespace { // Added for LibFuzzer
#ifdef __BIG_ENDIAN__
#define SHA_BIG_ENDIAN
// Windows is always little endian and MSVC doesn't have <endian.h>
#elif defined __LITTLE_ENDIAN__ || LIBFUZZER_WINDOWS
/* override */
#elif defined __BYTE_ORDER
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define SHA_BIG_ENDIAN
#endif
#else // ! defined __LITTLE_ENDIAN__
#include <endian.h> // machine/endian.h
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define SHA_BIG_ENDIAN
#endif
#endif
/* header */
#define HASH_LENGTH 20
#define BLOCK_LENGTH 64
typedef struct sha1nfo {
uint32_t buffer[BLOCK_LENGTH / 4];
uint32_t state[HASH_LENGTH / 4];
uint32_t byteCount;
uint8_t bufferOffset;
uint8_t keyBuffer[BLOCK_LENGTH];
uint8_t innerHash[HASH_LENGTH];
} sha1nfo;
/* public API - prototypes - TODO: doxygen*/
/**
*/
void sha1_init(sha1nfo *s);
/**
*/
void sha1_writebyte(sha1nfo *s, uint8_t data);
/**
*/
void sha1_write(sha1nfo *s, const char *data, size_t len);
/**
*/
uint8_t *sha1_result(sha1nfo *s);
/* code */
#define SHA1_K0 0x5a827999
#define SHA1_K20 0x6ed9eba1
#define SHA1_K40 0x8f1bbcdc
#define SHA1_K60 0xca62c1d6
void sha1_init(sha1nfo *s) {
s->state[0] = 0x67452301;
s->state[1] = 0xefcdab89;
s->state[2] = 0x98badcfe;
s->state[3] = 0x10325476;
s->state[4] = 0xc3d2e1f0;
s->byteCount = 0;
s->bufferOffset = 0;
}
uint32_t sha1_rol32(uint32_t number, uint8_t bits) {
return ((number << bits) | (number >> (32 - bits)));
}
void sha1_hashBlock(sha1nfo *s) {
uint8_t i;
uint32_t a, b, c, d, e, t;
a = s->state[0];
b = s->state[1];
c = s->state[2];
d = s->state[3];
e = s->state[4];
for (i = 0; i < 80; i++) {
if (i >= 16) {
t = s->buffer[(i + 13) & 15] ^ s->buffer[(i + 8) & 15] ^
s->buffer[(i + 2) & 15] ^ s->buffer[i & 15];
s->buffer[i & 15] = sha1_rol32(t, 1);
}
if (i < 20) {
t = (d ^ (b & (c ^ d))) + SHA1_K0;
} else if (i < 40) {
t = (b ^ c ^ d) + SHA1_K20;
} else if (i < 60) {
t = ((b & c) | (d & (b | c))) + SHA1_K40;
} else {
t = (b ^ c ^ d) + SHA1_K60;
}
t += sha1_rol32(a, 5) + e + s->buffer[i & 15];
e = d;
d = c;
c = sha1_rol32(b, 30);
b = a;
a = t;
}
s->state[0] += a;
s->state[1] += b;
s->state[2] += c;
s->state[3] += d;
s->state[4] += e;
}
void sha1_addUncounted(sha1nfo *s, uint8_t data) {
uint8_t *const b = (uint8_t *)s->buffer;
#ifdef SHA_BIG_ENDIAN
b[s->bufferOffset] = data;
#else
b[s->bufferOffset ^ 3] = data;
#endif
s->bufferOffset++;
if (s->bufferOffset == BLOCK_LENGTH) {
sha1_hashBlock(s);
s->bufferOffset = 0;
}
}
void sha1_writebyte(sha1nfo *s, uint8_t data) {
++s->byteCount;
sha1_addUncounted(s, data);
}
void sha1_write(sha1nfo *s, const char *data, size_t len) {
for (; len--;)
sha1_writebyte(s, (uint8_t)*data++);
}
void sha1_pad(sha1nfo *s) {
// Implement SHA-1 padding (fips180-2 §5.1.1)
// Pad with 0x80 followed by 0x00 until the end of the block
sha1_addUncounted(s, 0x80);
while (s->bufferOffset != 56)
sha1_addUncounted(s, 0x00);
// Append length in the last 8 bytes
sha1_addUncounted(s, 0); // We're only using 32 bit lengths
sha1_addUncounted(s, 0); // But SHA-1 supports 64 bit lengths
sha1_addUncounted(s, 0); // So zero pad the top bits
sha1_addUncounted(s, s->byteCount >> 29); // Shifting to multiply by 8
sha1_addUncounted(
s, s->byteCount >> 21); // as SHA-1 supports bitstreams as well as
sha1_addUncounted(s, s->byteCount >> 13); // byte.
sha1_addUncounted(s, s->byteCount >> 5);
sha1_addUncounted(s, s->byteCount << 3);
}
uint8_t *sha1_result(sha1nfo *s) {
// Pad to complete the last block
sha1_pad(s);
#ifndef SHA_BIG_ENDIAN
// Swap byte order back
int i;
for (i = 0; i < 5; i++) {
s->state[i] = (((s->state[i]) << 24) & 0xff000000) |
(((s->state[i]) << 8) & 0x00ff0000) |
(((s->state[i]) >> 8) & 0x0000ff00) |
(((s->state[i]) >> 24) & 0x000000ff);
}
#endif
// Return pointer to hash (20 characters)
return (uint8_t *)s->state;
}
} // namespace
namespace fuzzer {
// The rest is added for LibFuzzer
void ComputeSHA1(const uint8_t *Data, size_t Len, uint8_t *Out) {
sha1nfo s;
sha1_init(&s);
sha1_write(&s, (const char *)Data, Len);
memcpy(Out, sha1_result(&s), HASH_LENGTH);
}
std::string Sha1ToString(const uint8_t Sha1[kSHA1NumBytes]) {
std::stringstream SS;
for (int i = 0; i < kSHA1NumBytes; i++)
SS << std::hex << std::setfill('0') << std::setw(2) << (unsigned)Sha1[i];
return SS.str();
}
std::string Hash(const Unit &U) {
uint8_t Hash[kSHA1NumBytes];
ComputeSHA1(U.data(), U.size(), Hash);
return Sha1ToString(Hash);
}
} // namespace fuzzer

View File

@ -0,0 +1,32 @@
//===- FuzzerSHA1.h - Internal header for the SHA1 utils --------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// SHA1 utils.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_SHA1_H
#define LLVM_FUZZER_SHA1_H
#include "FuzzerDefs.h"
#include <cstddef>
#include <stdint.h>
namespace fuzzer {
// Private copy of SHA1 implementation.
static const int kSHA1NumBytes = 20;
// Computes SHA1 hash of 'Len' bytes in 'Data', writes kSHA1NumBytes to 'Out'.
void ComputeSHA1(const uint8_t *Data, size_t Len, uint8_t *Out);
std::string Sha1ToString(const uint8_t Sha1[kSHA1NumBytes]);
std::string Hash(const Unit &U);
} // namespace fuzzer
#endif // LLVM_FUZZER_SHA1_H

View File

@ -0,0 +1,819 @@
//===- FuzzerTracePC.cpp - PC tracing--------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Trace PCs.
// This module implements __sanitizer_cov_trace_pc_guard[_init],
// the callback required for -fsanitize-coverage=trace-pc-guard instrumentation.
//
//===----------------------------------------------------------------------===//
#include "FuzzerTracePC.h"
#include "FuzzerBuiltins.h"
#include "FuzzerBuiltinsMsvc.h"
#include "FuzzerCorpus.h"
#include "FuzzerDefs.h"
#include "FuzzerDictionary.h"
#include "FuzzerExtFunctions.h"
#include "FuzzerIO.h"
#include "FuzzerPlatform.h"
#include "FuzzerUtil.h"
#include "FuzzerValueBitMap.h"
#include <set>
// Used by -fsanitize-coverage=stack-depth to track stack depth
ATTRIBUTES_INTERFACE_TLS_INITIAL_EXEC uintptr_t __sancov_lowest_stack;
namespace fuzzer {
TracePC TPC;
size_t TracePC::GetTotalPCCoverage() {
return ObservedPCs.size();
}
void TracePC::HandleInline8bitCountersInit(uint8_t *Start, uint8_t *Stop) {
if (Start == Stop) return;
if (NumModules && Modules[NumModules - 1].Start() == Start) return;
assert(NumModules < sizeof(Modules) / sizeof(Modules[0]));
auto & M = Modules[NumModules++];
uint8_t *AlignedStart = RoundUpByPage(Start);
uint8_t *AlignedStop = RoundDownByPage(Stop);
size_t NumFullPages = AlignedStop > AlignedStart
? (AlignedStop - AlignedStart) / PageSize()
: 0;
bool NeedFirst = Start < AlignedStart || !NumFullPages;
bool NeedLast = Stop > AlignedStop && AlignedStop >= AlignedStart;
M.NumRegions = NumFullPages + NeedFirst + NeedLast;
;
assert(M.NumRegions > 0);
M.Regions = new Module::Region[M.NumRegions];
assert(M.Regions);
size_t R = 0;
if (NeedFirst)
M.Regions[R++] = {Start, std::min(Stop, AlignedStart), true, false};
for (uint8_t *P = AlignedStart; P < AlignedStop; P += PageSize())
M.Regions[R++] = {P, P + PageSize(), true, true};
if (NeedLast) M.Regions[R++] = {AlignedStop, Stop, true, false};
assert(R == M.NumRegions);
assert(M.Size() == (size_t)(Stop - Start));
assert(M.Stop() == Stop);
assert(M.Start() == Start);
NumInline8bitCounters += M.Size();
}
void TracePC::HandlePCsInit(const uintptr_t *Start, const uintptr_t *Stop) {
const PCTableEntry *B = reinterpret_cast<const PCTableEntry *>(Start);
const PCTableEntry *E = reinterpret_cast<const PCTableEntry *>(Stop);
if (NumPCTables && ModulePCTable[NumPCTables - 1].Start == B) return;
assert(NumPCTables < sizeof(ModulePCTable) / sizeof(ModulePCTable[0]));
ModulePCTable[NumPCTables++] = {B, E};
NumPCsInPCTables += E - B;
}
void TracePC::PrintModuleInfo() {
if (NumModules) {
Printf("INFO: Loaded %zd modules (%zd inline 8-bit counters): ",
NumModules, NumInline8bitCounters);
for (size_t i = 0; i < NumModules; i++)
Printf("%zd [%p, %p), ", Modules[i].Size(), Modules[i].Start(),
Modules[i].Stop());
Printf("\n");
}
if (NumPCTables) {
Printf("INFO: Loaded %zd PC tables (%zd PCs): ", NumPCTables,
NumPCsInPCTables);
for (size_t i = 0; i < NumPCTables; i++) {
Printf("%zd [%p,%p), ", ModulePCTable[i].Stop - ModulePCTable[i].Start,
ModulePCTable[i].Start, ModulePCTable[i].Stop);
}
Printf("\n");
if (NumInline8bitCounters && NumInline8bitCounters != NumPCsInPCTables) {
Printf(
"ERROR: The size of coverage PC tables does not match the\n"
"number of instrumented PCs. This might be a compiler bug,\n"
"please contact the libFuzzer developers.\n"
"Also check https://bugs.llvm.org/show_bug.cgi?id=34636\n"
"for possible workarounds (tl;dr: don't use the old GNU ld)\n");
_Exit(1);
}
}
if (size_t NumExtraCounters = ExtraCountersEnd() - ExtraCountersBegin())
Printf("INFO: %zd Extra Counters\n", NumExtraCounters);
}
ATTRIBUTE_NO_SANITIZE_ALL
void TracePC::HandleCallerCallee(uintptr_t Caller, uintptr_t Callee) {
const uintptr_t kBits = 12;
const uintptr_t kMask = (1 << kBits) - 1;
uintptr_t Idx = (Caller & kMask) | ((Callee & kMask) << kBits);
ValueProfileMap.AddValueModPrime(Idx);
}
/// \return the address of the previous instruction.
/// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.h`
inline ALWAYS_INLINE uintptr_t GetPreviousInstructionPc(uintptr_t PC) {
#if defined(__arm__)
// T32 (Thumb) branch instructions might be 16 or 32 bit long,
// so we return (pc-2) in that case in order to be safe.
// For A32 mode we return (pc-4) because all instructions are 32 bit long.
return (PC - 3) & (~1);
#elif defined(__powerpc__) || defined(__powerpc64__) || defined(__aarch64__)
// PCs are always 4 byte aligned.
return PC - 4;
#elif defined(__sparc__) || defined(__mips__)
return PC - 8;
#else
return PC - 1;
#endif
}
/// \return the address of the next instruction.
/// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.cpp`
ALWAYS_INLINE uintptr_t TracePC::GetNextInstructionPc(uintptr_t PC) {
#if defined(__mips__)
return PC + 8;
#elif defined(__powerpc__) || defined(__sparc__) || defined(__arm__) || \
defined(__aarch64__)
return PC + 4;
#else
return PC + 1;
#endif
}
void TracePC::UpdateObservedPCs() {
Vector<uintptr_t> CoveredFuncs;
auto ObservePC = [&](const PCTableEntry *TE) {
if (ObservedPCs.insert(TE).second && DoPrintNewPCs) {
PrintPC("\tNEW_PC: %p %F %L", "\tNEW_PC: %p",
GetNextInstructionPc(TE->PC));
Printf("\n");
}
};
auto Observe = [&](const PCTableEntry *TE) {
if (PcIsFuncEntry(TE))
if (++ObservedFuncs[TE->PC] == 1 && NumPrintNewFuncs)
CoveredFuncs.push_back(TE->PC);
ObservePC(TE);
};
if (NumPCsInPCTables) {
if (NumInline8bitCounters == NumPCsInPCTables) {
for (size_t i = 0; i < NumModules; i++) {
auto &M = Modules[i];
assert(M.Size() ==
(size_t)(ModulePCTable[i].Stop - ModulePCTable[i].Start));
for (size_t r = 0; r < M.NumRegions; r++) {
auto &R = M.Regions[r];
if (!R.Enabled) continue;
for (uint8_t *P = R.Start; P < R.Stop; P++)
if (*P) Observe(&ModulePCTable[i].Start[M.Idx(P)]);
}
}
}
}
for (size_t i = 0, N = Min(CoveredFuncs.size(), NumPrintNewFuncs); i < N;
i++) {
Printf("\tNEW_FUNC[%zd/%zd]: ", i + 1, CoveredFuncs.size());
PrintPC("%p %F %L", "%p", GetNextInstructionPc(CoveredFuncs[i]));
Printf("\n");
}
}
uintptr_t TracePC::PCTableEntryIdx(const PCTableEntry *TE) {
size_t TotalTEs = 0;
for (size_t i = 0; i < NumPCTables; i++) {
auto &M = ModulePCTable[i];
if (TE >= M.Start && TE < M.Stop) return TotalTEs + TE - M.Start;
TotalTEs += M.Stop - M.Start;
}
assert(0);
return 0;
}
const TracePC::PCTableEntry *TracePC::PCTableEntryByIdx(uintptr_t Idx) {
for (size_t i = 0; i < NumPCTables; i++) {
auto & M = ModulePCTable[i];
size_t Size = M.Stop - M.Start;
if (Idx < Size) return &M.Start[Idx];
Idx -= Size;
}
return nullptr;
}
static std::string GetModuleName(uintptr_t PC) {
char ModulePathRaw[4096] = ""; // What's PATH_MAX in portable C++?
void *OffsetRaw = nullptr;
if (!EF->__sanitizer_get_module_and_offset_for_pc(
reinterpret_cast<void *>(PC), ModulePathRaw, sizeof(ModulePathRaw),
&OffsetRaw))
return "";
return ModulePathRaw;
}
template <class CallBack>
void TracePC::IterateCoveredFunctions(CallBack CB) {
for (size_t i = 0; i < NumPCTables; i++) {
auto &M = ModulePCTable[i];
assert(M.Start < M.Stop);
auto ModuleName = GetModuleName(M.Start->PC);
for (auto NextFE = M.Start; NextFE < M.Stop;) {
auto FE = NextFE;
assert(PcIsFuncEntry(FE) && "Not a function entry point");
do {
NextFE++;
} while (NextFE < M.Stop && !(PcIsFuncEntry(NextFE)));
CB(FE, NextFE, ObservedFuncs[FE->PC]);
}
}
}
void TracePC::SetFocusFunction(const std::string &FuncName) {
// This function should be called once.
assert(!FocusFunctionCounterPtr);
// "auto" is not a valid function name. If this function is called with "auto"
// that means the auto focus functionality failed.
if (FuncName.empty() || FuncName == "auto") return;
for (size_t M = 0; M < NumModules; M++) {
auto & PCTE = ModulePCTable[M];
size_t N = PCTE.Stop - PCTE.Start;
for (size_t I = 0; I < N; I++) {
if (!(PcIsFuncEntry(&PCTE.Start[I]))) continue; // not a function entry.
auto Name = DescribePC("%F", GetNextInstructionPc(PCTE.Start[I].PC));
if (Name[0] == 'i' && Name[1] == 'n' && Name[2] == ' ')
Name = Name.substr(3, std::string::npos);
if (FuncName != Name) continue;
Printf("INFO: Focus function is set to '%s'\n", Name.c_str());
FocusFunctionCounterPtr = Modules[M].Start() + I;
return;
}
}
Printf(
"ERROR: Failed to set focus function. Make sure the function name is "
"valid (%s) and symbolization is enabled.\n",
FuncName.c_str());
exit(1);
}
bool TracePC::ObservedFocusFunction() {
return FocusFunctionCounterPtr && *FocusFunctionCounterPtr;
}
void TracePC::PrintCoverage() {
if (!EF->__sanitizer_symbolize_pc ||
!EF->__sanitizer_get_module_and_offset_for_pc) {
Printf(
"INFO: __sanitizer_symbolize_pc or "
"__sanitizer_get_module_and_offset_for_pc is not available,"
" not printing coverage\n");
return;
}
Printf("COVERAGE:\n");
auto CoveredFunctionCallback = [&](const PCTableEntry *First,
const PCTableEntry *Last,
uintptr_t Counter) {
assert(First < Last);
auto VisualizePC = GetNextInstructionPc(First->PC);
std::string FileStr = DescribePC("%s", VisualizePC);
if (!IsInterestingCoverageFile(FileStr)) return;
std::string FunctionStr = DescribePC("%F", VisualizePC);
if (FunctionStr.find("in ") == 0) FunctionStr = FunctionStr.substr(3);
std::string LineStr = DescribePC("%l", VisualizePC);
size_t NumEdges = Last - First;
Vector<uintptr_t> UncoveredPCs;
for (auto TE = First; TE < Last; TE++)
if (!ObservedPCs.count(TE)) UncoveredPCs.push_back(TE->PC);
Printf("%sCOVERED_FUNC: hits: %zd", Counter ? "" : "UN", Counter);
Printf(" edges: %zd/%zd", NumEdges - UncoveredPCs.size(), NumEdges);
Printf(" %s %s:%s\n", FunctionStr.c_str(), FileStr.c_str(),
LineStr.c_str());
if (Counter)
for (auto PC : UncoveredPCs)
Printf(" UNCOVERED_PC: %s\n",
DescribePC("%s:%l", GetNextInstructionPc(PC)).c_str());
};
IterateCoveredFunctions(CoveredFunctionCallback);
}
// Value profile.
// We keep track of various values that affect control flow.
// These values are inserted into a bit-set-based hash map.
// Every new bit in the map is treated as a new coverage.
//
// For memcmp/strcmp/etc the interesting value is the length of the common
// prefix of the parameters.
// For cmp instructions the interesting value is a XOR of the parameters.
// The interesting value is mixed up with the PC and is then added to the map.
ATTRIBUTE_NO_SANITIZE_ALL
void TracePC::AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
size_t n, bool StopAtZero) {
if (!n) return;
size_t Len = std::min(n, Word::GetMaxSize());
const uint8_t *A1 = reinterpret_cast<const uint8_t *>(s1);
const uint8_t *A2 = reinterpret_cast<const uint8_t *>(s2);
uint8_t B1[Word::kMaxSize];
uint8_t B2[Word::kMaxSize];
// Copy the data into locals in this non-msan-instrumented function
// to avoid msan complaining further.
size_t Hash = 0; // Compute some simple hash of both strings.
for (size_t i = 0; i < Len; i++) {
B1[i] = A1[i];
B2[i] = A2[i];
size_t T = B1[i];
Hash ^= (T << 8) | B2[i];
}
size_t I = 0;
uint8_t HammingDistance = 0;
for (; I < Len; I++) {
if (B1[I] != B2[I] || (StopAtZero && B1[I] == 0)) {
HammingDistance = Popcountll(B1[I] ^ B2[I]);
break;
}
}
size_t PC = reinterpret_cast<size_t>(caller_pc);
size_t Idx = (PC & 4095) | (I << 12);
Idx += HammingDistance;
ValueProfileMap.AddValue(Idx);
TORCW.Insert(Idx ^ Hash, Word(B1, Len), Word(B2, Len));
}
template <class T>
ATTRIBUTE_TARGET_POPCNT ALWAYS_INLINE ATTRIBUTE_NO_SANITIZE_ALL void
TracePC::HandleCmp(uintptr_t PC, T Arg1, T Arg2) {
uint64_t ArgXor = Arg1 ^ Arg2;
if (sizeof(T) == 4)
TORC4.Insert(ArgXor, Arg1, Arg2);
else if (sizeof(T) == 8)
TORC8.Insert(ArgXor, Arg1, Arg2);
uint64_t HammingDistance = Popcountll(ArgXor); // [0,64]
uint64_t AbsoluteDistance = (Arg1 == Arg2 ? 0 : Clzll(Arg1 - Arg2) + 1);
ValueProfileMap.AddValue(PC * 128 + HammingDistance);
ValueProfileMap.AddValue(PC * 128 + 64 + AbsoluteDistance);
}
static size_t InternalStrnlen(const char *S, size_t MaxLen) {
size_t Len = 0;
for (; Len < MaxLen && S[Len]; Len++) {}
return Len;
}
// Finds min of (strlen(S1), strlen(S2)).
// Needed bacause one of these strings may actually be non-zero terminated.
static size_t InternalStrnlen2(const char *S1, const char *S2) {
size_t Len = 0;
for (; S1[Len] && S2[Len]; Len++) {}
return Len;
}
void TracePC::ClearInlineCounters() {
IterateCounterRegions([](const Module::Region &R) {
if (R.Enabled) memset(R.Start, 0, R.Stop - R.Start);
});
}
ATTRIBUTE_NO_SANITIZE_ALL
void TracePC::RecordInitialStack() {
int stack;
__sancov_lowest_stack = InitialStack = reinterpret_cast<uintptr_t>(&stack);
}
uintptr_t TracePC::GetMaxStackOffset() const {
return InitialStack - __sancov_lowest_stack; // Stack grows down
}
void WarnAboutDeprecatedInstrumentation(const char *flag) {
// Use RawPrint because Printf cannot be used on Windows before OutputFile is
// initialized.
RawPrint(flag);
RawPrint(
" is no longer supported by libFuzzer.\n"
"Please either migrate to a compiler that supports -fsanitize=fuzzer\n"
"or use an older version of libFuzzer\n");
exit(1);
}
} // namespace fuzzer
extern "C" {
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
void __sanitizer_cov_trace_pc_guard(uint32_t *Guard) {
fuzzer::WarnAboutDeprecatedInstrumentation(
"-fsanitize-coverage=trace-pc-guard");
}
// Best-effort support for -fsanitize-coverage=trace-pc, which is available
// in both Clang and GCC.
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
void __sanitizer_cov_trace_pc() {
fuzzer::WarnAboutDeprecatedInstrumentation("-fsanitize-coverage=trace-pc");
}
ATTRIBUTE_INTERFACE
void __sanitizer_cov_trace_pc_guard_init(uint32_t *Start, uint32_t *Stop) {
fuzzer::WarnAboutDeprecatedInstrumentation(
"-fsanitize-coverage=trace-pc-guard");
}
ATTRIBUTE_INTERFACE
void __sanitizer_cov_8bit_counters_init(uint8_t *Start, uint8_t *Stop) {
fuzzer::TPC.HandleInline8bitCountersInit(Start, Stop);
}
ATTRIBUTE_INTERFACE
void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg,
const uintptr_t *pcs_end) {
fuzzer::TPC.HandlePCsInit(pcs_beg, pcs_end);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
void __sanitizer_cov_trace_pc_indir(uintptr_t Callee) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCallerCallee(PC, Callee);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_cmp8(uint64_t Arg1, uint64_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
// Now the __sanitizer_cov_trace_const_cmp[1248] callbacks just mimic
// the behaviour of __sanitizer_cov_trace_cmp[1248] ones. This, however,
// should be changed later to make full use of instrumentation.
void __sanitizer_cov_trace_const_cmp8(uint64_t Arg1, uint64_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_cmp4(uint32_t Arg1, uint32_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_const_cmp4(uint32_t Arg1, uint32_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_cmp2(uint16_t Arg1, uint16_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_const_cmp2(uint16_t Arg1, uint16_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_cmp1(uint8_t Arg1, uint8_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_const_cmp1(uint8_t Arg1, uint8_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) {
uint64_t N = Cases[0];
uint64_t ValSizeInBits = Cases[1];
uint64_t *Vals = Cases + 2;
// Skip the most common and the most boring case: all switch values are small.
// We may want to skip this at compile-time, but it will make the
// instrumentation less general.
if (Vals[N - 1] < 256) return;
// Also skip small inputs values, they won't give good signal.
if (Val < 256) return;
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
size_t i;
uint64_t Smaller = 0;
uint64_t Larger = ~(uint64_t)0;
// Find two switch values such that Smaller < Val < Larger.
// Use 0 and 0xfff..f as the defaults.
for (i = 0; i < N; i++) {
if (Val < Vals[i]) {
Larger = Vals[i];
break;
}
if (Val > Vals[i]) Smaller = Vals[i];
}
// Apply HandleCmp to {Val,Smaller} and {Val, Larger},
// use i as the PC modifier for HandleCmp.
if (ValSizeInBits == 16) {
fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint16_t>(Val),
(uint16_t)(Smaller));
fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint16_t>(Val),
(uint16_t)(Larger));
} else if (ValSizeInBits == 32) {
fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint32_t>(Val),
(uint32_t)(Smaller));
fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint32_t>(Val),
(uint32_t)(Larger));
} else {
fuzzer::TPC.HandleCmp(PC + 2 * i, Val, Smaller);
fuzzer::TPC.HandleCmp(PC + 2 * i + 1, Val, Larger);
}
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_div4(uint32_t Val) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Val, (uint32_t)0);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_div8(uint64_t Val) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Val, (uint64_t)0);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT
void __sanitizer_cov_trace_gep(uintptr_t Idx) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Idx, (uintptr_t)0);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2,
size_t n, int result) {
if (!fuzzer::RunningUserCallback) return;
if (result == 0) return; // No reason to mutate.
if (n <= 1) return; // Not interesting.
fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/ false);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_strncmp(void *caller_pc, const char *s1, const char *s2,
size_t n, int result) {
if (!fuzzer::RunningUserCallback) return;
if (result == 0) return; // No reason to mutate.
size_t Len1 = fuzzer::InternalStrnlen(s1, n);
size_t Len2 = fuzzer::InternalStrnlen(s2, n);
n = std::min(n, Len1);
n = std::min(n, Len2);
if (n <= 1) return; // Not interesting.
fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/ true);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_strcmp(void *caller_pc, const char *s1, const char *s2,
int result) {
if (!fuzzer::RunningUserCallback) return;
if (result == 0) return; // No reason to mutate.
size_t N = fuzzer::InternalStrnlen2(s1, s2);
if (N <= 1) return; // Not interesting.
fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, N, /*StopAtZero*/ true);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_strncasecmp(void *called_pc, const char *s1,
const char *s2, size_t n, int result) {
if (!fuzzer::RunningUserCallback) return;
return __sanitizer_weak_hook_strncmp(called_pc, s1, s2, n, result);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_strcasecmp(void *called_pc, const char *s1,
const char *s2, int result) {
if (!fuzzer::RunningUserCallback) return;
return __sanitizer_weak_hook_strcmp(called_pc, s1, s2, result);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_strstr(void *called_pc, const char *s1, const char *s2,
char *result) {
if (!fuzzer::RunningUserCallback) return;
fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), strlen(s2));
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_strcasestr(void *called_pc, const char *s1,
const char *s2, char *result) {
if (!fuzzer::RunningUserCallback) return;
fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), strlen(s2));
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void
__sanitizer_weak_hook_memmem(void *called_pc, const void *s1, size_t len1,
const void *s2, size_t len2, void *result) {
if (!fuzzer::RunningUserCallback) return;
fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), len2);
}
} // extern "C"

View File

@ -0,0 +1,291 @@
//===- FuzzerTracePC.h - Internal header for the Fuzzer ---------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// fuzzer::TracePC
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_TRACE_PC
#define LLVM_FUZZER_TRACE_PC
#include "FuzzerDefs.h"
#include "FuzzerDictionary.h"
#include "FuzzerValueBitMap.h"
#include <set>
#include <unordered_map>
namespace fuzzer {
// TableOfRecentCompares (TORC) remembers the most recently performed
// comparisons of type T.
// We record the arguments of CMP instructions in this table unconditionally
// because it seems cheaper this way than to compute some expensive
// conditions inside __sanitizer_cov_trace_cmp*.
// After the unit has been executed we may decide to use the contents of
// this table to populate a Dictionary.
template<class T, size_t kSizeT>
struct TableOfRecentCompares {
static const size_t kSize = kSizeT;
struct Pair {
T A, B;
};
ATTRIBUTE_NO_SANITIZE_ALL
void Insert(size_t Idx, const T &Arg1, const T &Arg2) {
Idx = Idx % kSize;
Table[Idx].A = Arg1;
Table[Idx].B = Arg2;
}
Pair Get(size_t I) { return Table[I % kSize]; }
Pair Table[kSize];
};
template <size_t kSizeT>
struct MemMemTable {
static const size_t kSize = kSizeT;
Word MemMemWords[kSize];
Word EmptyWord;
void Add(const uint8_t *Data, size_t Size) {
if (Size <= 2) return;
Size = std::min(Size, Word::GetMaxSize());
size_t Idx = SimpleFastHash(Data, Size) % kSize;
MemMemWords[Idx].Set(Data, Size);
}
const Word &Get(size_t Idx) {
for (size_t i = 0; i < kSize; i++) {
const Word &W = MemMemWords[(Idx + i) % kSize];
if (W.size()) return W;
}
EmptyWord.Set(nullptr, 0);
return EmptyWord;
}
};
class TracePC {
public:
void HandleInline8bitCountersInit(uint8_t *Start, uint8_t *Stop);
void HandlePCsInit(const uintptr_t *Start, const uintptr_t *Stop);
void HandleCallerCallee(uintptr_t Caller, uintptr_t Callee);
template <class T> void HandleCmp(uintptr_t PC, T Arg1, T Arg2);
size_t GetTotalPCCoverage();
void SetUseCounters(bool UC) { UseCounters = UC; }
void SetUseValueProfileMask(uint32_t VPMask) { UseValueProfileMask = VPMask; }
void SetPrintNewPCs(bool P) { DoPrintNewPCs = P; }
void SetPrintNewFuncs(size_t P) { NumPrintNewFuncs = P; }
void UpdateObservedPCs();
template <class Callback> void CollectFeatures(Callback CB) const;
void ResetMaps() {
ValueProfileMap.Reset();
ClearExtraCounters();
ClearInlineCounters();
}
void ClearInlineCounters();
void UpdateFeatureSet(size_t CurrentElementIdx, size_t CurrentElementSize);
void PrintFeatureSet();
void PrintModuleInfo();
void PrintCoverage();
template<class CallBack>
void IterateCoveredFunctions(CallBack CB);
void AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
size_t n, bool StopAtZero);
TableOfRecentCompares<uint32_t, 32> TORC4;
TableOfRecentCompares<uint64_t, 32> TORC8;
TableOfRecentCompares<Word, 32> TORCW;
MemMemTable<1024> MMT;
void RecordInitialStack();
uintptr_t GetMaxStackOffset() const;
template<class CallBack>
void ForEachObservedPC(CallBack CB) {
for (auto PC : ObservedPCs)
CB(PC);
}
void SetFocusFunction(const std::string &FuncName);
bool ObservedFocusFunction();
struct PCTableEntry {
uintptr_t PC, PCFlags;
};
uintptr_t PCTableEntryIdx(const PCTableEntry *TE);
const PCTableEntry *PCTableEntryByIdx(uintptr_t Idx);
static uintptr_t GetNextInstructionPc(uintptr_t PC);
bool PcIsFuncEntry(const PCTableEntry *TE) { return TE->PCFlags & 1; }
private:
bool UseCounters = false;
uint32_t UseValueProfileMask = false;
bool DoPrintNewPCs = false;
size_t NumPrintNewFuncs = 0;
// Module represents the array of 8-bit counters split into regions
// such that every region, except maybe the first and the last one, is one
// full page.
struct Module {
struct Region {
uint8_t *Start, *Stop;
bool Enabled;
bool OneFullPage;
};
Region *Regions;
size_t NumRegions;
uint8_t *Start() const { return Regions[0].Start; }
uint8_t *Stop() const { return Regions[NumRegions - 1].Stop; }
size_t Size() const { return Stop() - Start(); }
size_t Idx(uint8_t *P) const {
assert(P >= Start() && P < Stop());
return P - Start();
}
};
Module Modules[4096];
size_t NumModules; // linker-initialized.
size_t NumInline8bitCounters;
template <class Callback>
void IterateCounterRegions(Callback CB) {
for (size_t m = 0; m < NumModules; m++)
for (size_t r = 0; r < Modules[m].NumRegions; r++)
CB(Modules[m].Regions[r]);
}
struct { const PCTableEntry *Start, *Stop; } ModulePCTable[4096];
size_t NumPCTables;
size_t NumPCsInPCTables;
Set<const PCTableEntry*> ObservedPCs;
std::unordered_map<uintptr_t, uintptr_t> ObservedFuncs; // PC => Counter.
uint8_t *FocusFunctionCounterPtr = nullptr;
ValueBitMap ValueProfileMap;
uintptr_t InitialStack;
};
template <class Callback>
// void Callback(size_t FirstFeature, size_t Idx, uint8_t Value);
ATTRIBUTE_NO_SANITIZE_ALL
size_t ForEachNonZeroByte(const uint8_t *Begin, const uint8_t *End,
size_t FirstFeature, Callback Handle8bitCounter) {
typedef uintptr_t LargeType;
const size_t Step = sizeof(LargeType) / sizeof(uint8_t);
const size_t StepMask = Step - 1;
auto P = Begin;
// Iterate by 1 byte until either the alignment boundary or the end.
for (; reinterpret_cast<uintptr_t>(P) & StepMask && P < End; P++)
if (uint8_t V = *P)
Handle8bitCounter(FirstFeature, P - Begin, V);
// Iterate by Step bytes at a time.
for (; P < End; P += Step)
if (LargeType Bundle = *reinterpret_cast<const LargeType *>(P)) {
Bundle = HostToLE(Bundle);
for (size_t I = 0; I < Step; I++, Bundle >>= 8)
if (uint8_t V = Bundle & 0xff)
Handle8bitCounter(FirstFeature, P - Begin + I, V);
}
// Iterate by 1 byte until the end.
for (; P < End; P++)
if (uint8_t V = *P)
Handle8bitCounter(FirstFeature, P - Begin, V);
return End - Begin;
}
// Given a non-zero Counter returns a number in the range [0,7].
template<class T>
unsigned CounterToFeature(T Counter) {
// Returns a feature number by placing Counters into buckets as illustrated
// below.
//
// Counter bucket: [1] [2] [3] [4-7] [8-15] [16-31] [32-127] [128+]
// Feature number: 0 1 2 3 4 5 6 7
//
// This is a heuristic taken from AFL (see
// http://lcamtuf.coredump.cx/afl/technical_details.txt).
//
// This implementation may change in the future so clients should
// not rely on it.
assert(Counter);
unsigned Bit = 0;
/**/ if (Counter >= 128) Bit = 7;
else if (Counter >= 32) Bit = 6;
else if (Counter >= 16) Bit = 5;
else if (Counter >= 8) Bit = 4;
else if (Counter >= 4) Bit = 3;
else if (Counter >= 3) Bit = 2;
else if (Counter >= 2) Bit = 1;
return Bit;
}
template <class Callback> // void Callback(size_t Feature)
ATTRIBUTE_NO_SANITIZE_ADDRESS
ATTRIBUTE_NOINLINE
void TracePC::CollectFeatures(Callback HandleFeature) const {
auto Handle8bitCounter = [&](size_t FirstFeature,
size_t Idx, uint8_t Counter) {
if (UseCounters)
HandleFeature(FirstFeature + Idx * 8 + CounterToFeature(Counter));
else
HandleFeature(FirstFeature + Idx);
};
size_t FirstFeature = 0;
for (size_t i = 0; i < NumModules; i++) {
for (size_t r = 0; r < Modules[i].NumRegions; r++) {
if (!Modules[i].Regions[r].Enabled) continue;
FirstFeature += 8 * ForEachNonZeroByte(Modules[i].Regions[r].Start,
Modules[i].Regions[r].Stop,
FirstFeature, Handle8bitCounter);
}
}
FirstFeature +=
8 * ForEachNonZeroByte(ExtraCountersBegin(), ExtraCountersEnd(),
FirstFeature, Handle8bitCounter);
if (UseValueProfileMask) {
ValueProfileMap.ForEach([&](size_t Idx) {
HandleFeature(FirstFeature + Idx);
});
FirstFeature += ValueProfileMap.SizeInBits();
}
// Step function, grows similar to 8 * Log_2(A).
auto StackDepthStepFunction = [](uint32_t A) -> uint32_t {
if (!A) return A;
uint32_t Log2 = Log(A);
if (Log2 < 3) return A;
Log2 -= 3;
return (Log2 + 1) * 8 + ((A >> Log2) & 7);
};
assert(StackDepthStepFunction(1024) == 64);
assert(StackDepthStepFunction(1024 * 4) == 80);
assert(StackDepthStepFunction(1024 * 1024) == 144);
if (auto MaxStackOffset = GetMaxStackOffset())
HandleFeature(FirstFeature + StackDepthStepFunction(MaxStackOffset / 8));
}
extern TracePC TPC;
} // namespace fuzzer
#endif // LLVM_FUZZER_TRACE_PC

View File

@ -0,0 +1,314 @@
//===- FuzzerUtil.cpp - Misc utils ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Misc utils.
//===----------------------------------------------------------------------===//
#include "FuzzerUtil.h"
#include "FuzzerIO.h"
#include "FuzzerInternal.h"
#include <cassert>
#include <chrono>
#include <cstring>
#include <errno.h>
#include <mutex>
#include <signal.h>
#include <sstream>
#include <stdio.h>
#include <sys/types.h>
#include <thread>
namespace fuzzer {
void PrintHexArray(const uint8_t *Data, size_t Size, const char *PrintAfter) {
for (size_t i = 0; i < Size; i++)
Printf("0x%x,", (unsigned)Data[i]);
Printf("%s", PrintAfter);
}
void Print(const Unit &v, const char *PrintAfter) {
PrintHexArray(v.data(), v.size(), PrintAfter);
}
void PrintASCIIByte(uint8_t Byte) {
if (Byte == '\\')
Printf("\\\\");
else if (Byte == '"')
Printf("\\\"");
else if (Byte >= 32 && Byte < 127)
Printf("%c", Byte);
else
Printf("\\x%02x", Byte);
}
void PrintASCII(const uint8_t *Data, size_t Size, const char *PrintAfter) {
for (size_t i = 0; i < Size; i++)
PrintASCIIByte(Data[i]);
Printf("%s", PrintAfter);
}
void PrintASCII(const Unit &U, const char *PrintAfter) {
PrintASCII(U.data(), U.size(), PrintAfter);
}
bool ToASCII(uint8_t *Data, size_t Size) {
bool Changed = false;
for (size_t i = 0; i < Size; i++) {
uint8_t &X = Data[i];
auto NewX = X;
NewX &= 127;
if (!isspace(NewX) && !isprint(NewX)) NewX = ' ';
Changed |= NewX != X;
X = NewX;
}
return Changed;
}
bool IsASCII(const Unit &U) {
return IsASCII(U.data(), U.size());
}
bool IsASCII(const uint8_t *Data, size_t Size) {
for (size_t i = 0; i < Size; i++)
if (!(isprint(Data[i]) || isspace(Data[i]))) return false;
return true;
}
bool ParseOneDictionaryEntry(const std::string &Str, Unit *U) {
U->clear();
if (Str.empty()) return false;
size_t L = 0, R = Str.size() - 1; // We are parsing the range [L,R].
// Skip spaces from both sides.
while (L < R && isspace(Str[L]))
L++;
while (R > L && isspace(Str[R]))
R--;
if (R - L < 2) return false;
// Check the closing "
if (Str[R] != '"') return false;
R--;
// Find the opening "
while (L < R && Str[L] != '"')
L++;
if (L >= R) return false;
assert(Str[L] == '\"');
L++;
assert(L <= R);
for (size_t Pos = L; Pos <= R; Pos++) {
uint8_t V = (uint8_t)Str[Pos];
if (!isprint(V) && !isspace(V)) return false;
if (V == '\\') {
// Handle '\\'
if (Pos + 1 <= R && (Str[Pos + 1] == '\\' || Str[Pos + 1] == '"')) {
U->push_back(Str[Pos + 1]);
Pos++;
continue;
}
// Handle '\xAB'
if (Pos + 3 <= R && Str[Pos + 1] == 'x' && isxdigit(Str[Pos + 2]) &&
isxdigit(Str[Pos + 3])) {
char Hex[] = "0xAA";
Hex[2] = Str[Pos + 2];
Hex[3] = Str[Pos + 3];
U->push_back(strtol(Hex, nullptr, 16));
Pos += 3;
continue;
}
return false; // Invalid escape.
} else {
// Any other character.
U->push_back(V);
}
}
return true;
}
bool ParseDictionaryFile(const std::string &Text, Vector<Unit> *Units) {
if (Text.empty()) {
Printf("ParseDictionaryFile: file does not exist or is empty\n");
return false;
}
std::istringstream ISS(Text);
Units->clear();
Unit U;
int LineNo = 0;
std::string S;
while (std::getline(ISS, S, '\n')) {
LineNo++;
size_t Pos = 0;
while (Pos < S.size() && isspace(S[Pos]))
Pos++; // Skip spaces.
if (Pos == S.size()) continue; // Empty line.
if (S[Pos] == '#') continue; // Comment line.
if (ParseOneDictionaryEntry(S, &U)) {
Units->push_back(U);
} else {
Printf("ParseDictionaryFile: error in line %d\n\t\t%s\n", LineNo,
S.c_str());
return false;
}
}
return true;
}
// Code duplicated (and tested) in llvm/include/llvm/Support/Base64.h
std::string Base64(const Unit &U) {
static const char Table[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string Buffer;
Buffer.resize(((U.size() + 2) / 3) * 4);
size_t i = 0, j = 0;
for (size_t n = U.size() / 3 * 3; i < n; i += 3, j += 4) {
uint32_t x = ((unsigned char)U[i] << 16) | ((unsigned char)U[i + 1] << 8) |
(unsigned char)U[i + 2];
Buffer[j + 0] = Table[(x >> 18) & 63];
Buffer[j + 1] = Table[(x >> 12) & 63];
Buffer[j + 2] = Table[(x >> 6) & 63];
Buffer[j + 3] = Table[x & 63];
}
if (i + 1 == U.size()) {
uint32_t x = ((unsigned char)U[i] << 16);
Buffer[j + 0] = Table[(x >> 18) & 63];
Buffer[j + 1] = Table[(x >> 12) & 63];
Buffer[j + 2] = '=';
Buffer[j + 3] = '=';
} else if (i + 2 == U.size()) {
uint32_t x = ((unsigned char)U[i] << 16) | ((unsigned char)U[i + 1] << 8);
Buffer[j + 0] = Table[(x >> 18) & 63];
Buffer[j + 1] = Table[(x >> 12) & 63];
Buffer[j + 2] = Table[(x >> 6) & 63];
Buffer[j + 3] = '=';
}
return Buffer;
}
static std::mutex SymbolizeMutex;
std::string DescribePC(const char *SymbolizedFMT, uintptr_t PC) {
std::unique_lock<std::mutex> l(SymbolizeMutex, std::try_to_lock);
if (!EF->__sanitizer_symbolize_pc || !l.owns_lock())
return "<can not symbolize>";
char PcDescr[1024] = {};
EF->__sanitizer_symbolize_pc(reinterpret_cast<void *>(PC), SymbolizedFMT,
PcDescr, sizeof(PcDescr));
PcDescr[sizeof(PcDescr) - 1] = 0; // Just in case.
return PcDescr;
}
void PrintPC(const char *SymbolizedFMT, const char *FallbackFMT, uintptr_t PC) {
if (EF->__sanitizer_symbolize_pc)
Printf("%s", DescribePC(SymbolizedFMT, PC).c_str());
else
Printf(FallbackFMT, PC);
}
void PrintStackTrace() {
std::unique_lock<std::mutex> l(SymbolizeMutex, std::try_to_lock);
if (EF->__sanitizer_print_stack_trace && l.owns_lock())
EF->__sanitizer_print_stack_trace();
}
void PrintMemoryProfile() {
std::unique_lock<std::mutex> l(SymbolizeMutex, std::try_to_lock);
if (EF->__sanitizer_print_memory_profile && l.owns_lock())
EF->__sanitizer_print_memory_profile(95, 8);
}
unsigned NumberOfCpuCores() {
unsigned N = std::thread::hardware_concurrency();
if (!N) {
Printf(
"WARNING: std::thread::hardware_concurrency not well defined for "
"your platform. Assuming CPU count of 1.\n");
N = 1;
}
return N;
}
size_t SimpleFastHash(const uint8_t *Data, size_t Size) {
size_t Res = 0;
for (size_t i = 0; i < Size; i++)
Res = Res * 11 + Data[i];
return Res;
}
} // namespace fuzzer

View File

@ -0,0 +1,117 @@
//===- FuzzerUtil.h - Internal header for the Fuzzer Utils ------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Util functions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_UTIL_H
#define LLVM_FUZZER_UTIL_H
#include "FuzzerBuiltins.h"
#include "FuzzerBuiltinsMsvc.h"
#include "FuzzerCommand.h"
#include "FuzzerDefs.h"
namespace fuzzer {
void PrintHexArray(const Unit &U, const char *PrintAfter = "");
void PrintHexArray(const uint8_t *Data, size_t Size,
const char *PrintAfter = "");
void PrintASCII(const uint8_t *Data, size_t Size, const char *PrintAfter = "");
void PrintASCII(const Unit &U, const char *PrintAfter = "");
// Changes U to contain only ASCII (isprint+isspace) characters.
// Returns true iff U has been changed.
bool ToASCII(uint8_t *Data, size_t Size);
bool IsASCII(const Unit &U);
bool IsASCII(const uint8_t *Data, size_t Size);
std::string Base64(const Unit &U);
void PrintPC(const char *SymbolizedFMT, const char *FallbackFMT, uintptr_t PC);
std::string DescribePC(const char *SymbolizedFMT, uintptr_t PC);
void PrintStackTrace();
void PrintMemoryProfile();
unsigned NumberOfCpuCores();
// Platform specific functions.
void SetSignalHandler(const FuzzingOptions& Options);
void SleepSeconds(int Seconds);
unsigned long GetPid();
size_t GetPeakRSSMb();
int ExecuteCommand(const Command &Cmd);
bool ExecuteCommand(const Command &Cmd, std::string *CmdOutput);
// Fuchsia does not have popen/pclose.
FILE *OpenProcessPipe(const char *Command, const char *Mode);
int CloseProcessPipe(FILE *F);
const void *SearchMemory(const void *haystack, size_t haystacklen,
const void *needle, size_t needlelen);
std::string CloneArgsWithoutX(const Vector<std::string> &Args,
const char *X1, const char *X2);
inline std::string CloneArgsWithoutX(const Vector<std::string> &Args,
const char *X) {
return CloneArgsWithoutX(Args, X, X);
}
inline std::pair<std::string, std::string> SplitBefore(std::string X,
std::string S) {
auto Pos = S.find(X);
if (Pos == std::string::npos)
return std::make_pair(S, "");
return std::make_pair(S.substr(0, Pos), S.substr(Pos));
}
void DiscardOutput(int Fd);
std::string DisassembleCmd(const std::string &FileName);
std::string SearchRegexCmd(const std::string &Regex);
size_t SimpleFastHash(const uint8_t *Data, size_t Size);
inline uint32_t Log(uint32_t X) { return 32 - Clz(X) - 1; }
inline size_t PageSize() { return 4096; }
inline uint8_t *RoundUpByPage(uint8_t *P) {
uintptr_t X = reinterpret_cast<uintptr_t>(P);
size_t Mask = PageSize() - 1;
X = (X + Mask) & ~Mask;
return reinterpret_cast<uint8_t *>(X);
}
inline uint8_t *RoundDownByPage(uint8_t *P) {
uintptr_t X = reinterpret_cast<uintptr_t>(P);
size_t Mask = PageSize() - 1;
X = X & ~Mask;
return reinterpret_cast<uint8_t *>(X);
}
#if __BYTE_ORDER == __LITTLE_ENDIAN
template <typename T> T HostToLE(T X) { return X; }
#else
template <typename T> T HostToLE(T X) { return Bswap(X); }
#endif
} // namespace fuzzer
#endif // LLVM_FUZZER_UTIL_H

View File

@ -0,0 +1,205 @@
//===- FuzzerUtilDarwin.cpp - Misc utils ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Misc utils for Darwin.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_APPLE
#include "FuzzerCommand.h"
#include "FuzzerIO.h"
#include <mutex>
#include <signal.h>
#include <spawn.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
// There is no header for this on macOS so declare here
extern "C" char **environ;
namespace fuzzer {
static std::mutex SignalMutex;
// Global variables used to keep track of how signal handling should be
// restored. They should **not** be accessed without holding `SignalMutex`.
static int ActiveThreadCount = 0;
static struct sigaction OldSigIntAction;
static struct sigaction OldSigQuitAction;
static sigset_t OldBlockedSignalsSet;
// This is a reimplementation of Libc's `system()`. On Darwin the Libc
// implementation contains a mutex which prevents it from being used
// concurrently. This implementation **can** be used concurrently. It sets the
// signal handlers when the first thread enters and restores them when the last
// thread finishes execution of the function and ensures this is not racey by
// using a mutex.
int ExecuteCommand(const Command &Cmd) {
std::string CmdLine = Cmd.toString();
posix_spawnattr_t SpawnAttributes;
if (posix_spawnattr_init(&SpawnAttributes)) return -1;
// Block and ignore signals of the current process when the first thread
// enters.
{
std::lock_guard<std::mutex> Lock(SignalMutex);
if (ActiveThreadCount == 0) {
static struct sigaction IgnoreSignalAction;
sigset_t BlockedSignalsSet;
memset(&IgnoreSignalAction, 0, sizeof(IgnoreSignalAction));
IgnoreSignalAction.sa_handler = SIG_IGN;
if (sigaction(SIGINT, &IgnoreSignalAction, &OldSigIntAction) == -1) {
Printf("Failed to ignore SIGINT\n");
(void)posix_spawnattr_destroy(&SpawnAttributes);
return -1;
}
if (sigaction(SIGQUIT, &IgnoreSignalAction, &OldSigQuitAction) == -1) {
Printf("Failed to ignore SIGQUIT\n");
// Try our best to restore the signal handlers.
(void)sigaction(SIGINT, &OldSigIntAction, NULL);
(void)posix_spawnattr_destroy(&SpawnAttributes);
return -1;
}
(void)sigemptyset(&BlockedSignalsSet);
(void)sigaddset(&BlockedSignalsSet, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &BlockedSignalsSet, &OldBlockedSignalsSet) ==
-1) {
Printf("Failed to block SIGCHLD\n");
// Try our best to restore the signal handlers.
(void)sigaction(SIGQUIT, &OldSigQuitAction, NULL);
(void)sigaction(SIGINT, &OldSigIntAction, NULL);
(void)posix_spawnattr_destroy(&SpawnAttributes);
return -1;
}
}
++ActiveThreadCount;
}
// NOTE: Do not introduce any new `return` statements past this
// point. It is important that `ActiveThreadCount` always be decremented
// when leaving this function.
// Make sure the child process uses the default handlers for the
// following signals rather than inheriting what the parent has.
sigset_t DefaultSigSet;
(void)sigemptyset(&DefaultSigSet);
(void)sigaddset(&DefaultSigSet, SIGQUIT);
(void)sigaddset(&DefaultSigSet, SIGINT);
(void)posix_spawnattr_setsigdefault(&SpawnAttributes, &DefaultSigSet);
// Make sure the child process doesn't block SIGCHLD
(void)posix_spawnattr_setsigmask(&SpawnAttributes, &OldBlockedSignalsSet);
short SpawnFlags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
(void)posix_spawnattr_setflags(&SpawnAttributes, SpawnFlags);
pid_t Pid;
char ** Environ = environ; // Read from global
const char *CommandCStr = CmdLine.c_str();
char *const Argv[] = {strdup("sh"), strdup("-c"), strdup(CommandCStr), NULL};
int ErrorCode = 0, ProcessStatus = 0;
// FIXME: We probably shouldn't hardcode the shell path.
ErrorCode =
posix_spawn(&Pid, "/bin/sh", NULL, &SpawnAttributes, Argv, Environ);
(void)posix_spawnattr_destroy(&SpawnAttributes);
if (!ErrorCode) {
pid_t SavedPid = Pid;
do {
// Repeat until call completes uninterrupted.
Pid = waitpid(SavedPid, &ProcessStatus, /*options=*/0);
} while (Pid == -1 && errno == EINTR);
if (Pid == -1) {
// Fail for some other reason.
ProcessStatus = -1;
}
} else if (ErrorCode == ENOMEM || ErrorCode == EAGAIN) {
// Fork failure.
ProcessStatus = -1;
} else {
// Shell execution failure.
ProcessStatus = W_EXITCODE(127, 0);
}
for (unsigned i = 0, n = sizeof(Argv) / sizeof(Argv[0]); i < n; ++i)
free(Argv[i]);
// Restore the signal handlers of the current process when the last thread
// using this function finishes.
{
std::lock_guard<std::mutex> Lock(SignalMutex);
--ActiveThreadCount;
if (ActiveThreadCount == 0) {
bool FailedRestore = false;
if (sigaction(SIGINT, &OldSigIntAction, NULL) == -1) {
Printf("Failed to restore SIGINT handling\n");
FailedRestore = true;
}
if (sigaction(SIGQUIT, &OldSigQuitAction, NULL) == -1) {
Printf("Failed to restore SIGQUIT handling\n");
FailedRestore = true;
}
if (sigprocmask(SIG_BLOCK, &OldBlockedSignalsSet, NULL) == -1) {
Printf("Failed to unblock SIGCHLD\n");
FailedRestore = true;
}
if (FailedRestore) ProcessStatus = -1;
}
}
return ProcessStatus;
}
void DiscardOutput(int Fd) {
FILE *Temp = fopen("/dev/null", "w");
if (!Temp) return;
dup2(fileno(Temp), Fd);
fclose(Temp);
}
} // namespace fuzzer
#endif // LIBFUZZER_APPLE

View File

@ -0,0 +1,658 @@
//===- FuzzerUtilFuchsia.cpp - Misc utils for Fuchsia. --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Misc utils implementation using Fuchsia/Zircon APIs.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_FUCHSIA
#include "FuzzerInternal.h"
#include "FuzzerUtil.h"
#include <cassert>
#include <cerrno>
#include <cinttypes>
#include <cstdint>
#include <fcntl.h>
#include <lib/fdio/fdio.h>
#include <lib/fdio/spawn.h>
#include <string>
#include <sys/select.h>
#include <thread>
#include <unistd.h>
#include <zircon/errors.h>
#include <zircon/process.h>
#include <zircon/sanitizer.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/debug.h>
#include <zircon/syscalls/exception.h>
#include <zircon/syscalls/object.h>
#include <zircon/types.h>
#include <vector>
namespace fuzzer {
// Given that Fuchsia doesn't have the POSIX signals that libFuzzer was written
// around, the general approach is to spin up dedicated threads to watch for
// each requested condition (alarm, interrupt, crash). Of these, the crash
// handler is the most involved, as it requires resuming the crashed thread in
// order to invoke the sanitizers to get the needed state.
// Forward declaration of assembly trampoline needed to resume crashed threads.
// This appears to have external linkage to C++, which is why it's not in the
// anonymous namespace. The assembly definition inside MakeTrampoline()
// actually defines the symbol with internal linkage only.
void CrashTrampolineAsm() __asm__("CrashTrampolineAsm");
namespace {
// Helper function to handle Zircon syscall failures.
void ExitOnErr(zx_status_t Status, const char *Syscall) {
if (Status != ZX_OK) {
Printf("libFuzzer: %s failed: %s\n", Syscall,
_zx_status_get_string(Status));
exit(1);
}
}
void AlarmHandler(int Seconds) {
while (true) {
SleepSeconds(Seconds);
Fuzzer::StaticAlarmCallback();
}
}
void InterruptHandler() {
fd_set readfds;
// Ctrl-C sends ETX in Zircon.
do {
FD_ZERO(&readfds);
FD_SET(STDIN_FILENO, &readfds);
select(STDIN_FILENO + 1, &readfds, nullptr, nullptr, nullptr);
} while (!FD_ISSET(STDIN_FILENO, &readfds) || getchar() != 0x03);
Fuzzer::StaticInterruptCallback();
}
// CFAOffset is used to reference the stack pointer before entering the
// trampoline (Stack Pointer + CFAOffset = prev Stack Pointer). Before jumping
// to the trampoline we copy all the registers onto the stack. We need to make
// sure that the new stack has enough space to store all the registers.
//
// The trampoline holds CFI information regarding the registers stored in the
// stack, which is then used by the unwinder to restore them.
#if defined(__x86_64__)
// In x86_64 the crashing function might also be using the red zone (128 bytes
// on top of their rsp).
constexpr size_t CFAOffset = 128 + sizeof(zx_thread_state_general_regs_t);
#elif defined(__aarch64__)
// In aarch64 we need to always have the stack pointer aligned to 16 bytes, so
// we make sure that we are keeping that same alignment.
constexpr size_t CFAOffset =
(sizeof(zx_thread_state_general_regs_t) + 15) & -(uintptr_t)16;
#endif
// For the crash handler, we need to call Fuzzer::StaticCrashSignalCallback
// without POSIX signal handlers. To achieve this, we use an assembly
// function to add the necessary CFI unwinding information and a C function to
// bridge from that back into C++.
// FIXME: This works as a short-term solution, but this code really shouldn't
// be architecture dependent. A better long term solution is to implement
// remote unwinding and expose the necessary APIs through sanitizer_common
// and/or ASAN to allow the exception handling thread to gather the crash
// state directly.
//
// Alternatively, Fuchsia may in future actually implement basic signal
// handling for the machine trap signals.
#if defined(__x86_64__)
#define FOREACH_REGISTER(OP_REG, OP_NUM) \
OP_REG(rax) \
OP_REG(rbx) \
OP_REG(rcx) \
OP_REG(rdx) \
OP_REG(rsi) \
OP_REG(rdi) \
OP_REG(rbp) \
OP_REG(rsp) \
OP_REG(r8) \
OP_REG(r9) \
OP_REG(r10) \
OP_REG(r11) \
OP_REG(r12) \
OP_REG(r13) \
OP_REG(r14) \
OP_REG(r15) \
OP_REG(rip)
#elif defined(__aarch64__)
#define FOREACH_REGISTER(OP_REG, OP_NUM) \
OP_NUM(0) \
OP_NUM(1) \
OP_NUM(2) \
OP_NUM(3) \
OP_NUM(4) \
OP_NUM(5) \
OP_NUM(6) \
OP_NUM(7) \
OP_NUM(8) \
OP_NUM(9) \
OP_NUM(10) \
OP_NUM(11) \
OP_NUM(12) \
OP_NUM(13) \
OP_NUM(14) \
OP_NUM(15) \
OP_NUM(16) \
OP_NUM(17) \
OP_NUM(18) \
OP_NUM(19) \
OP_NUM(20) \
OP_NUM(21) \
OP_NUM(22) \
OP_NUM(23) \
OP_NUM(24) \
OP_NUM(25) \
OP_NUM(26) \
OP_NUM(27) \
OP_NUM(28) \
OP_NUM(29) \
OP_REG(sp)
#else
#error "Unsupported architecture for fuzzing on Fuchsia"
#endif
// Produces a CFI directive for the named or numbered register.
// The value used refers to an assembler immediate operand with the same name
// as the register (see ASM_OPERAND_REG).
#define CFI_OFFSET_REG(reg) ".cfi_offset " #reg ", %c[" #reg "]\n"
#define CFI_OFFSET_NUM(num) CFI_OFFSET_REG(x##num)
// Produces an assembler immediate operand for the named or numbered register.
// This operand contains the offset of the register relative to the CFA.
#define ASM_OPERAND_REG(reg) \
[reg] "i"(offsetof(zx_thread_state_general_regs_t, reg) - CFAOffset),
#define ASM_OPERAND_NUM(num) \
[x##num] "i"(offsetof(zx_thread_state_general_regs_t, r[num]) - CFAOffset),
// Trampoline to bridge from the assembly below to the static C++ crash
// callback.
__attribute__((noreturn)) static void StaticCrashHandler() {
Fuzzer::StaticCrashSignalCallback();
for (;;) {
_Exit(1);
}
}
// Creates the trampoline with the necessary CFI information to unwind through
// to the crashing call stack:
// * Defining the CFA so that it points to the stack pointer at the point
// of crash.
// * Storing all registers at the point of crash in the stack and refer to them
// via CFI information (relative to the CFA).
// * Setting the return column so the unwinder knows how to continue unwinding.
// * (x86_64) making sure rsp is aligned before calling StaticCrashHandler.
// * Calling StaticCrashHandler that will trigger the unwinder.
//
// The __attribute__((used)) is necessary because the function
// is never called; it's just a container around the assembly to allow it to
// use operands for compile-time computed constants.
__attribute__((used)) void MakeTrampoline() {
__asm__(".cfi_endproc\n"
".pushsection .text.CrashTrampolineAsm\n"
".type CrashTrampolineAsm,STT_FUNC\n"
"CrashTrampolineAsm:\n"
".cfi_startproc simple\n"
".cfi_signal_frame\n"
#if defined(__x86_64__)
".cfi_return_column rip\n"
".cfi_def_cfa rsp, %c[CFAOffset]\n"
FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
"mov %%rsp, %%rbp\n"
".cfi_def_cfa_register rbp\n"
"andq $-16, %%rsp\n"
"call %c[StaticCrashHandler]\n"
"ud2\n"
#elif defined(__aarch64__)
".cfi_return_column 33\n"
".cfi_def_cfa sp, %c[CFAOffset]\n"
FOREACH_REGISTER(CFI_OFFSET_REG, CFI_OFFSET_NUM)
".cfi_offset 33, %c[pc]\n"
".cfi_offset 30, %c[lr]\n"
"bl %c[StaticCrashHandler]\n"
"brk 1\n"
#else
#error "Unsupported architecture for fuzzing on Fuchsia"
#endif
".cfi_endproc\n"
".size CrashTrampolineAsm, . - CrashTrampolineAsm\n"
".popsection\n"
".cfi_startproc\n"
: // No outputs
: FOREACH_REGISTER(ASM_OPERAND_REG, ASM_OPERAND_NUM)
#if defined(__aarch64__)
ASM_OPERAND_REG(pc)
ASM_OPERAND_REG(lr)
#endif
[StaticCrashHandler] "i" (StaticCrashHandler),
[CFAOffset] "i" (CFAOffset));
}
void CrashHandler(zx_handle_t *Event) {
// This structure is used to ensure we close handles to objects we create in
// this handler.
struct ScopedHandle {
~ScopedHandle() {
_zx_handle_close(Handle);
}
zx_handle_t Handle = ZX_HANDLE_INVALID;
};
// Create the exception channel. We need to claim to be a "debugger" so the
// kernel will allow us to modify and resume dying threads (see below). Once
// the channel is set, we can signal the main thread to continue and wait
// for the exception to arrive.
ScopedHandle Channel;
zx_handle_t Self = _zx_process_self();
ExitOnErr(_zx_task_create_exception_channel(
Self, ZX_EXCEPTION_CHANNEL_DEBUGGER, &Channel.Handle),
"_zx_task_create_exception_channel");
ExitOnErr(_zx_object_signal(*Event, 0, ZX_USER_SIGNAL_0),
"_zx_object_signal");
// This thread lives as long as the process in order to keep handling
// crashes. In practice, the first crashed thread to reach the end of the
// StaticCrashHandler will end the process.
while (true) {
ExitOnErr(_zx_object_wait_one(Channel.Handle, ZX_CHANNEL_READABLE,
ZX_TIME_INFINITE, nullptr),
"_zx_object_wait_one");
zx_exception_info_t ExceptionInfo;
ScopedHandle Exception;
ExitOnErr(
_zx_channel_read(Channel.Handle, 0, &ExceptionInfo, &Exception.Handle,
sizeof(ExceptionInfo), 1, nullptr, nullptr),
"_zx_channel_read");
// Ignore informational synthetic exceptions.
if (ZX_EXCP_THREAD_STARTING == ExceptionInfo.type ||
ZX_EXCP_THREAD_EXITING == ExceptionInfo.type ||
ZX_EXCP_PROCESS_STARTING == ExceptionInfo.type) {
continue;
}
// At this point, we want to get the state of the crashing thread, but
// libFuzzer and the sanitizers assume this will happen from that same
// thread via a POSIX signal handler. "Resurrecting" the thread in the
// middle of the appropriate callback is as simple as forcibly setting the
// instruction pointer/program counter, provided we NEVER EVER return from
// that function (since otherwise our stack will not be valid).
ScopedHandle Thread;
ExitOnErr(_zx_exception_get_thread(Exception.Handle, &Thread.Handle),
"_zx_exception_get_thread");
zx_thread_state_general_regs_t GeneralRegisters;
ExitOnErr(
_zx_thread_read_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
&GeneralRegisters, sizeof(GeneralRegisters)),
"_zx_thread_read_state");
// To unwind properly, we need to push the crashing thread's register state
// onto the stack and jump into a trampoline with CFI instructions on how
// to restore it.
#if defined(__x86_64__)
uintptr_t StackPtr = GeneralRegisters.rsp - CFAOffset;
__unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
sizeof(GeneralRegisters));
GeneralRegisters.rsp = StackPtr;
GeneralRegisters.rip = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
#elif defined(__aarch64__)
uintptr_t StackPtr = GeneralRegisters.sp - CFAOffset;
__unsanitized_memcpy(reinterpret_cast<void *>(StackPtr), &GeneralRegisters,
sizeof(GeneralRegisters));
GeneralRegisters.sp = StackPtr;
GeneralRegisters.pc = reinterpret_cast<zx_vaddr_t>(CrashTrampolineAsm);
#else
#error "Unsupported architecture for fuzzing on Fuchsia"
#endif
// Now force the crashing thread's state.
ExitOnErr(
_zx_thread_write_state(Thread.Handle, ZX_THREAD_STATE_GENERAL_REGS,
&GeneralRegisters, sizeof(GeneralRegisters)),
"_zx_thread_write_state");
// Set the exception to HANDLED so it resumes the thread on close.
uint32_t ExceptionState = ZX_EXCEPTION_STATE_HANDLED;
ExitOnErr(_zx_object_set_property(Exception.Handle, ZX_PROP_EXCEPTION_STATE,
&ExceptionState, sizeof(ExceptionState)),
"zx_object_set_property");
}
}
} // namespace
// Platform specific functions.
void SetSignalHandler(const FuzzingOptions &Options) {
// Make sure information from libFuzzer and the sanitizers are easy to
// reassemble. `__sanitizer_log_write` has the added benefit of ensuring the
// DSO map is always available for the symbolizer.
// A uint64_t fits in 20 chars, so 64 is plenty.
char Buf[64];
memset(Buf, 0, sizeof(Buf));
snprintf(Buf, sizeof(Buf), "==%lu== INFO: libFuzzer starting.\n", GetPid());
if (EF->__sanitizer_log_write) __sanitizer_log_write(Buf, sizeof(Buf));
Printf("%s", Buf);
// Set up alarm handler if needed.
if (Options.HandleAlrm && Options.UnitTimeoutSec > 0) {
std::thread T(AlarmHandler, Options.UnitTimeoutSec / 2 + 1);
T.detach();
}
// Set up interrupt handler if needed.
if (Options.HandleInt || Options.HandleTerm) {
std::thread T(InterruptHandler);
T.detach();
}
// Early exit if no crash handler needed.
if (!Options.HandleSegv && !Options.HandleBus && !Options.HandleIll &&
!Options.HandleFpe && !Options.HandleAbrt)
return;
// Set up the crash handler and wait until it is ready before proceeding.
zx_handle_t Event;
ExitOnErr(_zx_event_create(0, &Event), "_zx_event_create");
std::thread T(CrashHandler, &Event);
zx_status_t Status =
_zx_object_wait_one(Event, ZX_USER_SIGNAL_0, ZX_TIME_INFINITE, nullptr);
_zx_handle_close(Event);
ExitOnErr(Status, "_zx_object_wait_one");
T.detach();
}
void SleepSeconds(int Seconds) {
_zx_nanosleep(_zx_deadline_after(ZX_SEC(Seconds)));
}
unsigned long GetPid() {
zx_status_t rc;
zx_info_handle_basic_t Info;
if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_HANDLE_BASIC, &Info,
sizeof(Info), NULL, NULL)) != ZX_OK) {
Printf("libFuzzer: unable to get info about self: %s\n",
_zx_status_get_string(rc));
exit(1);
}
return Info.koid;
}
size_t GetPeakRSSMb() {
zx_status_t rc;
zx_info_task_stats_t Info;
if ((rc = _zx_object_get_info(_zx_process_self(), ZX_INFO_TASK_STATS, &Info,
sizeof(Info), NULL, NULL)) != ZX_OK) {
Printf("libFuzzer: unable to get info about self: %s\n",
_zx_status_get_string(rc));
exit(1);
}
return (Info.mem_private_bytes + Info.mem_shared_bytes) >> 20;
}
template <typename Fn>
class RunOnDestruction {
public:
explicit RunOnDestruction(Fn fn) : fn_(fn) {
}
~RunOnDestruction() {
fn_();
}
private:
Fn fn_;
};
template <typename Fn>
RunOnDestruction<Fn> at_scope_exit(Fn fn) {
return RunOnDestruction<Fn>(fn);
}
static fdio_spawn_action_t clone_fd_action(int localFd, int targetFd) {
return {
.action = FDIO_SPAWN_ACTION_CLONE_FD,
.fd =
{
.local_fd = localFd,
.target_fd = targetFd,
},
};
}
int ExecuteCommand(const Command &Cmd) {
zx_status_t rc;
// Convert arguments to C array
auto Args = Cmd.getArguments();
size_t Argc = Args.size();
assert(Argc != 0);
std::unique_ptr<const char *[]> Argv(new const char *[Argc + 1]);
for (size_t i = 0; i < Argc; ++i)
Argv[i] = Args[i].c_str();
Argv[Argc] = nullptr;
// Determine output. On Fuchsia, the fuzzer is typically run as a component
// that lacks a mutable working directory. Fortunately, when this is the case
// a mutable output directory must be specified using "-artifact_prefix=...",
// so write the log file(s) there.
// However, we don't want to apply this logic for absolute paths.
int FdOut = STDOUT_FILENO;
bool discardStdout = false;
bool discardStderr = false;
if (Cmd.hasOutputFile()) {
std::string Path = Cmd.getOutputFile();
if (Path == getDevNull()) {
// On Fuchsia, there's no "/dev/null" like-file, so we
// just don't copy the FDs into the spawned process.
discardStdout = true;
} else {
bool IsAbsolutePath = Path.length() > 1 && Path[0] == '/';
if (!IsAbsolutePath && Cmd.hasFlag("artifact_prefix"))
Path = Cmd.getFlagValue("artifact_prefix") + "/" + Path;
FdOut = open(Path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0);
if (FdOut == -1) {
Printf("libFuzzer: failed to open %s: %s\n", Path.c_str(),
strerror(errno));
return ZX_ERR_IO;
}
}
}
auto CloseFdOut = at_scope_exit([FdOut]() {
if (FdOut != STDOUT_FILENO) close(FdOut);
});
// Determine stderr
int FdErr = STDERR_FILENO;
if (Cmd.isOutAndErrCombined()) {
FdErr = FdOut;
if (discardStdout) discardStderr = true;
}
// Clone the file descriptors into the new process
std::vector<fdio_spawn_action_t> SpawnActions;
SpawnActions.push_back(clone_fd_action(STDIN_FILENO, STDIN_FILENO));
if (!discardStdout)
SpawnActions.push_back(clone_fd_action(FdOut, STDOUT_FILENO));
if (!discardStderr)
SpawnActions.push_back(clone_fd_action(FdErr, STDERR_FILENO));
// Start the process.
char ErrorMsg[FDIO_SPAWN_ERR_MSG_MAX_LENGTH];
zx_handle_t ProcessHandle = ZX_HANDLE_INVALID;
rc = fdio_spawn_etc(ZX_HANDLE_INVALID,
FDIO_SPAWN_CLONE_ALL & (~FDIO_SPAWN_CLONE_STDIO), Argv[0],
Argv.get(), nullptr, SpawnActions.size(),
SpawnActions.data(), &ProcessHandle, ErrorMsg);
if (rc != ZX_OK) {
Printf("libFuzzer: failed to launch '%s': %s, %s\n", Argv[0], ErrorMsg,
_zx_status_get_string(rc));
return rc;
}
auto CloseHandle = at_scope_exit([&]() { _zx_handle_close(ProcessHandle); });
// Now join the process and return the exit status.
if ((rc = _zx_object_wait_one(ProcessHandle, ZX_PROCESS_TERMINATED,
ZX_TIME_INFINITE, nullptr)) != ZX_OK) {
Printf("libFuzzer: failed to join '%s': %s\n", Argv[0],
_zx_status_get_string(rc));
return rc;
}
zx_info_process_t Info;
if ((rc = _zx_object_get_info(ProcessHandle, ZX_INFO_PROCESS, &Info,
sizeof(Info), nullptr, nullptr)) != ZX_OK) {
Printf("libFuzzer: unable to get return code from '%s': %s\n", Argv[0],
_zx_status_get_string(rc));
return rc;
}
return Info.return_code;
}
bool ExecuteCommand(const Command &BaseCmd, std::string *CmdOutput) {
auto LogFilePath = TempPath("SimPopenOut", ".txt");
Command Cmd(BaseCmd);
Cmd.setOutputFile(LogFilePath);
int Ret = ExecuteCommand(Cmd);
*CmdOutput = FileToString(LogFilePath);
RemoveFile(LogFilePath);
return Ret == 0;
}
const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
size_t PattLen) {
return memmem(Data, DataLen, Patt, PattLen);
}
// In fuchsia, accessing /dev/null is not supported. There's nothing
// similar to a file that discards everything that is written to it.
// The way of doing something similar in fuchsia is by using
// fdio_null_create and binding that to a file descriptor.
void DiscardOutput(int Fd) {
fdio_t *fdio_null = fdio_null_create();
if (fdio_null == nullptr) return;
int nullfd = fdio_bind_to_fd(fdio_null, -1, 0);
if (nullfd < 0) return;
dup2(nullfd, Fd);
}
} // namespace fuzzer
#endif // LIBFUZZER_FUCHSIA

View File

@ -0,0 +1,43 @@
//===- FuzzerUtilLinux.cpp - Misc utils for Linux. ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Misc utils for Linux.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_LINUX || LIBFUZZER_NETBSD || LIBFUZZER_FREEBSD || \
LIBFUZZER_OPENBSD || LIBFUZZER_EMSCRIPTEN
#include "FuzzerCommand.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
namespace fuzzer {
int ExecuteCommand(const Command &Cmd) {
std::string CmdLine = Cmd.toString();
int exit_code = system(CmdLine.c_str());
if (WIFEXITED(exit_code)) return WEXITSTATUS(exit_code);
return exit_code;
}
void DiscardOutput(int Fd) {
FILE *Temp = fopen("/dev/null", "w");
if (!Temp) return;
dup2(fileno(Temp), Fd);
fclose(Temp);
}
} // namespace fuzzer
#endif

View File

@ -0,0 +1,239 @@
//===- FuzzerUtilPosix.cpp - Misc utils for Posix. ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Misc utils implementation using Posix API.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_POSIX
#include "FuzzerIO.h"
#include "FuzzerInternal.h"
#include "FuzzerTracePC.h"
#include <cassert>
#include <chrono>
#include <cstring>
#include <errno.h>
#include <iomanip>
#include <signal.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <thread>
#include <unistd.h>
namespace fuzzer {
static void AlarmHandler(int, siginfo_t *, void *) {
Fuzzer::StaticAlarmCallback();
}
static void (*upstream_segv_handler)(int, siginfo_t *, void *);
static void SegvHandler(int sig, siginfo_t *si, void *ucontext) {
assert(si->si_signo == SIGSEGV);
if (upstream_segv_handler) return upstream_segv_handler(sig, si, ucontext);
Fuzzer::StaticCrashSignalCallback();
}
static void CrashHandler(int, siginfo_t *, void *) {
Fuzzer::StaticCrashSignalCallback();
}
static void InterruptHandler(int, siginfo_t *, void *) {
Fuzzer::StaticInterruptCallback();
}
static void GracefulExitHandler(int, siginfo_t *, void *) {
Fuzzer::StaticGracefulExitCallback();
}
static void FileSizeExceedHandler(int, siginfo_t *, void *) {
Fuzzer::StaticFileSizeExceedCallback();
}
static void SetSigaction(int signum,
void (*callback)(int, siginfo_t *, void *)) {
struct sigaction sigact = {};
if (sigaction(signum, nullptr, &sigact)) {
Printf("libFuzzer: sigaction failed with %d\n", errno);
exit(1);
}
if (sigact.sa_flags & SA_SIGINFO) {
if (sigact.sa_sigaction) {
if (signum != SIGSEGV) return;
upstream_segv_handler = sigact.sa_sigaction;
}
} else {
if (sigact.sa_handler != SIG_DFL && sigact.sa_handler != SIG_IGN &&
sigact.sa_handler != SIG_ERR)
return;
}
sigact = {};
sigact.sa_flags = SA_SIGINFO;
sigact.sa_sigaction = callback;
if (sigaction(signum, &sigact, 0)) {
Printf("libFuzzer: sigaction failed with %d\n", errno);
exit(1);
}
}
// Return true on success, false otherwise.
bool ExecuteCommand(const Command &Cmd, std::string *CmdOutput) {
FILE *Pipe = popen(Cmd.toString().c_str(), "r");
if (!Pipe) return false;
if (CmdOutput) {
char TmpBuffer[128];
while (fgets(TmpBuffer, sizeof(TmpBuffer), Pipe))
CmdOutput->append(TmpBuffer);
}
return pclose(Pipe) == 0;
}
void SetTimer(int Seconds) {
struct itimerval T {
{Seconds, 0}, {
Seconds, 0
}
};
if (setitimer(ITIMER_REAL, &T, nullptr)) {
Printf("libFuzzer: setitimer failed with %d\n", errno);
exit(1);
}
SetSigaction(SIGALRM, AlarmHandler);
}
void SetSignalHandler(const FuzzingOptions &Options) {
// setitimer is not implemented in emscripten.
if (Options.HandleAlrm && Options.UnitTimeoutSec > 0 && !LIBFUZZER_EMSCRIPTEN)
SetTimer(Options.UnitTimeoutSec / 2 + 1);
if (Options.HandleInt) SetSigaction(SIGINT, InterruptHandler);
if (Options.HandleTerm) SetSigaction(SIGTERM, InterruptHandler);
if (Options.HandleSegv) SetSigaction(SIGSEGV, SegvHandler);
if (Options.HandleBus) SetSigaction(SIGBUS, CrashHandler);
if (Options.HandleAbrt) SetSigaction(SIGABRT, CrashHandler);
if (Options.HandleIll) SetSigaction(SIGILL, CrashHandler);
if (Options.HandleFpe) SetSigaction(SIGFPE, CrashHandler);
if (Options.HandleXfsz) SetSigaction(SIGXFSZ, FileSizeExceedHandler);
if (Options.HandleUsr1) SetSigaction(SIGUSR1, GracefulExitHandler);
if (Options.HandleUsr2) SetSigaction(SIGUSR2, GracefulExitHandler);
}
void SleepSeconds(int Seconds) {
sleep(Seconds); // Use C API to avoid coverage from instrumented libc++.
}
unsigned long GetPid() {
return (unsigned long)getpid();
}
size_t GetPeakRSSMb() {
struct rusage usage;
if (getrusage(RUSAGE_SELF, &usage)) return 0;
if (LIBFUZZER_LINUX || LIBFUZZER_FREEBSD || LIBFUZZER_NETBSD ||
LIBFUZZER_OPENBSD || LIBFUZZER_EMSCRIPTEN) {
// ru_maxrss is in KiB
return usage.ru_maxrss >> 10;
} else if (LIBFUZZER_APPLE) {
// ru_maxrss is in bytes
return usage.ru_maxrss >> 20;
}
assert(0 && "GetPeakRSSMb() is not implemented for your platform");
return 0;
}
FILE *OpenProcessPipe(const char *Command, const char *Mode) {
return popen(Command, Mode);
}
int CloseProcessPipe(FILE *F) {
return pclose(F);
}
const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
size_t PattLen) {
return memmem(Data, DataLen, Patt, PattLen);
}
std::string DisassembleCmd(const std::string &FileName) {
return "objdump -d " + FileName;
}
std::string SearchRegexCmd(const std::string &Regex) {
return "grep '" + Regex + "'";
}
} // namespace fuzzer
#endif // LIBFUZZER_POSIX

View File

@ -0,0 +1,279 @@
//===- FuzzerUtilWindows.cpp - Misc utils for Windows. --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Misc utils implementation for Windows.
//===----------------------------------------------------------------------===//
#include "FuzzerPlatform.h"
#if LIBFUZZER_WINDOWS
#include "FuzzerCommand.h"
#include "FuzzerIO.h"
#include "FuzzerInternal.h"
#include <cassert>
#include <chrono>
#include <cstring>
#include <errno.h>
#include <io.h>
#include <iomanip>
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <windows.h>
// This must be included after windows.h.
#include <psapi.h>
namespace fuzzer {
static const FuzzingOptions *HandlerOpt = nullptr;
static LONG CALLBACK ExceptionHandler(PEXCEPTION_POINTERS ExceptionInfo) {
switch (ExceptionInfo->ExceptionRecord->ExceptionCode) {
case EXCEPTION_ACCESS_VIOLATION:
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
case EXCEPTION_STACK_OVERFLOW:
if (HandlerOpt->HandleSegv) Fuzzer::StaticCrashSignalCallback();
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
case EXCEPTION_IN_PAGE_ERROR:
if (HandlerOpt->HandleBus) Fuzzer::StaticCrashSignalCallback();
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
case EXCEPTION_PRIV_INSTRUCTION:
if (HandlerOpt->HandleIll) Fuzzer::StaticCrashSignalCallback();
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
case EXCEPTION_FLT_INEXACT_RESULT:
case EXCEPTION_FLT_INVALID_OPERATION:
case EXCEPTION_FLT_OVERFLOW:
case EXCEPTION_FLT_STACK_CHECK:
case EXCEPTION_FLT_UNDERFLOW:
case EXCEPTION_INT_DIVIDE_BY_ZERO:
case EXCEPTION_INT_OVERFLOW:
if (HandlerOpt->HandleFpe) Fuzzer::StaticCrashSignalCallback();
break;
// TODO: handle (Options.HandleXfsz)
}
return EXCEPTION_CONTINUE_SEARCH;
}
BOOL WINAPI CtrlHandler(DWORD dwCtrlType) {
switch (dwCtrlType) {
case CTRL_C_EVENT:
if (HandlerOpt->HandleInt) Fuzzer::StaticInterruptCallback();
return TRUE;
case CTRL_BREAK_EVENT:
if (HandlerOpt->HandleTerm) Fuzzer::StaticInterruptCallback();
return TRUE;
}
return FALSE;
}
void CALLBACK AlarmHandler(PVOID, BOOLEAN) {
Fuzzer::StaticAlarmCallback();
}
class TimerQ {
HANDLE TimerQueue;
public:
TimerQ() : TimerQueue(NULL) {
}
~TimerQ() {
if (TimerQueue) DeleteTimerQueueEx(TimerQueue, NULL);
}
void SetTimer(int Seconds) {
if (!TimerQueue) {
TimerQueue = CreateTimerQueue();
if (!TimerQueue) {
Printf("libFuzzer: CreateTimerQueue failed.\n");
exit(1);
}
}
HANDLE Timer;
if (!CreateTimerQueueTimer(&Timer, TimerQueue, AlarmHandler, NULL,
Seconds * 1000, Seconds * 1000, 0)) {
Printf("libFuzzer: CreateTimerQueueTimer failed.\n");
exit(1);
}
}
};
static TimerQ Timer;
static void CrashHandler(int) {
Fuzzer::StaticCrashSignalCallback();
}
void SetSignalHandler(const FuzzingOptions &Options) {
HandlerOpt = &Options;
if (Options.HandleAlrm && Options.UnitTimeoutSec > 0)
Timer.SetTimer(Options.UnitTimeoutSec / 2 + 1);
if (Options.HandleInt || Options.HandleTerm)
if (!SetConsoleCtrlHandler(CtrlHandler, TRUE)) {
DWORD LastError = GetLastError();
Printf("libFuzzer: SetConsoleCtrlHandler failed (Error code: %lu).\n",
LastError);
exit(1);
}
if (Options.HandleSegv || Options.HandleBus || Options.HandleIll ||
Options.HandleFpe)
SetUnhandledExceptionFilter(ExceptionHandler);
if (Options.HandleAbrt)
if (SIG_ERR == signal(SIGABRT, CrashHandler)) {
Printf("libFuzzer: signal failed with %d\n", errno);
exit(1);
}
}
void SleepSeconds(int Seconds) {
Sleep(Seconds * 1000);
}
unsigned long GetPid() {
return GetCurrentProcessId();
}
size_t GetPeakRSSMb() {
PROCESS_MEMORY_COUNTERS info;
if (!GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info))) return 0;
return info.PeakWorkingSetSize >> 20;
}
FILE *OpenProcessPipe(const char *Command, const char *Mode) {
return _popen(Command, Mode);
}
int CloseProcessPipe(FILE *F) {
return _pclose(F);
}
int ExecuteCommand(const Command &Cmd) {
std::string CmdLine = Cmd.toString();
return system(CmdLine.c_str());
}
bool ExecuteCommand(const Command &Cmd, std::string *CmdOutput) {
FILE *Pipe = _popen(Cmd.toString().c_str(), "r");
if (!Pipe) return false;
if (CmdOutput) {
char TmpBuffer[128];
while (fgets(TmpBuffer, sizeof(TmpBuffer), Pipe))
CmdOutput->append(TmpBuffer);
}
return _pclose(Pipe) == 0;
}
const void *SearchMemory(const void *Data, size_t DataLen, const void *Patt,
size_t PattLen) {
// TODO: make this implementation more efficient.
const char *Cdata = (const char *)Data;
const char *Cpatt = (const char *)Patt;
if (!Data || !Patt || DataLen == 0 || PattLen == 0 || DataLen < PattLen)
return NULL;
if (PattLen == 1) return memchr(Data, *Cpatt, DataLen);
const char *End = Cdata + DataLen - PattLen + 1;
for (const char *It = Cdata; It < End; ++It)
if (It[0] == Cpatt[0] && memcmp(It, Cpatt, PattLen) == 0) return It;
return NULL;
}
std::string DisassembleCmd(const std::string &FileName) {
Vector<std::string> command_vector;
command_vector.push_back("dumpbin /summary > nul");
if (ExecuteCommand(Command(command_vector)) == 0)
return "dumpbin /disasm " + FileName;
Printf("libFuzzer: couldn't find tool to disassemble (dumpbin)\n");
exit(1);
}
std::string SearchRegexCmd(const std::string &Regex) {
return "findstr /r \"" + Regex + "\"";
}
void DiscardOutput(int Fd) {
FILE *Temp = fopen("nul", "w");
if (!Temp) return;
_dup2(_fileno(Temp), Fd);
fclose(Temp);
}
} // namespace fuzzer
#endif // LIBFUZZER_WINDOWS

View File

@ -0,0 +1,73 @@
//===- FuzzerValueBitMap.h - INTERNAL - Bit map -----------------*- C++ -* ===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// ValueBitMap.
//===----------------------------------------------------------------------===//
#ifndef LLVM_FUZZER_VALUE_BIT_MAP_H
#define LLVM_FUZZER_VALUE_BIT_MAP_H
#include "FuzzerPlatform.h"
#include <cstdint>
namespace fuzzer {
// A bit map containing kMapSizeInWords bits.
struct ValueBitMap {
static const size_t kMapSizeInBits = 1 << 16;
static const size_t kMapPrimeMod = 65371; // Largest Prime < kMapSizeInBits;
static const size_t kBitsInWord = (sizeof(uintptr_t) * 8);
static const size_t kMapSizeInWords = kMapSizeInBits / kBitsInWord;
public:
// Clears all bits.
void Reset() { memset(Map, 0, sizeof(Map)); }
// Computes a hash function of Value and sets the corresponding bit.
// Returns true if the bit was changed from 0 to 1.
ATTRIBUTE_NO_SANITIZE_ALL
inline bool AddValue(uintptr_t Value) {
uintptr_t Idx = Value % kMapSizeInBits;
uintptr_t WordIdx = Idx / kBitsInWord;
uintptr_t BitIdx = Idx % kBitsInWord;
uintptr_t Old = Map[WordIdx];
uintptr_t New = Old | (1ULL << BitIdx);
Map[WordIdx] = New;
return New != Old;
}
ATTRIBUTE_NO_SANITIZE_ALL
inline bool AddValueModPrime(uintptr_t Value) {
return AddValue(Value % kMapPrimeMod);
}
inline bool Get(uintptr_t Idx) {
assert(Idx < kMapSizeInBits);
uintptr_t WordIdx = Idx / kBitsInWord;
uintptr_t BitIdx = Idx % kBitsInWord;
return Map[WordIdx] & (1ULL << BitIdx);
}
size_t SizeInBits() const { return kMapSizeInBits; }
template <class Callback>
ATTRIBUTE_NO_SANITIZE_ALL
void ForEach(Callback CB) const {
for (size_t i = 0; i < kMapSizeInWords; i++)
if (uintptr_t M = Map[i])
for (size_t j = 0; j < sizeof(M) * 8; j++)
if (M & ((uintptr_t)1 << j))
CB(i * sizeof(M) * 8 + j);
}
private:
ATTRIBUTE_ALIGNED(512) uintptr_t Map[kMapSizeInWords];
};
} // namespace fuzzer
#endif // LLVM_FUZZER_VALUE_BIT_MAP_H

View File

@ -0,0 +1,86 @@
CFLAGS = -g -O3 -funroll-loops -fPIC -fpermissive -std=c++11
#CFLAGS = -g -O0 -fPIC -fpermissive -std=c++11
CXX ?= clang++
ifdef INTROSPECTION
$(info Compiling with introspection documentation)
CFLAGS += -DINTROSPECTION=1
endif
all: libfuzzer-mutator.so
FuzzerCrossOver.o: FuzzerCrossOver.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerDataFlowTrace.o: FuzzerDataFlowTrace.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerDriver.o: FuzzerDriver.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerExtFunctionsDlsym.o: FuzzerExtFunctionsDlsym.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerExtFunctionsWeak.o: FuzzerExtFunctionsWeak.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerExtFunctionsWindows.o: FuzzerExtFunctionsWindows.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerExtraCounters.o: FuzzerExtraCounters.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerFork.o: FuzzerFork.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerIO.o: FuzzerIO.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerIOPosix.o: FuzzerIOPosix.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerIOWindows.o: FuzzerIOWindows.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerLoop.o: FuzzerLoop.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerMerge.o: FuzzerMerge.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerMutate.o: FuzzerMutate.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerSHA1.o: FuzzerSHA1.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerTracePC.o: FuzzerTracePC.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerUtil.o: FuzzerUtil.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerUtilDarwin.o: FuzzerUtilDarwin.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerUtilFuchsia.o: FuzzerUtilFuchsia.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerUtilLinux.o: FuzzerUtilLinux.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerUtilPosix.o: FuzzerUtilPosix.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
FuzzerUtilWindows.o: FuzzerUtilWindows.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
libfuzzer.o: libfuzzer.cpp
$(CXX) $(CFLAGS) -I../../include -I. -c $^
libfuzzer-mutator.so: FuzzerCrossOver.o FuzzerDataFlowTrace.o FuzzerDriver.o FuzzerExtFunctionsDlsym.o FuzzerExtFunctionsWeak.o FuzzerExtFunctionsWindows.o FuzzerExtraCounters.o FuzzerFork.o FuzzerIO.o FuzzerIOPosix.o FuzzerIOWindows.o FuzzerLoop.o FuzzerMerge.o FuzzerMutate.o FuzzerSHA1.o FuzzerTracePC.o FuzzerUtil.o FuzzerUtilDarwin.o FuzzerUtilFuchsia.o FuzzerUtilLinux.o FuzzerUtilPosix.o FuzzerUtilWindows.o libfuzzer.o
$(CXX) $(CFLAGS) -I../../include -I. -shared -o libfuzzer-mutator.so *.o
clean:
rm -f *.o *~ *.so core

View File

@ -0,0 +1,24 @@
# custum mutator: libfuzzer LLVMFuzzerMutate()
This uses the libfuzzer LLVMFuzzerMutate() function in llvm 12.
just type `make` to build
```AFL_CUSTOM_MUTATOR_LIBRARY=custom_mutators/libfuzzer/libfuzzer-mutator.so afl-fuzz ...```
Note that this is currently a simple implementation and it is missing two features:
* Splicing ("Crossover")
* Dictionary support
To update the source, all that is needed is that FuzzerDriver.cpp has to receive
```
#include "libfuzzer.inc"
```
before the closing namespace bracket.
It is also libfuzzer.inc where the configuration of the libfuzzer mutations
are done.
> Original repository: https://github.com/llvm/llvm-project
> Path: compiler-rt/lib/fuzzer/*.{h|cpp}
> Source commit: df3e903655e2499968fc7af64fb5fa52b2ee79bb

View File

@ -0,0 +1,160 @@
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
//#include "config.h"
//#include "debug.h"
#include "afl-fuzz.h"
#ifdef INTROSPECTION
const char *introspection_ptr;
#endif
afl_state_t *afl_struct;
extern "C" size_t LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize);
extern "C" int LLVMFuzzerRunDriver(int *argc, char ***argv,
int (*UserCb)(const uint8_t *Data,
size_t Size));
extern "C" void LLVMFuzzerMyInit(int (*UserCb)(const uint8_t *Data,
size_t Size),
unsigned int Seed);
typedef struct my_mutator {
afl_state_t *afl;
u8 * mutator_buf;
unsigned int seed;
unsigned int extras_cnt, a_extras_cnt;
} my_mutator_t;
extern "C" int dummy(const uint8_t *Data, size_t Size) {
(void)(Data);
(void)(Size);
fprintf(stderr, "dummy() called\n");
return 0;
}
extern "C" my_mutator_t *afl_custom_init(afl_state_t *afl, unsigned int seed) {
my_mutator_t *data = (my_mutator_t *)calloc(1, sizeof(my_mutator_t));
if (!data) {
perror("afl_custom_init alloc");
return NULL;
}
if ((data->mutator_buf = (u8 *)malloc(MAX_FILE)) == NULL) {
free(data);
perror("mutator_buf alloc");
return NULL;
}
data->afl = afl;
data->seed = seed;
afl_struct = afl;
/*
char **argv;
argv = (char**)malloc(sizeof(size_t) * 2);
argv[0] = (char*)"foo";
argv[1] = NULL;
int eins = 1;
LLVMFuzzerRunDriver(&eins, &argv, dummy);
*/
LLVMFuzzerMyInit(dummy, seed);
return data;
}
/* When a new queue entry is added we check if there are new dictionary
entries to add to honggfuzz structure */
#if 0
extern "C" void afl_custom_queue_new_entry(my_mutator_t * data,
const uint8_t *filename_new_queue,
const uint8_t *filename_orig_queue) {
while (data->extras_cnt < afl_struct->extras_cnt) {
/*
memcpy(run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].val,
afl_struct->extras[data->extras_cnt].data,
afl_struct->extras[data->extras_cnt].len);
run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].len =
afl_struct->extras[data->extras_cnt].len;
run.global->mutate.dictionaryCnt++;
*/
data->extras_cnt++;
}
while (data->a_extras_cnt < afl_struct->a_extras_cnt) {
/*
memcpy(run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].val,
afl_struct->a_extras[data->a_extras_cnt].data,
afl_struct->a_extras[data->a_extras_cnt].len);
run.global->mutate.dictionary[run.global->mutate.dictionaryCnt].len =
afl_struct->a_extras[data->a_extras_cnt].len;
run.global->mutate.dictionaryCnt++;
data->a_extras_cnt++;
*/
}
}
#endif
/* we could set only_printable if is_ascii is set ... let's see
uint8_t afl_custom_queue_get(void *data, const uint8_t *filename) {
//run.global->cfg.only_printable = ...
}
*/
/* here we run the honggfuzz mutator, which is really good */
extern "C" size_t afl_custom_fuzz(my_mutator_t *data, uint8_t *buf,
size_t buf_size, u8 **out_buf,
uint8_t *add_buf, size_t add_buf_size,
size_t max_size) {
memcpy(data->mutator_buf, buf, buf_size);
size_t ret = LLVMFuzzerMutate(data->mutator_buf, buf_size, max_size);
/* return size of mutated data */
*out_buf = data->mutator_buf;
return ret;
}
#ifdef INTROSPECTION
extern "C" const char* afl_custom_introspection(my_mutator_t *data) {
return introspection_ptr;
}
#endif
/**
* Deinitialize everything
*
* @param data The data ptr from afl_custom_init
*/
extern "C" void afl_custom_deinit(my_mutator_t *data) {
free(data->mutator_buf);
free(data);
}

View File

@ -0,0 +1,36 @@
extern "C" ATTRIBUTE_INTERFACE void
LLVMFuzzerMyInit(int (*Callback)(const uint8_t *Data, size_t Size), unsigned int Seed) {
Random Rand(Seed);
FuzzingOptions Options;
Options.Verbosity = 3;
Options.MaxLen = 1024000;
Options.LenControl = true;
Options.DoCrossOver = false;
Options.MutateDepth = 6;
Options.UseCounters = false;
Options.UseMemmem = false;
Options.UseCmp = false;
Options.UseValueProfile = false;
Options.Shrink = false;
Options.ReduceInputs = false;
Options.PreferSmall = false;
Options.ReloadIntervalSec = 0;
Options.OnlyASCII = false;
Options.DetectLeaks = false;
Options.PurgeAllocatorIntervalSec = 0;
Options.TraceMalloc = false;
Options.RssLimitMb = 100;
Options.MallocLimitMb = 100;
Options.MaxNumberOfRuns = 0;
Options.ReportSlowUnits = false;
Options.Entropic = false;
struct EntropicOptions Entropic;
Entropic.Enabled = Options.Entropic;
EF = new ExternalFunctions();
auto *MD = new MutationDispatcher(Rand, Options);
auto *Corpus = new InputCorpus(Options.OutputCorpus, Entropic);
auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
}

View File

@ -0,0 +1,32 @@
cc_library_shared {
name: "libprotobuf-mutator-example-afl",
vendor_available: true,
host_supported: true,
cflags: [
"-g",
"-O0",
"-fPIC",
"-Wall",
],
srcs: [
"lpm_aflpp_custom_mutator_input.cc",
"test.proto",
],
shared_libs: [
"libprotobuf-cpp-full",
"libprotobuf-mutator",
],
}
cc_binary {
name: "libprotobuf-mutator-vuln",
vendor_available: true,
host_supported: true,
srcs: [
"vuln.c",
],
}

View File

@ -0,0 +1 @@
Ported from [https://github.com/bruce30262/libprotobuf-mutator_fuzzing_learning/tree/master/5_libprotobuf_aflpp_custom_mutator_input](https://github.com/bruce30262/libprotobuf-mutator_fuzzing_learning/tree/master/5_libprotobuf_aflpp_custom_mutator_input)

View File

@ -0,0 +1,118 @@
#include "lpm_aflpp_custom_mutator_input.h"
#include <iostream>
#include <sstream>
#include <fstream>
using std::cin;
using std::cout;
using std::endl;
std::string ProtoToData(const TEST &test_proto) {
std::stringstream all;
const auto &aa = test_proto.a();
const auto &bb = test_proto.b();
all.write((const char*)&aa, sizeof(aa));
if(bb.size() != 0) {
all.write(bb.c_str(), bb.size());
}
std::string res = all.str();
if (bb.size() != 0 && res.size() != 0) {
// set PROTO_FUZZER_DUMP_PATH env to dump the serialized protobuf
if (const char *dump_path = getenv("PROTO_FUZZER_DUMP_PATH")) {
std::ofstream of(dump_path);
of.write(res.data(), res.size());
}
}
return res;
}
/**
* Initialize this custom mutator
*
* @param[in] afl a pointer to the internal state object. Can be ignored for
* now.
* @param[in] seed A seed for this mutator - the same seed should always mutate
* in the same way.
* @return Pointer to the data object this custom mutator instance should use.
* There may be multiple instances of this mutator in one afl-fuzz run!
* Return NULL on error.
*/
extern "C" MyMutator *afl_custom_init(void *afl, unsigned int seed) {
MyMutator *mutator = new MyMutator();
mutator->RegisterPostProcessor(
TEST::descriptor(),
[](google::protobuf::Message* message, unsigned int seed) {
// libprotobuf-mutator's built-in mutator is kind of....crappy :P
// Even a dumb fuzz like `TEST.a = rand();` is better in this case... Q_Q
// We register a post processor to apply our dumb fuzz
TEST *t = static_cast<TEST *>(message);
t->set_a(rand());
});
srand(seed);
return mutator;
}
/**
* Perform custom mutations on a given input
*
* @param[in] data pointer returned in afl_custom_init for this fuzz case
* @param[in] buf Pointer to input data to be mutated
* @param[in] buf_size Size of input data
* @param[out] out_buf the buffer we will work on. we can reuse *buf. NULL on
* error.
* @param[in] add_buf Buffer containing the additional test case
* @param[in] add_buf_size Size of the additional test case
* @param[in] max_size Maximum size of the mutated output. The mutation must not
* produce data larger than max_size.
* @return Size of the mutated output.
*/
extern "C" size_t afl_custom_fuzz(MyMutator *mutator, // return value from afl_custom_init
uint8_t *buf, size_t buf_size, // input data to be mutated
uint8_t **out_buf, // output buffer
uint8_t *add_buf, size_t add_buf_size, // add_buf can be NULL
size_t max_size) {
// This function can be named either "afl_custom_fuzz" or "afl_custom_mutator"
// A simple test shows that "buf" will be the content of the current test case
// "add_buf" will be the next test case ( from AFL++'s input queue )
TEST input;
// parse input data to TEST
// Notice that input data should be a serialized protobuf data
// Check ./in/ii and test_protobuf_serializer for more detail
bool parse_ok = input.ParseFromArray(buf, buf_size);
if(!parse_ok) {
// Invalid serialize protobuf data. Don't mutate.
// Return a dummy buffer. Also mutated_size = 0
static uint8_t *dummy = new uint8_t[10]; // dummy buffer with no data
*out_buf = dummy;
return 0;
}
// mutate the protobuf
mutator->Mutate(&input, max_size);
// Convert protobuf to raw data
const TEST *p = &input;
std::string s = ProtoToData(*p);
// Copy to a new buffer ( mutated_out )
size_t mutated_size = s.size() <= max_size ? s.size() : max_size; // check if raw data's size is larger than max_size
uint8_t *mutated_out = new uint8_t[mutated_size+1];
memcpy(mutated_out, s.c_str(), mutated_size); // copy the mutated data
// Assign the mutated data and return mutated_size
*out_buf = mutated_out;
return mutated_size;
}
/**
* Deinitialize everything
*
* @param data The data ptr from afl_custom_init
*/
extern "C" void afl_custom_deinit(void *data) {
// Honestly I don't know what to do with this...
return;
}

View File

@ -0,0 +1,5 @@
#include <src/mutator.h>
#include "test.pb.h"
class MyMutator : public protobuf_mutator::Mutator {
};

Some files were not shown because too many files have changed in this diff Show More