aboutsummaryrefslogtreecommitdiff
path: root/src/afl-fuzz-init.c
blob: 8ab44a3b564256462b857c4191dbf7d58592e313 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
/*
   american fuzzy lop++ - initialization related routines
   ------------------------------------------------------

   Originally written by Michal Zalewski

   Now maintained by Marc Heuse <mh@mh-sec.de>,
                        Heiko Eißfeldt <heiko.eissfeldt@hexco.de> and
                        Andrea Fioraldi <andreafioraldi@gmail.com>

   Copyright 2016, 2017 Google Inc. All rights reserved.
   Copyright 2019-2023 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:

     https://www.apache.org/licenses/LICENSE-2.0

   This is the real deal: the program takes an instrumented binary and
   attempts a variety of basic fuzzing tricks, paying close attention to
   how they affect the execution path.

 */

#include "afl-fuzz.h"
#include "common.h"
#include <limits.h>
#include <string.h>
#include "cmplog.h"

#ifdef HAVE_AFFINITY

/* bind process to a specific cpu. Returns 0 on failure. */

static u8 bind_cpu(afl_state_t *afl, s32 cpuid) {

  #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__)
  cpu_set_t c;
  #elif defined(__NetBSD__)
  cpuset_t *c;
  #elif defined(__sun)
  psetid_t c;
  #endif

  afl->cpu_aff = cpuid;

  #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__)

  CPU_ZERO(&c);
  CPU_SET(cpuid, &c);

  #elif defined(__NetBSD__)

  c = cpuset_create();
  if (c == NULL) { PFATAL("cpuset_create failed"); }
  cpuset_set(cpuid, c);

  #elif defined(__sun)

  pset_create(&c);
  if (pset_assign(c, cpuid, NULL)) { PFATAL("pset_assign failed"); }

  #endif

  #if defined(__linux__)

  return (sched_setaffinity(0, sizeof(c), &c) == 0);

  #elif defined(__FreeBSD__) || defined(__DragonFly__)

  return (pthread_setaffinity_np(pthread_self(), sizeof(c), &c) == 0);

  #elif defined(__NetBSD__)

  if (pthread_setaffinity_np(pthread_self(), cpuset_size(c), c)) {

    cpuset_destroy(c);
    return 0;

  }

  cpuset_destroy(c);
  return 1;

  #elif defined(__sun)

  if (pset_bind(c, P_PID, getpid(), NULL)) {

    pset_destroy(c);
    return 0;

  }

  pset_destroy(c);
  return 1;

  #else

  // this will need something for other platforms
  // TODO: Solaris/Illumos has processor_bind ... might worth a try
  WARNF("Cannot bind to CPU yet on this platform.");
  return 1;

  #endif

}

/* Build a list of processes bound to specific cores. Returns -1 if nothing
   can be found. Assumes an upper bound of 4k CPUs. */

