afl-as.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. american fuzzy lop - wrapper for GNU as
  3. ---------------------------------------
  4. Written and maintained by Michal Zalewski <lcamtuf@google.com>
  5. Copyright 2013, 2014, 2015 Google Inc. All rights reserved.
  6. Licensed under the Apache License, Version 2.0 (the "License");
  7. you may not use this file except in compliance with the License.
  8. You may obtain a copy of the License at:
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. The sole purpose of this wrapper is to preprocess assembly files generated
  11. by GCC / clang and inject the instrumentation bits included from afl-as.h. It
  12. is automatically invoked by the toolchain when compiling programs using
  13. afl-gcc / afl-clang.
  14. Note that it's an explicit non-goal to instrument hand-written assembly,
  15. be it in separate .s files or in __asm__ blocks. The only aspiration this
  16. utility has right now is to be able to skip them gracefully and allow the
  17. compilation process to continue.
  18. That said, see experimental/clang_asm_normalize/ for a solution that may
  19. allow clang users to make things work even with hand-crafted assembly. Just
  20. note that there is no equivalent for GCC.
  21. */
  22. #define AFL_MAIN
  23. #include "config.h"
  24. #include "types.h"
  25. #include "debug.h"
  26. #include "alloc-inl.h"
  27. #include "afl-as.h"
  28. #include <stdio.h>
  29. #include <unistd.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <time.h>
  33. #include <ctype.h>
  34. #include <fcntl.h>
  35. #include <sys/wait.h>
  36. #include <sys/time.h>
  37. static u8** as_params; /* Parameters passed to the real 'as' */
  38. static u8* input_file; /* Originally specified input file */
  39. static u8* modified_file; /* Instrumented file for the real 'as' */
  40. static u8 be_quiet, /* Quiet mode (no stderr output) */
  41. clang_mode, /* Running in clang mode? */
  42. pass_thru, /* Just pass data through? */
  43. just_version, /* Just show version? */
  44. sanitizer; /* Using ASAN / MSAN */
  45. static u32 inst_ratio = 100, /* Instrumentation probability (%) */
  46. as_par_cnt = 1; /* Number of params to 'as' */
  47. /* If we don't find --32 or --64 in the command line, default to
  48. instrumentation for whichever mode we were compiled with. This is not
  49. perfect, but should do the trick for almost all use cases. */
  50. #ifdef __x86_64__
  51. static u8 use_64bit = 1;
  52. #else
  53. static u8 use_64bit = 0;
  54. #ifdef __APPLE__
  55. # error "Sorry, 32-bit Apple platforms are not supported."
  56. #endif /* __APPLE__ */
  57. #endif /* ^__x86_64__ */
  58. /* Examine and modify parameters to pass to 'as'. Note that the file name
  59. is always the last parameter passed by GCC, so we exploit this property
  60. to keep the code simple. */
  61. static void edit_params(int argc, char** argv) {
  62. u8 *tmp_dir = getenv("TMPDIR"), *afl_as = getenv("AFL_AS");
  63. u32 i;
  64. #ifdef __APPLE__
  65. u8 use_clang_as = 0;
  66. /* On MacOS X, the Xcode cctool 'as' driver is a bit stale and does not work
  67. with the code generated by newer versions of clang that are hand-built
  68. by the user. See the thread here: http://goo.gl/HBWDtn.
  69. To work around this, when using clang and running without AFL_AS
  70. specified, we will actually call 'clang -c' instead of 'as -q' to
  71. compile the assembly file.
  72. The tools aren't cmdline-compatible, but at least for now, we can
  73. seemingly get away with this by making only very minor tweaks. Thanks
  74. to Nico Weber for the idea. */
  75. if (clang_mode && !afl_as) {
  76. use_clang_as = 1;
  77. afl_as = getenv("AFL_CC");
  78. if (!afl_as) afl_as = getenv("AFL_CXX");
  79. if (!afl_as) afl_as = "clang";
  80. }
  81. #endif /* __APPLE__ */
  82. /* Although this is not documented, GCC also uses TEMP and TMP when TMPDIR
  83. is not set. We need to check these non-standard variables to properly
  84. handle the pass_thru logic later on. */
  85. if (!tmp_dir) tmp_dir = getenv("TEMP");
  86. if (!tmp_dir) tmp_dir = getenv("TMP");
  87. if (!tmp_dir) tmp_dir = "/tmp";
  88. as_params = ck_alloc((argc + 32) * sizeof(u8*));
  89. as_params[0] = afl_as ? afl_as : (u8*)"as";
  90. as_params[argc] = 0;
  91. for (i = 1; i < argc - 1; i++) {
  92. if (!strcmp(argv[i], "--64")) use_64bit = 1;
  93. else if (!strcmp(argv[i], "--32")) use_64bit = 0;
  94. #ifdef __APPLE__
  95. /* The Apple case is a bit different... */
  96. if (!strcmp(argv[i], "-arch") && i + 1 < argc) {
  97. if (!strcmp(argv[i + 1], "x86_64")) use_64bit = 1;
  98. else if (!strcmp(argv[i + 1], "i386"))
  99. FATAL("Sorry, 32-bit Apple platforms are not supported.");
  100. }
  101. /* Strip options that set the preference for a particular upstream
  102. assembler in Xcode. */
  103. if (clang_mode && (!strcmp(argv[i], "-q") || !strcmp(argv[i], "-Q")))
  104. continue;
  105. #endif /* __APPLE__ */
  106. as_params[as_par_cnt++] = argv[i];
  107. }
  108. #ifdef __APPLE__
  109. /* When calling clang as the upstream assembler, append -c -x assembler
  110. and hope for the best. */
  111. if (use_clang_as) {
  112. as_params[as_par_cnt++] = "-c";
  113. as_params[as_par_cnt++] = "-x";
  114. as_params[as_par_cnt++] = "assembler";
  115. }
  116. #endif /* __APPLE__ */
  117. input_file = argv[argc - 1];
  118. if (input_file[0] == '-') {
  119. if (!strcmp(input_file + 1, "-version")) {
  120. just_version = 1;
  121. modified_file = input_file;
  122. goto wrap_things_up;
  123. }
  124. if (input_file[1]) FATAL("Incorrect use (not called through afl-gcc?)");
  125. else input_file = NULL;
  126. } else {
  127. /* Check if this looks like a standard invocation as a part of an attempt
  128. to compile a program, rather than using gcc on an ad-hoc .s file in
  129. a format we may not understand. This works around an issue compiling
  130. NSS. */
  131. if (strncmp(input_file, tmp_dir, strlen(tmp_dir)) &&
  132. strncmp(input_file, "/var/tmp/", 9) &&
  133. strncmp(input_file, "/tmp/", 5)) pass_thru = 1;
  134. }
  135. modified_file = alloc_printf("%s/.afl-%u-%u.s", tmp_dir, getpid(),
  136. (u32)time(NULL));
  137. wrap_things_up:
  138. as_params[as_par_cnt++] = modified_file;
  139. as_params[as_par_cnt] = NULL;
  140. }
  141. /* Process input file, generate modified_file. Insert instrumentation in all
  142. the appropriate places. */
  143. static void add_instrumentation(void) {
  144. static u8 line[MAX_LINE];
  145. FILE* inf;
  146. FILE* outf;
  147. s32 outfd;
  148. u32 ins_lines = 0;
  149. u8 instr_ok = 0, skip_csect = 0, skip_next_label = 0,
  150. skip_intel = 0, skip_app = 0, instrument_next = 0;
  151. #ifdef __APPLE__
  152. u8* colon_pos;
  153. #endif /* __APPLE__ */
  154. if (input_file) {
  155. inf = fopen(input_file, "r");
  156. if (!inf) PFATAL("Unable to read '%s'", input_file);
  157. } else inf = stdin;
  158. outfd = open(modified_file, O_WRONLY | O_EXCL | O_CREAT, 0600);
  159. if (outfd < 0) PFATAL("Unable to write to '%s'", modified_file);
  160. outf = fdopen(outfd, "w");
  161. if (!outf) PFATAL("fdopen() failed");
  162. while (fgets(line, MAX_LINE, inf)) {
  163. /* In some cases, we want to defer writing the instrumentation trampoline
  164. until after all the labels, macros, comments, etc. If we're in this
  165. mode, and if the line starts with a tab followed by a character, dump
  166. the trampoline now. */
  167. if (!pass_thru && !skip_intel && !skip_app && !skip_csect && instr_ok &&
  168. instrument_next && line[0] == '\t' && isalpha(line[1])) {
  169. fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
  170. R(MAP_SIZE));
  171. instrument_next = 0;
  172. ins_lines++;
  173. }
  174. /* Output the actual line, call it a day in pass-thru mode. */
  175. fputs(line, outf);
  176. if (pass_thru) continue;
  177. /* All right, this is where the actual fun begins. For one, we only want to
  178. instrument the .text section. So, let's keep track of that in processed
  179. files - and let's set instr_ok accordingly. */
  180. if (line[0] == '\t' && line[1] == '.') {
  181. /* OpenBSD puts jump tables directly inline with the code, which is
  182. a bit annoying. They use a specific format of p2align directives
  183. around them, so we use that as a signal. */
  184. if (!clang_mode && instr_ok && !strncmp(line + 2, "p2align ", 8) &&
  185. isdigit(line[10]) && line[11] == '\n') skip_next_label = 1;
  186. if (!strncmp(line + 2, "text\n", 5) ||
  187. !strncmp(line + 2, "section\t.text", 13) ||
  188. !strncmp(line + 2, "section\t__TEXT,__text", 21) ||
  189. !strncmp(line + 2, "section __TEXT,__text", 21)) {
  190. instr_ok = 1;
  191. continue;
  192. }
  193. if (!strncmp(line + 2, "section\t", 8) ||
  194. !strncmp(line + 2, "section ", 8) ||
  195. !strncmp(line + 2, "bss\n", 4) ||
  196. !strncmp(line + 2, "data\n", 5)) {
  197. instr_ok = 0;
  198. continue;
  199. }
  200. }
  201. /* Detect off-flavor assembly (rare, happens in gdb). When this is
  202. encountered, we set skip_csect until the opposite directive is
  203. seen, and we do not instrument. */
  204. if (strstr(line, ".code")) {
  205. if (strstr(line, ".code32")) skip_csect = use_64bit;
  206. if (strstr(line, ".code64")) skip_csect = !use_64bit;
  207. }
  208. /* Detect syntax changes, as could happen with hand-written assembly.
  209. Skip Intel blocks, resume instrumentation when back to AT&T. */
  210. if (strstr(line, ".intel_syntax")) skip_intel = 1;
  211. if (strstr(line, ".att_syntax")) skip_intel = 0;
  212. /* Detect and skip ad-hoc __asm__ blocks, likewise skipping them. */
  213. if (line[0] == '#' || line[1] == '#') {
  214. if (strstr(line, "#APP")) skip_app = 1;
  215. if (strstr(line, "#NO_APP")) skip_app = 0;
  216. }
  217. /* If we're in the right mood for instrumenting, check for function
  218. names or conditional labels. This is a bit messy, but in essence,
  219. we want to catch:
  220. ^main: - function entry point (always instrumented)
  221. ^.L0: - GCC branch label
  222. ^.LBB0_0: - clang branch label (but only in clang mode)
  223. ^\tjnz foo - conditional branches
  224. ...but not:
  225. ^# BB#0: - clang comments
  226. ^ # BB#0: - ditto
  227. ^.Ltmp0: - clang non-branch labels
  228. ^.LC0 - GCC non-branch labels
  229. ^.LBB0_0: - ditto (when in GCC mode)
  230. ^\tjmp foo - non-conditional jumps
  231. Additionally, clang and GCC on MacOS X follow a different convention
  232. with no leading dots on labels, hence the weird maze of #ifdefs
  233. later on.
  234. */
  235. if (skip_intel || skip_app || skip_csect || !instr_ok ||
  236. line[0] == '#' || line[0] == ' ') continue;
  237. /* Conditional branch instruction (jnz, etc). We append the instrumentation
  238. right after the branch (to instrument the not-taken path) and at the
  239. branch destination label (handled later on). */
  240. if (line[0] == '\t') {
  241. if (line[1] == 'j' && line[2] != 'm' && R(100) < inst_ratio) {
  242. fprintf(outf, use_64bit ? trampoline_fmt_64 : trampoline_fmt_32,
  243. R(MAP_SIZE));
  244. ins_lines++;
  245. }
  246. continue;
  247. }
  248. /* Label of some sort. This may be a branch destination, but we need to
  249. tread carefully and account for several different formatting
  250. conventions. */
  251. #ifdef __APPLE__
  252. /* Apple: L<whatever><digit>: */
  253. if ((colon_pos = strstr(line, ":"))) {
  254. if (line[0] == 'L' && isdigit(*(colon_pos - 1))) {
  255. #else
  256. /* Everybody else: .L<whatever>: */
  257. if (strstr(line, ":")) {
  258. if (line[0] == '.') {
  259. #endif /* __APPLE__ */
  260. /* .L0: or LBB0_0: style jump destination */
  261. #ifdef __APPLE__
  262. /* Apple: L<num> / LBB<num> */
  263. if ((isdigit(line[1]) || (clang_mode && !strncmp(line, "LBB", 3)))
  264. && R(100) < inst_ratio) {
  265. #else
  266. /* Apple: .L<num> / .LBB<num> */
  267. if ((isdigit(line[2]) || (clang_mode && !strncmp(line + 1, "LBB", 3)))
  268. && R(100) < inst_ratio) {
  269. #endif /* __APPLE__ */
  270. /* An optimization is possible here by adding the code only if the
  271. label is mentioned in the code in contexts other than call / jmp.
  272. That said, this complicates the code by requiring two-pass
  273. processing (messy with stdin), and results in a speed gain
  274. typically under 10%, because compilers are generally pretty good
  275. about not generating spurious intra-function jumps.
  276. We use deferred output chiefly to avoid disrupting
  277. .Lfunc_begin0-style exception handling calculations (a problem on
  278. MacOS X). */
  279. if (!skip_next_label) instrument_next = 1; else skip_next_label = 0;
  280. }
  281. } else {
  282. /* Function label (always instrumented, deferred mode). */
  283. instrument_next = 1;
  284. }
  285. }
  286. }
  287. if (ins_lines)
  288. fputs(use_64bit ? main_payload_64 : main_payload_32, outf);
  289. if (input_file) fclose(inf);
  290. fclose(outf);
  291. if (!be_quiet) {
  292. if (!ins_lines) WARNF("No instrumentation targets found%s.",
  293. pass_thru ? " (pass-thru mode)" : "");
  294. else OKF("Instrumented %u locations (%s-bit, %s mode, ratio %u%%).",
  295. ins_lines, use_64bit ? "64" : "32",
  296. getenv("AFL_HARDEN") ? "hardened" :
  297. (sanitizer ? "ASAN/MSAN" : "non-hardened"),
  298. inst_ratio);
  299. }
  300. }
  301. /* Main entry point */
  302. int main(int argc, char** argv) {
  303. s32 pid;
  304. u32 rand_seed;
  305. int status;
  306. u8* inst_ratio_str = getenv("AFL_INST_RATIO");
  307. struct timeval tv;
  308. struct timezone tz;
  309. clang_mode = !!getenv(CLANG_ENV_VAR);
  310. if (isatty(2) && !getenv("AFL_QUIET")) {
  311. SAYF(cCYA "afl-as " cBRI VERSION cRST " by <lcamtuf@google.com>\n");
  312. } else be_quiet = 1;
  313. if (argc < 2) {
  314. SAYF("\n"
  315. "This is a helper application for afl-fuzz. It is a wrapper around GNU 'as',\n"
  316. "executed by the toolchain whenever using afl-gcc or afl-clang. You probably\n"
  317. "don't want to run this program directly.\n\n"
  318. "Rarely, when dealing with extremely complex projects, it may be advisable to\n"
  319. "set AFL_INST_RATIO to a value less than 100 in order to reduce the odds of\n"
  320. "instrumenting every discovered branch.\n\n");
  321. exit(1);
  322. }
  323. gettimeofday(&tv, &tz);
  324. rand_seed = tv.tv_sec ^ tv.tv_usec ^ getpid();
  325. srandom(rand_seed);
  326. edit_params(argc, argv);
  327. if (inst_ratio_str) {
  328. if (sscanf(inst_ratio_str, "%u", &inst_ratio) != 1 || inst_ratio > 100)
  329. FATAL("Bad value of AFL_INST_RATIO (must be between 0 and 100)");
  330. }
  331. if (getenv(AS_LOOP_ENV_VAR))
  332. FATAL("Endless loop when calling 'as' (remove '.' from your PATH)");
  333. setenv(AS_LOOP_ENV_VAR, "1", 1);
  334. /* When compiling with ASAN, we don't have a particularly elegant way to skip
  335. ASAN-specific branches. But we can probabilistically compensate for
  336. that... */
  337. if (getenv("AFL_USE_ASAN") || getenv("AFL_USE_MSAN")) {
  338. sanitizer = 1;
  339. inst_ratio /= 3;
  340. }
  341. if (!just_version) add_instrumentation();
  342. if (!(pid = fork())) {
  343. execvp(as_params[0], (char**)as_params);
  344. FATAL("Oops, failed to execute '%s' - check your PATH", as_params[0]);
  345. }
  346. if (pid < 0) PFATAL("fork() failed");
  347. if (waitpid(pid, &status, 0) <= 0) PFATAL("waitpid() failed");
  348. if (!getenv("AFL_KEEP_ASSEMBLY")) unlink(modified_file);
  349. exit(WEXITSTATUS(status));
  350. }