afl-tmin.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  1. /*
  2. american fuzzy lop - test case minimizer
  3. ----------------------------------------
  4. Written and maintained by Michal Zalewski <lcamtuf@google.com>
  5. Copyright 2015, 2016, 2017 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. A simple test case minimizer that takes an input file and tries to remove
  11. as much data as possible while keeping the binary in a crashing state
  12. *or* producing consistent instrumentation output (the mode is auto-selected
  13. based on the initially observed behavior).
  14. */
  15. #define AFL_MAIN
  16. #include "config.h"
  17. #include "types.h"
  18. #include "debug.h"
  19. #include "alloc-inl.h"
  20. #include "hash.h"
  21. #include <stdio.h>
  22. #include <unistd.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <time.h>
  26. #include <errno.h>
  27. #include <signal.h>
  28. #include <dirent.h>
  29. #include <fcntl.h>
  30. #include <sys/wait.h>
  31. #include <sys/time.h>
  32. #include <sys/shm.h>
  33. #include <sys/stat.h>
  34. #include <sys/types.h>
  35. #include <sys/resource.h>
  36. static s32 child_pid; /* PID of the tested program */
  37. static u8 *trace_bits, /* SHM with instrumentation bitmap */
  38. *mask_bitmap; /* Mask for trace bits (-B) */
  39. static u8 *in_file, /* Minimizer input test case */
  40. *out_file, /* Minimizer output file */
  41. *prog_in, /* Targeted program input file */
  42. *target_path, /* Path to target binary */
  43. *doc_path; /* Path to docs */
  44. static u8* in_data; /* Input data for trimming */
  45. static u32 in_len, /* Input data length */
  46. orig_cksum, /* Original checksum */
  47. total_execs, /* Total number of execs */
  48. missed_hangs, /* Misses due to hangs */
  49. missed_crashes, /* Misses due to crashes */
  50. missed_paths, /* Misses due to exec path diffs */
  51. exec_tmout = EXEC_TIMEOUT; /* Exec timeout (ms) */
  52. static u64 mem_limit = MEM_LIMIT; /* Memory limit (MB) */
  53. static s32 shm_id, /* ID of the SHM region */
  54. dev_null_fd = -1; /* FD to /dev/null */
  55. static u8 crash_mode, /* Crash-centric mode? */
  56. exit_crash, /* Treat non-zero exit as crash? */
  57. edges_only, /* Ignore hit counts? */
  58. exact_mode, /* Require path match for crashes? */
  59. use_stdin = 1; /* Use stdin for program input? */
  60. static volatile u8
  61. stop_soon, /* Ctrl-C pressed? */
  62. child_timed_out; /* Child timed out? */
  63. /* Classify tuple counts. This is a slow & naive version, but good enough here. */
  64. static const u8 count_class_lookup[256] = {
  65. [0] = 0,
  66. [1] = 1,
  67. [2] = 2,
  68. [3] = 4,
  69. [4 ... 7] = 8,
  70. [8 ... 15] = 16,
  71. [16 ... 31] = 32,
  72. [32 ... 127] = 64,
  73. [128 ... 255] = 128
  74. };
  75. static void classify_counts(u8* mem) {
  76. u32 i = MAP_SIZE;
  77. if (edges_only) {
  78. while (i--) {
  79. if (*mem) *mem = 1;
  80. mem++;
  81. }
  82. } else {
  83. while (i--) {
  84. *mem = count_class_lookup[*mem];
  85. mem++;
  86. }
  87. }
  88. }
  89. /* Apply mask to classified bitmap (if set). */
  90. static void apply_mask(u32* mem, u32* mask) {
  91. u32 i = (MAP_SIZE >> 2);
  92. if (!mask) return;
  93. while (i--) {
  94. *mem &= ~*mask;
  95. mem++;
  96. mask++;
  97. }
  98. }
  99. /* See if any bytes are set in the bitmap. */
  100. static inline u8 anything_set(void) {
  101. u32* ptr = (u32*)trace_bits;
  102. u32 i = (MAP_SIZE >> 2);
  103. while (i--) if (*(ptr++)) return 1;
  104. return 0;
  105. }
  106. /* Get rid of shared memory and temp files (atexit handler). */
  107. static void remove_shm(void) {
  108. if (prog_in) unlink(prog_in); /* Ignore errors */
  109. shmctl(shm_id, IPC_RMID, NULL);
  110. }
  111. /* Configure shared memory. */
  112. static void setup_shm(void) {
  113. u8* shm_str;
  114. shm_id = shmget(IPC_PRIVATE, MAP_SIZE, IPC_CREAT | IPC_EXCL | 0600);
  115. if (shm_id < 0) PFATAL("shmget() failed");
  116. atexit(remove_shm);
  117. shm_str = alloc_printf("%d", shm_id);
  118. setenv(SHM_ENV_VAR, shm_str, 1);
  119. ck_free(shm_str);
  120. trace_bits = shmat(shm_id, NULL, 0);
  121. if (!trace_bits) PFATAL("shmat() failed");
  122. }
  123. /* Read initial file. */
  124. static void read_initial_file(void) {
  125. struct stat st;
  126. s32 fd = open(in_file, O_RDONLY);
  127. if (fd < 0) PFATAL("Unable to open '%s'", in_file);
  128. if (fstat(fd, &st) || !st.st_size)
  129. FATAL("Zero-sized input file.");
  130. if (st.st_size >= TMIN_MAX_FILE)
  131. FATAL("Input file is too large (%u MB max)", TMIN_MAX_FILE / 1024 / 1024);
  132. in_len = st.st_size;
  133. in_data = ck_alloc_nozero(in_len);
  134. ck_read(fd, in_data, in_len, in_file);
  135. close(fd);
  136. OKF("Read %u byte%s from '%s'.", in_len, in_len == 1 ? "" : "s", in_file);
  137. }
  138. /* Write output file. */
  139. static s32 write_to_file(u8* path, u8* mem, u32 len) {
  140. s32 ret;
  141. unlink(path); /* Ignore errors */
  142. ret = open(path, O_RDWR | O_CREAT | O_EXCL, 0600);
  143. if (ret < 0) PFATAL("Unable to create '%s'", path);
  144. ck_write(ret, mem, len, path);
  145. lseek(ret, 0, SEEK_SET);
  146. return ret;
  147. }
  148. /* Handle timeout signal. */
  149. static void handle_timeout(int sig) {
  150. child_timed_out = 1;
  151. if (child_pid > 0) kill(child_pid, SIGKILL);
  152. }
  153. /* Execute target application. Returns 0 if the changes are a dud, or
  154. 1 if they should be kept. */
  155. static u8 run_target(char** argv, u8* mem, u32 len, u8 first_run) {
  156. static struct itimerval it;
  157. int status = 0;
  158. s32 prog_in_fd;
  159. u32 cksum;
  160. memset(trace_bits, 0, MAP_SIZE);
  161. MEM_BARRIER();
  162. prog_in_fd = write_to_file(prog_in, mem, len);
  163. child_pid = fork();
  164. if (child_pid < 0) PFATAL("fork() failed");
  165. if (!child_pid) {
  166. struct rlimit r;
  167. if (dup2(use_stdin ? prog_in_fd : dev_null_fd, 0) < 0 ||
  168. dup2(dev_null_fd, 1) < 0 ||
  169. dup2(dev_null_fd, 2) < 0) {
  170. *(u32*)trace_bits = EXEC_FAIL_SIG;
  171. PFATAL("dup2() failed");
  172. }
  173. close(dev_null_fd);
  174. close(prog_in_fd);
  175. setsid();
  176. if (mem_limit) {
  177. r.rlim_max = r.rlim_cur = ((rlim_t)mem_limit) << 20;
  178. #ifdef RLIMIT_AS
  179. setrlimit(RLIMIT_AS, &r); /* Ignore errors */
  180. #else
  181. setrlimit(RLIMIT_DATA, &r); /* Ignore errors */
  182. #endif /* ^RLIMIT_AS */
  183. }
  184. r.rlim_max = r.rlim_cur = 0;
  185. setrlimit(RLIMIT_CORE, &r); /* Ignore errors */
  186. execv(target_path, argv);
  187. *(u32*)trace_bits = EXEC_FAIL_SIG;
  188. exit(0);
  189. }
  190. close(prog_in_fd);
  191. /* Configure timeout, wait for child, cancel timeout. */
  192. child_timed_out = 0;
  193. it.it_value.tv_sec = (exec_tmout / 1000);
  194. it.it_value.tv_usec = (exec_tmout % 1000) * 1000;
  195. setitimer(ITIMER_REAL, &it, NULL);
  196. if (waitpid(child_pid, &status, 0) <= 0) FATAL("waitpid() failed");
  197. child_pid = 0;
  198. it.it_value.tv_sec = 0;
  199. it.it_value.tv_usec = 0;
  200. setitimer(ITIMER_REAL, &it, NULL);
  201. MEM_BARRIER();
  202. /* Clean up bitmap, analyze exit condition, etc. */
  203. if (*(u32*)trace_bits == EXEC_FAIL_SIG)
  204. FATAL("Unable to execute '%s'", argv[0]);
  205. classify_counts(trace_bits);
  206. apply_mask((u32*)trace_bits, (u32*)mask_bitmap);
  207. total_execs++;
  208. if (stop_soon) {
  209. SAYF(cRST cLRD "\n+++ Minimization aborted by user +++\n" cRST);
  210. close(write_to_file(out_file, in_data, in_len));
  211. exit(1);
  212. }
  213. /* Always discard inputs that time out. */
  214. if (child_timed_out) {
  215. missed_hangs++;
  216. return 0;
  217. }
  218. /* Handle crashing inputs depending on current mode. */
  219. if (WIFSIGNALED(status) ||
  220. (WIFEXITED(status) && WEXITSTATUS(status) == MSAN_ERROR) ||
  221. (WIFEXITED(status) && WEXITSTATUS(status) && exit_crash)) {
  222. if (first_run) crash_mode = 1;
  223. if (crash_mode) {
  224. if (!exact_mode) return 1;
  225. } else {
  226. missed_crashes++;
  227. return 0;
  228. }
  229. } else
  230. /* Handle non-crashing inputs appropriately. */
  231. if (crash_mode) {
  232. missed_paths++;
  233. return 0;
  234. }
  235. cksum = hash32(trace_bits, MAP_SIZE, HASH_CONST);
  236. if (first_run) orig_cksum = cksum;
  237. if (orig_cksum == cksum) return 1;
  238. missed_paths++;
  239. return 0;
  240. }
  241. /* Find first power of two greater or equal to val. */
  242. static u32 next_p2(u32 val) {
  243. u32 ret = 1;
  244. while (val > ret) ret <<= 1;
  245. return ret;
  246. }
  247. /* Actually minimize! */
  248. static void minimize(char** argv) {
  249. static u32 alpha_map[256];
  250. u8* tmp_buf = ck_alloc_nozero(in_len);
  251. u32 orig_len = in_len, stage_o_len;
  252. u32 del_len, set_len, del_pos, set_pos, i, alpha_size, cur_pass = 0;
  253. u32 syms_removed, alpha_del0 = 0, alpha_del1, alpha_del2, alpha_d_total = 0;
  254. u8 changed_any, prev_del;
  255. /***********************
  256. * BLOCK NORMALIZATION *
  257. ***********************/
  258. set_len = next_p2(in_len / TMIN_SET_STEPS);
  259. set_pos = 0;
  260. if (set_len < TMIN_SET_MIN_SIZE) set_len = TMIN_SET_MIN_SIZE;
  261. ACTF(cBRI "Stage #0: " cRST "One-time block normalization...");
  262. while (set_pos < in_len) {
  263. u8 res;
  264. u32 use_len = MIN(set_len, in_len - set_pos);
  265. for (i = 0; i < use_len; i++)
  266. if (in_data[set_pos + i] != '0') break;
  267. if (i != use_len) {
  268. memcpy(tmp_buf, in_data, in_len);
  269. memset(tmp_buf + set_pos, '0', use_len);
  270. res = run_target(argv, tmp_buf, in_len, 0);
  271. if (res) {
  272. memset(in_data + set_pos, '0', use_len);
  273. changed_any = 1;
  274. alpha_del0 += use_len;
  275. }
  276. }
  277. set_pos += set_len;
  278. }
  279. alpha_d_total += alpha_del0;
  280. OKF("Block normalization complete, %u byte%s replaced.", alpha_del0,
  281. alpha_del0 == 1 ? "" : "s");
  282. next_pass:
  283. ACTF(cYEL "--- " cBRI "Pass #%u " cYEL "---", ++cur_pass);
  284. changed_any = 0;
  285. /******************
  286. * BLOCK DELETION *
  287. ******************/
  288. del_len = next_p2(in_len / TRIM_START_STEPS);
  289. stage_o_len = in_len;
  290. ACTF(cBRI "Stage #1: " cRST "Removing blocks of data...");
  291. next_del_blksize:
  292. if (!del_len) del_len = 1;
  293. del_pos = 0;
  294. prev_del = 1;
  295. SAYF(cGRA " Block length = %u, remaining size = %u\n" cRST,
  296. del_len, in_len);
  297. while (del_pos < in_len) {
  298. u8 res;
  299. s32 tail_len;
  300. tail_len = in_len - del_pos - del_len;
  301. if (tail_len < 0) tail_len = 0;
  302. /* If we have processed at least one full block (initially, prev_del == 1),
  303. and we did so without deleting the previous one, and we aren't at the
  304. very end of the buffer (tail_len > 0), and the current block is the same
  305. as the previous one... skip this step as a no-op. */
  306. if (!prev_del && tail_len && !memcmp(in_data + del_pos - del_len,
  307. in_data + del_pos, del_len)) {
  308. del_pos += del_len;
  309. continue;
  310. }
  311. prev_del = 0;
  312. /* Head */
  313. memcpy(tmp_buf, in_data, del_pos);
  314. /* Tail */
  315. memcpy(tmp_buf + del_pos, in_data + del_pos + del_len, tail_len);
  316. res = run_target(argv, tmp_buf, del_pos + tail_len, 0);
  317. if (res) {
  318. memcpy(in_data, tmp_buf, del_pos + tail_len);
  319. prev_del = 1;
  320. in_len = del_pos + tail_len;
  321. changed_any = 1;
  322. } else del_pos += del_len;
  323. }
  324. if (del_len > 1 && in_len >= 1) {
  325. del_len /= 2;
  326. goto next_del_blksize;
  327. }
  328. OKF("Block removal complete, %u bytes deleted.", stage_o_len - in_len);
  329. if (!in_len && changed_any)
  330. WARNF(cLRD "Down to zero bytes - check the command line and mem limit!" cRST);
  331. if (cur_pass > 1 && !changed_any) goto finalize_all;
  332. /*************************
  333. * ALPHABET MINIMIZATION *
  334. *************************/
  335. alpha_size = 0;
  336. alpha_del1 = 0;
  337. syms_removed = 0;
  338. memset(alpha_map, 0, 256 * sizeof(u32));
  339. for (i = 0; i < in_len; i++) {
  340. if (!alpha_map[in_data[i]]) alpha_size++;
  341. alpha_map[in_data[i]]++;
  342. }
  343. ACTF(cBRI "Stage #2: " cRST "Minimizing symbols (%u code point%s)...",
  344. alpha_size, alpha_size == 1 ? "" : "s");
  345. for (i = 0; i < 256; i++) {
  346. u32 r;
  347. u8 res;
  348. if (i == '0' || !alpha_map[i]) continue;
  349. memcpy(tmp_buf, in_data, in_len);
  350. for (r = 0; r < in_len; r++)
  351. if (tmp_buf[r] == i) tmp_buf[r] = '0';
  352. res = run_target(argv, tmp_buf, in_len, 0);
  353. if (res) {
  354. memcpy(in_data, tmp_buf, in_len);
  355. syms_removed++;
  356. alpha_del1 += alpha_map[i];
  357. changed_any = 1;
  358. }
  359. }
  360. alpha_d_total += alpha_del1;
  361. OKF("Symbol minimization finished, %u symbol%s (%u byte%s) replaced.",
  362. syms_removed, syms_removed == 1 ? "" : "s",
  363. alpha_del1, alpha_del1 == 1 ? "" : "s");
  364. /**************************
  365. * CHARACTER MINIMIZATION *
  366. **************************/
  367. alpha_del2 = 0;
  368. ACTF(cBRI "Stage #3: " cRST "Character minimization...");
  369. memcpy(tmp_buf, in_data, in_len);
  370. for (i = 0; i < in_len; i++) {
  371. u8 res, orig = tmp_buf[i];
  372. if (orig == '0') continue;
  373. tmp_buf[i] = '0';
  374. res = run_target(argv, tmp_buf, in_len, 0);
  375. if (res) {
  376. in_data[i] = '0';
  377. alpha_del2++;
  378. changed_any = 1;
  379. } else tmp_buf[i] = orig;
  380. }
  381. alpha_d_total += alpha_del2;
  382. OKF("Character minimization done, %u byte%s replaced.",
  383. alpha_del2, alpha_del2 == 1 ? "" : "s");
  384. if (changed_any) goto next_pass;
  385. finalize_all:
  386. SAYF("\n"
  387. cGRA " File size reduced by : " cRST "%0.02f%% (to %u byte%s)\n"
  388. cGRA " Characters simplified : " cRST "%0.02f%%\n"
  389. cGRA " Number of execs done : " cRST "%u\n"
  390. cGRA " Fruitless execs : " cRST "path=%u crash=%u hang=%s%u\n\n",
  391. 100 - ((double)in_len) * 100 / orig_len, in_len, in_len == 1 ? "" : "s",
  392. ((double)(alpha_d_total)) * 100 / (in_len ? in_len : 1),
  393. total_execs, missed_paths, missed_crashes, missed_hangs ? cLRD : "",
  394. missed_hangs);
  395. if (total_execs > 50 && missed_hangs * 10 > total_execs)
  396. WARNF(cLRD "Frequent timeouts - results may be skewed." cRST);
  397. }
  398. /* Handle Ctrl-C and the like. */
  399. static void handle_stop_sig(int sig) {
  400. stop_soon = 1;
  401. if (child_pid > 0) kill(child_pid, SIGKILL);
  402. }
  403. /* Do basic preparations - persistent fds, filenames, etc. */
  404. static void set_up_environment(void) {
  405. u8* x;
  406. dev_null_fd = open("/dev/null", O_RDWR);
  407. if (dev_null_fd < 0) PFATAL("Unable to open /dev/null");
  408. if (!prog_in) {
  409. u8* use_dir = ".";
  410. if (access(use_dir, R_OK | W_OK | X_OK)) {
  411. use_dir = getenv("TMPDIR");
  412. if (!use_dir) use_dir = "/tmp";
  413. }
  414. prog_in = alloc_printf("%s/.afl-tmin-temp-%u", use_dir, getpid());
  415. }
  416. /* Set sane defaults... */
  417. x = getenv("ASAN_OPTIONS");
  418. if (x) {
  419. if (!strstr(x, "abort_on_error=1"))
  420. FATAL("Custom ASAN_OPTIONS set without abort_on_error=1 - please fix!");
  421. if (!strstr(x, "symbolize=0"))
  422. FATAL("Custom ASAN_OPTIONS set without symbolize=0 - please fix!");
  423. }
  424. x = getenv("MSAN_OPTIONS");
  425. if (x) {
  426. if (!strstr(x, "exit_code=" STRINGIFY(MSAN_ERROR)))
  427. FATAL("Custom MSAN_OPTIONS set without exit_code="
  428. STRINGIFY(MSAN_ERROR) " - please fix!");
  429. if (!strstr(x, "symbolize=0"))
  430. FATAL("Custom MSAN_OPTIONS set without symbolize=0 - please fix!");
  431. }
  432. setenv("ASAN_OPTIONS", "abort_on_error=1:"
  433. "detect_leaks=0:"
  434. "symbolize=0:"
  435. "allocator_may_return_null=1", 0);
  436. setenv("MSAN_OPTIONS", "exit_code=" STRINGIFY(MSAN_ERROR) ":"
  437. "symbolize=0:"
  438. "abort_on_error=1:"
  439. "allocator_may_return_null=1:"
  440. "msan_track_origins=0", 0);
  441. if (getenv("AFL_PRELOAD")) {
  442. setenv("LD_PRELOAD", getenv("AFL_PRELOAD"), 1);
  443. setenv("DYLD_INSERT_LIBRARIES", getenv("AFL_PRELOAD"), 1);
  444. }
  445. }
  446. /* Setup signal handlers, duh. */
  447. static void setup_signal_handlers(void) {
  448. struct sigaction sa;
  449. sa.sa_handler = NULL;
  450. sa.sa_flags = SA_RESTART;
  451. sa.sa_sigaction = NULL;
  452. sigemptyset(&sa.sa_mask);
  453. /* Various ways of saying "stop". */
  454. sa.sa_handler = handle_stop_sig;
  455. sigaction(SIGHUP, &sa, NULL);
  456. sigaction(SIGINT, &sa, NULL);
  457. sigaction(SIGTERM, &sa, NULL);
  458. /* Exec timeout notifications. */
  459. sa.sa_handler = handle_timeout;
  460. sigaction(SIGALRM, &sa, NULL);
  461. }
  462. /* Detect @@ in args. */
  463. static void detect_file_args(char** argv) {
  464. u32 i = 0;
  465. u8* cwd = getcwd(NULL, 0);
  466. if (!cwd) PFATAL("getcwd() failed");
  467. while (argv[i]) {
  468. u8* aa_loc = strstr(argv[i], "@@");
  469. if (aa_loc) {
  470. u8 *aa_subst, *n_arg;
  471. /* Be sure that we're always using fully-qualified paths. */
  472. if (prog_in[0] == '/') aa_subst = prog_in;
  473. else aa_subst = alloc_printf("%s/%s", cwd, prog_in);
  474. /* Construct a replacement argv value. */
  475. *aa_loc = 0;
  476. n_arg = alloc_printf("%s%s%s", argv[i], aa_subst, aa_loc + 2);
  477. argv[i] = n_arg;
  478. *aa_loc = '@';
  479. if (prog_in[0] != '/') ck_free(aa_subst);
  480. }
  481. i++;
  482. }
  483. free(cwd); /* not tracked */
  484. }
  485. /* Display usage hints. */
  486. static void usage(u8* argv0) {
  487. SAYF("\n%s [ options ] -- /path/to/target_app [ ... ]\n\n"
  488. "Required parameters:\n\n"
  489. " -i file - input test case to be shrunk by the tool\n"
  490. " -o file - final output location for the minimized data\n\n"
  491. "Execution control settings:\n\n"
  492. " -f file - input file read by the tested program (stdin)\n"
  493. " -t msec - timeout for each run (%u ms)\n"
  494. " -m megs - memory limit for child process (%u MB)\n"
  495. " -Q - use binary-only instrumentation (QEMU mode)\n\n"
  496. "Minimization settings:\n\n"
  497. " -e - solve for edge coverage only, ignore hit counts\n"
  498. " -x - treat non-zero exit codes as crashes\n\n"
  499. "For additional tips, please consult %s/README.\n\n",
  500. argv0, EXEC_TIMEOUT, MEM_LIMIT, doc_path);
  501. exit(1);
  502. }
  503. /* Find binary. */
  504. static void find_binary(u8* fname) {
  505. u8* env_path = 0;
  506. struct stat st;
  507. if (strchr(fname, '/') || !(env_path = getenv("PATH"))) {
  508. target_path = ck_strdup(fname);
  509. if (stat(target_path, &st) || !S_ISREG(st.st_mode) ||
  510. !(st.st_mode & 0111) || st.st_size < 4)
  511. FATAL("Program '%s' not found or not executable", fname);
  512. } else {
  513. while (env_path) {
  514. u8 *cur_elem, *delim = strchr(env_path, ':');
  515. if (delim) {
  516. cur_elem = ck_alloc(delim - env_path + 1);
  517. memcpy(cur_elem, env_path, delim - env_path);
  518. delim++;
  519. } else cur_elem = ck_strdup(env_path);
  520. env_path = delim;
  521. if (cur_elem[0])
  522. target_path = alloc_printf("%s/%s", cur_elem, fname);
  523. else
  524. target_path = ck_strdup(fname);
  525. ck_free(cur_elem);
  526. if (!stat(target_path, &st) && S_ISREG(st.st_mode) &&
  527. (st.st_mode & 0111) && st.st_size >= 4) break;
  528. ck_free(target_path);
  529. target_path = 0;
  530. }
  531. if (!target_path) FATAL("Program '%s' not found or not executable", fname);
  532. }
  533. }
  534. /* Fix up argv for QEMU. */
  535. static char** get_qemu_argv(u8* own_loc, char** argv, int argc) {
  536. char** new_argv = ck_alloc(sizeof(char*) * (argc + 4));
  537. u8 *tmp, *cp, *rsl, *own_copy;
  538. /* Workaround for a QEMU stability glitch. */
  539. setenv("QEMU_LOG", "nochain", 1);
  540. memcpy(new_argv + 3, argv + 1, sizeof(char*) * argc);
  541. /* Now we need to actually find qemu for argv[0]. */
  542. new_argv[2] = target_path;
  543. new_argv[1] = "--";
  544. tmp = getenv("AFL_PATH");
  545. if (tmp) {
  546. cp = alloc_printf("%s/afl-qemu-trace", tmp);
  547. if (access(cp, X_OK))
  548. FATAL("Unable to find '%s'", tmp);
  549. target_path = new_argv[0] = cp;
  550. return new_argv;
  551. }
  552. own_copy = ck_strdup(own_loc);
  553. rsl = strrchr(own_copy, '/');
  554. if (rsl) {
  555. *rsl = 0;
  556. cp = alloc_printf("%s/afl-qemu-trace", own_copy);
  557. ck_free(own_copy);
  558. if (!access(cp, X_OK)) {
  559. target_path = new_argv[0] = cp;
  560. return new_argv;
  561. }
  562. } else ck_free(own_copy);
  563. if (!access(BIN_PATH "/afl-qemu-trace", X_OK)) {
  564. target_path = new_argv[0] = BIN_PATH "/afl-qemu-trace";
  565. return new_argv;
  566. }
  567. FATAL("Unable to find 'afl-qemu-trace'.");
  568. }
  569. /* Read mask bitmap from file. This is for the -B option. */
  570. static void read_bitmap(u8* fname) {
  571. s32 fd = open(fname, O_RDONLY);
  572. if (fd < 0) PFATAL("Unable to open '%s'", fname);
  573. ck_read(fd, mask_bitmap, MAP_SIZE, fname);
  574. close(fd);
  575. }
  576. /* Main entry point */
  577. int main(int argc, char** argv) {
  578. s32 opt;
  579. u8 mem_limit_given = 0, timeout_given = 0, qemu_mode = 0;
  580. char** use_argv;
  581. doc_path = access(DOC_PATH, F_OK) ? "docs" : DOC_PATH;
  582. SAYF(cCYA "afl-tmin " cBRI VERSION cRST " by <lcamtuf@google.com>\n");
  583. while ((opt = getopt(argc,argv,"+i:o:f:m:t:B:xeQ")) > 0)
  584. switch (opt) {
  585. case 'i':
  586. if (in_file) FATAL("Multiple -i options not supported");
  587. in_file = optarg;
  588. break;
  589. case 'o':
  590. if (out_file) FATAL("Multiple -o options not supported");
  591. out_file = optarg;
  592. break;
  593. case 'f':
  594. if (prog_in) FATAL("Multiple -f options not supported");
  595. use_stdin = 0;
  596. prog_in = optarg;
  597. break;
  598. case 'e':
  599. if (edges_only) FATAL("Multiple -e options not supported");
  600. edges_only = 1;
  601. break;
  602. case 'x':
  603. if (exit_crash) FATAL("Multiple -x options not supported");
  604. exit_crash = 1;
  605. break;
  606. case 'm': {
  607. u8 suffix = 'M';
  608. if (mem_limit_given) FATAL("Multiple -m options not supported");
  609. mem_limit_given = 1;
  610. if (!strcmp(optarg, "none")) {
  611. mem_limit = 0;
  612. break;
  613. }
  614. if (sscanf(optarg, "%llu%c", &mem_limit, &suffix) < 1 ||
  615. optarg[0] == '-') FATAL("Bad syntax used for -m");
  616. switch (suffix) {
  617. case 'T': mem_limit *= 1024 * 1024; break;
  618. case 'G': mem_limit *= 1024; break;
  619. case 'k': mem_limit /= 1024; break;
  620. case 'M': break;
  621. default: FATAL("Unsupported suffix or bad syntax for -m");
  622. }
  623. if (mem_limit < 5) FATAL("Dangerously low value of -m");
  624. if (sizeof(rlim_t) == 4 && mem_limit > 2000)
  625. FATAL("Value of -m out of range on 32-bit systems");
  626. }
  627. break;
  628. case 't':
  629. if (timeout_given) FATAL("Multiple -t options not supported");
  630. timeout_given = 1;
  631. exec_tmout = atoi(optarg);
  632. if (exec_tmout < 10 || optarg[0] == '-')
  633. FATAL("Dangerously low value of -t");
  634. break;
  635. case 'Q':
  636. if (qemu_mode) FATAL("Multiple -Q options not supported");
  637. if (!mem_limit_given) mem_limit = MEM_LIMIT_QEMU;
  638. qemu_mode = 1;
  639. break;
  640. case 'B': /* load bitmap */
  641. /* This is a secret undocumented option! It is speculated to be useful
  642. if you have a baseline "boring" input file and another "interesting"
  643. file you want to minimize.
  644. You can dump a binary bitmap for the boring file using
  645. afl-showmap -b, and then load it into afl-tmin via -B. The minimizer
  646. will then minimize to preserve only the edges that are unique to
  647. the interesting input file, but ignoring everything from the
  648. original map.
  649. The option may be extended and made more official if it proves
  650. to be useful. */
  651. if (mask_bitmap) FATAL("Multiple -B options not supported");
  652. mask_bitmap = ck_alloc(MAP_SIZE);
  653. read_bitmap(optarg);
  654. break;
  655. default:
  656. usage(argv[0]);
  657. }
  658. if (optind == argc || !in_file || !out_file) usage(argv[0]);
  659. setup_shm();
  660. setup_signal_handlers();
  661. set_up_environment();
  662. find_binary(argv[optind]);
  663. detect_file_args(argv + optind);
  664. if (qemu_mode)
  665. use_argv = get_qemu_argv(argv[0], argv + optind, argc - optind);
  666. else
  667. use_argv = argv + optind;
  668. exact_mode = !!getenv("AFL_TMIN_EXACT");
  669. SAYF("\n");
  670. read_initial_file();
  671. ACTF("Performing dry run (mem limit = %llu MB, timeout = %u ms%s)...",
  672. mem_limit, exec_tmout, edges_only ? ", edges only" : "");
  673. run_target(use_argv, in_data, in_len, 1);
  674. if (child_timed_out)
  675. FATAL("Target binary times out (adjusting -t may help).");
  676. if (!crash_mode) {
  677. OKF("Program terminates normally, minimizing in "
  678. cCYA "instrumented" cRST " mode.");
  679. if (!anything_set()) FATAL("No instrumentation detected.");
  680. } else {
  681. OKF("Program exits with a signal, minimizing in " cMGN "%scrash" cRST
  682. " mode.", exact_mode ? "EXACT " : "");
  683. }
  684. minimize(use_argv);
  685. ACTF("Writing output to '%s'...", out_file);
  686. unlink(prog_in);
  687. prog_in = NULL;
  688. close(write_to_file(out_file, in_data, in_len));
  689. OKF("We're done here. Have a nice day!\n");
  690. exit(0);
  691. }