void bind_to_free_cpu(afl_state_t *afl) {

  u8  cpu_used[4096] = {0};
  u8  lockfile[PATH_MAX] = "";
  s32 i;

  if (afl->afl_env.afl_no_affinity && !afl->afl_env.afl_try_affinity) {

    if (afl->cpu_to_bind != -1) {

      FATAL("-b and AFL_NO_AFFINITY are mututally exclusive.");

    }

    WARNF("Not binding to a CPU core (AFL_NO_AFFINITY set).");
  #ifdef __linux__
    if (afl->fsrv.nyx_mode) { afl->fsrv.nyx_bind_cpu_id = 0; }
  #endif
    return;

  }

  if (afl->cpu_to_bind != -1) {

    if (!bind_cpu(afl, afl->cpu_to_bind)) {

      if (afl->afl_env.afl_try_affinity) {

        WARNF(
            "Could not bind to requested CPU %d! Make sure you passed a valid "
            "-b.",
            afl->cpu_to_bind);

      } else {

        FATAL(
            "Could not bind to requested CPU %d! Make sure you passed a valid "
            "-b.",
            afl->cpu_to_bind);

      }

    } else {

      OKF("CPU binding request using -b %d successful.", afl->cpu_to_bind);
  #ifdef __linux__
      if (afl->fsrv.nyx_mode) { afl->fsrv.nyx_bind_cpu_id = afl->cpu_to_bind; }
  #endif

    }

    return;

  }

  if (afl->cpu_core_count < 2) { return; }

  if (afl->sync_id) {

    s32 lockfd, first = 1;

    snprintf(lockfile, sizeof(lockfile), "%s/.affinity_lock", afl->sync_dir);
    setenv(CPU_AFFINITY_ENV_VAR, lockfile, 1);

    do {

      if ((lockfd = open(lockfile, O_RDWR | O_CREAT | O_EXCL,
                         DEFAULT_PERMISSION)) < 0) {

        if (first) {

          WARNF("CPU affinity lock file present, waiting ...");
          first = 0;

        }

        usleep(1000);

      }

    } while (lockfd < 0);

    close(lockfd);

  }

  #if defined(__linux__)

  DIR           *d;
  struct dirent *de;
  d = opendir("/proc");

  if (!d) {

    if (lockfile[0]) unlink(lockfile);
    WARNF("Unable to access /proc - can't scan for free CPU cores.");
    return;

  }

  ACTF("Checking CPU core loadout...");

  /* Scan all /proc/<pid>/status entries, checking for Cpus_allowed_list.
     Flag all processes bound to a specific CPU using cpu_used[]. This will
     fail for some exotic binding setups, but is likely good enough in almost
     all real-world use cases. */

  while ((de = readdir(d))) {

    u8    fn[PATH_MAX];
    FILE *f;
    u8    tmp[MAX_LINE];
    u8    has_vmsize = 0;

    if (!isdigit(de->d_name[0])) { continue; }

    snprintf(fn, PATH_MAX, "/proc/%s/status", de->d_name);

    if (!(f = fopen(fn, "r"))) { continue; }

    while (fgets(tmp, MAX_LINE, f)) {

      u32 hval;

      /* Processes without VmSize are probably kernel tasks. */

      if (!strncmp(tmp, "VmSize:\t", 8)) { has_vmsize = 1; }

      if (!strncmp(tmp, "Cpus_allowed_list:\t", 19) && !strchr(tmp, '-') &&
          !strchr(tmp, ',') && sscanf(tmp + 19, "%u", &hval) == 1 &&
          hval < sizeof(cpu_used) && has_vmsize) {

        cpu_used[hval] = 1;
        break;

      }

    }

    fclose(f);

  }

  closedir(d);

  #elif defined(__FreeBSD__) || defined(__DragonFly__)

  struct kinfo_proc *procs;
  size_t             nprocs;
  size_t             proccount;
  int                s_name[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
  size_t             s_name_l = sizeof(s_name) / sizeof(s_name[0]);

  if (sysctl(s_name, s_name_l, NULL, &nprocs, NULL, 0) != 0) {

    if (lockfile[0]) unlink(lockfile);
    return;

  }

  proccount = nprocs / sizeof(*procs);
  nprocs = nprocs * 4 / 3;

  procs = ck_alloc(nprocs);
  if (sysctl(s_name, s_name_l, procs, &nprocs, NULL, 0) != 0) {

    if (lockfile[0]) unlink(lockfile);
    ck_free(procs);
    return;

  }

  for (i = 0; i < (s32)proccount; i++) {

    #if defined(__FreeBSD__)

    if (!strcmp(procs[i].ki_comm, "idle")) continue;

    // fix when ki_oncpu = -1
    s32 oncpu;
    oncpu = procs[i].ki_oncpu;
    if (oncpu == -1) oncpu = procs[i].ki_lastcpu;

    if (oncpu != -1 && oncpu < (s32)sizeof(cpu_used) && procs[i].ki_pctcpu > 60)
      cpu_used[oncpu] = 1;

    #elif defined(__DragonFly__)

    if (procs[i].kp_lwp.kl_cpuid < (s32)sizeof(cpu_used) &&
        procs[i].kp_lwp.kl_pctcpu > 10)
      cpu_used[procs[i].kp_lwp.kl_cpuid] = 1;

    #endif

  }

  ck_free(procs);

  #elif defined(__NetBSD__)

  struct kinfo_proc2 *procs;
  size_t              nprocs;
  size_t              proccount;
  int                 s_name[] = {

      CTL_KERN, KERN_PROC2, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), 0};
  size_t s_name_l = sizeof(s_name) / sizeof(s_name[0]);

  if (sysctl(s_name, s_name_l, NULL, &nprocs, NULL, 0) != 0) {

    if (lockfile[0]) unlink(lockfile);
    return;

  }

  proccount = nprocs / sizeof(struct kinfo_proc2);
  procs = ck_alloc(nprocs * sizeof(struct kinfo_proc2));
  s_name[5] = proccount;

  if (sysctl(s_name, s_name_l, procs, &nprocs, NULL, 0) != 0) {

    if (lockfile[0]) unlink(lockfile);
    ck_free(procs);
    return;

  }

  for (i = 0; i < (s32)proccount; i++) {

    if (procs[i].p_cpuid < sizeof(cpu_used) && procs[i].p_pctcpu > 0)
      cpu_used[procs[i].p_cpuid] = 1;

  }

  ck_free(procs);

  #elif defined(__sun)

  kstat_named_t *n;
  kstat_ctl_t   *m;
  kstat_t       *k;
  cpu_stat_t     cs;
  u32            ncpus;

  m = kstat_open();

  if (!m) FATAL("kstat_open failed");

  k = kstat_lookup(m, "unix", 0, "system_misc");

  if (!k) {

    if (lockfile[0]) unlink(lockfile);
    kstat_close(m);
    return;

  }

  if (kstat_read(m, k, NULL)) {

    if (lockfile[0]) unlink(lockfile);
    kstat_close(m);
    return;

  }

  n = kstat_data_lookup(k, "ncpus");
  ncpus = n->value.i32;

  if (ncpus > sizeof(cpu_used)) ncpus = sizeof(cpu_used);

  for (i = 0; i < (s32)ncpus; i++) {

    k = kstat_lookup(m, "cpu_stat", i, NULL);
    if (kstat_read(m, k, &cs)) {

      if (lockfile[0]) unlink(lockfile);
      kstat_close(m);
      return;

    }

    if (cs.cpu_sysinfo.cpu[CPU_IDLE] > 0) continue;

    if (cs.cpu_sysinfo.cpu[CPU_USER] > 0 || cs.cpu_sysinfo.cpu[CPU_KERNEL] > 0)
      cpu_used[i] = 1;

  }

  kstat_close(m);

  #else
    #warning \
        "For this platform we do not have free CPU binding code yet. If possible, please supply a PR to https://github.com/AFLplusplus/AFLplusplus"
  #endif

  #if !defined(__aarch64__) && !defined(__arm__) && !defined(__arm64__)

  for (i = 0; i < afl->cpu_core_count; i++) {

  #else

  /* many ARM devices have performance and efficiency cores, the slower
     efficiency cores seem to always come first */

  for (i = afl->cpu_core_count - 1; i > -1; i--) {

  #endif

    if (cpu_used[i]) { continue; }

    OKF("Found a free CPU core, try binding to #%u.", i);

    if (bind_cpu(afl, i)) {

  #ifdef __linux__
      if (afl->fsrv.nyx_mode) { afl->fsrv.nyx_bind_cpu_id = i; }
  #endif
      /* Success :) */
      break;

    }

    WARNF("setaffinity failed to CPU %d, trying next CPU", i);

  }

  if (lockfile[0]) unlink(lockfile);

  if (i == afl->cpu_core_count || i == -1) {

    SAYF("\n" cLRD "[-] " cRST
         "Uh-oh, looks like all %d CPU cores on your system are allocated to\n"
         "    other instances of afl-fuzz (or similar CPU-locked tasks). "
         "Starting\n"
         "    another fuzzer on this machine is probably a bad plan.\n"
         "%s",
         afl->cpu_core_count,
         afl->afl_env.afl_try_affinity ? ""
                                       : "    If you are sure, you can set "
                                         "AFL_NO_AFFINITY and try again.\n");

    if (!afl->afl_env.afl_try_affinity) { FATAL("No more free CPU cores"); }

  }

}

#endif                                                     /* HAVE_AFFINITY */

/* Shuffle an array of pointers. Might be slightly biased. */

static void shuffle_ptrs(afl_state_t *afl, void **ptrs, u32 cnt) {

  u32 i;

  for (i = 0; i < cnt - 2; ++i) {

    u32   j = i + rand_below(afl, cnt - i);
    void *s = ptrs[i];
    ptrs[i] = ptrs[j];
    ptrs[j] = s;

  }

}

/* Read all testcases from foreign input directories, then queue them for
   testing. Called at startup and at sync intervals.
   Does not descend into subdirectories! */

void read_foreign_testcases(afl_state_t *afl, int first) {

  if (!afl->foreign_sync_cnt) return;

  struct dirent **nl;
  s32             nl_cnt;
  u32             i, iter;

  u8 val_buf[2][STRINGIFY_VAL_SIZE_MAX];
  u8 foreign_name[16];

  for (iter = 0; iter < afl->foreign_sync_cnt; iter++) {

    if (afl->foreign_syncs[iter].dir && afl->foreign_syncs[iter].dir[0]) {

      if (first) ACTF("Scanning '%s'...", afl->foreign_syncs[iter].dir);
      time_t mtime_max = 0;

      u8 *name = strrchr(afl->foreign_syncs[iter].dir, '/');
      if (!name) {

        name = afl->foreign_syncs[iter].dir;

      } else {

        ++name;

      }

      if (!strcmp(name, "queue") || !strcmp(name, "out") ||
          !strcmp(name, "default")) {

        snprintf(foreign_name, sizeof(foreign_name), "foreign_%u", iter);

      } else {

        snprintf(foreign_name, sizeof(foreign_name), "%s_%u", name, iter);

      }

      /* We do not use sorting yet and do a more expensive mtime check instead.
         a mtimesort() implementation would be better though. */

      nl_cnt = scandir(afl->foreign_syncs[iter].dir, &nl, NULL, NULL);

      if (nl_cnt < 0) {

        if (first) {

          WARNF("Unable to open directory '%s'", afl->foreign_syncs[iter].dir);
          sleep(1);

        }

        continue;

      }

      if (nl_cnt == 0) {

        if (first) {

          WARNF("directory %s is currently empty",
                afl->foreign_syncs[iter].dir);

        }

        continue;

      }

      /* Show stats */

      snprintf(afl->stage_name_buf, STAGE_BUF_SIZE, "foreign sync %u", iter);

      afl->stage_name = afl->stage_name_buf;
      afl->stage_cur = 0;
      afl->stage_max = 0;

      for (i = 0; i < (u32)nl_cnt; ++i) {

        struct stat st;

        u8 *fn2 =
            alloc_printf("%s/%s", afl->foreign_syncs[iter].dir, nl[i]->d_name);

        free(nl[i]);                                         /* not tracked */

        if (unlikely(lstat(fn2, &st) || access(fn2, R_OK))) {

          if (first) PFATAL("Unable to access '%s'", fn2);
          continue;

        }

        /* we detect new files by their mtime */
        if (likely(st.st_mtime <= afl->foreign_syncs[iter].mtime)) {

          ck_free(fn2);
          continue;

        }

        /* This also takes care of . and .. */

        if (!S_ISREG(st.st_mode) || !st.st_size || strstr(fn2, "/README.txt")) {

          ck_free(fn2);
          continue;

        }

        if (st.st_size > MAX_FILE) {

          if (first) {

            WARNF(
                "Test case '%s' is too big (%s, limit is %s), skipping", fn2,
                stringify_mem_size(val_buf[0], sizeof(val_buf[0]), st.st_size),
                stringify_mem_size(val_buf[1], sizeof(val_buf[1]), MAX_FILE));

          }

          ck_free(fn2);
          continue;

        }

        // lets do not use add_to_queue(afl, fn2, st.st_size, 0);
        // as this could add duplicates of the startup input corpus

        int fd = open(fn2, O_RDONLY);
        if (fd < 0) {

          ck_free(fn2);
          continue;

        }

        u8  fault;
        u8 *mem = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

        if (mem == MAP_FAILED) {

          ck_free(fn2);
          continue;

        }

        u32 len = write_to_testcase(afl, (void **)&mem, st.st_size, 1);
        fault = fuzz_run_target(afl, &afl->fsrv, afl->fsrv.exec_tmout);
        afl->syncing_party = foreign_name;
        afl->queued_imported += save_if_interesting(afl, mem, len, fault);
        afl->syncing_party = 0;
        munmap(mem, st.st_size);
        close(fd);

        if (st.st_mtime > mtime_max) mtime_max = st.st_mtime;

      }

      afl->foreign_syncs[iter].mtime = mtime_max;
      free(nl);                                              /* not tracked */

    }

  }

  if (first) {

    afl->last_find_time = 0;
    afl->queued_at_start = afl->queued_items;

  }

}

/* Read all testcases from the input directory, then queue them for testing.
   Called at startup. */

void read_testcases(afl_state_t *afl, u8 *directory) {

  struct dirent **nl;
  s32             nl_cnt, subdirs = 1;
  u32             i;
  u8             *fn1, *dir = directory;
  u8              val_buf[2][STRINGIFY_VAL_SIZE_MAX];

  /* Auto-detect non-in-place resumption attempts. */

  if (dir == NULL) {

    fn1 = alloc_printf("%s/queue", afl->in_dir);
    if (!access(fn1, F_OK)) {

      afl->in_dir = fn1;
      subdirs = 0;

    } else {

      ck_free(fn1);

    }

    dir = afl->in_dir;

  }

  ACTF("Scanning '%s'...", dir);

  /* We use scandir() + alphasort() rather than readdir() because otherwise,
     the ordering of test cases would vary somewhat randomly and would be
     difficult to control. */

  nl_cnt = scandir(dir, &nl, NULL, alphasort);

  if (nl_cnt < 0 && directory == NULL) {

    if (errno == ENOENT || errno == ENOTDIR) {

      SAYF("\n" cLRD "[-] " cRST
           "The input directory does not seem to be valid - try again. The "
           "fuzzer needs\n"
           "    one or more test case to start with - ideally, a small file "
           "under 1 kB\n"
           "    or so. The cases must be stored as regular files directly in "
           "the input\n"
           "    directory.\n");

    }

    PFATAL("Unable to open '%s'", dir);

  }

  if (unlikely(afl->old_seed_selection && afl->shuffle_queue && nl_cnt > 1)) {

    ACTF("Shuffling queue...");
    shuffle_ptrs(afl, (void **)nl, nl_cnt);

  }

  // if (getenv("MYTEST")) afl->in_place_resume = 1;

  if (nl_cnt) {

    u32 done = 0;

    if (unlikely(afl->in_place_resume)) {

      i = nl_cnt;

    } else {

      i = 0;

    }

    do {

      if (unlikely(afl->in_place_resume)) { --i; }

      struct stat st;
      u8          dfn[PATH_MAX];
      snprintf(dfn, PATH_MAX, "%s/.state/deterministic_done/%s", afl->in_dir,
               nl[i]->d_name);
      u8 *fn2 = alloc_printf("%s/%s", dir, nl[i]->d_name);

      u8 passed_det = 0;

      if (lstat(fn2, &st) || access(fn2, R_OK)) {

        PFATAL("Unable to access '%s'", fn2);

      }

      /* obviously we want to skip "descending" into . and .. directories,
         however it is a good idea to skip also directories that start with
         a dot */
      if (subdirs && S_ISDIR(st.st_mode) && nl[i]->d_name[0] != '.') {

        free(nl[i]);                                         /* not tracked */
        read_testcases(afl, fn2);
        ck_free(fn2);
        goto next_entry;

      }

      free(nl[i]);

      if (!S_ISREG(st.st_mode) || !st.st_size || strstr(fn2, "/README.txt")) {

        ck_free(fn2);
        goto next_entry;

      }

      if (st.st_size > MAX_FILE) {

        WARNF("Test case '%s' is too big (%s, limit is %s), partial reading",
              fn2,
              stringify_mem_size(val_buf[0], sizeof(val_buf[0]), st.st_size),
              stringify_mem_size(val_buf[1], sizeof(val_buf[1]), MAX_FILE));

      }

      /* Check for metadata that indicates that deterministic fuzzing
         is complete for this entry. We don't want to repeat deterministic
         fuzzing when resuming aborted scans, because it would be pointless
         and probably very time-consuming. */

      if (!access(dfn, F_OK)) { passed_det = 1; }

      add_to_queue(afl, fn2, st.st_size >= MAX_FILE ? MAX_FILE : st.st_size,
                   passed_det);

      if (unlikely(afl->shm.cmplog_mode)) {

        if (afl->cmplog_lvl == 1) {

          if (!afl->cmplog_max_filesize ||
              afl->cmplog_max_filesize < st.st_size) {

            afl->cmplog_max_filesize = st.st_size;

          }

        } else if (afl->cmplog_lvl == 2) {

          if (!afl->cmplog_max_filesize ||
              afl->cmplog_max_filesize > st.st_size) {

            afl->cmplog_max_filesize = st.st_size;

          }

        }

      }

    next_entry:
      if (unlikely(afl->in_place_resume)) {

        if (unlikely(i == 0)) { done = 1; }

      } else {

        if (unlikely(++i >= (u32)nl_cnt)) { done = 1; }

      }

    } while (!done);

  }

  // if (getenv("MYTEST")) afl->in_place_resume = 0;

  free(nl);                                                  /* not tracked */

  if (!afl->queued_items && directory == NULL) {

    SAYF("\n" cLRD "[-] " cRST
         "Looks like there are no valid test cases in the input directory! The "
         "fuzzer\n"
         "    needs one or more test case to start with - ideally, a small "
         "file under\n"
         "    1 kB or so. The cases must be stored as regular files directly "
         "in the\n"
         "    input directory.\n");

    FATAL("No usable test cases in '%s'", afl->in_dir);

  }

  if (unlikely(afl->shm.cmplog_mode)) {

    if (afl->cmplog_max_filesize < 1024) {

      afl->cmplog_max_filesize = 1024;

    } else {

      afl->cmplog_max_filesize = (((afl->cmplog_max_filesize >> 10) + 1) << 10);

    }

  }

  afl->last_find_time = 0;
  afl->queued_at_start = afl->queued_items;

}

/* Perform dry run of all test cases to confirm that the app is working as
   expected. This is done only for the initial inputs, and only once. */

void perform_dry_run(afl_state_t *afl) {

  struct queue_entry *q;
  u32                 cal_failures = 0, idx;
  u8                 *use_mem;

  for (idx = 0; idx < afl->queued_items; idx++) {

    q = afl->queue_buf[idx];
    if (unlikely(!q || q->disabled)) { continue; }

    u8  res;
    s32 fd;

    if (unlikely(!q->len)) {

      WARNF("Skipping 0-sized entry in queue (%s)", q->fname);
      continue;

    }

    if (afl->afl_env.afl_cmplog_only_new) { q->colorized = CMPLOG_LVL_MAX; }

    u8 *fn = strrchr(q->fname, '/') + 1;

    ACTF("Attempting dry run with '%s'...", fn);

    fd = open(q->fname, O_RDONLY);
    if (fd < 0) { PFATAL("Unable to open '%s'", q->fname); }

    u32 read_len = MIN(q->len, (u32)MAX_FILE);
    use_mem = afl_realloc(AFL_BUF_PARAM(in), read_len);
    ck_read(fd, use_mem, read_len, q->fname);

    close(fd);

    res = calibrate_case(afl, q, use_mem, 0, 1);

    if (afl->stop_soon) { return; }

    if (res == afl->crash_mode || res == FSRV_RUN_NOBITS) {

      SAYF(cGRA
           "    len = %u, map size = %u, exec speed = %llu us, hash = "
           "%016llx\n" cRST,
           q->len, q->bitmap_size, q->exec_us, q->exec_cksum);

    }

    switch (res) {

      case FSRV_RUN_OK:

        if (afl->crash_mode) { FATAL("Test case '%s' does *NOT* crash", fn); }

        break;

      case FSRV_RUN_TMOUT:

        if (afl->timeout_given && !afl->afl_env.afl_exit_on_seed_issues) {

          /* if we have a timeout but a timeout value was given then always
             skip. The '+' meaning has been changed! */
          WARNF("Test case results in a timeout (skipping)");
          ++cal_failures;
          q->cal_failed = CAL_CHANCES;
          q->disabled = 1;
          q->perf_score = 0;

          if (!q->was_fuzzed) {

            q->was_fuzzed = 1;
            afl->reinit_table = 1;
            --afl->pending_not_fuzzed;
            --afl->active_items;

          }

          break;

        } else {

          static int say_once = 0;

          if (!say_once) {

            SAYF(
                "\n" cLRD "[-] " cRST
                "The program took more than %u ms to process one of the "
                "initial "
                "test cases.\n"
                "    This is bad news; raising the limit with the -t option is "
                "possible, but\n"
                "    will probably make the fuzzing process extremely slow.\n\n"

                "    If this test case is just a fluke, the other option is to "
                "just avoid it\n"
                "    altogether, and find one that is less of a CPU hog.\n",
                afl->fsrv.exec_tmout);

            if (!afl->afl_env.afl_ignore_seed_problems) {

              FATAL("Test case '%s' results in a timeout", fn);

            }

            say_once = 1;

          }

          if (!q->was_fuzzed) {

            q->was_fuzzed = 1;
            afl->reinit_table = 1;
            --afl->pending_not_fuzzed;
            --afl->active_items;

          }

          q->disabled = 1;
          q->perf_score = 0;

          WARNF("Test case '%s' results in a timeout, skipping", fn);
          break;

        }

      case FSRV_RUN_CRASH:

        if (afl->crash_mode) { break; }

        if (afl->fsrv.mem_limit) {

          u8 val_buf[STRINGIFY_VAL_SIZE_MAX];

          SAYF("\n" cLRD "[-] " cRST
               "Oops, the program crashed with one of the test cases provided. "
               "There are\n"
               "    several possible explanations:\n\n"

               "    - The test case causes known crashes under normal working "
               "conditions. If\n"
               "      so, please remove it. The fuzzer should be seeded with "
               "interesting\n"
               "      inputs - but not ones that cause an outright crash.\n\n"

               "    - The current memory limit (%s) is too low for this "
               "program, causing\n"
               "      it to die due to OOM when parsing valid files. To fix "
               "this, try\n"
               "      bumping it up with the -m setting in the command line. "
               "If in doubt,\n"
               "      try something along the lines of:\n\n"

               MSG_ULIMIT_USAGE
               " /path/to/binary [...] <testcase )\n\n"

               "      Tip: you can use https://jwilk.net/software/recidivm to\n"
               "      estimate the required amount of virtual memory for the "
               "binary. Also,\n"
               "      if you are using ASAN, set '-m 0'.\n\n"

               "    - In QEMU persistent mode the selected address(es) for the "
               "loop are not\n"
               "      properly cleaning up variables and memory. Try adding\n"
               "      AFL_QEMU_PERSISTENT_GPR=1 or select better addresses in "
               "the binary.\n\n"

               MSG_FORK_ON_APPLE

               "    - Least likely, there is a horrible bug in the fuzzer. If "
               "other options\n"
               "      fail, poke the Awesome Fuzzing Discord for "
               "troubleshooting tips.\n",
               stringify_mem_size(val_buf, sizeof(val_buf),
                                  afl->fsrv.mem_limit << 20),
               afl->fsrv.mem_limit - 1);

        } else {

          SAYF("\n" cLRD "[-] " cRST
               "Oops, the program crashed with one of the test cases provided. "
               "There are\n"
               "    several possible explanations:\n\n"

               "    - The test case causes known crashes under normal working "
               "conditions. If\n"
               "      so, please remove it. The fuzzer should be seeded with "
               "interesting\n"
               "      inputs - but not ones that cause an outright crash.\n\n"

               "    - In QEMU persistent mode the selected address(es) for the "
               "loop are not\n"
               "      properly cleaning up variables and memory. Try adding\n"
               "      AFL_QEMU_PERSISTENT_GPR=1 or select better addresses in "
               "the binary.\n\n"

               MSG_FORK_ON_APPLE

               "    - Least likely, there is a horrible bug in the fuzzer. If "
               "other options\n"
               "      fail, poke the Awesome Fuzzing Discord for "
               "troubleshooting tips.\n");

        }

#undef MSG_ULIMIT_USAGE
#undef MSG_FORK_ON_APPLE

        if (afl->fsrv.uses_crash_exitcode) {

          WARNF(
              "Test case '%s' results in a crash or AFL_CRASH_EXITCODE %d, "
              "skipping",
              fn, (int)(s8)afl->fsrv.crash_exitcode);

        } else {

          if (afl->afl_env.afl_crashing_seeds_as_new_crash) {

            WARNF(
                "Test case '%s' results in a crash, "
                "as AFL_CRASHING_SEEDS_AS_NEW_CRASH is set, "
                "saving as a new crash",
                fn);

          } else {

            WARNF("Test case '%s' results in a crash, skipping", fn);

          }

        }

        if (afl->afl_env.afl_exit_on_seed_issues) {

          FATAL("As AFL_EXIT_ON_SEED_ISSUES is set, afl-fuzz exits.");

        }

        /* Remove from fuzzing queue but keep for splicing */

        if (!q->was_fuzzed) {

          q->was_fuzzed = 1;
          afl->reinit_table = 1;
          --afl->pending_not_fuzzed;
          --afl->active_items;

        }

        /* Crashing seeds will be regarded as new crashes on startup */
        if (afl->afl_env.afl_crashing_seeds_as_new_crash) {

          ++afl->total_crashes;

          if (likely(!afl->non_instrumented_mode)) {

            classify_counts(&afl->fsrv);

            simplify_trace(afl, afl->fsrv.trace_bits);

            if (!has_new_bits(afl, afl->virgin_crash)) { break; }

          }

          if (unlikely(!afl->saved_crashes) &&
              (afl->afl_env.afl_no_crash_readme != 1)) {

            write_crash_readme(afl);

          }

          u8  crash_fn[PATH_MAX];
          u8 *use_name = strstr(q->fname, ",orig:");

          afl->stage_name = "dry_run";
          afl->stage_short = "dry_run";

#ifndef SIMPLE_FILES

          snprintf(crash_fn, PATH_MAX, "%s/crashes/id:%06llu,sig:%02u,%s%s",
                   afl->out_dir, afl->saved_crashes, afl->fsrv.last_kill_signal,
                   describe_op(afl, 0,
                               NAME_MAX - strlen("id:000000,sig:00,") -
                                   strlen(use_name)),
                   use_name);

#else

          snprintf(crash_fn, PATH_MAX, "%s/crashes/id_%06llu_%02u",
                   afl->out_dir, afl->saved_crashes,
                   afl->fsrv.last_kill_signal);

#endif

          ++afl->saved_crashes;

          fd = open(crash_fn, O_WRONLY | O_CREAT | O_EXCL, DEFAULT_PERMISSION);
          if (unlikely(fd < 0)) { PFATAL("Unable to create '%s'", crash_fn); }
          ck_write(fd, use_mem, read_len, crash_fn);
          close(fd);

          afl->last_crash_time = get_cur_time();
          afl->last_crash_execs = afl->fsrv.total_execs;

        } else {

          u32 i = 0;
          while (unlikely(i < afl->queued_items && afl->queue_buf[i] &&
                          afl->queue_buf[i]->disabled)) {

            ++i;

          }

          if (i < afl->queued_items && afl->queue_buf[i]) {

            afl->queue = afl->queue_buf[i];

          } else {

            afl->queue = afl->queue_buf[0];

          }

          afl->max_depth = 0;
          for (i = 0; i < afl->queued_items && likely(afl->queue_buf[i]); i++) {

            if (!afl->queue_buf[i]->disabled &&
                afl->queue_buf[i]->depth > afl->max_depth)
              afl->max_depth = afl->queue_buf[i]->depth;

          }

        }

        q->disabled = 1;
        q->perf_score = 0;

        break;

      case FSRV_RUN_ERROR:

        FATAL("Unable to execute target application ('%s')", afl->argv[0]);

      case FSRV_RUN_NOINST:
#ifdef __linux__
        if (afl->fsrv.nyx_mode && afl->fsrv.nyx_runner != NULL) {

          afl->fsrv.nyx_handlers->nyx_shutdown(afl->fsrv.nyx_runner);

        }

#endif
        FATAL("No instrumentation detected");

      case FSRV_RUN_NOBITS:

        ++afl->useless_at_start;

        if (!afl->in_bitmap && !afl->shuffle_queue) {

          WARNF("No new instrumentation output, test case may be useless.");

        }

        break;

    }

    if (unlikely(q->var_behavior && !afl->afl_env.afl_no_warn_instability)) {

      WARNF("Instrumentation output varies across runs.");

    }

  }

  if (cal_failures) {

    if (cal_failures == afl->queued_items) {

      FATAL("All test cases time out or crash, giving up!");

    }

    WARNF("Skipped %u test cases (%0.02f%%) due to timeouts or crashes.",
          cal_failures, ((double)cal_failures) * 100 / afl->queued_items);

    if (cal_failures * 5 > afl->queued_items) {

      WARNF(cLRD "High percentage of rejected test cases, check settings!");

    }

  }

  /* Now we remove all entries from the queue that have a duplicate trace map */

  u32 duplicates = 0, i;

  for (idx = 0; idx < afl->queued_items - 1; idx++) {

    q = afl->queue_buf[idx];
    if (!q || q->disabled || q->cal_failed || !q->exec_cksum) { continue; }
    u32 done = 0;

    for (i = idx + 1;
         likely(i < afl->queued_items && afl->queue_buf[i] && !done); ++i) {

      struct queue_entry *p = afl->queue_buf[i];
      if (p->disabled || p->cal_failed || !p->exec_cksum) { continue; }

      if (p->exec_cksum == q->exec_cksum) {

        duplicates = 1;

        // we keep the shorter file
        if (p->len >= q->len) {

          if (!p->was_fuzzed) {

            p->was_fuzzed = 1;
            afl->reinit_table = 1;
            --afl->pending_not_fuzzed;
            --afl->active_items;

          }

          p->disabled = 1;
          p->perf_score = 0;

          if (afl->debug) {

            WARNF("Same coverage - %s is kept active, %s is disabled.",
                  q->fname, p->fname);

          }

        } else {

          if (!q->was_fuzzed) {

            q->was_fuzzed = 1;
            afl->reinit_table = 1;
            --afl->pending_not_fuzzed;
            --afl->active_items;

          }

          q->disabled = 1;
          q->perf_score = 0;

          if (afl->debug) {

            WARNF("Same coverage - %s is kept active, %s is disabled.",
                  p->fname, q->fname);

          }

          done = 1;  // end inner loop because outer loop entry is disabled now

        }

      }

    }

  }

  if (duplicates) {

    afl->max_depth = 0;

    for (idx = 0; idx < afl->queued_items; idx++) {

      if (afl->queue_buf[idx] && !afl->queue_buf[idx]->disabled &&
          afl->queue_buf[idx]->depth > afl->max_depth)
        afl->max_depth = afl->queue_buf[idx]->depth;

    }

    afl->queue_top = afl->queue;

  }

  OKF("All test cases processed.");

}

/* Helper function: link() if possible, copy otherwise. */

static void link_or_copy(u8 *old_path, u8 *new_path) {

  s32 i = link(old_path, new_path);
  s32 sfd, dfd;
  u8 *tmp;

  if (!i) { return; }

  sfd = open(old_path, O_RDONLY);
  if (sfd < 0) { PFATAL("Unable to open '%s'", old_path); }

  dfd = open(new_path, O_WRONLY | O_CREAT | O_EXCL, DEFAULT_PERMISSION);
  if (dfd < 0) { PFATAL("Unable to create '%s'", new_path); }

  tmp = ck_alloc(64 * 1024);

  while ((i = read(sfd, tmp, 64 * 1024)) > 0) {

    ck_write(dfd, tmp, i, new_path);

  }

  if (i < 0) { PFATAL("read() failed"); }

  ck_free(tmp);
  close(sfd);
  close(dfd);

}

/* Create hard links for input test cases in the output directory, choosing
   good names and pivoting accordingly. */

void pivot_inputs(afl_state_t *afl) {

  struct queue_entry *q;
  u32                 id = 0, i;

  ACTF("Creating hard links for all input files...");

  for (i = 0; i < afl->queued_items && likely(afl->queue_buf[i]); i++) {

    q = afl->queue_buf[i];

    if (unlikely(q->disabled)) { continue; }

    u8 *nfn, *rsl = strrchr(q->fname, '/');
    u32 orig_id;

    if (!rsl) {

      rsl = q->fname;

    } else {

      ++rsl;

    }

    /* If the original file name conforms to the syntax and the recorded
       ID matches the one we'd assign, just use the original file name.
       This is valuable for resuming fuzzing runs. */

    if (!strncmp(rsl, CASE_PREFIX, 3) &&
        sscanf(rsl + 3, "%06u", &orig_id) == 1 && orig_id == id) {

      u8 *src_str;
      u32 src_id;

      afl->resuming_fuzz = 1;
      nfn = alloc_printf("%s/queue/%s", afl->out_dir, rsl);

      /* Since we're at it, let's also get the parent and figure out the
         appropriate depth for this entry. */

      src_str = strchr(rsl + 3, ':');

      if (src_str && sscanf(src_str + 1, "%06u", &src_id) == 1) {

        if (src_id < afl->queued_items) {

          struct queue_entry *s = afl->queue_buf[src_id];

          if (s) { q->depth = s->depth + 1; }

        }

        if (afl->max_depth < q->depth) { afl->max_depth = q->depth; }

      }

    } else {

      /* No dice - invent a new name, capturing the original one as a
         substring. */

#ifndef SIMPLE_FILES

      u8 *use_name = strstr(rsl, ",orig:");

      if (use_name) {

        use_name += 6;

      } else {

        use_name = rsl;

      }

      nfn = alloc_printf("%s/queue/id:%06u,time:0,execs:%llu,orig:%s",
                         afl->out_dir, id, afl->fsrv.total_execs, use_name);

#else

      nfn = alloc_printf("%s/queue/id_%06u", afl->out_dir, id);

#endif                                                    /* ^!SIMPLE_FILES */

    }

    /* Pivot to the new queue entry. */

    link_or_copy(q->fname, nfn);
    ck_free(q->fname);
    q->fname = nfn;

    /* Make sure that the passed_det value carries over, too. */

    if (q->passed_det) { mark_as_det_done(afl, q); }

    if (afl->custom_mutators_count) {

      run_afl_custom_queue_new_entry(afl, q, q->fname, NULL);

    }

    ++id;

  }

  if (afl->in_place_resume) { nuke_resume_dir(afl); }

}

/* When resuming, try to find the queue position to start from. This makes sense
   only when resuming, and when we can find the original fuzzer_stats. */

u32 find_start_position(afl_state_t *afl) {

  u8 tmp[4096] = {0};                    /* Ought to be enough for anybody. */

  u8 *fn, *off;
  s32 fd, i;
  u32 ret;

  if (!afl->resuming_fuzz) { return 0; }

  if (afl->in_place_resume) {

    fn = alloc_printf("%s/fuzzer_stats", afl->out_dir);

  } else {

    fn = alloc_printf("%s/../fuzzer_stats", afl->in_dir);

  }

  fd = open(fn, O_RDONLY);
  ck_free(fn);

  if (fd < 0) { return 0; }

  i = read(fd, tmp, sizeof(tmp) - 1);
  (void)i;                                                 /* Ignore errors */
  close(fd);

  off = strstr(tmp, "cur_item          : ");
  if (!off) { return 0; }

  ret = atoi(off + 20);
  if (ret >= afl->queued_items) { ret = 0; }
  return ret;

}

/* The same, but for timeouts. The idea is that when resuming sessions without
   -t given, we don't want to keep auto-scaling the timeout over and over
   again to prevent it from growing due to random flukes. */

void find_timeout(afl_state_t *afl) {

  u8 tmp[4096] = {0};                    /* Ought to be enough for anybody. */

  u8 *fn, *off;
  s32 fd, i;
  u32 ret;

  if (!afl->resuming_fuzz) { return; }

  if (afl->in_place_resume) {

    fn = alloc_printf("%s/fuzzer_stats", afl->out_dir);

  } else {

    fn = alloc_printf("%s/../fuzzer_stats", afl->in_dir);

  }

  fd = open(fn, O_RDONLY);
  ck_free(fn);

  if (fd < 0) { return; }

  i = read(fd, tmp, sizeof(tmp) - 1);
  (void)i;                                                 /* Ignore errors */
  close(fd);

  off = strstr(tmp, "exec_timeout      : ");
  if (!off) { return; }

  ret = atoi(off + 20);
  if (ret <= 4) { return; }

  afl->fsrv.exec_tmout = ret;
  afl->timeout_given = 3;

}

/* A helper function for handle_existing_out_dir(), deleting all prefixed
   files in a directory. */

static u8 delete_files(u8 *path, u8 *prefix) {

  DIR           *d;
  struct dirent *d_ent;

  d = opendir(path);

  if (!d) { return 0; }

  while ((d_ent = readdir(d))) {

    if (d_ent->d_name[0] != '.' &&
        (!prefix || !strncmp(d_ent->d_name, prefix, strlen(prefix)))) {

      u8 *fname = alloc_printf("%s/%s", path, d_ent->d_name);
      if (unlink(fname)) { PFATAL("Unable to delete '%s'", fname); }
      ck_free(fname);

    }

  }

  closedir(d);

  return !!rmdir(path);

}

/* Get the number of runnable processes, with some simple smoothing. */

double get_runnable_processes(void) {

  double res = 0;

#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
    defined(__NetBSD__) || defined(__DragonFly__)

  /* I don't see any portable sysctl or so that would quickly give us the
     number of runnable processes; the 1-minute load average can be a
     semi-decent approximation, though. */

  if (getloadavg(&res, 1) != 1) return 0;

#else

  /* On Linux, /proc/stat is probably the best way; load averages are
     computed in funny ways and sometimes don't reflect extremely short-lived
     processes well. */

  FILE *f = fopen("/proc/stat", "r");
  u8    tmp[1024];
  u32   val = 0;

  if (!f) { return 0; }

  while (fgets(tmp, sizeof(tmp), f)) {

    if (!strncmp(tmp, "procs_running ", 14) ||
        !strncmp(tmp, "procs_blocked ", 14)) {

      val += atoi(tmp + 14);

    }

  }

  fclose(f);

  if (!res) {

    res = val;

  } else {

    res = res * (1.0 - 1.0 / AVG_SMOOTHING) +
          ((double)val) * (1.0 / AVG_SMOOTHING);

  }

#endif          /* ^(__APPLE__ || __FreeBSD__ || __OpenBSD__ || __NetBSD__) */

  return res;

}

/* Delete the temporary directory used for in-place session resume. */

void nuke_resume_dir(afl_state_t *afl) {

  u8 *fn;

  fn = alloc_printf("%s/_resume/.state/deterministic_done", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/_resume/.state/auto_extras", afl->out_dir);
  if (delete_files(fn, "auto_")) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/_resume/.state/redundant_edges", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/_resume/.state/variable_behavior", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/_resume/.state", afl->out_dir);
  if (rmdir(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/_resume", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  return;

dir_cleanup_failed:

  FATAL("_resume directory cleanup failed");

}

/* Delete fuzzer output directory if we recognize it as ours, if the fuzzer
   is not currently running, and if the last run time isn't too great.
   Resume fuzzing if `-` is set as in_dir or if AFL_AUTORESUME is set */

static void handle_existing_out_dir(afl_state_t *afl) {

  FILE *f;
  u8   *fn = alloc_printf("%s/fuzzer_stats", afl->out_dir);

  /* See if the output directory is locked. If yes, bail out. If not,
     create a lock that will persist for the lifetime of the process
     (this requires leaving the descriptor open).*/

  afl->fsrv.out_dir_fd = open(afl->out_dir, O_RDONLY);
  if (afl->fsrv.out_dir_fd < 0) { PFATAL("Unable to open '%s'", afl->out_dir); }

#ifndef __sun

  if (flock(afl->fsrv.out_dir_fd, LOCK_EX | LOCK_NB) && errno == EWOULDBLOCK) {

    SAYF("\n" cLRD "[-] " cRST
         "Looks like the job output directory is being actively used by "
         "another\n"
         "    instance of afl-fuzz. You will need to choose a different %s\n"
         "    or stop the other process first.\n",
         afl->sync_id ? "fuzzer ID" : "output location");

    FATAL("Directory '%s' is in use", afl->out_dir);

  }

#endif                                                            /* !__sun */

  f = fopen(fn, "r");

  if (f) {

    u64 start_time2, last_update;

    if (fscanf(f,
               "start_time     : %llu\n"
               "last_update    : %llu\n",
               &start_time2, &last_update) != 2) {

      FATAL("Malformed data in '%s'", fn);

    }

    fclose(f);

    /* Autoresume treats a normal run as in_place_resume if a valid out dir
     * already exists */

    if (!afl->in_place_resume && afl->autoresume) {

      OKF("Detected prior run with AFL_AUTORESUME set. Resuming.");
      afl->in_place_resume = 1;

    }

    /* Let's see how much work is at stake. */

    if (!afl->in_place_resume && last_update > start_time2 &&
        last_update - start_time2 > OUTPUT_GRACE * 60) {

      SAYF("\n" cLRD "[-] " cRST
           "The job output directory already exists and contains the results "
           "of more\n"
           "    than %d minutes worth of fuzzing. To avoid data loss, afl-fuzz "
           "will *NOT*\n"
           "    automatically delete this data for you.\n\n"

           "    If you wish to start a new session, remove or rename the "
           "directory manually,\n"
           "    or specify a different output location for this job. To resume "
           "the old\n"
           "    session, pass '-' as input directory in the command line ('-i "
           "-')\n"
           "    or set the 'AFL_AUTORESUME=1' env variable and try again.\n",
           OUTPUT_GRACE);

      FATAL("At-risk data found in '%s'", afl->out_dir);

    }

  }

  ck_free(fn);

  /* The idea for in-place resume is pretty simple: we temporarily move the old
     queue/ to a new location that gets deleted once import to the new queue/
     is finished. If _resume/ already exists, the current queue/ may be
     incomplete due to an earlier abort, so we want to use the old _resume/
     dir instead, and we let rename() fail silently. */

  if (afl->in_place_resume) {

    u8 *orig_q = alloc_printf("%s/queue", afl->out_dir);

    afl->in_dir = alloc_printf("%s/_resume", afl->out_dir);

    rename(orig_q, afl->in_dir);                           /* Ignore errors */

    OKF("Output directory exists, will attempt session resume.");

    ck_free(orig_q);

  } else {

    OKF("Output directory exists but deemed OK to reuse.");

  }

  ACTF("Deleting old session data...");

  /* Okay, let's get the ball rolling! First, we need to get rid of the entries
     in <afl->out_dir>/.synced/.../id:*, if any are present. */

  if (!afl->in_place_resume) {

    fn = alloc_printf("%s/.synced", afl->out_dir);
    if (delete_files(fn, NULL)) { goto dir_cleanup_failed; }
    ck_free(fn);

  }

  /* Next, we need to clean up <afl->out_dir>/queue/.state/ subdirectories: */

  fn = alloc_printf("%s/queue/.state/deterministic_done", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/queue/.state/auto_extras", afl->out_dir);
  if (delete_files(fn, "auto_")) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/queue/.state/redundant_edges", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/queue/.state/variable_behavior", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  /* Then, get rid of the .state subdirectory itself (should be empty by now)
     and everything matching <afl->out_dir>/queue/id:*. */

  fn = alloc_printf("%s/queue/.state", afl->out_dir);
  if (rmdir(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/queue", afl->out_dir);
  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  /* All right, let's do <afl->out_dir>/crashes/id:* and
   * <afl->out_dir>/hangs/id:*. */

  if (!afl->in_place_resume) {

    fn = alloc_printf("%s/crashes/README.txt", afl->out_dir);
    unlink(fn);                                            /* Ignore errors */
    ck_free(fn);

  }

  fn = alloc_printf("%s/crashes", afl->out_dir);

  /* Make backup of the crashes directory if it's not empty and if we're
     doing in-place resume. */

  if (afl->in_place_resume && rmdir(fn)) {

    time_t    cur_t = time(0);
    struct tm t;
    localtime_r(&cur_t, &t);

#ifndef SIMPLE_FILES

    u8 *nfn =
        alloc_printf("%s.%04d-%02d-%02d-%02d:%02d:%02d", fn, t.tm_year + 1900,
                     t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);

#else

    u8 *nfn =
        alloc_printf("%s_%04d%02d%02d%02d%02d%02d", fn, t.tm_year + 1900,
                     t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);

#endif                                                    /* ^!SIMPLE_FILES */

    rename(fn, nfn);                                      /* Ignore errors. */
    ck_free(nfn);

  }

  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/hangs", afl->out_dir);

  /* Backup hangs, too. */

  if (afl->in_place_resume && rmdir(fn)) {

    time_t    cur_t = time(0);
    struct tm t;
    localtime_r(&cur_t, &t);

#ifndef SIMPLE_FILES

    u8 *nfn =
        alloc_printf("%s.%04d-%02d-%02d-%02d:%02d:%02d", fn, t.tm_year + 1900,
                     t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);

#else

    u8 *nfn =
        alloc_printf("%s_%04d%02d%02d%02d%02d%02d", fn, t.tm_year + 1900,
                     t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);

#endif                                                    /* ^!SIMPLE_FILES */

    rename(fn, nfn);                                      /* Ignore errors. */
    ck_free(nfn);

  }

  if (delete_files(fn, CASE_PREFIX)) { goto dir_cleanup_failed; }
  ck_free(fn);

  /* And now, for some finishing touches. */

  if (afl->file_extension) {

    fn = alloc_printf("%s/.cur_input.%s", afl->out_dir, afl->file_extension);

  } else {

    fn = alloc_printf("%s/.cur_input", afl->out_dir);

  }

  if (unlink(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
  ck_free(fn);

  if (afl->afl_env.afl_tmpdir) {

    if (afl->file_extension) {

      fn = alloc_printf("%s/.cur_input.%s", afl->afl_env.afl_tmpdir,
                        afl->file_extension);

    } else {

      fn = alloc_printf("%s/.cur_input", afl->afl_env.afl_tmpdir);

    }

    if (unlink(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
    ck_free(fn);

  }

  fn = alloc_printf("%s/fuzz_bitmap", afl->out_dir);
  if (unlink(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
  ck_free(fn);

  if (!afl->in_place_resume) {

    fn = alloc_printf("%s/fuzzer_stats", afl->out_dir);
    if (unlink(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
    ck_free(fn);

  }

  if (!afl->in_place_resume) {

    fn = alloc_printf("%s/plot_data", afl->out_dir);
    if (unlink(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
    ck_free(fn);

  }

  fn = alloc_printf("%s/queue_data", afl->out_dir);
  if (unlink(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
  ck_free(fn);

  fn = alloc_printf("%s/cmdline", afl->out_dir);
  if (unlink(fn) && errno != ENOENT) { goto dir_cleanup_failed; }
  ck_free(fn);

  OKF("Output dir cleanup successful.");

  /* Wow... is that all? If yes, celebrate! */

  return;

dir_cleanup_failed:

  SAYF("\n" cLRD "[-] " cRST
       "Whoops, the fuzzer tried to reuse your output directory, but bumped "
       "into\n"
       "    some files that shouldn't be there or that couldn't be removed - "
       "so it\n"
       "    decided to abort! This happened while processing this path:\n\n"

       "    %s\n\n"
       "    Please examine and manually delete the files, or specify a "
       "different\n"
       "    output location for the tool.\n",
       fn);

  FATAL("Output directory cleanup failed");

}

/* If this is a -S secondary node, ensure a -M main node is running,
  if a main node is running when another main is started, then warn */

int check_main_node_exists(afl_state_t *afl) {

  DIR           *sd;
  struct dirent *sd_ent;
  u8            *fn;

  sd = opendir(afl->sync_dir);
  if (!sd) { return 0; }

  while ((sd_ent = readdir(sd))) {

    /* Skip dot files and our own output directory. */

    if (sd_ent->d_name[0] == '.' || !strcmp(afl->sync_id, sd_ent->d_name)) {

      continue;

    }

    fn = alloc_printf("%s/%s/is_main_node", afl->sync_dir, sd_ent->d_name);
    int res = access(fn, F_OK);
    free(fn);
    if (res == 0) return 1;

  }

  return 0;

}

/* Prepare output directories and fds. */

void setup_dirs_fds(afl_state_t *afl) {

  u8 *tmp;

  ACTF("Setting up output directories...");

  if (afl->sync_id && mkdir(afl->sync_dir, 0700) && errno != EEXIST) {

    PFATAL("Unable to create '%s'", afl->sync_dir);

  }

  if (mkdir(afl->out_dir, 0700)) {

    if (errno != EEXIST) { PFATAL("Unable to create '%s'", afl->out_dir); }

    handle_existing_out_dir(afl);

  } else {

    if (afl->in_place_resume) {

      FATAL("Resume attempted but old output directory not found");

    }

    afl->fsrv.out_dir_fd = open(afl->out_dir, O_RDONLY);

#ifndef __sun

    if (afl->fsrv.out_dir_fd < 0 ||
        flock(afl->fsrv.out_dir_fd, LOCK_EX | LOCK_NB)) {

      PFATAL("Unable to flock() output directory.");

    }

#endif                                                            /* !__sun */

  }

  if (afl->is_main_node) {

    u8 *x = alloc_printf("%s/is_main_node", afl->out_dir);
    int fd = open(x, O_CREAT | O_RDWR, 0644);
    if (fd < 0) FATAL("cannot create %s", x);
    free(x);
    close(fd);

  }

  /* Queue directory for any starting & discovered paths. */

  tmp = alloc_printf("%s/queue", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* Top-level directory for queue metadata used for session
     resume and related tasks. */

  tmp = alloc_printf("%s/queue/.state/", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* Directory for flagging queue entries that went through
     deterministic fuzzing in the past. */

  tmp = alloc_printf("%s/queue/.state/deterministic_done/", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* Directory with the auto-selected dictionary entries. */

  tmp = alloc_printf("%s/queue/.state/auto_extras/", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* The set of paths currently deemed redundant. */

  tmp = alloc_printf("%s/queue/.state/redundant_edges/", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* The set of paths showing variable behavior. */

  tmp = alloc_printf("%s/queue/.state/variable_behavior/", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* Sync directory for keeping track of cooperating fuzzers. */

  if (afl->sync_id) {

    tmp = alloc_printf("%s/.synced/", afl->out_dir);

    if (mkdir(tmp, 0700) && (!afl->in_place_resume || errno != EEXIST)) {

      PFATAL("Unable to create '%s'", tmp);

    }

    ck_free(tmp);

  }

  /* All recorded crashes. */

  tmp = alloc_printf("%s/crashes", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* All recorded hangs. */

  tmp = alloc_printf("%s/hangs", afl->out_dir);
  if (mkdir(tmp, 0700)) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  /* Generally useful file descriptors. */

  afl->fsrv.dev_null_fd = open("/dev/null", O_RDWR);
  if (afl->fsrv.dev_null_fd < 0) { PFATAL("Unable to open /dev/null"); }

  afl->fsrv.dev_urandom_fd = open("/dev/urandom", O_RDONLY);
  if (afl->fsrv.dev_urandom_fd < 0) { PFATAL("Unable to open /dev/urandom"); }

  /* Gnuplot output file. */

  tmp = alloc_printf("%s/plot_data", afl->out_dir);

  if (!afl->in_place_resume) {

    int fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL, DEFAULT_PERMISSION);
    if (fd < 0) { PFATAL("Unable to create '%s'", tmp); }
    ck_free(tmp);

    afl->fsrv.plot_file = fdopen(fd, "w");
    if (!afl->fsrv.plot_file) { PFATAL("fdopen() failed"); }

    fprintf(
        afl->fsrv.plot_file,
        "# relative_time, cycles_done, cur_item, corpus_count, "
        "pending_total, pending_favs, map_size, saved_crashes, "
        "saved_hangs, max_depth, execs_per_sec, total_execs, edges_found\n");

  } else {

    int fd = open(tmp, O_WRONLY | O_CREAT, DEFAULT_PERMISSION);
    if (fd < 0) { PFATAL("Unable to create '%s'", tmp); }
    ck_free(tmp);

    afl->fsrv.plot_file = fdopen(fd, "w");
    if (!afl->fsrv.plot_file) { PFATAL("fdopen() failed"); }

    fseek(afl->fsrv.plot_file, 0, SEEK_END);

  }

  fflush(afl->fsrv.plot_file);

  /* ignore errors */

}

void setup_cmdline_file(afl_state_t *afl, char **argv) {

  u8 *tmp;
  s32 fd;
  u32 i = 0;

  FILE *cmdline_file = NULL;

  /* Store the command line to reproduce our findings */
  tmp = alloc_printf("%s/cmdline", afl->out_dir);
  fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL, DEFAULT_PERMISSION);
  if (fd < 0) { PFATAL("Unable to create '%s'", tmp); }
  ck_free(tmp);

  cmdline_file = fdopen(fd, "w");
  if (!cmdline_file) { PFATAL("fdopen() failed"); }

  while (argv[i]) {

    fprintf(cmdline_file, "%s\n", argv[i]);
    ++i;

  }

  fclose(cmdline_file);

}

/* Setup the output file for fuzzed data, if not using -f. */

void setup_stdio_file(afl_state_t *afl) {

  if (afl->file_extension) {

    afl->fsrv.out_file =
        alloc_printf("%s/.cur_input.%s", afl->tmp_dir, afl->file_extension);

  } else {

    afl->fsrv.out_file = alloc_printf("%s/.cur_input", afl->tmp_dir);

  }

  unlink(afl->fsrv.out_file);                              /* Ignore errors */

  afl->fsrv.out_fd =
      open(afl->fsrv.out_file, O_RDWR | O_CREAT | O_EXCL, DEFAULT_PERMISSION);

  if (afl->fsrv.out_fd < 0) {

    PFATAL("Unable to create '%s'", afl->fsrv.out_file);

  }

}

/* Make sure that core dumps don't go to a program. */

void check_crash_handling(void) {

#ifdef __APPLE__

  /* Yuck! There appears to be no simple C API to query for the state of
     loaded daemons on MacOS X, and I'm a bit hesitant to do something
     more sophisticated, such as disabling crash reporting via Mach ports,
     until I get a box to test the code. So, for now, we check for crash
     reporting the awful way. */

  #if !TARGET_OS_IPHONE
  if (system("launchctl list 2>/dev/null | grep -q '\\.ReportCrash\\>'"))
    return;

  SAYF(
      "\n" cLRD "[-] " cRST
      "Whoops, your system is configured to forward crash notifications to an\n"
      "    external crash reporting utility. This will cause issues due to "
      "the\n"
      "    extended delay between the fuzzed binary malfunctioning and this "
      "fact\n"
      "    being relayed to the fuzzer via the standard waitpid() API.\n\n"
      "    To avoid having crashes misinterpreted as timeouts, please run the\n"
      "    following commands:\n\n"

      "    SL=/System/Library; PL=com.apple.ReportCrash\n"
      "    launchctl unload -w ${SL}/LaunchAgents/${PL}.plist\n"
      "    sudo launchctl unload -w ${SL}/LaunchDaemons/${PL}.Root.plist\n");

  #endif
  if (!get_afl_env("AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES"))
    FATAL("Crash reporter detected");

#else

  /* This is Linux specific, but I don't think there's anything equivalent on
   *BSD, so we can just let it slide for now. */

  s32 fd = open("/proc/sys/kernel/core_pattern", O_RDONLY);
  u8  fchar;

  if (fd < 0) { return; }

  ACTF("Checking core_pattern...");

  if (read(fd, &fchar, 1) == 1 && fchar == '|') {

    SAYF(
        "\n" cLRD "[-] " cRST
        "Hmm, your system is configured to send core dump notifications to an\n"
        "    external utility. This will cause issues: there will be an "
        "extended delay\n"
        "    between stumbling upon a crash and having this information "
        "relayed to the\n"
        "    fuzzer via the standard waitpid() API.\n"
        "    If you're just testing, set "
        "'AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1'.\n\n"

        "    To avoid having crashes misinterpreted as timeouts, please log in "
        "as root\n"
        "    and temporarily modify /proc/sys/kernel/core_pattern, like so:\n\n"

        "    echo core >/proc/sys/kernel/core_pattern\n");

    if (!getenv("AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES")) {

      FATAL("Pipe at the beginning of 'core_pattern'");

    }

  }

  close(fd);

#endif                                                        /* ^__APPLE__ */

}

/* Check CPU governor. */

void check_cpu_governor(afl_state_t *afl) {

#ifdef __linux__
  FILE *f;
  u8    tmp[128];
  u64   min = 0, max = 0;

  if (afl->afl_env.afl_skip_cpufreq) { return; }

  if (afl->cpu_aff > 0) {

    snprintf(tmp, sizeof(tmp), "%s%d%s", "/sys/devices/system/cpu/cpu",
             afl->cpu_aff, "/cpufreq/scaling_governor");

  } else {

    snprintf(tmp, sizeof(tmp), "%s",
             "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor");

  }

  f = fopen("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", "r");
  if (!f) {

    if (afl->cpu_aff > 0) {

      snprintf(tmp, sizeof(tmp), "%s%d%s",
               "/sys/devices/system/cpu/cpufreq/policy", afl->cpu_aff,
               "/scaling_governor");

    } else {

      snprintf(tmp, sizeof(tmp), "%s",
               "/sys/devices/system/cpu/cpufreq/policy0/scaling_governor");

    }

    f = fopen(tmp, "r");

  }

  if (!f) {

    WARNF("Could not check CPU scaling governor");
    return;

  }

  ACTF("Checking CPU scaling governor...");

  if (!fgets(tmp, 128, f)) { PFATAL("fgets() failed"); }

  fclose(f);

  if (!strncmp(tmp, "perf", 4)) { return; }

  f = fopen("/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq", "r");

  if (f) {

    if (fscanf(f, "%llu", &min) != 1) { min = 0; }
    fclose(f);

  }

  f = fopen("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq", "r");

  if (f) {

    if (fscanf(f, "%llu", &max) != 1) { max = 0; }
    fclose(f);

  }

  if (min == max) { return; }

  SAYF("\n" cLRD "[-] " cRST
       "Whoops, your system uses on-demand CPU frequency scaling, adjusted\n"
       "    between %llu and %llu MHz. Unfortunately, the scaling algorithm in "
       "the\n"
       "    kernel is imperfect and can miss the short-lived processes spawned "
       "by\n"
       "    afl-fuzz. To keep things moving, run these commands as root:\n\n"

       "    cd /sys/devices/system/cpu\n"
       "    echo performance | tee cpu*/cpufreq/scaling_governor\n\n"

       "    You can later go back to the original state by replacing "
       "'performance'\n"
       "    with 'ondemand' or 'powersave'. If you don't want to change the "
       "settings,\n"
       "    set AFL_SKIP_CPUFREQ to make afl-fuzz skip this check - but expect "
       "some\n"
       "    performance drop.\n",
       min / 1024, max / 1024);
  FATAL("Suboptimal CPU scaling governor");

#elif defined __APPLE__
  u64    min = 0, max = 0;
  size_t mlen = sizeof(min);
  if (afl->afl_env.afl_skip_cpufreq) return;

  ACTF("Checking CPU scaling governor...");

  if (sysctlbyname("hw.cpufrequency_min", &min, &mlen, NULL, 0) == -1) {

    WARNF("Could not check CPU min frequency");
    return;

  }

  if (sysctlbyname("hw.cpufrequency_max", &max, &mlen, NULL, 0) == -1) {

    WARNF("Could not check CPU max frequency");
    return;

  }

  if (min == max) return;

  SAYF("\n" cLRD "[-] " cRST
       "Whoops, your system uses on-demand CPU frequency scaling, adjusted\n"
       "    between %llu and %llu MHz.\n"
       "    If you don't want to check those settings, set "
       "AFL_SKIP_CPUFREQ\n"
       "    to make afl-fuzz skip this check - but expect some performance "
       "drop.\n",
       min / 1024, max / 1024);
  FATAL("Suboptimal CPU scaling governor");
#else
  (void)afl;
#endif

}

/* Count the number of logical CPU cores. */

void get_core_count(afl_state_t *afl) {

#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
    defined(__DragonFly__)

  size_t s = sizeof(afl->cpu_core_count);

  /* On *BSD systems, we can just use a sysctl to get the number of CPUs. */

  #ifdef __APPLE__

  if (sysctlbyname("hw.logicalcpu", &afl->cpu_core_count, &s, NULL, 0) < 0)
    return;

  #else

  int s_name[2] = {CTL_HW, HW_NCPU};

  if (sysctl(s_name, 2, &afl->cpu_core_count, &s, NULL, 0) < 0) return;

  #endif                                                      /* ^__APPLE__ */

#else

  #ifdef HAVE_AFFINITY

  afl->cpu_core_count = sysconf(_SC_NPROCESSORS_ONLN);

  #else

  FILE *f = fopen("/proc/stat", "r");
  u8    tmp[1024];

  if (!f) return;

  while (fgets(tmp, sizeof(tmp), f))
    if (!strncmp(tmp, "cpu", 3) && isdigit(tmp[3])) ++afl->cpu_core_count;

  fclose(f);

  #endif                                                  /* ^HAVE_AFFINITY */

#endif                        /* ^(__APPLE__ || __FreeBSD__ || __OpenBSD__) */

  if (afl->cpu_core_count > 0) {

    u32 cur_runnable = 0;

    cur_runnable = (u32)get_runnable_processes();

#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || \
    defined(__DragonFly__)

    /* Add ourselves, since the 1-minute average doesn't include that yet. */

    ++cur_runnable;

#endif                           /* __APPLE__ || __FreeBSD__ || __OpenBSD__ */

    OKF("You have %d CPU core%s and %u runnable tasks (utilization: %0.0f%%).",
        afl->cpu_core_count, afl->cpu_core_count > 1 ? "s" : "", cur_runnable,
        cur_runnable * 100.0 / afl->cpu_core_count);

    if (afl->cpu_core_count > 1) {

      if (cur_runnable > afl->cpu_core_count * 1.5) {

        WARNF("System under apparent load, performance may be spotty.");

      } else if ((s64)cur_runnable + 1 <= (s64)afl->cpu_core_count) {

        OKF("Try parallel jobs - see "
            "%s/fuzzing_in_depth.md#c-using-multiple-cores",
            doc_path);

      }

    }

  } else {

    afl->cpu_core_count = 0;
    WARNF("Unable to figure out the number of CPU cores.");

  }

}

/* Validate and fix up afl->out_dir and sync_dir when using -S. */

void fix_up_sync(afl_state_t *afl) {

  u8 *x = afl->sync_id;

  while (*x) {

    if (!isalnum(*x) && *x != '_' && *x != '-') {

      FATAL("Non-alphanumeric fuzzer ID specified via -S or -M");

    }

    ++x;

  }

  if (strlen(afl->sync_id) > 32) { FATAL("Fuzzer ID too long"); }

  x = alloc_printf("%s/%s", afl->out_dir, afl->sync_id);

#ifdef __linux__
  if (afl->fsrv.nyx_mode) { afl->fsrv.out_dir_path = afl->out_dir; }
#endif
  afl->sync_dir = afl->out_dir;
  afl->out_dir = x;

}

/* Handle screen resize (SIGWINCH). */

static void handle_resize(int sig) {

  (void)sig;
  afl_states_clear_screen();

}

/* Check ASAN options. */

void check_asan_opts(afl_state_t *afl) {

  u8 *x = get_afl_env("ASAN_OPTIONS");

  (void)(afl);

  if (x) {

    if (!strstr(x, "abort_on_error=1")) {

      FATAL("Custom ASAN_OPTIONS set without abort_on_error=1 - please fix!");

    }

#ifndef ASAN_BUILD
    if (!afl->debug && !strstr(x, "symbolize=0")) {

      FATAL("Custom ASAN_OPTIONS set without symbolize=0 - please fix!");

    }

#endif

  }

  x = get_afl_env("MSAN_OPTIONS");

  if (x) {

    if (!strstr(x, "exit_code=" STRINGIFY(MSAN_ERROR))) {

      FATAL("Custom MSAN_OPTIONS set without exit_code=" STRINGIFY(
          MSAN_ERROR) " - please fix!");

    }

    if (!afl->debug && !strstr(x, "symbolize=0")) {

      FATAL("Custom MSAN_OPTIONS set without symbolize=0 - please fix!");

    }

  }

  x = get_afl_env("LSAN_OPTIONS");

  if (x) {

    if (!strstr(x, "symbolize=0")) {

      FATAL("Custom LSAN_OPTIONS set without symbolize=0 - please fix!");

    }

  }

}

/* Handle stop signal (Ctrl-C, etc). */

static void handle_stop_sig(int sig) {

  (void)sig;
  afl_states_stop();

}

/* Handle skip request (SIGUSR1). */

static void handle_skipreq(int sig) {

  (void)sig;
  afl_states_request_skip();

}

/* Setup shared map for fuzzing with input via sharedmem */

void setup_testcase_shmem(afl_state_t *afl) {

  afl->shm_fuzz = ck_alloc(sizeof(sharedmem_t));

  // we need to set the non-instrumented mode to not overwrite the SHM_ENV_VAR
  u8 *map = afl_shm_init(afl->shm_fuzz, MAX_FILE + sizeof(u32), 1);
  afl->shm_fuzz->shmemfuzz_mode = 1;

  if (!map) { FATAL("BUG: Zero return from afl_shm_init."); }

#ifdef USEMMAP
  setenv(SHM_FUZZ_ENV_VAR, afl->shm_fuzz->g_shm_file_path, 1);
#else
  u8 *shm_str = alloc_printf("%d", afl->shm_fuzz->shm_id);
  setenv(SHM_FUZZ_ENV_VAR, shm_str, 1);
  ck_free(shm_str);
#endif
  afl->fsrv.support_shmem_fuzz = 1;
  afl->fsrv.shmem_fuzz_len = (u32 *)map;
  afl->fsrv.shmem_fuzz = map + sizeof(u32);

}

/* Do a PATH search and find target binary to see that it exists and
   isn't a shell script - a common and painful mistake. We also check for
   a valid ELF header and for evidence of AFL instrumentation. */

void check_binary(afl_state_t *afl, u8 *fname) {

  if (unlikely(!fname)) { FATAL("BUG: Binary name is NULL"); }

  u8         *env_path = 0;
  struct stat st;

  s32 fd;
  u8 *f_data;
  u32 f_len = 0;

  ACTF("Validating target binary...");

  if (strchr(fname, '/') || !(env_path = getenv("PATH"))) {

    afl->fsrv.target_path = ck_strdup(fname);
#ifdef __linux__
    if (afl->fsrv.nyx_mode) {

      /* check if target_path is a nyx sharedir */
      if (stat(afl->fsrv.target_path, &st) || S_ISDIR(st.st_mode)) {

        char *tmp = alloc_printf("%s/config.ron", afl->fsrv.target_path);
        if (stat(tmp, &st) || S_ISREG(st.st_mode)) {

          free(tmp);
          return;

        }

      }

      FATAL("Directory '%s' not found or is not a nyx share directory",
            afl->fsrv.target_path);

    }

#endif
    if (stat(afl->fsrv.target_path, &st) || !S_ISREG(st.st_mode) ||
        !(st.st_mode & 0111) || (f_len = st.st_size) < 4) {

      FATAL("Program '%s' not found or not executable", fname);

    }

  } else {

    while (env_path) {

      u8 *cur_elem, *delim = strchr(env_path, ':');

      if (delim) {

        cur_elem = ck_alloc(delim - env_path + 1);
        if (unlikely(!cur_elem)) { FATAL("Unexpected large PATH"); }
        memcpy(cur_elem, env_path, delim - env_path);
        ++delim;

      } else {

        cur_elem = ck_strdup(env_path);

      }

      env_path = delim;

      if (cur_elem[0]) {

        afl->fsrv.target_path = alloc_printf("%s/%s", cur_elem, fname);

      } else {

        afl->fsrv.target_path = ck_strdup(fname);

      }

      ck_free(cur_elem);

      if (!stat(afl->fsrv.target_path, &st) && S_ISREG(st.st_mode) &&
          (st.st_mode & 0111) && (f_len = st.st_size) >= 4) {

        break;

      }

      ck_free(afl->fsrv.target_path);
      afl->fsrv.target_path = 0;

    }

    if (!afl->fsrv.target_path) {

      FATAL("Program '%s' not found or not executable", fname);

    }

  }

  if (afl->afl_env.afl_skip_bin_check || afl->use_wine || afl->unicorn_mode ||
      (afl->fsrv.qemu_mode && getenv("AFL_QEMU_CUSTOM_BIN")) ||
      (afl->fsrv.cs_mode && getenv("AFL_CS_CUSTOM_BIN")) ||
      afl->non_instrumented_mode) {

    return;

  }

  /* Check for blatant user errors. */

  /*  disabled. not a real-worl scenario where this is a problem.
    if ((!strncmp(afl->fsrv.target_path, "/tmp/", 5) &&
         !strchr(afl->fsrv.target_path + 5, '/')) ||
        (!strncmp(afl->fsrv.target_path, "/var/tmp/", 9) &&
         !strchr(afl->fsrv.target_path + 9, '/'))) {

      FATAL("Please don't keep binaries in /tmp or /var/tmp");

    }

  */

  fd = open(afl->fsrv.target_path, O_RDONLY);

  if (fd < 0) { PFATAL("Unable to open '%s'", afl->fsrv.target_path); }

  f_data = mmap(0, f_len, PROT_READ, MAP_PRIVATE, fd, 0);

  if (f_data == MAP_FAILED) {

    PFATAL("Unable to mmap file '%s'", afl->fsrv.target_path);

  }

  close(fd);

  if (f_data[0] == '#' && f_data[1] == '!') {

    SAYF("\n" cLRD "[-] " cRST
         "Oops, the target binary looks like a shell script. Some build "
         "systems will\n"
         "    sometimes generate shell stubs for dynamically linked programs; "
         "try static\n"
         "    library mode (./configure --disable-shared) if that's the "
         "case.\n\n"

         "    Another possible cause is that you are actually trying to use a "
         "shell\n"
         "    wrapper around the fuzzed component. Invoking shell can slow "
         "down the\n"
         "    fuzzing process by a factor of 20x or more; it's best to write "
         "the wrapper\n"
         "    in a compiled language instead.\n");

    FATAL("Program '%s' is a shell script", afl->fsrv.target_path);

  }

#ifndef __APPLE__

  if (f_data[0] != 0x7f || memcmp(f_data + 1, "ELF", 3)) {

    FATAL("Program '%s' is not an ELF binary", afl->fsrv.target_path);

  }

#else

  #if !defined(__arm__) && !defined(__arm64__)
  if ((f_data[0] != 0xCF || f_data[1] != 0xFA || f_data[2] != 0xED) &&
      (f_data[0] != 0xCA || f_data[1] != 0xFE || f_data[2] != 0xBA))
    FATAL("Program '%s' is not a 64-bit or universal Mach-O binary",
          afl->fsrv.target_path);
  #endif

#endif                                                       /* ^!__APPLE__ */

  if (!afl->fsrv.qemu_mode && !afl->fsrv.frida_mode && !afl->unicorn_mode &&
#ifdef __linux__
      !afl->fsrv.nyx_mode &&
#endif
      !afl->fsrv.cs_mode && !afl->non_instrumented_mode &&
      !afl_memmem(f_data, f_len, SHM_ENV_VAR, strlen(SHM_ENV_VAR) + 1)) {

    SAYF("\n" cLRD "[-] " cRST
         "Looks like the target binary is not instrumented! The fuzzer depends "
         "on\n"
         "    compile-time instrumentation to isolate interesting test cases "
         "while\n"
         "    mutating the input data. For more information, and for tips on "
         "how to\n"
         "    instrument binaries, please see %s/README.md.\n\n"

         "    When source code is not available, you may be able to leverage "
         "QEMU\n"
         "    mode support. Consult the README.md for tips on how to enable "
         "this.\n\n"

         "    If your target is an instrumented binary (e.g. with zafl, "
         "retrowrite,\n"
         "    etc.) then set 'AFL_SKIP_BIN_CHECK=1'\n\n"

         "    (It is also possible to use afl-fuzz as a traditional, "
         "non-instrumented\n"
         "    fuzzer. For that use the -n option - but expect much worse "
         "results.)\n",
         doc_path);

    FATAL("No instrumentation detected");

  }

  if ((afl->fsrv.cs_mode || afl->fsrv.qemu_mode || afl->fsrv.frida_mode) &&
      afl_memmem(f_data, f_len, SHM_ENV_VAR, strlen(SHM_ENV_VAR) + 1)) {

    SAYF("\n" cLRD "[-] " cRST
         "This program appears to be instrumented with afl-gcc, but is being "
         "run in\n"
         "    QEMU mode (-Q). This is probably not what you "
         "want -\n"
         "    this setup will be slow and offer no practical benefits.\n");

    FATAL("Instrumentation found in -Q mode");

  }

  if (afl_memmem(f_data, f_len, "__asan_init", 11) ||
      afl_memmem(f_data, f_len, "__msan_init", 11) ||
      afl_memmem(f_data, f_len, "__lsan_init", 11)) {

    afl->fsrv.uses_asan = 1;

  }

  /* Detect persistent & deferred init signatures in the binary. */

  if (afl_memmem(f_data, f_len, PERSIST_SIG, strlen(PERSIST_SIG) + 1)) {

    OKF(cPIN "Persistent mode binary detected.");
    setenv(PERSIST_ENV_VAR, "1", 1);
    afl->persistent_mode = 1;
    afl->fsrv.persistent_mode = 1;
    afl->shmem_testcase_mode = 1;

  } else if (getenv("AFL_PERSISTENT")) {

    OKF(cPIN "Persistent mode enforced.");
    setenv(PERSIST_ENV_VAR, "1", 1);
    afl->persistent_mode = 1;
    afl->fsrv.persistent_mode = 1;
    afl->shmem_testcase_mode = 1;

  } else if (getenv("AFL_FRIDA_PERSISTENT_ADDR")) {

    OKF("FRIDA Persistent mode configuration options detected.");
    setenv(PERSIST_ENV_VAR, "1", 1);
    afl->persistent_mode = 1;
    afl->fsrv.persistent_mode = 1;
    afl->shmem_testcase_mode = 1;

  }

  if (afl->fsrv.frida_mode ||
      afl_memmem(f_data, f_len, DEFER_SIG, strlen(DEFER_SIG) + 1)) {

    OKF(cPIN "Deferred forkserver binary detected.");
    setenv(DEFER_ENV_VAR, "1", 1);
    afl->deferred_mode = 1;

  } else if (getenv("AFL_DEFER_FORKSRV")) {

    OKF(cPIN "Deferred forkserver enforced.");
    setenv(DEFER_ENV_VAR, "1", 1);
    afl->deferred_mode = 1;

  }

  if (munmap(f_data, f_len)) { PFATAL("unmap() failed"); }

}

/* Check if we're on TTY. */

void check_if_tty(afl_state_t *afl) {

  struct winsize ws;

  if (afl->afl_env.afl_no_ui) {

    OKF("Disabling the UI because AFL_NO_UI is set.");
    afl->not_on_tty = 1;
    return;

  }

  if (ioctl(1, TIOCGWINSZ, &ws)) {

    if (errno == ENOTTY) {

      OKF("Looks like we're not running on a tty, so I'll be a bit less "
          "verbose.");
      afl->not_on_tty = 1;

    }

    return;

  }

}

/* Set up signal handlers. More complicated that needs to be, because libc on
   Solaris doesn't resume interrupted reads(), sets SA_RESETHAND when you call
   siginterrupt(), and does other stupid things. */

void setup_signal_handlers(void) {

  struct sigaction sa;

  memset((void *)&sa, 0, sizeof(sa));
  sa.sa_handler = NULL;
#ifdef SA_RESTART
  sa.sa_flags = SA_RESTART;
#endif
  sa.sa_sigaction = NULL;

  sigemptyset(&sa.sa_mask);

  /* Various ways of saying "stop". */

  sa.sa_handler = handle_stop_sig;
  sigaction(SIGHUP, &sa, NULL);
  sigaction(SIGINT, &sa, NULL);
  sigaction(SIGTERM, &sa, NULL);

  /* Window resize */

  sa.sa_handler = handle_resize;
  sigaction(SIGWINCH, &sa, NULL);

  /* SIGUSR1: skip entry */

  sa.sa_handler = handle_skipreq;
  sigaction(SIGUSR1, &sa, NULL);

  /* Things we don't care about. */

  sa.sa_handler = SIG_IGN;
  sigaction(SIGTSTP, &sa, NULL);
  sigaction(SIGPIPE, &sa, NULL);

}

/* Make a copy of the current command line. */

void save_cmdline(afl_state_t *afl, u32 argc, char **argv) {

  u32 len = 1, i;
  u8 *buf;

  for (i = 0; i < argc; ++i) {

    len += strlen(argv[i]) + 1;

  }

  buf = afl->orig_cmdline = ck_alloc(len);

  for (i = 0; i < argc; ++i) {

    u32 l = strlen(argv[i]);

    if (!argv[i] || !buf) { FATAL("null deref detected"); }

    memcpy(buf, argv[i], l);
    buf += l;

    if (i != argc - 1) { *(buf++) = ' '; }

  }

  *buf = 0;

}