写在前面

经历过面试以后,开始怀疑自己并不是真的懂fuzzing,所以花了小半个月把afl的源码从头读了一遍,然后直接在源码里写满了注释。

原作者用的都是/**/风格的注释,我用的都是//,所以不会混淆

未来空闲了考虑重新整理一下吧

直接看注释吧

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
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
/*
Copyright 2013 Google LLC All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at:

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
american fuzzy lop - fuzzer code
--------------------------------

Written and maintained by Michal Zalewski <lcamtuf@google.com>

Forkserver design by Jann Horn <jannhorn@googlemail.com>

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.

*/

#define AFL_MAIN
#include "android-ashmem.h"
#define MESSAGES_TO_STDOUT

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _FILE_OFFSET_BITS 64

#include "config.h"
#include "types.h"
#include "debug.h"
#include "alloc-inl.h"
#include "hash.h"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <dirent.h>
#include <ctype.h>
#include <fcntl.h>
#include <termios.h>
#include <dlfcn.h>
#include <sched.h>

#include <sys/wait.h>
#include <sys/time.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/file.h>

#if defined(__APPLE__) || defined(__FreeBSD__) || defined (__OpenBSD__)
# include <sys/sysctl.h>
#endif /* __APPLE__ || __FreeBSD__ || __OpenBSD__ */

/* For systems that have sched_setaffinity; right now just Linux, but one
can hope... */

#ifdef __linux__
# define HAVE_AFFINITY 1
#endif /* __linux__ */

/* A toggle to export some variables when building as a library. Not very
useful for the general public. */

#ifdef AFL_LIB
# define EXP_ST
#else
# define EXP_ST static
#endif /* ^AFL_LIB */

/* Lots of globals, but mostly for the status UI and other things where it
really makes no sense to haul them around as function parameters. */


EXP_ST u8 *in_dir, /* Input directory with test cases */
*out_file, /* File to fuzz, if any */
*out_dir, /* Working & output directory */
*sync_dir, /* Synchronization directory */
*sync_id, /* Fuzzer ID */
*use_banner, /* Display banner */
*in_bitmap, /* Input bitmap */
*doc_path, /* Path to documentation dir */
*target_path, /* Path to target binary */
*orig_cmdline; /* Original command line */

EXP_ST u32 exec_tmout = EXEC_TIMEOUT; /* Configurable exec timeout (ms) */
static u32 hang_tmout = EXEC_TIMEOUT; /* Timeout used for hang det (ms) */

EXP_ST u64 mem_limit = MEM_LIMIT; /* Memory cap for child (MB) */

EXP_ST u32 cpu_to_bind = 0; /* id of free CPU core to bind */

static u32 stats_update_freq = 1; /* Stats update frequency (execs) */

EXP_ST u8 skip_deterministic, /* Skip deterministic stages? */
force_deterministic, /* Force deterministic stages? */
use_splicing, /* Recombine input files? */
dumb_mode, /* Run in non-instrumented mode? */
score_changed, /* Scoring for favorites changed? */
kill_signal, /* Signal that killed the child */
resuming_fuzz, /* Resuming an older fuzzing job? */
timeout_given, /* Specific timeout given? */
cpu_to_bind_given, /* Specified cpu_to_bind given? */
not_on_tty, /* stdout is not a tty */
term_too_small, /* terminal dimensions too small */
uses_asan, /* Target uses ASAN? */
no_forkserver, /* Disable forkserver? */
crash_mode, /* Crash mode! Yeah! */
in_place_resume, /* Attempt in-place resume? */
auto_changed, /* Auto-generated tokens changed? */
no_cpu_meter_red, /* Feng shui on the status screen */
no_arith, /* Skip most arithmetic ops */
shuffle_queue, /* Shuffle input queue? */
bitmap_changed = 1, /* Time to update bitmap? */
qemu_mode, /* Running in QEMU mode? */
skip_requested, /* Skip request, via SIGUSR1 */
run_over10m, /* Run time over 10 minutes? */
persistent_mode, /* Running in persistent mode? */
deferred_mode, /* Deferred forkserver mode? */
fast_cal; /* Try to calibrate faster? */

static s32 out_fd, /* Persistent fd for out_file */
dev_urandom_fd = -1, /* Persistent fd for /dev/urandom */
dev_null_fd = -1, /* Persistent fd for /dev/null */
fsrv_ctl_fd, /* Fork server control pipe (write) */
fsrv_st_fd; /* Fork server status pipe (read) */

static s32 forksrv_pid, /* PID of the fork server */
child_pid = -1, /* PID of the fuzzed program */
out_dir_fd = -1; /* FD of the lock file */

EXP_ST u8* trace_bits; /* SHM with instrumentation bitmap */

EXP_ST u8 virgin_bits[MAP_SIZE], /* Regions yet untouched by fuzzing */
virgin_tmout[MAP_SIZE], /* Bits we haven't seen in tmouts */
virgin_crash[MAP_SIZE]; /* Bits we haven't seen in crashes */

static u8 var_bytes[MAP_SIZE]; /* Bytes that appear to be variable */

static s32 shm_id; /* ID of the SHM region */

static volatile u8 stop_soon, /* Ctrl-C pressed? */
clear_screen = 1, /* Window resized? */
child_timed_out; /* Traced process timed out? */

EXP_ST u32 queued_paths, /* Total number of queued testcases */
queued_variable, /* Testcases with variable behavior */
queued_at_start, /* Total number of initial inputs */
queued_discovered, /* Items discovered during this run */
queued_imported, /* Items imported via -S */
queued_favored, /* Paths deemed favorable */
queued_with_cov, /* Paths with new coverage bytes */
pending_not_fuzzed, /* Queued but not done yet */
pending_favored, /* Pending favored paths */
cur_skipped_paths, /* Abandoned inputs in cur cycle */
cur_depth, /* Current path depth */
max_depth, /* Max path depth */
useless_at_start, /* Number of useless starting paths */
var_byte_count, /* Bitmap bytes with var behavior */
current_entry, /* Current queue entry ID */
havoc_div = 1; /* Cycle count divisor for havoc */

EXP_ST u64 total_crashes, /* Total number of crashes */
unique_crashes, /* Crashes with unique signatures */
total_tmouts, /* Total number of timeouts */
unique_tmouts, /* Timeouts with unique signatures */
unique_hangs, /* Hangs with unique signatures */
total_execs, /* Total execve() calls */
slowest_exec_ms, /* Slowest testcase non hang in ms */
start_time, /* Unix start time (ms) */
last_path_time, /* Time for most recent path (ms) */
last_crash_time, /* Time for most recent crash (ms) */
last_hang_time, /* Time for most recent hang (ms) */
last_crash_execs, /* Exec counter at last crash */
queue_cycle, /* Queue round counter */
cycles_wo_finds, /* Cycles without any new paths */
trim_execs, /* Execs done to trim input files */
bytes_trim_in, /* Bytes coming into the trimmer */
bytes_trim_out, /* Bytes coming outa the trimmer */
blocks_eff_total, /* Blocks subject to effector maps */
blocks_eff_select; /* Blocks selected as fuzzable */

static u32 subseq_tmouts; /* Number of timeouts in a row */

static u8 *stage_name = "init", /* Name of the current fuzz stage */
*stage_short, /* Short stage name */
*syncing_party; /* Currently syncing with... */

static s32 stage_cur, stage_max; /* Stage progression */
static s32 splicing_with = -1; /* Splicing with which test case? */

static u32 master_id, master_max; /* Master instance job splitting */

static u32 syncing_case; /* Syncing with case #... */

static s32 stage_cur_byte, /* Byte offset of current stage op */
stage_cur_val; /* Value used for stage op */

static u8 stage_val_type; /* Value type (STAGE_VAL_*) */

static u64 stage_finds[32], /* Patterns found per fuzz stage */
stage_cycles[32]; /* Execs per fuzz stage */

static u32 rand_cnt; /* Random number counter */

static u64 total_cal_us, /* Total calibration time (us) */
total_cal_cycles; /* Total calibration cycles */

static u64 total_bitmap_size, /* Total bit count for all bitmaps */
total_bitmap_entries; /* Number of bitmaps counted */

static s32 cpu_core_count; /* CPU core count */

#ifdef HAVE_AFFINITY

static s32 cpu_aff = -1; /* Selected CPU core */

#endif /* HAVE_AFFINITY */

static FILE* plot_file; /* Gnuplot output file */

struct queue_entry {

u8* fname; /* File name for the test case */
u32 len; /* Input length */

u8 cal_failed, /* Calibration failed? */
trim_done, /* Trimmed? */
was_fuzzed, /* Had any fuzzing done yet? */
passed_det, /* Deterministic stages passed? */
has_new_cov, /* Triggers new coverage? */
var_behavior, /* Variable behavior? */
favored, /* Currently favored? */
fs_redundant; /* Marked as redundant in the fs? */

u32 bitmap_size, /* Number of bits set in bitmap */
exec_cksum; /* Checksum of the execution trace */

u64 exec_us, /* Execution time (us) */
handicap, /* Number of queue cycles behind */
depth; /* Path depth */

u8* trace_mini; /* Trace bytes, if kept */
u32 tc_ref; /* Trace bytes ref count */

struct queue_entry *next, /* Next element, if any */
*next_100; /* 100 elements ahead */

};

static struct queue_entry *queue, /* Fuzzing queue (linked list) */
*queue_cur, /* Current offset within the queue */
*queue_top, /* Top of the list */
*q_prev100; /* Previous 100 marker */

static struct queue_entry*
top_rated[MAP_SIZE]; /* Top entries for bitmap bytes */

struct extra_data {
u8* data; /* Dictionary token data */
u32 len; /* Dictionary token length */
u32 hit_cnt; /* Use count in the corpus */
};

static struct extra_data* extras; /* Extra tokens to fuzz with */
static u32 extras_cnt; /* Total number of tokens read */

static struct extra_data* a_extras; /* Automatically selected extras */
static u32 a_extras_cnt; /* Total number of tokens available */

static u8* (*post_handler)(u8* buf, u32* len);

/* Interesting values, as per config.h */

static s8 interesting_8[] = { INTERESTING_8 };
static s16 interesting_16[] = { INTERESTING_8, INTERESTING_16 };
static s32 interesting_32[] = { INTERESTING_8, INTERESTING_16, INTERESTING_32 };

/* Fuzzing stages */

enum {
/* 00 */ STAGE_FLIP1,
/* 01 */ STAGE_FLIP2,
/* 02 */ STAGE_FLIP4,
/* 03 */ STAGE_FLIP8,
/* 04 */ STAGE_FLIP16,
/* 05 */ STAGE_FLIP32,
/* 06 */ STAGE_ARITH8,
/* 07 */ STAGE_ARITH16,
/* 08 */ STAGE_ARITH32,
/* 09 */ STAGE_INTEREST8,
/* 10 */ STAGE_INTEREST16,
/* 11 */ STAGE_INTEREST32,
/* 12 */ STAGE_EXTRAS_UO,
/* 13 */ STAGE_EXTRAS_UI,
/* 14 */ STAGE_EXTRAS_AO,
/* 15 */ STAGE_HAVOC,
/* 16 */ STAGE_SPLICE
};

/* Stage value types */

enum {
/* 00 */ STAGE_VAL_NONE,
/* 01 */ STAGE_VAL_LE,
/* 02 */ STAGE_VAL_BE
};

/* Execution status fault codes */

enum {
/* 00 */ FAULT_NONE,
/* 01 */ FAULT_TMOUT,
/* 02 */ FAULT_CRASH,
/* 03 */ FAULT_ERROR,
/* 04 */ FAULT_NOINST,
/* 05 */ FAULT_NOBITS
};


/* Get unix time in milliseconds */

static u64 get_cur_time(void) {

struct timeval tv;
struct timezone tz;

gettimeofday(&tv, &tz);

return (tv.tv_sec * 1000ULL) + (tv.tv_usec / 1000);

}


/* Get unix time in microseconds */

static u64 get_cur_time_us(void) {

struct timeval tv;
struct timezone tz;

gettimeofday(&tv, &tz);

return (tv.tv_sec * 1000000ULL) + tv.tv_usec;

}


/* Generate a random number (from 0 to limit - 1). This may
have slight bias. */

static inline u32 UR(u32 limit) {

if (unlikely(!rand_cnt--)) {

u32 seed[2];

ck_read(dev_urandom_fd, &seed, sizeof(seed), "/dev/urandom");

srandom(seed[0]);
rand_cnt = (RESEED_RNG / 2) + (seed[1] % RESEED_RNG);

}

return random() % limit;

}


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

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

u32 i;

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

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

}

}


#ifdef HAVE_AFFINITY

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

static void bind_to_free_cpu(void) {

DIR* d;
struct dirent* de;
cpu_set_t c;

u8 cpu_used[4096] = { 0 };
u32 i;

if (cpu_core_count < 2) return;

if (getenv("AFL_NO_AFFINITY")) {

WARNF("Not binding to a CPU core (AFL_NO_AFFINITY set).");
return;

}

d = opendir("/proc");

if (!d) {

WARNF("Unable to access /proc - can't scan for free CPU cores.");
return;

}

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

/* Introduce some jitter, in case multiple AFL tasks are doing the same
thing at the same time... */

usleep(R(1000) * 250);

/* 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;
FILE* f;
u8 tmp[MAX_LINE];
u8 has_vmsize = 0;

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

fn = alloc_printf("/proc/%s/status", de->d_name);

if (!(f = fopen(fn, "r"))) {
ck_free(fn);
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;

}

}

ck_free(fn);
fclose(f);

}

closedir(d);
if (cpu_to_bind_given) {

if (cpu_to_bind >= cpu_core_count)
FATAL("The CPU core id to bind should be between 0 and %u", cpu_core_count - 1);

if (cpu_used[cpu_to_bind])
FATAL("The CPU core #%u to bind is not free!", cpu_to_bind);

i = cpu_to_bind;

} else {

for (i = 0; i < cpu_core_count; i++) if (!cpu_used[i]) break;

}

if (i == cpu_core_count) {

SAYF("\n" cLRD "[-] " cRST
"Uh-oh, looks like all %u 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, but if you are\n"
" absolutely sure, you can set AFL_NO_AFFINITY and try again.\n",
cpu_core_count);

FATAL("No more free CPU cores");

}

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

cpu_aff = i;

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

if (sched_setaffinity(0, sizeof(c), &c))
PFATAL("sched_setaffinity failed");

}

#endif /* HAVE_AFFINITY */

#ifndef IGNORE_FINDS

/* Helper function to compare buffers; returns first and last differing offset. We
use this to find reasonable locations for splicing two files. */
//定位ptr1和ptr2的第一处差异的偏移和最后一处差异的偏移。
static void locate_diffs(u8* ptr1, u8* ptr2, u32 len, s32* first, s32* last) {

s32 f_loc = -1;
s32 l_loc = -1;
u32 pos;

for (pos = 0; pos < len; pos++) {

if (*(ptr1++) != *(ptr2++)) {

if (f_loc == -1) f_loc = pos;//只在f_loc为初始值-1时更新一次
l_loc = pos;//无条件更新

}

}

*first = f_loc;
*last = l_loc;

return;

}

#endif /* !IGNORE_FINDS */


/* Describe integer. Uses 12 cyclic static buffers for return values. The value
returned should be five characters or less for all the integers we reasonably
expect to see. */

static u8* DI(u64 val) {

static u8 tmp[12][16];
static u8 cur;

cur = (cur + 1) % 12;

#define CHK_FORMAT(_divisor, _limit_mult, _fmt, _cast) do { \
if (val < (_divisor) * (_limit_mult)) { \
sprintf(tmp[cur], _fmt, ((_cast)val) / (_divisor)); \
return tmp[cur]; \
} \
} while (0)

/* 0-9999 */
CHK_FORMAT(1, 10000, "%llu", u64);

/* 10.0k - 99.9k */
CHK_FORMAT(1000, 99.95, "%0.01fk", double);

/* 100k - 999k */
CHK_FORMAT(1000, 1000, "%lluk", u64);

/* 1.00M - 9.99M */
CHK_FORMAT(1000 * 1000, 9.995, "%0.02fM", double);

/* 10.0M - 99.9M */
CHK_FORMAT(1000 * 1000, 99.95, "%0.01fM", double);

/* 100M - 999M */
CHK_FORMAT(1000 * 1000, 1000, "%lluM", u64);

/* 1.00G - 9.99G */
CHK_FORMAT(1000LL * 1000 * 1000, 9.995, "%0.02fG", double);

/* 10.0G - 99.9G */
CHK_FORMAT(1000LL * 1000 * 1000, 99.95, "%0.01fG", double);

/* 100G - 999G */
CHK_FORMAT(1000LL * 1000 * 1000, 1000, "%lluG", u64);

/* 1.00T - 9.99G */
CHK_FORMAT(1000LL * 1000 * 1000 * 1000, 9.995, "%0.02fT", double);

/* 10.0T - 99.9T */
CHK_FORMAT(1000LL * 1000 * 1000 * 1000, 99.95, "%0.01fT", double);

/* 100T+ */
strcpy(tmp[cur], "infty");
return tmp[cur];

}


/* Describe float. Similar to the above, except with a single
static buffer. */

static u8* DF(double val) {

static u8 tmp[16];

if (val < 99.995) {
sprintf(tmp, "%0.02f", val);
return tmp;
}

if (val < 999.95) {
sprintf(tmp, "%0.01f", val);
return tmp;
}

return DI((u64)val);

}


/* Describe integer as memory size. */

static u8* DMS(u64 val) {

static u8 tmp[12][16];
static u8 cur;

cur = (cur + 1) % 12;

/* 0-9999 */
CHK_FORMAT(1, 10000, "%llu B", u64);

/* 10.0k - 99.9k */
CHK_FORMAT(1024, 99.95, "%0.01f kB", double);

/* 100k - 999k */
CHK_FORMAT(1024, 1000, "%llu kB", u64);

/* 1.00M - 9.99M */
CHK_FORMAT(1024 * 1024, 9.995, "%0.02f MB", double);

/* 10.0M - 99.9M */
CHK_FORMAT(1024 * 1024, 99.95, "%0.01f MB", double);

/* 100M - 999M */
CHK_FORMAT(1024 * 1024, 1000, "%llu MB", u64);

/* 1.00G - 9.99G */
CHK_FORMAT(1024LL * 1024 * 1024, 9.995, "%0.02f GB", double);

/* 10.0G - 99.9G */
CHK_FORMAT(1024LL * 1024 * 1024, 99.95, "%0.01f GB", double);

/* 100G - 999G */
CHK_FORMAT(1024LL * 1024 * 1024, 1000, "%llu GB", u64);

/* 1.00T - 9.99G */
CHK_FORMAT(1024LL * 1024 * 1024 * 1024, 9.995, "%0.02f TB", double);

/* 10.0T - 99.9T */
CHK_FORMAT(1024LL * 1024 * 1024 * 1024, 99.95, "%0.01f TB", double);

#undef CHK_FORMAT

/* 100T+ */
strcpy(tmp[cur], "infty");
return tmp[cur];

}


/* Describe time delta. Returns one static buffer, 34 chars of less. */

static u8* DTD(u64 cur_ms, u64 event_ms) {

static u8 tmp[64];
u64 delta;
s32 t_d, t_h, t_m, t_s;

if (!event_ms) return "none seen yet";

delta = cur_ms - event_ms;

t_d = delta / 1000 / 60 / 60 / 24;
t_h = (delta / 1000 / 60 / 60) % 24;
t_m = (delta / 1000 / 60) % 60;
t_s = (delta / 1000) % 60;

sprintf(tmp, "%s days, %u hrs, %u min, %u sec", DI(t_d), t_h, t_m, t_s);
return tmp;

}


/* Mark deterministic checks as done for a particular queue entry. We use the
.state file to avoid repeating deterministic fuzzing when resuming aborted
scans. */

static void mark_as_det_done(struct queue_entry* q) {

u8* fn = strrchr(q->fname, '/');
s32 fd;

fn = alloc_printf("%s/queue/.state/deterministic_done/%s", out_dir, fn + 1);

fd = open(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) PFATAL("Unable to create '%s'", fn);
close(fd);

ck_free(fn);

q->passed_det = 1;

}


/* Mark as variable. Create symlinks if possible to make it easier to examine
the files. */

static void mark_as_variable(struct queue_entry* q) {

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

ldest = alloc_printf("../../%s", fn);
fn = alloc_printf("%s/queue/.state/variable_behavior/%s", out_dir, fn);

if (symlink(ldest, fn)) {

s32 fd = open(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) PFATAL("Unable to create '%s'", fn);
close(fd);

}

ck_free(ldest);
ck_free(fn);

q->var_behavior = 1;

}


/* Mark / unmark as redundant (edge-only). This is not used for restoring state,
but may be useful for post-processing datasets. */

static void mark_as_redundant(struct queue_entry* q, u8 state) {

u8* fn;
s32 fd;

if (state == q->fs_redundant) return;

q->fs_redundant = state;

fn = strrchr(q->fname, '/');
fn = alloc_printf("%s/queue/.state/redundant_edges/%s", out_dir, fn + 1);

if (state) {

fd = open(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) PFATAL("Unable to create '%s'", fn);
close(fd);

} else {

if (unlink(fn)) PFATAL("Unable to remove '%s'", fn);

}

ck_free(fn);

}


/* Append new test case to the queue. */

static void add_to_queue(u8* fname, u32 len, u8 passed_det) {

struct queue_entry* q = ck_alloc(sizeof(struct queue_entry));

q->fname = fname;
q->len = len;
q->depth = cur_depth + 1;
q->passed_det = passed_det;

if (q->depth > max_depth) max_depth = q->depth;

if (queue_top) {

queue_top->next = q;
queue_top = q;

} else q_prev100 = queue = queue_top = q;

queued_paths++;
pending_not_fuzzed++;

cycles_wo_finds = 0;

/* Set next_100 pointer for every 100th element (index 0, 100, etc) to allow faster iteration. */
if ((queued_paths - 1) % 100 == 0 && queued_paths > 1) {

q_prev100->next_100 = q;
q_prev100 = q;

}

last_path_time = get_cur_time();

}


/* Destroy the entire queue. */

EXP_ST void destroy_queue(void) {

struct queue_entry *q = queue, *n;

while (q) {

n = q->next;
ck_free(q->fname);
ck_free(q->trace_mini);
ck_free(q);
q = n;

}

}


/* Write bitmap to file. The bitmap is useful mostly for the secret
-B option, to focus a separate fuzzing session on a particular
interesting input without rediscovering all the others. */

EXP_ST void write_bitmap(void) {

u8* fname;
s32 fd;

if (!bitmap_changed) return;
bitmap_changed = 0;

fname = alloc_printf("%s/fuzz_bitmap", out_dir);
fd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, 0600);

if (fd < 0) PFATAL("Unable to open '%s'", fname);

ck_write(fd, virgin_bits, MAP_SIZE, fname);

close(fd);
ck_free(fname);

}


/* Read bitmap from file. This is for the -B option again. */

EXP_ST void read_bitmap(u8* fname) {

s32 fd = open(fname, O_RDONLY);

if (fd < 0) PFATAL("Unable to open '%s'", fname);

ck_read(fd, virgin_bits, MAP_SIZE, fname);

close(fd);

}


/* Check if the current execution path brings anything new to the table.
Update virgin bits to reflect the finds. Returns 1 if the only change is
the hit-count for a particular tuple; 2 if there are new tuples seen.
Updates the map, so subsequent calls will always return 0.

This function is called after every exec() on a fairly large buffer, so
it needs to be fast. We do this in 32-bit and 64-bit flavors. */

static inline u8 has_new_bits(u8* virgin_map) {
//某个特定tuple的命中数发生变化--返回1;有新的tuples--返回2;
#ifdef WORD_SIZE_64

u64* current = (u64*)trace_bits;
u64* virgin = (u64*)virgin_map;

u32 i = (MAP_SIZE >> 3);

#else

u32* current = (u32*)trace_bits;
u32* virgin = (u32*)virgin_map;

u32 i = (MAP_SIZE >> 2);

#endif /* ^WORD_SIZE_64 */

u8 ret = 0;

while (i--) {

/* Optimize for (*current & *virgin) == 0 - i.e., no bits in current bitmap
that have not been already cleared from the virgin map - since this will
almost always be the case. */

if (unlikely(*current) && unlikely(*current & *virgin)) {

if (likely(ret < 2)) {

u8* cur = (u8*)current;
u8* vir = (u8*)virgin;

/* Looks like we have not found any new bytes yet; see if any non-zero
bytes in current[] are pristine in virgin[]. */

#ifdef WORD_SIZE_64

if ((cur[0] && vir[0] == 0xff) || (cur[1] && vir[1] == 0xff) ||
(cur[2] && vir[2] == 0xff) || (cur[3] && vir[3] == 0xff) ||
(cur[4] && vir[4] == 0xff) || (cur[5] && vir[5] == 0xff) ||
(cur[6] && vir[6] == 0xff) || (cur[7] && vir[7] == 0xff)) ret = 2;
else ret = 1;

#else

if ((cur[0] && vir[0] == 0xff) || (cur[1] && vir[1] == 0xff) ||
(cur[2] && vir[2] == 0xff) || (cur[3] && vir[3] == 0xff)) ret = 2;
else ret = 1;

#endif /* ^WORD_SIZE_64 */

}

*virgin &= ~*current;

}

current++;
virgin++;

}

if (ret && virgin_map == virgin_bits) bitmap_changed = 1;

return ret;

}


/* Count the number of bits set in the provided bitmap. Used for the status
screen several times every second, does not have to be fast. */

static u32 count_bits(u8* mem) {

u32* ptr = (u32*)mem;
u32 i = (MAP_SIZE >> 2);
u32 ret = 0;

while (i--) {

u32 v = *(ptr++);

/* This gets called on the inverse, virgin bitmap; optimize for sparse
data. */

if (v == 0xffffffff) {
ret += 32;
continue;
}

v -= ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
ret += (((v + (v >> 4)) & 0xF0F0F0F) * 0x01010101) >> 24;

}

return ret;

}


#define FF(_b) (0xff << ((_b) << 3))

/* Count the number of bytes set in the bitmap. Called fairly sporadically,
mostly to update the status screen or calibrate and examine confirmed
new paths. */

static u32 count_bytes(u8* mem) {

u32* ptr = (u32*)mem;
u32 i = (MAP_SIZE >> 2);
u32 ret = 0;

while (i--) {

u32 v = *(ptr++);

if (!v) continue;
if (v & FF(0)) ret++;
if (v & FF(1)) ret++;
if (v & FF(2)) ret++;
if (v & FF(3)) ret++;

}

return ret;

}


/* Count the number of non-255 bytes set in the bitmap. Used strictly for the
status screen, several calls per second or so. */

static u32 count_non_255_bytes(u8* mem) {

u32* ptr = (u32*)mem;
u32 i = (MAP_SIZE >> 2);
u32 ret = 0;

while (i--) {

u32 v = *(ptr++);

/* This is called on the virgin bitmap, so optimize for the most likely
case. */

if (v == 0xffffffff) continue;
if ((v & FF(0)) != FF(0)) ret++;
if ((v & FF(1)) != FF(1)) ret++;
if ((v & FF(2)) != FF(2)) ret++;
if ((v & FF(3)) != FF(3)) ret++;

}

return ret;

}


/* Destructively simplify trace by eliminating hit count information
and replacing it with 0x80 or 0x01 depending on whether the tuple
is hit or not. Called on every new crash or timeout, should be
reasonably fast. */
//通过消除命中计数信息破坏性简化trace,无命中则字节值为0x00替换成0x01,[0x01,0xFF]次命中的字节一律替换成0x80
static const u8 simplify_lookup[256] = {

[0] = 1,
[1 ... 255] = 128

};

#ifdef WORD_SIZE_64

static void simplify_trace(u64* mem) {

u32 i = MAP_SIZE >> 3;

while (i--) {

/* Optimize for sparse bitmaps. */

if (unlikely(*mem)) {

u8* mem8 = (u8*)mem;

mem8[0] = simplify_lookup[mem8[0]];
mem8[1] = simplify_lookup[mem8[1]];
mem8[2] = simplify_lookup[mem8[2]];
mem8[3] = simplify_lookup[mem8[3]];
mem8[4] = simplify_lookup[mem8[4]];
mem8[5] = simplify_lookup[mem8[5]];
mem8[6] = simplify_lookup[mem8[6]];
mem8[7] = simplify_lookup[mem8[7]];

} else *mem = 0x0101010101010101ULL;

mem++;

}

}

#else

static void simplify_trace(u32* mem) {

u32 i = MAP_SIZE >> 2;

while (i--) {

/* Optimize for sparse bitmaps. */

if (unlikely(*mem)) {//unlikely不影响条件判断,而是表示这个条件判断通常不成立,即通常为false or 0,即更有可能执行else的语句,会指导编译器将else的语句编译到前面来

u8* mem8 = (u8*)mem;

mem8[0] = simplify_lookup[mem8[0]];//simplify_lookup 通过消除命中计数信息破坏性简化trace,无命中则字节值为0x00替换成0x01,[0x01,0xFF]次命中的字节一律替换成0x80
mem8[1] = simplify_lookup[mem8[1]];
mem8[2] = simplify_lookup[mem8[2]];
mem8[3] = simplify_lookup[mem8[3]];

} else *mem = 0x01010101;

mem++;
}

}

#endif /* ^WORD_SIZE_64 */


/* Destructively classify execution counts in a trace. This is used as a
preprocessing step for any newly acquired traces. Called on every exec,
must be fast. */

static const u8 count_class_lookup8[256] = {

[0] = 0,
[1] = 1,
[2] = 2,
[3] = 4,
[4 ... 7] = 8,
[8 ... 15] = 16,
[16 ... 31] = 32,
[32 ... 127] = 64,
[128 ... 255] = 128

};
//AFL在统计一条路径的执行次数时,
static u16 count_class_lookup16[65536];


EXP_ST void init_count_class16(void) {
//count_class_lookup8支持用一个字节表示路径的执行次数,并通过lookup8数组进行快速规整;lookup16将执行次数扩展成2个字节,因此用lookup8的规整逻辑,创建一个lookup16,即用lookup8的规整逻辑分别设置高8位和低8位
u32 b1, b2;

for (b1 = 0; b1 < 256; b1++)
for (b2 = 0; b2 < 256; b2++)
count_class_lookup16[(b1 << 8) + b2] =
(count_class_lookup8[b1] << 8) |
count_class_lookup8[b2];

}


#ifdef WORD_SIZE_64

static inline void classify_counts(u64* mem) {

u32 i = MAP_SIZE >> 3;

while (i--) {

/* Optimize for sparse bitmaps. */

if (unlikely(*mem)) {

u16* mem16 = (u16*)mem;

mem16[0] = count_class_lookup16[mem16[0]];
mem16[1] = count_class_lookup16[mem16[1]];
mem16[2] = count_class_lookup16[mem16[2]];
mem16[3] = count_class_lookup16[mem16[3]];

}

mem++;

}

}

#else

static inline void classify_counts(u32* mem) {

u32 i = MAP_SIZE >> 2;

while (i--) {

/* Optimize for sparse bitmaps. */

if (unlikely(*mem)) {

u16* mem16 = (u16*)mem;

mem16[0] = count_class_lookup16[mem16[0]];
mem16[1] = count_class_lookup16[mem16[1]];

}

mem++;

}

}

#endif /* ^WORD_SIZE_64 */


/* Get rid of shared memory (atexit handler). */

static void remove_shm(void) {

shmctl(shm_id, IPC_RMID, NULL);

}


/* Compact trace bytes into a smaller bitmap. We effectively just drop the
count information here. This is called only sporadically, for some
new paths. */

static void minimize_bits(u8* dst, u8* src) {

u32 i = 0;

while (i < MAP_SIZE) {

if (*(src++)) dst[i >> 3] |= 1 << (i & 7);
i++;

}

}


/* When we bump into a new path, we call this to see if the path appears
more "favorable" than any of the existing ones. The purpose of the
"favorables" is to have a minimal set of paths that trigger all the bits
seen in the bitmap so far, and focus on fuzzing them at the expense of
the rest.

The first step of the process is to maintain a list of top_rated[] entries
for every byte in the bitmap. We win that slot if there is no previous
contender, or if the contender has a more favorable speed x size factor. */

static void update_bitmap_score(struct queue_entry* q) {

u32 i;
u64 fav_factor = q->exec_us * q->len;//因子fav_factor用时间×长度作为评判一个testcase的依据

/* For every byte set in trace_bits[], see if there is a previous winner,
and how it compares to us. */

for (i = 0; i < MAP_SIZE; i++)

if (trace_bits[i]) {

if (top_rated[i]) {//如果top_rated中已经存在与trace_bits的第i位对应的case,就进入下面的比较逻辑,如果没有,就直接在top_rate[i]中插入q

/* Faster-executing or smaller test cases are favored. */

if (fav_factor > top_rated[i]->exec_us * top_rated[i]->len) continue;//更快执行或者更小的测试用例更受afl欢迎.如果此处fav_factor更大,afl会直接跳过这一case,直接计算下一个case.但这里这种简陋的策略,有改进的空间吗

/* Looks like we're going to win. Decrease ref count for the
previous winner, discard its trace_bits[] if necessary. */

if (!--top_rated[i]->tc_ref) {//trace bytes ref count. 如果--tc_ref==0,说明这一bit上空出来了
ck_free(top_rated[i]->trace_mini);//trace_mini:trace bytes, if kept
top_rated[i]->trace_mini = 0;
}

}

/* Insert ourselves as the new winner. */

top_rated[i] = q;
q->tc_ref++;

if (!q->trace_mini) {
q->trace_mini = ck_alloc(MAP_SIZE >> 3);//trace_mini中每个位对应bitmap中的一个byte 就是trace_bits变trace_bytes
minimize_bits(q->trace_mini, trace_bits);//把trace_bits存进更紧凑的trace_bytes里,用计数的方式记录原trace_bits中的每个byte中多少个bits置1
}

score_changed = 1;

}

}


/* The second part of the mechanism discussed above is a routine that
goes over top_rated[] entries, and then sequentially grabs winners for
previously-unseen bytes (temp_v) and marks them as favored, at least
until the next run. The favored entries are given more air time during
all fuzzing steps. */

static void cull_queue(void) {

struct queue_entry* q;
static u8 temp_v[MAP_SIZE >> 3];
u32 i;

if (dumb_mode || !score_changed) return;//执行下列逻辑的前提是运行在非dumb mode并且score有被更新过

score_changed = 0;

memset(temp_v, 255, MAP_SIZE >> 3);//把temp_v的(1<<13)字节塞满0xFF

queued_favored = 0;
pending_favored = 0;

q = queue;

while (q) {
q->favored = 0;
q = q->next;
}

/* Let's see if anything in the bitmap isn't captured in temp_v.
If yes, and if it has a top_rated[] contender, let's use it. */

for (i = 0; i < MAP_SIZE; i++)
if (top_rated[i] && (temp_v[i >> 3] & (1 << (i & 7)))) {//temp_v是以字节为单位存放,&&后的条件判断是判断temp_v中每一bit是否为1 即byte to bit.

u32 j = MAP_SIZE >> 3;

/* Remove all bits belonging to the current entry from temp_v. */

while (j--)
if (top_rated[i]->trace_mini[j])
temp_v[j] &= ~top_rated[i]->trace_mini[j];//trace_mini中所有"1"位,在temp_v中都置0

top_rated[i]->favored = 1;
queued_favored++;

if (!top_rated[i]->was_fuzzed) pending_favored++;//如果还没fuzz过,就给pending_favored计数加一,等待fuzzing

}

q = queue;

while (q) {
mark_as_redundant(q, !q->favored);//遍历queue,如果这个条目不是favored,就标记为redundant(多余的)
q = q->next;
}

}


/* Configure shared memory and virgin_bits. This is called at startup. */

EXP_ST void setup_shm(void) {

u8* shm_str;

if (!in_bitmap) memset(virgin_bits, 255, MAP_SIZE);

memset(virgin_tmout, 255, MAP_SIZE);
memset(virgin_crash, 255, MAP_SIZE);

shm_id = shmget(IPC_PRIVATE, MAP_SIZE, IPC_CREAT | IPC_EXCL | 0600);//shmget用来创建共享内存,int shmget(key_t key, size_t size, int shmflg)
//reference:https://www.cnblogs.com/52php/p/5861372.html shm相关操作
if (shm_id < 0) PFATAL("shmget() failed");

atexit(remove_shm);

shm_str = alloc_printf("%d", shm_id);

/* If somebody is asking us to fuzz instrumented binaries in dumb mode,
we don't want them to detect instrumentation, since we won't be sending
fork server commands. This should be replaced with better auto-detection
later on, perhaps? */
//有趣的问题,dumb模式下fuzz一个插桩后的程序
if (!dumb_mode) setenv(SHM_ENV_VAR, shm_str, 1);//如果不是dumb mode 就设置SHM_ENV_VAR的环境变量 值为shm_id

ck_free(shm_str);

trace_bits = shmat(shm_id, NULL, 0);//启动对该shared memory的访问,并把共享内存连接到当前进程的地址空间, at=>attach 第二个参数shm_addr指定共享内存在当前进程中的地址,通常为NULL,表示由系统决定共享内存的地址

if (trace_bits == (void *)-1) PFATAL("shmat() failed");

}


/* Load postprocessor, if available. */

static void setup_post(void) {

void* dh;
u8* fn = getenv("AFL_POST_LIBRARY");
u32 tlen = 6;

if (!fn) return;

ACTF("Loading postprocessor from '%s'...", fn);

dh = dlopen(fn, RTLD_NOW);
if (!dh) FATAL("%s", dlerror());

post_handler = dlsym(dh, "afl_postprocess");
if (!post_handler) FATAL("Symbol 'afl_postprocess' not found.");

/* Do a quick test. It's better to segfault now than later =) */

post_handler("hello", &tlen);

OKF("Postprocessor installed successfully.");

}


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

static void read_testcases(void) {

struct dirent **nl;
s32 nl_cnt;
u32 i;
u8* fn;

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

fn = alloc_printf("%s/queue", in_dir);
if (!access(fn, F_OK)) in_dir = fn; else ck_free(fn);

ACTF("Scanning '%s'...", in_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. */
//readdir会导致测试用例的顺序出现很大的随机性?
nl_cnt = scandir(in_dir, &nl, NULL, alphasort);

if (nl_cnt < 0) {

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'", in_dir);

}

if (shuffle_queue && nl_cnt > 1) {

ACTF("Shuffling queue...");
shuffle_ptrs((void**)nl, nl_cnt);//洗牌

}

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

struct stat st;

u8* fn = alloc_printf("%s/%s", in_dir, nl[i]->d_name);
u8* dfn = alloc_printf("%s/.state/deterministic_done/%s", in_dir, nl[i]->d_name);

u8 passed_det = 0;

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

if (lstat(fn, &st) || access(fn, R_OK))//lstat,获取fn指向的testcase,获取状态存入st;同时要求fn可读
PFATAL("Unable to access '%s'", fn);

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

if (!S_ISREG(st.st_mode) || !st.st_size || strstr(fn, "/README.txt")) {//S_ISREG():如果参数(struct stat中的st_mode成员)是常规文件,则计算结果为true。
//如果文件不是常规文件,或者获取不到文件size,或者发现输入时README.txt 就算了
ck_free(fn);
ck_free(dfn);
continue;

}

if (st.st_size > MAX_FILE) //testcase太大也不行 MAX_FILE是2^20 但是注释是小于100MB,单位和st_size都是bytes,这100MB怎么算的
FATAL("Test case '%s' is too big (%s, limit is %s)", fn,
DMS(st.st_size), DMS(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;//F_OK判断dfn文件是否存在
ck_free(dfn);

add_to_queue(fn, st.st_size, passed_det);

}

free(nl); /* not tracked */

if (!queued_paths) {

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'", in_dir);

}

last_path_time = 0;
queued_at_start = queued_paths;

}


/* Helper function for load_extras. */

static int compare_extras_len(const void* p1, const void* p2) {
struct extra_data *e1 = (struct extra_data*)p1,
*e2 = (struct extra_data*)p2;

return e1->len - e2->len;
}

static int compare_extras_use_d(const void* p1, const void* p2) {
struct extra_data *e1 = (struct extra_data*)p1,
*e2 = (struct extra_data*)p2;

return e2->hit_cnt - e1->hit_cnt;
}


/* Read extras from a file, sort by size. */

static void load_extras_file(u8* fname, u32* min_len, u32* max_len,
u32 dict_level) {

FILE* f;
u8 buf[MAX_LINE];
u8 *lptr;
u32 cur_line = 0;

f = fopen(fname, "r");

if (!f) PFATAL("Unable to open '%s'", fname);

while ((lptr = fgets(buf, MAX_LINE, f))) {

u8 *rptr, *wptr;
u32 klen = 0;

cur_line++;

/* Trim on left and right. */

while (isspace(*lptr)) lptr++;

rptr = lptr + strlen(lptr) - 1;
while (rptr >= lptr && isspace(*rptr)) rptr--;
rptr++;
*rptr = 0;

/* Skip empty lines and comments. */

if (!*lptr || *lptr == '#') continue;

/* All other lines must end with '"', which we can consume. */

rptr--;

if (rptr < lptr || *rptr != '"')
FATAL("Malformed name=\"value\" pair in line %u.", cur_line);

*rptr = 0;

/* Skip alphanumerics and dashes (label). */

while (isalnum(*lptr) || *lptr == '_') lptr++;

/* If @number follows, parse that. */

if (*lptr == '@') {

lptr++;
if (atoi(lptr) > dict_level) continue;
while (isdigit(*lptr)) lptr++;

}

/* Skip whitespace and = signs. */

while (isspace(*lptr) || *lptr == '=') lptr++;

/* Consume opening '"'. */

if (*lptr != '"')
FATAL("Malformed name=\"keyword\" pair in line %u.", cur_line);

lptr++;

if (!*lptr) FATAL("Empty keyword in line %u.", cur_line);

/* Okay, let's allocate memory and copy data between "...", handling
\xNN escaping, \\, and \". */

extras = ck_realloc_block(extras, (extras_cnt + 1) *
sizeof(struct extra_data));

wptr = extras[extras_cnt].data = ck_alloc(rptr - lptr);

while (*lptr) {

char* hexdigits = "0123456789abcdef";

switch (*lptr) {

case 1 ... 31:
case 128 ... 255:
FATAL("Non-printable characters in line %u.", cur_line);

case '\\':

lptr++;

if (*lptr == '\\' || *lptr == '"') {
*(wptr++) = *(lptr++);
klen++;
break;
}

if (*lptr != 'x' || !isxdigit(lptr[1]) || !isxdigit(lptr[2]))
FATAL("Invalid escaping (not \\xNN) in line %u.", cur_line);

*(wptr++) =
((strchr(hexdigits, tolower(lptr[1])) - hexdigits) << 4) |
(strchr(hexdigits, tolower(lptr[2])) - hexdigits);

lptr += 3;
klen++;

break;

default:

*(wptr++) = *(lptr++);
klen++;

}

}

extras[extras_cnt].len = klen;

if (extras[extras_cnt].len > MAX_DICT_FILE)
FATAL("Keyword too big in line %u (%s, limit is %s)", cur_line,
DMS(klen), DMS(MAX_DICT_FILE));

if (*min_len > klen) *min_len = klen;
if (*max_len < klen) *max_len = klen;

extras_cnt++;

}

fclose(f);

}


/* Read extras from the extras directory and sort them by size. */

static void load_extras(u8* dir) {

DIR* d;
struct dirent* de;
u32 min_len = MAX_DICT_FILE, max_len = 0, dict_level = 0;
u8* x;

/* If the name ends with @, extract level and continue. */

if ((x = strchr(dir, '@'))) {

*x = 0;
dict_level = atoi(x + 1);

}

ACTF("Loading extra dictionary from '%s' (level %u)...", dir, dict_level);

d = opendir(dir);

if (!d) {

if (errno == ENOTDIR) {
load_extras_file(dir, &min_len, &max_len, dict_level);
goto check_and_sort;
}

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

}

if (x) FATAL("Dictionary levels not supported for directories.");

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

struct stat st;
u8* fn = alloc_printf("%s/%s", dir, de->d_name);
s32 fd;

if (lstat(fn, &st) || access(fn, R_OK))
PFATAL("Unable to access '%s'", fn);

/* This also takes care of . and .. */
if (!S_ISREG(st.st_mode) || !st.st_size) {

ck_free(fn);
continue;

}

if (st.st_size > MAX_DICT_FILE)
FATAL("Extra '%s' is too big (%s, limit is %s)", fn,
DMS(st.st_size), DMS(MAX_DICT_FILE));

if (min_len > st.st_size) min_len = st.st_size;
if (max_len < st.st_size) max_len = st.st_size;

extras = ck_realloc_block(extras, (extras_cnt + 1) *
sizeof(struct extra_data));

extras[extras_cnt].data = ck_alloc(st.st_size);
extras[extras_cnt].len = st.st_size;

fd = open(fn, O_RDONLY);

if (fd < 0) PFATAL("Unable to open '%s'", fn);

ck_read(fd, extras[extras_cnt].data, st.st_size, fn);

close(fd);
ck_free(fn);

extras_cnt++;

}

closedir(d);

check_and_sort:

if (!extras_cnt) FATAL("No usable files in '%s'", dir);

qsort(extras, extras_cnt, sizeof(struct extra_data), compare_extras_len);

OKF("Loaded %u extra tokens, size range %s to %s.", extras_cnt,
DMS(min_len), DMS(max_len));

if (max_len > 32)
WARNF("Some tokens are relatively large (%s) - consider trimming.",
DMS(max_len));

if (extras_cnt > MAX_DET_EXTRAS)
WARNF("More than %u tokens - will use them probabilistically.",
MAX_DET_EXTRAS);

}




/* Helper function for maybe_add_auto() */

static inline u8 memcmp_nocase(u8* m1, u8* m2, u32 len) {

while (len--) if (tolower(*(m1++)) ^ tolower(*(m2++))) return 1;
return 0;

}


/* Maybe add automatic extra. */

static void maybe_add_auto(u8* mem, u32 len) {

u32 i;

/* Allow users to specify that they don't want auto dictionaries. */

if (!MAX_AUTO_EXTRAS || !USE_AUTO_EXTRAS) return;

/* Skip runs of identical bytes. */

for (i = 1; i < len; i++)
if (mem[0] ^ mem[i]) break;

if (i == len) return;//匹配字典

/* Reject builtin interesting values. */

if (len == 2) {

i = sizeof(interesting_16) >> 1;//i=sizeof({8+16})>>2 => i=12

while (i--)
if (*((u16*)mem) == interesting_16[i] ||
*((u16*)mem) == SWAP16(interesting_16[i])) return;//SWAP16 将16位unsigned int的前8位和后8位互换

}

if (len == 4) {

i = sizeof(interesting_32) >> 2;//i = 14

while (i--)
if (*((u32*)mem) == interesting_32[i] ||
*((u32*)mem) == SWAP32(interesting_32[i])) return;//[31-24][23-16][15-8][7-0]=>[7-0][15-8][23-16][31-24] SWAP16和SWAP32实现的其实就是大小端转换

}

/* Reject anything that matches existing extras. Do a case-insensitive
match. We optimize by exploiting the fact that extras[] are sorted
by size. */

for (i = 0; i < extras_cnt; i++)
if (extras[i].len >= len) break;//extras按照size排序,用这个loop快速定位len

for (; i < extras_cnt && extras[i].len == len; i++)
if (!memcmp_nocase(extras[i].data, mem, len)) return;//不分大小写的字符串匹配

/* Last but not least, check a_extras[] for matches. There are no
guarantees of a particular sort order. */

auto_changed = 1;

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

if (a_extras[i].len == len && !memcmp_nocase(a_extras[i].data, mem, len)) {

a_extras[i].hit_cnt++;
goto sort_a_extras;

}

}

/* At this point, looks like we're dealing with a new entry. So, let's
append it if we have room. Otherwise, let's randomly evict some other
entry from the bottom half of the list. */

if (a_extras_cnt < MAX_AUTO_EXTRAS) {

a_extras = ck_realloc_block(a_extras, (a_extras_cnt + 1) *
sizeof(struct extra_data));

a_extras[a_extras_cnt].data = ck_memdup(mem, len);
a_extras[a_extras_cnt].len = len;
a_extras_cnt++;

} else {

i = MAX_AUTO_EXTRAS / 2 +
UR((MAX_AUTO_EXTRAS + 1) / 2);

ck_free(a_extras[i].data);

a_extras[i].data = ck_memdup(mem, len);
a_extras[i].len = len;
a_extras[i].hit_cnt = 0;

}

sort_a_extras:

/* First, sort all auto extras by use count, descending order. */

qsort(a_extras, a_extras_cnt, sizeof(struct extra_data),
compare_extras_use_d);

/* Then, sort the top USE_AUTO_EXTRAS entries by size. */

qsort(a_extras, MIN(USE_AUTO_EXTRAS, a_extras_cnt),
sizeof(struct extra_data), compare_extras_len);

}


/* Save automatically generated extras. */

static void save_auto(void) {

u32 i;

if (!auto_changed) return;//为0就直接返回,非零就继续往下执行
auto_changed = 0;// 非零就把自己置零

for (i = 0; i < MIN(USE_AUTO_EXTRAS, a_extras_cnt); i++) {

u8* fn = alloc_printf("%s/queue/.state/auto_extras/auto_%06u", out_dir, i);
s32 fd;

fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0600);

if (fd < 0) PFATAL("Unable to create '%s'", fn);

ck_write(fd, a_extras[i].data, a_extras[i].len, fn);

close(fd);
ck_free(fn);

}

}


/* Load automatically generated extras. */

static void load_auto(void) {

u32 i;

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

u8 tmp[MAX_AUTO_EXTRA + 1];
u8* fn = alloc_printf("%s/.state/auto_extras/auto_%06u", in_dir, i);
s32 fd, len;

fd = open(fn, O_RDONLY, 0600);

if (fd < 0) {

if (errno != ENOENT) PFATAL("Unable to open '%s'", fn);
ck_free(fn);
break;

}

/* We read one byte more to cheaply detect tokens that are too
long (and skip them). */

len = read(fd, tmp, MAX_AUTO_EXTRA + 1);
//比最大长度多读1位,就能简单的实现"太短不要,太长不要"
if (len < 0) PFATAL("Unable to read from '%s'", fn);

if (len >= MIN_AUTO_EXTRA && len <= MAX_AUTO_EXTRA)
maybe_add_auto(tmp, len);

close(fd);
ck_free(fn);

}

if (i) OKF("Loaded %u auto-discovered dictionary tokens.", i);
else OKF("No auto-generated dictionary tokens to reuse.");

}


/* Destroy extras. */

static void destroy_extras(void) {

u32 i;

for (i = 0; i < extras_cnt; i++)
ck_free(extras[i].data);

ck_free(extras);

for (i = 0; i < a_extras_cnt; i++)
ck_free(a_extras[i].data);

ck_free(a_extras);

}


/* Spin up fork server (instrumented mode only). The idea is explained here:

http://lcamtuf.blogspot.com/2014/10/fuzzing-binaries-without-execve.html

In essence, the instrumentation allows us to skip execve(), and just keep
cloning a stopped child. So, we just execute once, and then send commands
through a pipe. The other part of this logic is in afl-as.h. */

EXP_ST void init_forkserver(char** argv) {

static struct itimerval it;
int st_pipe[2], ctl_pipe[2];
int status;
s32 rlen;

ACTF("Spinning up the fork server...");

if (pipe(st_pipe) || pipe(ctl_pipe)) PFATAL("pipe() failed");

forksrv_pid = fork();

if (forksrv_pid < 0) PFATAL("fork() failed");

if (!forksrv_pid) {

struct rlimit r;

/* Umpf. On OpenBSD, the default fd limit for root users is set to
soft 128. Let's try to fix that... */

if (!getrlimit(RLIMIT_NOFILE, &r) && r.rlim_cur < FORKSRV_FD + 2) {

r.rlim_cur = FORKSRV_FD + 2;
setrlimit(RLIMIT_NOFILE, &r); /* Ignore errors */

}

if (mem_limit) {

r.rlim_max = r.rlim_cur = ((rlim_t)mem_limit) << 20;

#ifdef RLIMIT_AS

setrlimit(RLIMIT_AS, &r); /* Ignore errors */

#else

/* This takes care of OpenBSD, which doesn't have RLIMIT_AS, but
according to reliable sources, RLIMIT_DATA covers anonymous
maps - so we should be getting good protection against OOM bugs. */

setrlimit(RLIMIT_DATA, &r); /* Ignore errors */

#endif /* ^RLIMIT_AS */


}

/* Dumping cores is slow and can lead to anomalies if SIGKILL is delivered
before the dump is complete. */

r.rlim_max = r.rlim_cur = 0;

setrlimit(RLIMIT_CORE, &r); /* Ignore errors */

/* Isolate the process and configure standard descriptors. If out_file is
specified, stdin is /dev/null; otherwise, out_fd is cloned instead. */

setsid();

dup2(dev_null_fd, 1);
dup2(dev_null_fd, 2);

if (out_file) {

dup2(dev_null_fd, 0);

} else {

dup2(out_fd, 0);
close(out_fd);

}

/* Set up control and status pipes, close the unneeded original fds. */

if (dup2(ctl_pipe[0], FORKSRV_FD) < 0) PFATAL("dup2() failed");
if (dup2(st_pipe[1], FORKSRV_FD + 1) < 0) PFATAL("dup2() failed");

close(ctl_pipe[0]);
close(ctl_pipe[1]);
close(st_pipe[0]);
close(st_pipe[1]);

close(out_dir_fd);
close(dev_null_fd);
close(dev_urandom_fd);
close(fileno(plot_file));

/* This should improve performance a bit, since it stops the linker from
doing extra work post-fork(). */

if (!getenv("LD_BIND_LAZY")) setenv("LD_BIND_NOW", "1", 0);
//LD_BIND_LAZY 运行时链接程序执行延迟绑定的缺省模式 LD_BIND_NOW覆盖运行时链接程序执行延迟绑定的缺省模式
/* Set sane defaults for ASAN if nothing else specified. */

setenv("ASAN_OPTIONS", "abort_on_error=1:"
"detect_leaks=0:"
"symbolize=0:"
"allocator_may_return_null=1", 0);

/* MSAN is tricky, because it doesn't support abort_on_error=1 at this
point. So, we do this in a very hacky way. */

setenv("MSAN_OPTIONS", "exit_code=" STRINGIFY(MSAN_ERROR) ":"
"symbolize=0:"
"abort_on_error=1:"
"allocator_may_return_null=1:"
"msan_track_origins=0", 0);

execv(target_path, argv);

/* Use a distinctive bitmap signature to tell the parent about execv()
falling through. */

*(u32*)trace_bits = EXEC_FAIL_SIG;
exit(0);

}

/* Close the unneeded endpoints. */

close(ctl_pipe[0]);
close(st_pipe[1]);

fsrv_ctl_fd = ctl_pipe[1];
fsrv_st_fd = st_pipe[0];

/* Wait for the fork server to come up, but don't wait too long. */

it.it_value.tv_sec = ((exec_tmout * FORK_WAIT_MULT) / 1000);
it.it_value.tv_usec = ((exec_tmout * FORK_WAIT_MULT) % 1000) * 1000;

setitimer(ITIMER_REAL, &it, NULL);

rlen = read(fsrv_st_fd, &status, 4);

it.it_value.tv_sec = 0;
it.it_value.tv_usec = 0;

setitimer(ITIMER_REAL, &it, NULL);

/* If we have a four-byte "hello" message from the server, we're all set.
Otherwise, try to figure out what went wrong. */

if (rlen == 4) {
OKF("All right - fork server is up.");
return;
}

if (child_timed_out)
FATAL("Timeout while initializing fork server (adjusting -t may help)");

if (waitpid(forksrv_pid, &status, 0) <= 0)
PFATAL("waitpid() failed");

if (WIFSIGNALED(status)) {

if (mem_limit && mem_limit < 500 && uses_asan) {

SAYF("\n" cLRD "[-] " cRST
"Whoops, the target binary crashed suddenly, before receiving any input\n"
" from the fuzzer! Since it seems to be built with ASAN and you have a\n"
" restrictive memory limit configured, this is expected; please read\n"
" %s/notes_for_asan.txt for help.\n", doc_path);

} else if (!mem_limit) {

SAYF("\n" cLRD "[-] " cRST
"Whoops, the target binary crashed suddenly, before receiving any input\n"
" from the fuzzer! There are several probable explanations:\n\n"

" - The binary is just buggy and explodes entirely on its own. If so, you\n"
" need to fix the underlying problem or find a better replacement.\n\n"

#ifdef __APPLE__

" - On MacOS X, the semantics of fork() syscalls are non-standard and may\n"
" break afl-fuzz performance optimizations when running platform-specific\n"
" targets. To fix this, set AFL_NO_FORKSRV=1 in the environment.\n\n"

#endif /* __APPLE__ */

" - Less likely, there is a horrible bug in the fuzzer. If other options\n"
" fail, poke <lcamtuf@coredump.cx> for troubleshooting tips.\n");

} else {

SAYF("\n" cLRD "[-] " cRST
"Whoops, the target binary crashed suddenly, before receiving any input\n"
" from the fuzzer! There are several probable explanations:\n\n"

" - The current memory limit (%s) is too restrictive, causing the\n"
" target to hit an OOM condition in the dynamic linker. Try bumping up\n"
" the limit with the -m setting in the command line. A simple way confirm\n"
" this diagnosis would be:\n\n"

#ifdef RLIMIT_AS
" ( ulimit -Sv $[%llu << 10]; /path/to/fuzzed_app )\n\n"
#else
" ( ulimit -Sd $[%llu << 10]; /path/to/fuzzed_app )\n\n"
#endif /* ^RLIMIT_AS */

" Tip: you can use http://jwilk.net/software/recidivm to quickly\n"
" estimate the required amount of virtual memory for the binary.\n\n"

" - The binary is just buggy and explodes entirely on its own. If so, you\n"
" need to fix the underlying problem or find a better replacement.\n\n"

#ifdef __APPLE__

" - On MacOS X, the semantics of fork() syscalls are non-standard and may\n"
" break afl-fuzz performance optimizations when running platform-specific\n"
" targets. To fix this, set AFL_NO_FORKSRV=1 in the environment.\n\n"

#endif /* __APPLE__ */

" - Less likely, there is a horrible bug in the fuzzer. If other options\n"
" fail, poke <lcamtuf@coredump.cx> for troubleshooting tips.\n",
DMS(mem_limit << 20), mem_limit - 1);

}

FATAL("Fork server crashed with signal %d", WTERMSIG(status));

}

if (*(u32*)trace_bits == EXEC_FAIL_SIG)
FATAL("Unable to execute target application ('%s')", argv[0]);

if (mem_limit && mem_limit < 500 && uses_asan) {

SAYF("\n" cLRD "[-] " cRST
"Hmm, looks like the target binary terminated before we could complete a\n"
" handshake with the injected code. Since it seems to be built with ASAN and\n"
" you have a restrictive memory limit configured, this is expected; please\n"
" read %s/notes_for_asan.txt for help.\n", doc_path);

} else if (!mem_limit) {

SAYF("\n" cLRD "[-] " cRST
"Hmm, looks like the target binary terminated before we could complete a\n"
" handshake with the injected code. Perhaps there is a horrible bug in the\n"
" fuzzer. Poke <lcamtuf@coredump.cx> for troubleshooting tips.\n");

} else {

SAYF("\n" cLRD "[-] " cRST
"Hmm, looks like the target binary terminated before we could complete a\n"
" handshake with the injected code. There are %s probable explanations:\n\n"

"%s"
" - The current memory limit (%s) is too restrictive, causing an OOM\n"
" fault in the dynamic linker. This can be fixed with the -m option. A\n"
" simple way to confirm the diagnosis may be:\n\n"

#ifdef RLIMIT_AS
" ( ulimit -Sv $[%llu << 10]; /path/to/fuzzed_app )\n\n"
#else
" ( ulimit -Sd $[%llu << 10]; /path/to/fuzzed_app )\n\n"
#endif /* ^RLIMIT_AS */

" Tip: you can use http://jwilk.net/software/recidivm to quickly\n"
" estimate the required amount of virtual memory for the binary.\n\n"

" - Less likely, there is a horrible bug in the fuzzer. If other options\n"
" fail, poke <lcamtuf@coredump.cx> for troubleshooting tips.\n",
getenv(DEFER_ENV_VAR) ? "three" : "two",
getenv(DEFER_ENV_VAR) ?
" - You are using deferred forkserver, but __AFL_INIT() is never\n"
" reached before the program terminates.\n\n" : "",
DMS(mem_limit << 20), mem_limit - 1);

}

FATAL("Fork server handshake failed");

}


/* Execute target application, monitoring for timeouts. Return status
information. The called program will update trace_bits[]. */

static u8 run_target(char** argv, u32 timeout) {

static struct itimerval it;
static u32 prev_timed_out = 0;
static u64 exec_ms = 0;

int status = 0;
u32 tb4;

child_timed_out = 0;

/* After this memset, trace_bits[] are effectively volatile, so we
must prevent any earlier operations from venturing into that
territory. */

memset(trace_bits, 0, MAP_SIZE);
MEM_BARRIER();

/* If we're running in "dumb" mode, we can't rely on the fork server
logic compiled into the target program, so we will just keep calling
execve(). There is a bit of code duplication between here and
init_forkserver(), but c'est la vie. */

if (dumb_mode == 1 || no_forkserver) {//如果afl-fuzz运行在dumb_mode中或者没有forkserver

child_pid = fork();//尝试fork一个字进程,返回一个child_pid

if (child_pid < 0) PFATAL("fork() failed");

if (!child_pid) {//如果返回的pid为0,说明当前进程即为子进程

struct rlimit r;//rlimit 表示进程资源限制的结构体,两个元素: rlim_t rlim_cur; rlim_t rlim_max

if (mem_limit) {//如果设置了内存限制

r.rlim_max = r.rlim_cur = ((rlim_t)mem_limit) << 20;//mem_limit左移20位,就是以MB为单位,存入rlimit结构体中

#ifdef RLIMIT_AS

setrlimit(RLIMIT_AS, &r); /* Ignore errors */
//RLIMIT_AS 进程虚拟内存的最大size
#else

setrlimit(RLIMIT_DATA, &r); /* Ignore errors */
//进程数据段(initialized data, uninitialized和heap)的最大size
#endif /* ^RLIMIT_AS */

}

r.rlim_max = r.rlim_cur = 0;

setrlimit(RLIMIT_CORE, &r); /* Ignore errors */
//进程可能dump进core文件的最大值 单位byte
/* Isolate the process and configure standard descriptors. If out_file is
specified, stdin is /dev/null; otherwise, out_fd is cloned instead. */

setsid();//脱离从父进程继承而来的已打开终端,隶属进程组和隶属的会话

dup2(dev_null_fd, 1);
dup2(dev_null_fd, 2);

if (out_file) {

dup2(dev_null_fd, 0);

} else {

dup2(out_fd, 0);
close(out_fd);

}

/* On Linux, would be faster to use O_CLOEXEC. Maybe TODO. */

close(dev_null_fd);
close(out_dir_fd);
close(dev_urandom_fd);
close(fileno(plot_file));

/* Set sane defaults for ASAN if nothing else specified. */

setenv("ASAN_OPTIONS", "abort_on_error=1:"
"detect_leaks=0:"
"symbolize=0:"
"allocator_may_return_null=1", 0);

setenv("MSAN_OPTIONS", "exit_code=" STRINGIFY(MSAN_ERROR) ":"
"symbolize=0:"
"msan_track_origins=0", 0);

execv(target_path, argv);

/* Use a distinctive bitmap value to tell the parent about execv()
falling through. */

*(u32*)trace_bits = EXEC_FAIL_SIG; //EXEC_FAIL_SIG 0xfee1dead 用来指示执行失败的位图签名
exit(0);

}

} else {//afl-fuzz运行在非dumb模式,fork server会上线

s32 res;

/* In non-dumb mode, we have the fork server up and running, so simply
tell it to have at it, and then read back PID. */

if ((res = write(fsrv_ctl_fd, &prev_timed_out, 4)) != 4) {//fsrv_ctl_fd fork server控制管道(写)

if (stop_soon) return 0;
RPFATAL(res, "Unable to request new process from fork server (OOM?)");

}

if ((res = read(fsrv_st_fd, &child_pid, 4)) != 4) {//fsrv_st_fd sork server状态管道(读)

if (stop_soon) return 0;
RPFATAL(res, "Unable to request new process from fork server (OOM?)");

}

if (child_pid <= 0) FATAL("Fork server is misbehaving (OOM?)");

}

/* Configure timeout, as requested by user, then wait for child to terminate. */
//配置itimer timeout的单位应该是毫秒,将毫秒拆分成秒和微秒两部分
it.it_value.tv_sec = (timeout / 1000);//配置秒
it.it_value.tv_usec = (timeout % 1000) * 1000;//配置微秒

setitimer(ITIMER_REAL, &it, NULL);

/* The SIGALRM handler simply kills the child_pid and sets child_timed_out. */

if (dumb_mode == 1 || no_forkserver) {

if (waitpid(child_pid, &status, 0) <= 0) PFATAL("waitpid() failed");

} else {

s32 res;

if ((res = read(fsrv_st_fd, &status, 4)) != 4) {

if (stop_soon) return 0;
RPFATAL(res, "Unable to communicate with fork server (OOM?)");

}

}

if (!WIFSTOPPED(status)) child_pid = 0;

getitimer(ITIMER_REAL, &it);
exec_ms = (u64) timeout - (it.it_value.tv_sec * 1000 +
it.it_value.tv_usec / 1000);

it.it_value.tv_sec = 0;
it.it_value.tv_usec = 0;

setitimer(ITIMER_REAL, &it, NULL);

total_execs++;

/* Any subsequent operations on trace_bits must not be moved by the
compiler below this point. Past this location, trace_bits[] behave
very normally and do not have to be treated as volatile. */
//避免编译器过度优化
MEM_BARRIER();

tb4 = *(u32*)trace_bits;

#ifdef WORD_SIZE_64
classify_counts((u64*)trace_bits);
#else
classify_counts((u32*)trace_bits);
#endif /* ^WORD_SIZE_64 */

prev_timed_out = child_timed_out;

/* Report outcome to caller. */

if (WIFSIGNALED(status) && !stop_soon) {

kill_signal = WTERMSIG(status);

if (child_timed_out && kill_signal == SIGKILL) return FAULT_TMOUT;

return FAULT_CRASH;

}

/* A somewhat nasty hack for MSAN, which doesn't support abort_on_error and
must use a special exit code. */

if (uses_asan && WEXITSTATUS(status) == MSAN_ERROR) {
kill_signal = 0;
return FAULT_CRASH;
}

if ((dumb_mode == 1 || no_forkserver) && tb4 == EXEC_FAIL_SIG)
return FAULT_ERROR;

/* It makes sense to account for the slowest units only if the testcase was run
under the user defined timeout. */
if (!(timeout > exec_tmout) && (slowest_exec_ms < exec_ms)) {
slowest_exec_ms = exec_ms;
}

return FAULT_NONE;

}


/* Write modified data to file for testing. If out_file is set, the old file
is unlinked and a new one is created. Otherwise, out_fd is rewound and
truncated. */

static void write_to_testcase(void* mem, u32 len) {

s32 fd = out_fd;

if (out_file) {

unlink(out_file); /* Ignore errors. */

fd = open(out_file, O_WRONLY | O_CREAT | O_EXCL, 0600);

if (fd < 0) PFATAL("Unable to create '%s'", out_file);

} else lseek(fd, 0, SEEK_SET);

ck_write(fd, mem, len, out_file);

if (!out_file) {

if (ftruncate(fd, len)) PFATAL("ftruncate() failed");
lseek(fd, 0, SEEK_SET);

} else close(fd);

}


/* The same, but with an adjustable gap. Used for trimming. */

static void write_with_gap(void* mem, u32 len, u32 skip_at, u32 skip_len) {

s32 fd = out_fd;
u32 tail_len = len - skip_at - skip_len;

if (out_file) {

unlink(out_file); /* Ignore errors. */

fd = open(out_file, O_WRONLY | O_CREAT | O_EXCL, 0600);

if (fd < 0) PFATAL("Unable to create '%s'", out_file);

} else lseek(fd, 0, SEEK_SET);

if (skip_at) ck_write(fd, mem, skip_at, out_file);

if (tail_len) ck_write(fd, mem + skip_at + skip_len, tail_len, out_file);

if (!out_file) {

if (ftruncate(fd, len - skip_len)) PFATAL("ftruncate() failed");
lseek(fd, 0, SEEK_SET);

} else close(fd);

}


static void show_stats(void);

/* Calibrate a new test case. This is done when processing the input directory
to warn about flaky or otherwise problematic test cases early on; and when
new paths are discovered to detect variable behavior and so on. */

static u8 calibrate_case(char** argv, struct queue_entry* q, u8* use_mem,
u32 handicap, u8 from_queue) {
//handicap表示为经历的cycles数,以此体现该case的阻碍
static u8 first_trace[MAP_SIZE];

u8 fault = 0, new_bits = 0, var_detected = 0, hnb = 0,
first_run = (q->exec_cksum == 0);//每次执行后都会紧跟一个checksum的计算,如果q->exec_chsum为0,说明当前执行为第一次执行

u64 start_us, stop_us;

s32 old_sc = stage_cur, old_sm = stage_max;
u32 use_tmout = exec_tmout;
u8* old_sn = stage_name;

/* Be a bit more generous about timeouts when resuming sessions, or when
trying to calibrate already-added finds. This helps avoid trouble due
to intermittent latency. */

if (!from_queue || resuming_fuzz)
use_tmout = MAX(exec_tmout + CAL_TMOUT_ADD,
exec_tmout * CAL_TMOUT_PERC / 100);

q->cal_failed++;

stage_name = "calibration";
stage_max = fast_cal ? 3 : CAL_CYCLES;//校准的轮数.减少轮数了来实现快速校准.但是有些程序的行为在多次运行中可能有差异

/* Make sure the forkserver is up before we do anything, and let's not
count its spin-up time toward binary calibration. */

if (dumb_mode != 1 && !no_forkserver && !forksrv_pid)
init_forkserver(argv);//初始化一个forkserver

if (q->exec_cksum) {//如果获取得到cksum,说明当前queue_entry不是第一次执行

memcpy(first_trace, trace_bits, MAP_SIZE);//trace_bits的内容,copy进first_trace
hnb = has_new_bits(virgin_bits);//检查bitmap virgin_bits中是否有新的bits
if (hnb > new_bits) new_bits = hnb;//初始new_bits为0所以会直接hnb赋值

}

start_us = get_cur_time_us();

for (stage_cur = 0; stage_cur < stage_max; stage_cur++) {

u32 cksum;

if (!first_run && !(stage_cur % stats_update_freq)) show_stats();

write_to_testcase(use_mem, q->len);//将修改后的数据写入文件
//这里的use_mem 根据对calibrate_case()的调用者的不同,use_mem也不同
//第一次调用是perform_dry_run,这一参数为 use_mem = ck_alloc_nozero(q->len)
fault = run_target(argv, use_tmout);//执行target 返回状态信息 同时更新tarce_bits

/* stop_soon is set by the handler for Ctrl+C. When it's pressed,
we want to bail out quickly. */

if (stop_soon || fault != crash_mode) goto abort_calibration;//如果输入了CTRL+C或者执行target后返回的状态信息不是crash_mode 就中止校准状态 跳转到abort_calibration

if (!dumb_mode && !stage_cur && !count_bytes(trace_bits)) {//count_bytes 计数bitmap中设置的字节数,目的主要是更新状态屏幕以及校准/检查新路径
fault = FAULT_NOINST;
goto abort_calibration;
}

cksum = hash32(trace_bits, MAP_SIZE, HASH_CONST);//将trace_bits作一个hash

if (q->exec_cksum != cksum) {//如果队列中记录的checksum与当前执行计算出的checksum不同

hnb = has_new_bits(virgin_bits);//更新一次hnb
if (hnb > new_bits) new_bits = hnb;

if (q->exec_cksum) {//如果当前queue_entry执行过,

u32 i;

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

if (!var_bytes[i] && first_trace[i] != trace_bits[i]) {//var_bytes:看起来是变量的字节;

var_bytes[i] = 1;
stage_max = CAL_CYCLES_LONG;

}//这个循环是在找新增的变量字节

}

var_detected = 1;

} else {//如果是第一次执行,把trace_bits copy进first_trace

q->exec_cksum = cksum;
memcpy(first_trace, trace_bits, MAP_SIZE);

}

}

}

stop_us = get_cur_time_us();

total_cal_us += stop_us - start_us;
total_cal_cycles += stage_max;

/* OK, let's collect some stats about the performance of this test case.
This is used for fuzzing air time calculations in calculate_score(). */

q->exec_us = (stop_us - start_us) / stage_max;
q->bitmap_size = count_bytes(trace_bits);
q->handicap = handicap;//handicap:Number of queue cyclees behind
q->cal_failed = 0;

total_bitmap_size += q->bitmap_size;
total_bitmap_entries++;

update_bitmap_score(q);//更新top_rated和q->trace_mini

/* If this case didn't result in new output from the instrumentation, tell
parent. This is a non-critical problem, but something to warn the user
about. */

if (!dumb_mode && first_run && !fault && !new_bits) fault = FAULT_NOBITS;//如果这个case没有从插桩中产生新的输出,就告诉parent.具体表现就是没有fault又没有new_bits

abort_calibration:

if (new_bits == 2 && !q->has_new_cov) {
q->has_new_cov = 1;//如果这次执行涉及发现了新的tuple,就认为发现了新的coverage
queued_with_cov++;
}

/* Mark variable paths. */

if (var_detected) {

var_byte_count = count_bytes(var_bytes);//统计发现了多少字节是变量

if (!q->var_behavior) {
mark_as_variable(q);//q->var_behavior置1,并且在out_dir中同步记录
queued_variable++;
}

}

stage_name = old_sn;
stage_cur = old_sc;
stage_max = old_sm;

if (!first_run) show_stats();

return fault;

}


/* Examine map coverage. Called once, for first test case. */

static void check_map_coverage(void) {
//check方式就是计数trace_bits
u32 i;

if (count_bytes(trace_bits) < 100) return;

for (i = (1 << (MAP_SIZE_POW2 - 1)); i < MAP_SIZE; i++)
if (trace_bits[i]) return;

WARNF("Recompile binary with newer version of afl to improve coverage!");

}


/* 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. */

static void perform_dry_run(char** argv) {

struct queue_entry* q = queue;
u32 cal_failures = 0;
u8* skip_crashes = getenv("AFL_SKIP_CRASHES");

while (q) {

u8* use_mem;
u8 res;
s32 fd;

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);

use_mem = ck_alloc_nozero(q->len);

if (read(fd, use_mem, q->len) != q->len)
FATAL("Short read from '%s'", q->fname);

close(fd);

res = calibrate_case(argv, q, use_mem, 0, 1);//校准测试用例;初始化forkserver;
ck_free(use_mem);

if (stop_soon) return;

if (res == crash_mode || res == FAULT_NOBITS)
SAYF(cGRA " len = %u, map size = %u, exec speed = %llu us\n" cRST,
q->len, q->bitmap_size, q->exec_us);

switch (res) {//根据不同的FAULT,选择不同的处理方式

case FAULT_NONE:

if (q == queue) check_map_coverage();//如果没有发生FAULT,并且q是queue的头部(即测试的第一个testcase),就检查coverage

if (crash_mode) FATAL("Test case '%s' does *NOT* crash", fn);

break;

case FAULT_TMOUT:

if (timeout_given) {

/* The -t nn+ syntax in the command line sets timeout_given to '2' and
instructs afl-fuzz to tolerate but skip queue entries that time
out. */

if (timeout_given > 1) {
WARNF("Test case results in a timeout (skipping)");
q->cal_failed = CAL_CHANCES;
cal_failures++;
break;
}

SAYF("\n" cLRD "[-] " cRST
"The program took more than %u ms to process one of the initial test cases.\n"
" Usually, the right thing to do is to relax the -t option - or to delete it\n"
" altogether and allow the fuzzer to auto-calibrate. That said, if you know\n"
" what you are doing and want to simply skip the unruly test cases, append\n"
" '+' at the end of the value passed to -t ('-t %u+').\n", exec_tmout,
exec_tmout);

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

} else {

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", exec_tmout);

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

}

case FAULT_CRASH:

if (crash_mode) break;

if (skip_crashes) {
WARNF("Test case results in a crash (skipping)");
q->cal_failed = CAL_CHANCES;
cal_failures++;
break;
}

if (mem_limit) {//如果进了Crash mode,又设置了内存限制,会直接给你报下面的内存不足的"小作文"?

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"

#ifdef RLIMIT_AS
" ( ulimit -Sv $[%llu << 10]; /path/to/binary [...] <testcase )\n\n"
#else
" ( ulimit -Sd $[%llu << 10]; /path/to/binary [...] <testcase )\n\n"
#endif /* ^RLIMIT_AS */

" Tip: you can use http://jwilk.net/software/recidivm to quickly\n"
" estimate the required amount of virtual memory for the binary. Also,\n"
" if you are using ASAN, see %s/notes_for_asan.txt.\n\n"

#ifdef __APPLE__

" - On MacOS X, the semantics of fork() syscalls are non-standard and may\n"
" break afl-fuzz performance optimizations when running platform-specific\n"
" binaries. To fix this, set AFL_NO_FORKSRV=1 in the environment.\n\n"

#endif /* __APPLE__ */

" - Least likely, there is a horrible bug in the fuzzer. If other options\n"
" fail, poke <lcamtuf@coredump.cx> for troubleshooting tips.\n",
DMS(mem_limit << 20), mem_limit - 1, doc_path);

} 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"

#ifdef __APPLE__

" - On MacOS X, the semantics of fork() syscalls are non-standard and may\n"
" break afl-fuzz performance optimizations when running platform-specific\n"
" binaries. To fix this, set AFL_NO_FORKSRV=1 in the environment.\n\n"

#endif /* __APPLE__ */

" - Least likely, there is a horrible bug in the fuzzer. If other options\n"
" fail, poke <lcamtuf@coredump.cx> for troubleshooting tips.\n");

}

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

case FAULT_ERROR:

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

case FAULT_NOINST:

FATAL("No instrumentation detected");

case FAULT_NOBITS:

useless_at_start++;//无用的起始路径

if (!in_bitmap && !shuffle_queue)
WARNF("No new instrumentation output, test case may be useless.");

break;

}

if (q->var_behavior) WARNF("Instrumentation output varies across runs.");

q = q->next;

}

if (cal_failures) {

if (cal_failures == queued_paths)//如果所有case都timeout或者crash了,那基本没什么办法
FATAL("All test cases time out%s, giving up!",
skip_crashes ? " or crash" : "");

WARNF("Skipped %u test cases (%0.02f%%) due to timeouts%s.", cal_failures,
((double)cal_failures) * 100 / queued_paths,
skip_crashes ? " or crashes" : "");

if (cal_failures * 5 > queued_paths)//如果有20%以上timeout或者crash,可能设置里出了问题
WARNF(cLRD "High percentage of rejected test cases, check settings!");

}

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, 0600);
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);

}


static void nuke_resume_dir(void);

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

static void pivot_inputs(void) {

struct queue_entry* q = queue;
u32 id = 0;

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

while (q) {

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. */

#ifndef SIMPLE_FILES
# define CASE_PREFIX "id:"
#else
# define CASE_PREFIX "id_"
#endif /* ^!SIMPLE_FILES */

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

u8* src_str;
u32 src_id;

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

/* Since we're at it, let's also try to find 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) {

struct queue_entry* s = queue;
while (src_id-- && s) s = s->next;
if (s) q->depth = s->depth + 1;

if (max_depth < q->depth) 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,orig:%s", out_dir, id, use_name);

#else

nfn = alloc_printf("%s/queue/id_%06u", 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(q);

q = q->next;
id++;

}

if (in_place_resume) nuke_resume_dir();

}


#ifndef SIMPLE_FILES

/* Construct a file name for a new test case, capturing the operation
that led to its discovery. Uses a static buffer. */
//为新的testcase生成文件名,文件名中简要表示了该case的信息
static u8* describe_op(u8 hnb) {

static u8 ret[256];

if (syncing_party) {

sprintf(ret, "sync:%s,src:%06u", syncing_party, syncing_case);//开启并行fuzzing的话,会标上所在的party,同步的case

} else {

sprintf(ret, "src:%06u", current_entry);//非并行,就单列当前的case

if (splicing_with >= 0)
sprintf(ret + strlen(ret), "+%06u", splicing_with);//与之进行拼接的名称

sprintf(ret + strlen(ret), ",op:%s", stage_short);//缩写 阶段名

if (stage_cur_byte >= 0) {

sprintf(ret + strlen(ret), ",pos:%u", stage_cur_byte);

if (stage_val_type != STAGE_VAL_NONE)
sprintf(ret + strlen(ret), ",val:%s%+d",
(stage_val_type == STAGE_VAL_BE) ? "be:" : "",
stage_cur_val);

} else sprintf(ret + strlen(ret), ",rep:%u", stage_cur_val);

}

if (hnb == 2) strcat(ret, ",+cov");

return ret;

}

#endif /* !SIMPLE_FILES */


/* Write a message accompanying the crash directory :-) */

static void write_crash_readme(void) {

u8* fn = alloc_printf("%s/crashes/README.txt", out_dir);
s32 fd;
FILE* f;

fd = open(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
ck_free(fn);

/* Do not die on errors here - that would be impolite. */

if (fd < 0) return;

f = fdopen(fd, "w");

if (!f) {
close(fd);
return;
}

fprintf(f, "Command line used to find this crash:\n\n"

"%s\n\n"

"If you can't reproduce a bug outside of afl-fuzz, be sure to set the same\n"
"memory limit. The limit used for this fuzzing session was %s.\n\n"

"Need a tool to minimize test cases before investigating the crashes or sending\n"
"them to a vendor? Check out the afl-tmin that comes with the fuzzer!\n\n"

"Found any cool bugs in open-source tools using afl-fuzz? If yes, please drop\n"
"me a mail at <lcamtuf@coredump.cx> once the issues are fixed - I'd love to\n"
"add your finds to the gallery at:\n\n"

" http://lcamtuf.coredump.cx/afl/\n\n"

"Thanks :-)\n",

orig_cmdline, DMS(mem_limit << 20)); /* ignore errors */

fclose(f);

}


/* Check if the result of an execve() during routine fuzzing is interesting,
save or queue the input test case for further analysis if so. Returns 1 if
entry is saved, 0 otherwise. */

static u8 save_if_interesting(char** argv, void* mem, u32 len, u8 fault) {

u8 *fn = "";
u8 hnb;
s32 fd;
u8 keeping = 0, res;

if (fault == crash_mode) {//条件成立的两种可能:两者为0,即没有timeout也没有crash,afl也没开crash mode;两者为2,即target发生了crash,同时开启了crash mode

/* Keep only if there are new bits in the map, add to queue for
future fuzzing, etc. */

if (!(hnb = has_new_bits(virgin_bits))) {//如果没有new bits,就看看有没有crash,有的话crash总数+1,但是依旧返回0,认为这个case不是很有趣
if (crash_mode) total_crashes++;
return 0;
}

#ifndef SIMPLE_FILES

fn = alloc_printf("%s/queue/id:%06u,%s", out_dir, queued_paths,
describe_op(hnb));

#else

fn = alloc_printf("%s/queue/id_%06u", out_dir, queued_paths);

#endif /* ^!SIMPLE_FILES */

add_to_queue(fn, len, 0);

if (hnb == 2) {
queue_top->has_new_cov = 1;
queued_with_cov++;
}

queue_top->exec_cksum = hash32(trace_bits, MAP_SIZE, HASH_CONST);

/* Try to calibrate inline; this also calls update_bitmap_score() when
successful. */

res = calibrate_case(argv, queue_top, mem, queue_cycle - 1, 0);//又一次校准

if (res == FAULT_ERROR)
FATAL("Unable to execute target application");

fd = open(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) PFATAL("Unable to create '%s'", fn);
ck_write(fd, mem, len, fn);
close(fd);

keeping = 1;//如果出现crash,这里把keeping置1,后续代码执行时,会根据是否出现crash决定是否保留case

}

switch (fault) {

case FAULT_TMOUT:

/* Timeouts are not very interesting, but we're still obliged to keep
a handful of samples. We use the presence of new bits in the
hang-specific bitmap as a signal of uniqueness. In "dumb" mode, we
just keep everything. */

total_tmouts++;

if (unique_hangs >= KEEP_UNIQUE_HANG) return keeping;

if (!dumb_mode) {

#ifdef WORD_SIZE_64
simplify_trace((u64*)trace_bits);
#else
simplify_trace((u32*)trace_bits);//简化trace 舍弃具体的hit数,仅保留是否hit标记
#endif /* ^WORD_SIZE_64 */

if (!has_new_bits(virgin_tmout)) return keeping;

}

unique_tmouts++;

/* Before saving, we make sure that it's a genuine hang by re-running
the target with a more generous timeout (unless the default timeout
is already generous). */

if (exec_tmout < hang_tmout) {//可能exec_tmout太小,导致没有运行到crash就被认为timeout了,所以这里用更大的hang_tmout(如果更大)来运行target

u8 new_fault;
write_to_testcase(mem, len);
new_fault = run_target(argv, hang_tmout);//再次运行target,这次使用hang_tmout作为阈值,检查是否会有新的fault状态

/* A corner case that one user reported bumping into: increasing the
timeout actually uncovers a crash. Make sure we don't discard it if
so. */

if (!stop_soon && new_fault == FAULT_CRASH) goto keep_as_crash;//如果发现crash,直接跳转到crash的流程

if (stop_soon || new_fault != FAULT_TMOUT) return keeping;

}

#ifndef SIMPLE_FILES

fn = alloc_printf("%s/hangs/id:%06llu,%s", out_dir,
unique_hangs, describe_op(0));

#else

fn = alloc_printf("%s/hangs/id_%06llu", out_dir,
unique_hangs);

#endif /* ^!SIMPLE_FILES */

unique_hangs++;

last_hang_time = get_cur_time();

break;

case FAULT_CRASH:

keep_as_crash:

/* This is handled in a manner roughly similar to timeouts,
except for slightly different limits and no need to re-run test
cases. */

total_crashes++;

if (unique_crashes >= KEEP_UNIQUE_CRASH) return keeping;

if (!dumb_mode) {

#ifdef WORD_SIZE_64
simplify_trace((u64*)trace_bits);
#else
simplify_trace((u32*)trace_bits);
#endif /* ^WORD_SIZE_64 */

if (!has_new_bits(virgin_crash)) return keeping;

}

if (!unique_crashes) write_crash_readme();

#ifndef SIMPLE_FILES

fn = alloc_printf("%s/crashes/id:%06llu,sig:%02u,%s", out_dir,
unique_crashes, kill_signal, describe_op(0));

#else

fn = alloc_printf("%s/crashes/id_%06llu_%02u", out_dir, unique_crashes,
kill_signal);

#endif /* ^!SIMPLE_FILES */

unique_crashes++;

last_crash_time = get_cur_time();
last_crash_execs = total_execs;

break;

case FAULT_ERROR: FATAL("Unable to execute target application");

default: return keeping;

}

/* If we're here, we apparently want to save the crash or hang
test case, too. */

fd = open(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) PFATAL("Unable to create '%s'", fn);
ck_write(fd, mem, len, fn);
close(fd);

ck_free(fn);

return keeping;

}


/* 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. */

static u32 find_start_position(void) {

static u8 tmp[4096]; /* Ought to be enough for anybody. */

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

if (!resuming_fuzz) return 0;

if (in_place_resume) fn = alloc_printf("%s/fuzzer_stats", out_dir);
else fn = alloc_printf("%s/../fuzzer_stats", 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_path : ");
if (!off) return 0;

ret = atoi(off + 20);
if (ret >= queued_paths) 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. */

static void find_timeout(void) {

static u8 tmp[4096]; /* Ought to be enough for anybody. */

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

if (!resuming_fuzz) return;

if (in_place_resume) fn = alloc_printf("%s/fuzzer_stats", out_dir);
else fn = alloc_printf("%s/../fuzzer_stats", 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;

exec_tmout = ret;
timeout_given = 3;

}


/* Update stats file for unattended monitoring. */

static void write_stats_file(double bitmap_cvg, double stability, double eps) {

static double last_bcvg, last_stab, last_eps;
static struct rusage usage;

u8* fn = alloc_printf("%s/fuzzer_stats", out_dir);
s32 fd;
FILE* f;

fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0600);

if (fd < 0) PFATAL("Unable to create '%s'", fn);

ck_free(fn);

f = fdopen(fd, "w");

if (!f) PFATAL("fdopen() failed");

/* Keep last values in case we're called from another context
where exec/sec stats and such are not readily available. */

if (!bitmap_cvg && !stability && !eps) {
bitmap_cvg = last_bcvg;
stability = last_stab;
eps = last_eps;
} else {
last_bcvg = bitmap_cvg;
last_stab = stability;
last_eps = eps;
}

fprintf(f, "start_time : %llu\n"
"last_update : %llu\n"
"fuzzer_pid : %u\n"
"cycles_done : %llu\n"
"execs_done : %llu\n"
"execs_per_sec : %0.02f\n"
"paths_total : %u\n"
"paths_favored : %u\n"
"paths_found : %u\n"
"paths_imported : %u\n"
"max_depth : %u\n"
"cur_path : %u\n" /* Must match find_start_position() */
"pending_favs : %u\n"
"pending_total : %u\n"
"variable_paths : %u\n"
"stability : %0.02f%%\n"
"bitmap_cvg : %0.02f%%\n"
"unique_crashes : %llu\n"
"unique_hangs : %llu\n"
"last_path : %llu\n"
"last_crash : %llu\n"
"last_hang : %llu\n"
"execs_since_crash : %llu\n"
"exec_timeout : %u\n" /* Must match find_timeout() */
"afl_banner : %s\n"
"afl_version : " VERSION "\n"
"target_mode : %s%s%s%s%s%s%s\n"
"command_line : %s\n"
"slowest_exec_ms : %llu\n",
start_time / 1000, get_cur_time() / 1000, getpid(),
queue_cycle ? (queue_cycle - 1) : 0, total_execs, eps,
queued_paths, queued_favored, queued_discovered, queued_imported,
max_depth, current_entry, pending_favored, pending_not_fuzzed,
queued_variable, stability, bitmap_cvg, unique_crashes,
unique_hangs, last_path_time / 1000, last_crash_time / 1000,
last_hang_time / 1000, total_execs - last_crash_execs,
exec_tmout, use_banner,
qemu_mode ? "qemu " : "", dumb_mode ? " dumb " : "",
no_forkserver ? "no_forksrv " : "", crash_mode ? "crash " : "",
persistent_mode ? "persistent " : "", deferred_mode ? "deferred " : "",
(qemu_mode || dumb_mode || no_forkserver || crash_mode ||
persistent_mode || deferred_mode) ? "" : "default",
orig_cmdline, slowest_exec_ms);
/* ignore errors */

/* Get rss value from the children
We must have killed the forkserver process and called waitpid
before calling getrusage */
if (getrusage(RUSAGE_CHILDREN, &usage)) {
WARNF("getrusage failed");
} else if (usage.ru_maxrss == 0) {
fprintf(f, "peak_rss_mb : not available while afl is running\n");
} else {
#ifdef __APPLE__
fprintf(f, "peak_rss_mb : %zu\n", usage.ru_maxrss >> 20);
#else
fprintf(f, "peak_rss_mb : %zu\n", usage.ru_maxrss >> 10);
#endif /* ^__APPLE__ */
}

fclose(f);

}


/* Update the plot file if there is a reason to. */

static void maybe_update_plot_file(double bitmap_cvg, double eps) {

static u32 prev_qp, prev_pf, prev_pnf, prev_ce, prev_md;
static u64 prev_qc, prev_uc, prev_uh;

if (prev_qp == queued_paths && prev_pf == pending_favored &&
prev_pnf == pending_not_fuzzed && prev_ce == current_entry &&
prev_qc == queue_cycle && prev_uc == unique_crashes &&
prev_uh == unique_hangs && prev_md == max_depth) return;

prev_qp = queued_paths;
prev_pf = pending_favored;
prev_pnf = pending_not_fuzzed;
prev_ce = current_entry;
prev_qc = queue_cycle;
prev_uc = unique_crashes;
prev_uh = unique_hangs;
prev_md = max_depth;

/* Fields in the file:

unix_time, cycles_done, cur_path, paths_total, paths_not_fuzzed,
favored_not_fuzzed, unique_crashes, unique_hangs, max_depth,
execs_per_sec */

fprintf(plot_file,
"%llu, %llu, %u, %u, %u, %u, %0.02f%%, %llu, %llu, %u, %0.02f\n",
get_cur_time() / 1000, queue_cycle - 1, current_entry, queued_paths,
pending_not_fuzzed, pending_favored, bitmap_cvg, unique_crashes,
unique_hangs, max_depth, eps); /* ignore errors */

fflush(plot_file);

}



/* A helper function for maybe_delete_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. */

static double get_runnable_processes(void) {

static double res;

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

/* 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__) */

return res;

}


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

static void nuke_resume_dir(void) {

u8* fn;

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

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

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

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

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

fn = alloc_printf("%s/_resume", 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. */

static void maybe_delete_out_dir(void) {

FILE* f;
u8 *fn = alloc_printf("%s/fuzzer_stats", 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).*/

out_dir_fd = open(out_dir, O_RDONLY);
if (out_dir_fd < 0) PFATAL("Unable to open '%s'", out_dir);

#ifndef __sun

if (flock(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",
sync_id ? "fuzzer ID" : "output location");

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

}

#endif /* !__sun */

f = fopen(fn, "r");

if (f) {

u64 start_time, last_update;

if (fscanf(f, "start_time : %llu\n"
"last_update : %llu\n", &start_time, &last_update) != 2)
FATAL("Malformed data in '%s'", fn);

fclose(f);

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

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

SAYF("\n" cLRD "[-] " cRST
"The job output directory already exists and contains the results of more\n"
" than %u 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, put '-' as the input directory in the command line ('-i -') and\n"
" try again.\n", OUTPUT_GRACE);

FATAL("At-risk data found in '%s'", 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 (in_place_resume) {

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

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

rename(orig_q, 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 <out_dir>/.synced/.../id:*, if any are present. */

if (!in_place_resume) {

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

}

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

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

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

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

fn = alloc_printf("%s/queue/.state/variable_behavior", 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 <out_dir>/queue/id:*. */

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

fn = alloc_printf("%s/queue", out_dir);
if (delete_files(fn, CASE_PREFIX)) goto dir_cleanup_failed;
ck_free(fn);

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

if (!in_place_resume) {

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

}

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

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

if (in_place_resume && rmdir(fn)) {

time_t cur_t = time(0);
struct tm* t = localtime(&cur_t);

#ifndef SIMPLE_FILES

u8* nfn = alloc_printf("%s.%04u-%02u-%02u-%02u:%02u:%02u", 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_%04u%02u%02u%02u%02u%02u", 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", out_dir);

/* Backup hangs, too. */

if (in_place_resume && rmdir(fn)) {

time_t cur_t = time(0);
struct tm* t = localtime(&cur_t);

#ifndef SIMPLE_FILES

u8* nfn = alloc_printf("%s.%04u-%02u-%02u-%02u:%02u:%02u", 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_%04u%02u%02u%02u%02u%02u", 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. */

fn = alloc_printf("%s/.cur_input", out_dir);
if (unlink(fn) && errno != ENOENT) goto dir_cleanup_failed;
ck_free(fn);

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

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

fn = alloc_printf("%s/plot_data", 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");

}


static void check_term_size(void);


/* A spiffy retro stats screen! This is called every stats_update_freq
execve() calls, plus in several other circumstances. */

static void show_stats(void) {

static u64 last_stats_ms, last_plot_ms, last_ms, last_execs;
static double avg_exec;
double t_byte_ratio, stab_ratio;

u64 cur_ms;
u32 t_bytes, t_bits;

u32 banner_len, banner_pad;
u8 tmp[256];

cur_ms = get_cur_time();

/* If not enough time has passed since last UI update, bail out. */

if (cur_ms - last_ms < 1000 / UI_TARGET_HZ) return;

/* Check if we're past the 10 minute mark. */

if (cur_ms - start_time > 10 * 60 * 1000) run_over10m = 1;

/* Calculate smoothed exec speed stats. */

if (!last_execs) {

avg_exec = ((double)total_execs) * 1000 / (cur_ms - start_time);

} else {

double cur_avg = ((double)(total_execs - last_execs)) * 1000 /
(cur_ms - last_ms);

/* If there is a dramatic (5x+) jump in speed, reset the indicator
more quickly. */

if (cur_avg * 5 < avg_exec || cur_avg / 5 > avg_exec)
avg_exec = cur_avg;

avg_exec = avg_exec * (1.0 - 1.0 / AVG_SMOOTHING) +
cur_avg * (1.0 / AVG_SMOOTHING);

}

last_ms = cur_ms;
last_execs = total_execs;

/* Tell the callers when to contact us (as measured in execs). */

stats_update_freq = avg_exec / (UI_TARGET_HZ * 10);
if (!stats_update_freq) stats_update_freq = 1;

/* Do some bitmap stats. */

t_bytes = count_non_255_bytes(virgin_bits);//计数virgin_bits中非0xFF的字节
t_byte_ratio = ((double)t_bytes * 100) / MAP_SIZE;

if (t_bytes)
stab_ratio = 100 - ((double)var_byte_count) * 100 / t_bytes;
else
stab_ratio = 100;

/* Roughly every minute, update fuzzer stats and save auto tokens. */

if (cur_ms - last_stats_ms > STATS_UPDATE_SEC * 1000) {//当前时间-上次更新状态时间 每60秒更新一次状态 但是 last_stats_ms不初始化就直接用?

last_stats_ms = cur_ms;
write_stats_file(t_byte_ratio, stab_ratio, avg_exec);
save_auto();
write_bitmap();

}

/* Every now and then, write plot data. */

if (cur_ms - last_plot_ms > PLOT_UPDATE_SEC * 1000) {//每5秒 写一次plot数据

last_plot_ms = cur_ms;
maybe_update_plot_file(t_byte_ratio, avg_exec);

}

/* Honor AFL_EXIT_WHEN_DONE and AFL_BENCH_UNTIL_CRASH. */

if (!dumb_mode && cycles_wo_finds > 100 && !pending_not_fuzzed &&
getenv("AFL_EXIT_WHEN_DONE")) stop_soon = 2;//AFL_EXIT_WHEN_DONE 完成fuzzing之后退出afl 这里认为空转100轮(即100轮中没有发现新路径)即为DONE,就退出

if (total_crashes && getenv("AFL_BENCH_UNTIL_CRASH")) stop_soon = 2;//AFL_BENCH_UNTIL_CRASH 在发现第一个crash之后退出afl

/* If we're not on TTY, bail out. */

if (not_on_tty) return;

/* Compute some mildly useful bitmap stats. */

t_bits = (MAP_SIZE << 3) - count_bits(virgin_bits);//计算bitmap中已经被afl触及的bits,及总bits数目 - virgin_bits

/* Now, for the visuals... */

if (clear_screen) {

SAYF(TERM_CLEAR CURSOR_HIDE);
clear_screen = 0;

check_term_size();

}

SAYF(TERM_HOME);

if (term_too_small) {

SAYF(cBRI "Your terminal is too small to display the UI.\n"
"Please resize terminal window to at least 80x25.\n" cRST);

return;

}

/* Let's start by drawing a centered banner. */

banner_len = (crash_mode ? 24 : 22) + strlen(VERSION) + strlen(use_banner);
banner_pad = (80 - banner_len) / 2;
memset(tmp, ' ', banner_pad);

sprintf(tmp + banner_pad, "%s " cLCY VERSION cLGN
" (%s)", crash_mode ? cPIN "peruvian were-rabbit" :
cYEL "american fuzzy lop", use_banner);

SAYF("\n%s\n\n", tmp);

/* "Handy" shortcuts for drawing boxes... */

#define bSTG bSTART cGRA
#define bH2 bH bH
#define bH5 bH2 bH2 bH
#define bH10 bH5 bH5
#define bH20 bH10 bH10
#define bH30 bH20 bH10
#define SP5 " "
#define SP10 SP5 SP5
#define SP20 SP10 SP10

/* Lord, forgive me this. */

SAYF(SET_G1 bSTG bLT bH bSTOP cCYA " process timing " bSTG bH30 bH5 bH2 bHB
bH bSTOP cCYA " overall results " bSTG bH5 bRT "\n");

if (dumb_mode) {//这一块跟afl监控窗口中cycle done数字的颜色相关.afl用字体颜色指示这一次fuzzing的进度

strcpy(tmp, cRST);//dumb mode中不设置颜色 cRST指代重置颜色

} else {

u64 min_wo_finds = (cur_ms - last_path_time) / 1000 / 60;

/* First queue cycle: don't stop now! */
if (queue_cycle == 1 || min_wo_finds < 15) strcpy(tmp, cMGN); else//一轮cycle或者没有新发现的时间小于15分钟,cycle的颜色为紫色

/* Subsequent cycles, but we're still making finds. */
if (cycles_wo_finds < 25 || min_wo_finds < 30) strcpy(tmp, cYEL); else//25轮以内没有新发现,或者30分钟内没有新发现,黄色

/* No finds for a long time and no test cases to try. */
if (cycles_wo_finds > 100 && !pending_not_fuzzed && min_wo_finds > 120)//100轮以上没有新发现,且队列中没有等待的case,且120分钟以上没有新发现,使用亮绿色
strcpy(tmp, cLGN);

/* Default: cautiously OK to stop? */
else strcpy(tmp, cLBL);//其他情况下 使用亮蓝色

}

SAYF(bV bSTOP " run time : " cRST "%-34s " bSTG bV bSTOP
" cycles done : %s%-5s " bSTG bV "\n",
DTD(cur_ms, start_time), tmp, DI(queue_cycle - 1));

/* We want to warn people about not seeing new paths after a full cycle,
except when resuming fuzzing or running in non-instrumented mode. */

if (!dumb_mode && (last_path_time || resuming_fuzz || queue_cycle == 1 ||
in_bitmap || crash_mode)) {

SAYF(bV bSTOP " last new path : " cRST "%-34s ",
DTD(cur_ms, last_path_time));

} else {

if (dumb_mode)

SAYF(bV bSTOP " last new path : " cPIN "n/a" cRST
" (non-instrumented mode) ");

else

SAYF(bV bSTOP " last new path : " cRST "none yet " cLRD
"(odd, check syntax!) ");

}

SAYF(bSTG bV bSTOP " total paths : " cRST "%-5s " bSTG bV "\n",
DI(queued_paths));

/* Highlight crashes in red if found, denote going over the KEEP_UNIQUE_CRASH
limit with a '+' appended to the count. */

sprintf(tmp, "%s%s", DI(unique_crashes),
(unique_crashes >= KEEP_UNIQUE_CRASH) ? "+" : "");

SAYF(bV bSTOP " last uniq crash : " cRST "%-34s " bSTG bV bSTOP
" uniq crashes : %s%-6s " bSTG bV "\n",
DTD(cur_ms, last_crash_time), unique_crashes ? cLRD : cRST,
tmp);

sprintf(tmp, "%s%s", DI(unique_hangs),
(unique_hangs >= KEEP_UNIQUE_HANG) ? "+" : "");

SAYF(bV bSTOP " last uniq hang : " cRST "%-34s " bSTG bV bSTOP
" uniq hangs : " cRST "%-6s " bSTG bV "\n",
DTD(cur_ms, last_hang_time), tmp);

SAYF(bVR bH bSTOP cCYA " cycle progress " bSTG bH20 bHB bH bSTOP cCYA
" map coverage " bSTG bH bHT bH20 bH2 bH bVL "\n");

/* This gets funny because we want to print several variable-length variables
together, but then cram them into a fixed-width field - so we need to
put them in a temporary buffer first. */

sprintf(tmp, "%s%s (%0.02f%%)", DI(current_entry),
queue_cur->favored ? "" : "*",
((double)current_entry * 100) / queued_paths);

SAYF(bV bSTOP " now processing : " cRST "%-17s " bSTG bV bSTOP, tmp);

sprintf(tmp, "%0.02f%% / %0.02f%%", ((double)queue_cur->bitmap_size) *
100 / MAP_SIZE, t_byte_ratio);

SAYF(" map density : %s%-21s " bSTG bV "\n", t_byte_ratio > 70 ? cLRD :
((t_bytes < 200 && !dumb_mode) ? cPIN : cRST), tmp);

sprintf(tmp, "%s (%0.02f%%)", DI(cur_skipped_paths),
((double)cur_skipped_paths * 100) / queued_paths);

SAYF(bV bSTOP " paths timed out : " cRST "%-17s " bSTG bV, tmp);

sprintf(tmp, "%0.02f bits/tuple",
t_bytes ? (((double)t_bits) / t_bytes) : 0);

SAYF(bSTOP " count coverage : " cRST "%-21s " bSTG bV "\n", tmp);

SAYF(bVR bH bSTOP cCYA " stage progress " bSTG bH20 bX bH bSTOP cCYA
" findings in depth " bSTG bH20 bVL "\n");

sprintf(tmp, "%s (%0.02f%%)", DI(queued_favored),
((double)queued_favored) * 100 / queued_paths);

/* Yeah... it's still going on... halp? */

SAYF(bV bSTOP " now trying : " cRST "%-21s " bSTG bV bSTOP
" favored paths : " cRST "%-22s " bSTG bV "\n", stage_name, tmp);

if (!stage_max) {

sprintf(tmp, "%s/-", DI(stage_cur));

} else {

sprintf(tmp, "%s/%s (%0.02f%%)", DI(stage_cur), DI(stage_max),
((double)stage_cur) * 100 / stage_max);

}

SAYF(bV bSTOP " stage execs : " cRST "%-21s " bSTG bV bSTOP, tmp);

sprintf(tmp, "%s (%0.02f%%)", DI(queued_with_cov),
((double)queued_with_cov) * 100 / queued_paths);

SAYF(" new edges on : " cRST "%-22s " bSTG bV "\n", tmp);

sprintf(tmp, "%s (%s%s unique)", DI(total_crashes), DI(unique_crashes),
(unique_crashes >= KEEP_UNIQUE_CRASH) ? "+" : "");

if (crash_mode) {

SAYF(bV bSTOP " total execs : " cRST "%-21s " bSTG bV bSTOP
" new crashes : %s%-22s " bSTG bV "\n", DI(total_execs),
unique_crashes ? cLRD : cRST, tmp);

} else {

SAYF(bV bSTOP " total execs : " cRST "%-21s " bSTG bV bSTOP
" total crashes : %s%-22s " bSTG bV "\n", DI(total_execs),
unique_crashes ? cLRD : cRST, tmp);

}

/* Show a warning about slow execution. */

if (avg_exec < 100) {

sprintf(tmp, "%s/sec (%s)", DF(avg_exec), avg_exec < 20 ?
"zzzz..." : "slow!");

SAYF(bV bSTOP " exec speed : " cLRD "%-21s ", tmp);

} else {

sprintf(tmp, "%s/sec", DF(avg_exec));
SAYF(bV bSTOP " exec speed : " cRST "%-21s ", tmp);

}

sprintf(tmp, "%s (%s%s unique)", DI(total_tmouts), DI(unique_tmouts),
(unique_hangs >= KEEP_UNIQUE_HANG) ? "+" : "");

SAYF (bSTG bV bSTOP " total tmouts : " cRST "%-22s " bSTG bV "\n", tmp);

/* Aaaalmost there... hold on! */

SAYF(bVR bH cCYA bSTOP " fuzzing strategy yields " bSTG bH10 bH bHT bH10
bH5 bHB bH bSTOP cCYA " path geometry " bSTG bH5 bH2 bH bVL "\n");

if (skip_deterministic) {

strcpy(tmp, "n/a, n/a, n/a");

} else {

sprintf(tmp, "%s/%s, %s/%s, %s/%s",
DI(stage_finds[STAGE_FLIP1]), DI(stage_cycles[STAGE_FLIP1]),
DI(stage_finds[STAGE_FLIP2]), DI(stage_cycles[STAGE_FLIP2]),
DI(stage_finds[STAGE_FLIP4]), DI(stage_cycles[STAGE_FLIP4]));

}

SAYF(bV bSTOP " bit flips : " cRST "%-37s " bSTG bV bSTOP " levels : "
cRST "%-10s " bSTG bV "\n", tmp, DI(max_depth));

if (!skip_deterministic)
sprintf(tmp, "%s/%s, %s/%s, %s/%s",
DI(stage_finds[STAGE_FLIP8]), DI(stage_cycles[STAGE_FLIP8]),
DI(stage_finds[STAGE_FLIP16]), DI(stage_cycles[STAGE_FLIP16]),
DI(stage_finds[STAGE_FLIP32]), DI(stage_cycles[STAGE_FLIP32]));

SAYF(bV bSTOP " byte flips : " cRST "%-37s " bSTG bV bSTOP " pending : "
cRST "%-10s " bSTG bV "\n", tmp, DI(pending_not_fuzzed));

if (!skip_deterministic)
sprintf(tmp, "%s/%s, %s/%s, %s/%s",
DI(stage_finds[STAGE_ARITH8]), DI(stage_cycles[STAGE_ARITH8]),
DI(stage_finds[STAGE_ARITH16]), DI(stage_cycles[STAGE_ARITH16]),
DI(stage_finds[STAGE_ARITH32]), DI(stage_cycles[STAGE_ARITH32]));

SAYF(bV bSTOP " arithmetics : " cRST "%-37s " bSTG bV bSTOP " pend fav : "
cRST "%-10s " bSTG bV "\n", tmp, DI(pending_favored));

if (!skip_deterministic)
sprintf(tmp, "%s/%s, %s/%s, %s/%s",
DI(stage_finds[STAGE_INTEREST8]), DI(stage_cycles[STAGE_INTEREST8]),
DI(stage_finds[STAGE_INTEREST16]), DI(stage_cycles[STAGE_INTEREST16]),
DI(stage_finds[STAGE_INTEREST32]), DI(stage_cycles[STAGE_INTEREST32]));

SAYF(bV bSTOP " known ints : " cRST "%-37s " bSTG bV bSTOP " own finds : "
cRST "%-10s " bSTG bV "\n", tmp, DI(queued_discovered));

if (!skip_deterministic)
sprintf(tmp, "%s/%s, %s/%s, %s/%s",
DI(stage_finds[STAGE_EXTRAS_UO]), DI(stage_cycles[STAGE_EXTRAS_UO]),
DI(stage_finds[STAGE_EXTRAS_UI]), DI(stage_cycles[STAGE_EXTRAS_UI]),
DI(stage_finds[STAGE_EXTRAS_AO]), DI(stage_cycles[STAGE_EXTRAS_AO]));

SAYF(bV bSTOP " dictionary : " cRST "%-37s " bSTG bV bSTOP
" imported : " cRST "%-10s " bSTG bV "\n", tmp,
sync_id ? DI(queued_imported) : (u8*)"n/a");

sprintf(tmp, "%s/%s, %s/%s",
DI(stage_finds[STAGE_HAVOC]), DI(stage_cycles[STAGE_HAVOC]),
DI(stage_finds[STAGE_SPLICE]), DI(stage_cycles[STAGE_SPLICE]));

SAYF(bV bSTOP " havoc : " cRST "%-37s " bSTG bV bSTOP, tmp);

if (t_bytes) sprintf(tmp, "%0.02f%%", stab_ratio);
else strcpy(tmp, "n/a");

SAYF(" stability : %s%-10s " bSTG bV "\n", (stab_ratio < 85 && var_byte_count > 40)
? cLRD : ((queued_variable && (!persistent_mode || var_byte_count > 20))
? cMGN : cRST), tmp);

if (!bytes_trim_out) {

sprintf(tmp, "n/a, ");

} else {

sprintf(tmp, "%0.02f%%/%s, ",
((double)(bytes_trim_in - bytes_trim_out)) * 100 / bytes_trim_in,
DI(trim_execs));

}

if (!blocks_eff_total) {

u8 tmp2[128];

sprintf(tmp2, "n/a");
strcat(tmp, tmp2);

} else {

u8 tmp2[128];

sprintf(tmp2, "%0.02f%%",
((double)(blocks_eff_total - blocks_eff_select)) * 100 /
blocks_eff_total);

strcat(tmp, tmp2);

}

SAYF(bV bSTOP " trim : " cRST "%-37s " bSTG bVR bH20 bH2 bH2 bRB "\n"
bLB bH30 bH20 bH2 bH bRB bSTOP cRST RESET_G1, tmp);

/* Provide some CPU utilization stats. */

if (cpu_core_count) {

double cur_runnable = get_runnable_processes();//获取当前可运行的进程数
u32 cur_utilization = cur_runnable * 100 / cpu_core_count;

u8* cpu_color = cCYA;

/* If we could still run one or more processes, use green. */

if (cpu_core_count > 1 && cur_runnable + 1 <= cpu_core_count)
cpu_color = cLGN;

/* If we're clearly oversubscribed, use red. */

if (!no_cpu_meter_red && cur_utilization >= 150) cpu_color = cLRD;//如果cpu使用率高于150,将这一条目在终端内显示为红色

#ifdef HAVE_AFFINITY

if (cpu_aff >= 0) {

SAYF(SP10 cGRA "[cpu%03u:%s%3u%%" cGRA "]\r" cRST,
MIN(cpu_aff, 999), cpu_color,
MIN(cur_utilization, 999));

} else {

SAYF(SP10 cGRA " [cpu:%s%3u%%" cGRA "]\r" cRST,
cpu_color, MIN(cur_utilization, 999));

}

#else

SAYF(SP10 cGRA " [cpu:%s%3u%%" cGRA "]\r" cRST,
cpu_color, MIN(cur_utilization, 999));

#endif /* ^HAVE_AFFINITY */

} else SAYF("\r");

/* Hallelujah! */

fflush(0);

}


/* Display quick statistics at the end of processing the input directory,
plus a bunch of warnings. Some calibration stuff also ended up here,
along with several hardcoded constants. Maybe clean up eventually. */

static void show_init_stats(void) {

struct queue_entry* q = queue;
u32 min_bits = 0, max_bits = 0;
u64 min_us = 0, max_us = 0;
u64 avg_us = 0;
u32 max_len = 0;

if (total_cal_cycles) avg_us = total_cal_us / total_cal_cycles;//计算平均时间

while (q) {//遍历队列,统计一轮队列执行之后的最短执行时间,最长执行时间,最小bitmap_size,最大bitmap_size,最大testcase长度

if (!min_us || q->exec_us < min_us) min_us = q->exec_us;
if (q->exec_us > max_us) max_us = q->exec_us;

if (!min_bits || q->bitmap_size < min_bits) min_bits = q->bitmap_size;
if (q->bitmap_size > max_bits) max_bits = q->bitmap_size;

if (q->len > max_len) max_len = q->len;

q = q->next;

}

SAYF("\n");

if (avg_us > (qemu_mode ? 50000 : 10000)) //常规模式下平均校准时间超过10000μs就提示"slow",qemu mode下放宽到50000μs
WARNF(cLRD "The target binary is pretty slow! See %s/perf_tips.txt.",
doc_path);

/* Let's keep things moving with slow binaries. */
//对于执行速度慢的binary,AFL会选择增大havoc_div,从而影响havoc阶段中stage_max的值,减少havoc阶段的长度
if (avg_us > 50000) havoc_div = 10; /* 0-19 execs/sec */ //例Line.6143 stage_max = SPLICE_HAVOC * perf_score / havoc_div / 100;
else if (avg_us > 20000) havoc_div = 5; /* 20-49 execs/sec */
else if (avg_us > 10000) havoc_div = 2; /* 50-100 execs/sec */

if (!resuming_fuzz) {//如果不是恢复先前的fuzzing,这里会把一些基础提示信息都过一遍

if (max_len > 50 * 1024)//如果testcase超过50KB,提示"huge"
WARNF(cLRD "Some test cases are huge (%s) - see %s/perf_tips.txt!",
DMS(max_len), doc_path);
else if (max_len > 10 * 1024)//如果testcase超过10KB,提示"big"
WARNF("Some test cases are big (%s) - see %s/perf_tips.txt.",
DMS(max_len), doc_path);

if (useless_at_start && !in_bitmap)//perform_dry_run()中,如果这次执行没有发生fault,没有发现new_bits,就会标记为FAULT_NOBITS,然后useless_at_start计数+1.如果useless_at_start!=0,并且没有在一开始提供input_bitmap,AFL会提示选择一个更小的集合,因为其中有些testcase没有用
WARNF(cLRD "Some test cases look useless. Consider using a smaller set.");

if (queued_paths > 100)//100个测试用例太多了
WARNF(cLRD "You probably have far too many input files! Consider trimming down.");
else if (queued_paths > 20)//20个测试用例也有点多
WARNF("You have lots of input files; try starting small.");

}

OKF("Here are some useful stats:\n\n"

cGRA " Test case count : " cRST "%u favored, %u variable, %u total\n"
cGRA " Bitmap range : " cRST "%u to %u bits (average: %0.02f bits)\n"
cGRA " Exec timing : " cRST "%s to %s us (average: %s us)\n",
queued_favored, queued_variable, queued_paths, min_bits, max_bits,
((double)total_bitmap_size) / (total_bitmap_entries ? total_bitmap_entries : 1),
DI(min_us), DI(max_us), DI(avg_us));

if (!timeout_given) {//如果没有人工提供timeout,那这里根据binary的执行时间赋予一个倍数作为timeout

/* Figure out the appropriate timeout. The basic idea is: 5x average or
1x max, rounded up to EXEC_TM_ROUND ms and capped at 1 second.

If the program is slow, the multiplier is lowered to 2x or 3x, because
random scheduler jitter is less likely to have any impact, and because
our patience is wearing thin =) */

if (avg_us > 50000) exec_tmout = avg_us * 2 / 1000;//如果平均执行时间超过50000μs,timeout设置为平均值的2倍,"/1000"的目的是μs和ms的转换
else if (avg_us > 10000) exec_tmout = avg_us * 3 / 1000;//如果avg_us在[10000,50000]之中,倍数为3
else exec_tmout = avg_us * 5 / 1000;//执行比较快的Binary,倍数就选择为5

exec_tmout = MAX(exec_tmout, max_us / 1000);//初步的timeout计算出来后,还要求不能超过实际执行中的最大执行时间
exec_tmout = (exec_tmout + EXEC_TM_ROUND) / EXEC_TM_ROUND * EXEC_TM_ROUND;//EXEC_TM_ROUND 20 自动缩放时的超时舍入因子
//exec_tmout = (exec_tmout+20)/20*20
if (exec_tmout > EXEC_TIMEOUT) exec_tmout = EXEC_TIMEOUT;//最后AFL内部有一个固定的EXEC_TIMEOUT 1000,任何执行无论如何不能超过EXEC_TIMEOUT

ACTF("No -t option specified, so I'll use exec timeout of %u ms.",
exec_tmout);

timeout_given = 1;

} else if (timeout_given == 3) {//find_timeout()中,针对resuming_fuzz,afl会去out_dir中找stats,然后读取exec_timeout,这种情况下就直接用已经确定的timeout

ACTF("Applying timeout settings from resumed session (%u ms).", exec_tmout);

}

/* In dumb mode, re-running every timing out test case with a generous time
limit is very expensive, so let's select a more conservative default. */
//dumb mode下要重新运行每个超时的testcase开销太大,所以直接选择一个更保守的默认timeout,即将上述计算出的timeout再放宽要求
if (dumb_mode && !getenv("AFL_HANG_TMOUT"))
hang_tmout = MIN(EXEC_TIMEOUT, exec_tmout * 2 + 100);//在1000和exec_tmout*2+100中选择最小值

OKF("All set and ready to roll!");

}


/* Find first power of two greater or equal to val (assuming val under
2^31). */

static u32 next_p2(u32 val) {

u32 ret = 1;
while (val > ret) ret <<= 1;
return ret;

}


/* Trim all new test cases to save cycles when doing deterministic checks. The
trimmer uses power-of-two increments somewhere between 1/16 and 1/1024 of
file size, to keep the stage short and sweet. */

static u8 trim_case(char** argv, struct queue_entry* q, u8* in_buf) {

static u8 tmp[64];
static u8 clean_trace[MAP_SIZE];

u8 needs_write = 0, fault = 0;
u32 trim_exec = 0;
u32 remove_len;
u32 len_p2;

/* Although the trimmer will be less useful when variable behavior is
detected, it will still work to some extent, so we don't check for
this. */

if (q->len < 5) return 0;//如果case的length小于5就没有修建必要,直接返回

stage_name = tmp;
bytes_trim_in += q->len;//

/* Select initial chunk len, starting with large steps. */

len_p2 = next_p2(q->len);//计算len_p2,取大于q->len的2的幂的最小值

remove_len = MAX(len_p2 / TRIM_START_STEPS, TRIM_MIN_BYTES);//起始的trim步长取len_p2/16和4中的最大值,最小步长为4字节

/* Continue until the number of steps gets too high or the stepover
gets too small. */

while (remove_len >= MAX(len_p2 / TRIM_END_STEPS, TRIM_MIN_BYTES)) {//每轮循环过后步长减半,最终步长会小于TRIM_MIN_BYTES,此时循环结束

u32 remove_pos = remove_len;

sprintf(tmp, "trim %s/%s", DI(remove_len), DI(remove_len));

stage_cur = 0;
stage_max = q->len / remove_len;

while (remove_pos < q->len) {//每次循环,删除位向后移一个步长

u32 trim_avail = MIN(remove_len, q->len - remove_pos);//可以删减的长度
u32 cksum;

write_with_gap(in_buf, q->len, remove_pos, trim_avail);//将in_buf中q->len长度的case,从remove_pos开始,跳过trim_avail长度的字符串

fault = run_target(argv, exec_tmout);//用新的trimmed in_buf运行target,记录fault状态
trim_execs++;

if (stop_soon || fault == FAULT_ERROR) goto abort_trimming;

/* Note that we don't keep track of crashes or hangs here; maybe TODO? */

cksum = hash32(trace_bits, MAP_SIZE, HASH_CONST);

/* If the deletion had no impact on the trace, make it permanent. This
isn't perfect for variable-path inputs, but we're just making a
best-effort pass, so it's not a big deal if we end up with false
negatives every now and then. */

if (cksum == q->exec_cksum) {//比较修剪前后两次的bitmap的checksum,如果相等,即trim对程序运行没有影响,就保留这次修剪

u32 move_tail = q->len - remove_pos - trim_avail;

q->len -= trim_avail;
len_p2 = next_p2(q->len);

memmove(in_buf + remove_pos, in_buf + remove_pos + trim_avail,
move_tail);//从in_buf + remove_pos + trim_avail位置复制move_tail长度的字符串到in_buf + remove_pos,效果就是删除了中间这段字符串

/* Let's save a clean trace, which will be needed by
update_bitmap_score once we're done with the trimming stuff. */

if (!needs_write) {

needs_write = 1;
memcpy(clean_trace, trace_bits, MAP_SIZE);//从trace_bits复制一份clean_trace作备份

}

} else remove_pos += remove_len;

/* Since this can be slow, update the screen every now and then. */

if (!(trim_exec++ % stats_update_freq)) show_stats();
stage_cur++;

}

remove_len >>= 1;//每次循环,步长减半

}

/* If we have made changes to in_buf, we also need to update the on-disk
version of the test case. */

if (needs_write) {

s32 fd;

unlink(q->fname); /* ignore errors */

fd = open(q->fname, O_WRONLY | O_CREAT | O_EXCL, 0600);

if (fd < 0) PFATAL("Unable to create '%s'", q->fname);

ck_write(fd, in_buf, q->len, q->fname);
close(fd);

memcpy(trace_bits, clean_trace, MAP_SIZE);
update_bitmap_score(q);//更新bitmap评分

}

abort_trimming:

bytes_trim_out += q->len;
return fault;

}


/* Write a modified test case, run program, process results. Handle
error conditions, returning 1 if it's time to bail out. This is
a helper function for fuzz_one(). */

EXP_ST u8 common_fuzz_stuff(char** argv, u8* out_buf, u32 len) {

u8 fault;

if (post_handler) {

out_buf = post_handler(out_buf, &len);
if (!out_buf || !len) return 0;

}

write_to_testcase(out_buf, len);

fault = run_target(argv, exec_tmout);//用处理后的新case运行target

if (stop_soon) return 1;

if (fault == FAULT_TMOUT) {

if (subseq_tmouts++ > TMOUT_LIMIT) {
cur_skipped_paths++;
return 1;//出现TMOUT就舍弃这个case
}

} else subseq_tmouts = 0;

/* Users can hit us with SIGUSR1 to request the current input
to be abandoned. */

if (skip_requested) {

skip_requested = 0;
cur_skipped_paths++;
return 1;

}

/* This handles FAULT_ERROR for us: */

queued_discovered += save_if_interesting(argv, out_buf, len, fault);

if (!(stage_cur % stats_update_freq) || stage_cur + 1 == stage_max)
show_stats();

return 0;

}


/* Helper to choose random block len for block operations in fuzz_one().
Doesn't return zero, provided that max_len is > 0. */

static u32 choose_block_len(u32 limit) {

u32 min_value, max_value;
u32 rlim = MIN(queue_cycle, 3);

if (!run_over10m) rlim = 1;//运行时间超过10分钟,rilm=1

switch (UR(rlim)) {

case 0: min_value = 1;
max_value = HAVOC_BLK_SMALL;
break;

case 1: min_value = HAVOC_BLK_SMALL;
max_value = HAVOC_BLK_MEDIUM;
break;

default:

if (UR(10)) {

min_value = HAVOC_BLK_MEDIUM;
max_value = HAVOC_BLK_LARGE;

} else {

min_value = HAVOC_BLK_LARGE;
max_value = HAVOC_BLK_XL;

}
//随机设置block长度取值的上下限
}

if (min_value >= limit) min_value = 1;//如果min_value比limit都大了,那干脆Min设置成1,保证limit>=min

return min_value + UR(MIN(max_value, limit) - min_value + 1);//在min和MIN(max,limit)之间取一个随机数

}


/* Calculate case desirability score to adjust the length of havoc fuzzing.
A helper function for fuzz_one(). Maybe some of these constants should
go into config.h. */

static u32 calculate_score(struct queue_entry* q) {

u32 avg_exec_us = total_cal_us / total_cal_cycles;
u32 avg_bitmap_size = total_bitmap_size / total_bitmap_entries;
u32 perf_score = 100;

/* Adjust score based on execution speed of this path, compared to the
global average. Multiplier ranges from 0.1x to 3x. Fast inputs are
less expensive to fuzz, so we're giving them more air time. */

if (q->exec_us * 0.1 > avg_exec_us) perf_score = 10;
else if (q->exec_us * 0.25 > avg_exec_us) perf_score = 25;
else if (q->exec_us * 0.5 > avg_exec_us) perf_score = 50;
else if (q->exec_us * 0.75 > avg_exec_us) perf_score = 75;
else if (q->exec_us * 4 < avg_exec_us) perf_score = 300;
else if (q->exec_us * 3 < avg_exec_us) perf_score = 200;
else if (q->exec_us * 2 < avg_exec_us) perf_score = 150;

/* Adjust score based on bitmap size. The working theory is that better
coverage translates to better targets. Multiplier from 0.25x to 3x. */

if (q->bitmap_size * 0.3 > avg_bitmap_size) perf_score *= 3;
else if (q->bitmap_size * 0.5 > avg_bitmap_size) perf_score *= 2;
else if (q->bitmap_size * 0.75 > avg_bitmap_size) perf_score *= 1.5;
else if (q->bitmap_size * 3 < avg_bitmap_size) perf_score *= 0.25;
else if (q->bitmap_size * 2 < avg_bitmap_size) perf_score *= 0.5;
else if (q->bitmap_size * 1.5 < avg_bitmap_size) perf_score *= 0.75;

/* Adjust score based on handicap. Handicap is proportional to how late
in the game we learned about this path. Latecomers are allowed to run
for a bit longer until they catch up with the rest. */

if (q->handicap >= 4) {

perf_score *= 4;
q->handicap -= 4;

} else if (q->handicap) {

perf_score *= 2;
q->handicap--;

}

/* Final adjustment based on input depth, under the assumption that fuzzing
deeper test cases is more likely to reveal stuff that can't be
discovered with traditional fuzzers. */

switch (q->depth) {

case 0 ... 3: break;
case 4 ... 7: perf_score *= 2; break;
case 8 ... 13: perf_score *= 3; break;
case 14 ... 25: perf_score *= 4; break;
default: perf_score *= 5;

}

/* Make sure that we don't go over limit. */

if (perf_score > HAVOC_MAX_MULT * 100) perf_score = HAVOC_MAX_MULT * 100;
//给一个分数上限
return perf_score;

}


/* Helper function to see if a particular change (xor_val = old ^ new) could
be a product of deterministic bit flips with the lengths and stepovers
attempted by afl-fuzz. This is used to avoid dupes in some of the
deterministic fuzzing operations that follow bit flips. We also
return 1 if xor_val is zero, which implies that the old and attempted new
values are identical and the exec would be a waste of time. */

static u8 could_be_bitflip(u32 xor_val) {

u32 sh = 0;

if (!xor_val) return 1;//但是这个应该不可能

/* Shift left until first bit set. */

while (!(xor_val & 1)) { sh++; xor_val >>= 1; }//不停右移,直到遇到第一个为1的位

/* 1-, 2-, and 4-bit patterns are OK anywhere. */
//0b1 0b11 0b1111 对应bitflip四个粒度 arith阶段的ARITH_MAX为35(0b100011)
if (xor_val == 1 || xor_val == 3 || xor_val == 15) return 1;

/* 8-, 16-, and 32-bit patterns are OK only if shift factor is
divisible by 8, since that's the stepover for these ops. */

if (sh & 7) return 0;//仅当sh可被8整除时,才考虑8,16,32位模式
//对应8位,16位,32位的粒度
if (xor_val == 0xff || xor_val == 0xffff || xor_val == 0xffffffff)
return 1;

return 0;

}


/* Helper function to see if a particular value is reachable through
arithmetic operations. Used for similar purposes. */

static u8 could_be_arith(u32 old_val, u32 new_val, u8 blen) {

u32 i, ov = 0, nv = 0, diffs = 0;

if (old_val == new_val) return 1;

/* See if one-byte adjustments to any byte could produce this result. */

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

u8 a = old_val >> (8 * i),
b = new_val >> (8 * i);

if (a != b) { diffs++; ov = a; nv = b; }

}

/* If only one byte differs and the values are within range, return 1. */

if (diffs == 1) {

if ((u8)(ov - nv) <= ARITH_MAX ||
(u8)(nv - ov) <= ARITH_MAX) return 1;

}

if (blen == 1) return 0;

/* See if two-byte adjustments to any byte would produce this result. */

diffs = 0;

for (i = 0; i < blen / 2; i++) {

u16 a = old_val >> (16 * i),
b = new_val >> (16 * i);

if (a != b) { diffs++; ov = a; nv = b; }

}

/* If only one word differs and the values are within range, return 1. */

if (diffs == 1) {

if ((u16)(ov - nv) <= ARITH_MAX ||
(u16)(nv - ov) <= ARITH_MAX) return 1;

ov = SWAP16(ov); nv = SWAP16(nv);

if ((u16)(ov - nv) <= ARITH_MAX ||
(u16)(nv - ov) <= ARITH_MAX) return 1;

}

/* Finally, let's do the same thing for dwords. */

if (blen == 4) {

if ((u32)(old_val - new_val) <= ARITH_MAX ||
(u32)(new_val - old_val) <= ARITH_MAX) return 1;

new_val = SWAP32(new_val);
old_val = SWAP32(old_val);

if ((u32)(old_val - new_val) <= ARITH_MAX ||
(u32)(new_val - old_val) <= ARITH_MAX) return 1;

}

return 0;

}


/* Last but not least, a similar helper to see if insertion of an
interesting integer is redundant given the insertions done for
shorter blen. The last param (check_le) is set if the caller
already executed LE insertion for current blen and wants to see
if BE variant passed in new_val is unique. */

static u8 could_be_interest(u32 old_val, u32 new_val, u8 blen, u8 check_le) {

u32 i, j;

if (old_val == new_val) return 1;

/* See if one-byte insertions from interesting_8 over old_val could
produce new_val. */

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

for (j = 0; j < sizeof(interesting_8); j++) {

u32 tval = (old_val & ~(0xff << (i * 8))) |
(((u8)interesting_8[j]) << (i * 8));

if (new_val == tval) return 1;

}

}

/* Bail out unless we're also asked to examine two-byte LE insertions
as a preparation for BE attempts. */

if (blen == 2 && !check_le) return 0;

/* See if two-byte insertions over old_val could give us new_val. */

for (i = 0; i < blen - 1; i++) {

for (j = 0; j < sizeof(interesting_16) / 2; j++) {

u32 tval = (old_val & ~(0xffff << (i * 8))) |
(((u16)interesting_16[j]) << (i * 8));

if (new_val == tval) return 1;

/* Continue here only if blen > 2. */

if (blen > 2) {

tval = (old_val & ~(0xffff << (i * 8))) |
(SWAP16(interesting_16[j]) << (i * 8));

if (new_val == tval) return 1;

}

}

}

if (blen == 4 && check_le) {

/* See if four-byte insertions could produce the same result
(LE only). */

for (j = 0; j < sizeof(interesting_32) / 4; j++)
if (new_val == (u32)interesting_32[j]) return 1;

}

return 0;

}


/* Take the current entry from the queue, fuzz it for a while. This
function is a tad too long... returns 0 if fuzzed successfully, 1 if
skipped or bailed out. */

static u8 fuzz_one(char** argv) {

s32 len, fd, temp_len, i, j;
u8 *in_buf, *out_buf, *orig_in, *ex_tmp, *eff_map = 0;
u64 havoc_queued, orig_hit_cnt, new_hit_cnt;
u32 splice_cycle = 0, perf_score = 100, orig_perf, prev_cksum, eff_cnt = 1;

u8 ret_val = 1, doing_det = 0;

u8 a_collect[MAX_AUTO_EXTRA];
u32 a_len = 0;

#ifdef IGNORE_FINDS

/* In IGNORE_FINDS mode, skip any entries that weren't in the
initial data set. */

if (queue_cur->depth > 1) return 1;

#else

if (pending_favored) {//如果有favored的case在等待,afl会考虑跳过当前的普通case

/* If we have any favored, non-fuzzed new arrivals in the queue,
possibly skip to them at the expense of already-fuzzed or non-favored
cases. */

if ((queue_cur->was_fuzzed || !queue_cur->favored) &&
UR(100) < SKIP_TO_NEW_PROB) return 1;//如果队列中当前case是fuzz过的,且不是favored,默认以99%的概率跳过

} else if (!dumb_mode && !queue_cur->favored && queued_paths > 10) {//如果队列中没有favored case,在非dumb mode中,如果当前case非favored,且队列中排了10个以上的case,afl会考虑以一定概率放弃没产出的case

/* Otherwise, still possibly skip non-favored cases, albeit less often.
The odds of skipping stuff are higher for already-fuzzed inputs and
lower for never-fuzzed entries. */

if (queue_cycle > 1 && !queue_cur->was_fuzzed) {//cycle大于1之后,afl才会进行skip

if (UR(100) < SKIP_NFAV_NEW_PROB) return 1;//没有新的favors,当前case没有fuzz过,75%概率跳过

} else {

if (UR(100) < SKIP_NFAV_OLD_PROB) return 1;//没有新的favors,当前case已经fuzz过,95%概率跳过

}

}

#endif /* ^IGNORE_FINDS */

if (not_on_tty) {
ACTF("Fuzzing test case #%u (%u total, %llu uniq crashes found)...",
current_entry, queued_paths, unique_crashes);
fflush(stdout);
}

/* Map the test case into memory. */
//不跳过,那就在把testcase导入内存里
fd = open(queue_cur->fname, O_RDONLY);

if (fd < 0) PFATAL("Unable to open '%s'", queue_cur->fname);

len = queue_cur->len;

orig_in = in_buf = mmap(0, len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);

if (orig_in == MAP_FAILED) PFATAL("Unable to mmap '%s'", queue_cur->fname);

close(fd);

/* We could mmap() out_buf as MAP_PRIVATE, but we end up clobbering every
single byte anyway, so it wouldn't give us any performance or memory usage
benefits. */

out_buf = ck_alloc_nozero(len);

subseq_tmouts = 0;

cur_depth = queue_cur->depth;//路径深度

/*******************************************
* CALIBRATION (only if failed earlier on) *
*******************************************/

if (queue_cur->cal_failed) {//如果在之前的校准中失败了,再次执行校准

u8 res = FAULT_TMOUT;

if (queue_cur->cal_failed < CAL_CHANCES) {

/* Reset exec_cksum to tell calibrate_case to re-execute the testcase
avoiding the usage of an invalid trace_bits.
For more info: https://github.com/AFLplusplus/AFLplusplus/pull/425 */

queue_cur->exec_cksum = 0;

res = calibrate_case(argv, queue_cur, in_buf, queue_cycle - 1, 0);

if (res == FAULT_ERROR)//如果不能执行target,抛出异常
FATAL("Unable to execute target application");

}

if (stop_soon || res != crash_mode) {
cur_skipped_paths++;
goto abandon_entry;//如果crash mode下没有发生crash 或者 crash mode下发生了fault,抛弃这个case
}

}

/************
* TRIMMING *
************/

if (!dumb_mode && !queue_cur->trim_done) {

u8 res = trim_case(argv, queue_cur, in_buf);//修剪case,

if (res == FAULT_ERROR)
FATAL("Unable to execute target application");

if (stop_soon) {
cur_skipped_paths++;
goto abandon_entry;
}

/* Don't retry trimming, even if it failed. */

queue_cur->trim_done = 1;//trim只对每个case进行一次,无论成功与否

if (len != queue_cur->len) len = queue_cur->len;//更新修建后的case长度

}

memcpy(out_buf, in_buf, len);

/*********************
* PERFORMANCE SCORE *
*********************/

orig_perf = perf_score = calculate_score(queue_cur);//计算case的分数,根据queue_cur中记录的执行时长(越小越好),bitmap_size(越大越好),handicap(在fuzzing过程后期进入队列的case,可以有更多的时间测试),路径深度(越深越好)

/* Skip right away if -d is given, if we have done deterministic fuzzing on
this entry ourselves (was_fuzzed), or if it has gone through deterministic
testing in earlier, resumed runs (passed_det). */

if (skip_deterministic || queue_cur->was_fuzzed || queue_cur->passed_det)
goto havoc_stage;//如果设置了-d,或者当前case已经fuzz过,或者该case已经通过了deterministic,直接跳转到havoc_stage

/* Skip deterministic fuzzing if exec path checksum puts this out of scope
for this master instance. */

if (master_max && (queue_cur->exec_cksum % master_max) != master_id - 1)
goto havoc_stage;//TODO 这个逻辑我是真没看懂

doing_det = 1;

/*********************************************
* SIMPLE BITFLIP (+dictionary construction) *
*********************************************/

#define FLIP_BIT(_ar, _b) do { \
u8* _arf = (u8*)(_ar); \
u32 _bf = (_b); \
_arf[(_bf) >> 3] ^= (128 >> ((_bf) & 7)); \
} while (0)

/* Single walking bit. */

stage_short = "flip1";
stage_max = len << 3;//获取case长度,单位Bit
stage_name = "bitflip 1/1";

stage_val_type = STAGE_VAL_NONE;

orig_hit_cnt = queued_paths + unique_crashes;//原始命中次数=队列中的case数+已经发现的互不相同的crash数

prev_cksum = queue_cur->exec_cksum;

for (stage_cur = 0; stage_cur < stage_max; stage_cur++) {

stage_cur_byte = stage_cur >> 3;

FLIP_BIT(out_buf, stage_cur);//依次对每个位作位翻转

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;//common_fuzz_stuff会运行变异后的case,决定这个翻转是否interesting

FLIP_BIT(out_buf, stage_cur);//经过上面的测试,将这个bit翻转回来,确保每一轮循环产生的新case与原始case只有一位之差

/* While flipping the least significant bit in every byte, pull of an extra
trick to detect possible syntax tokens. In essence, the idea is that if
you have a binary blob like this:

xxxxxxxxIHDRxxxxxxxx

...and changing the leading and trailing bytes causes variable or no
changes in program flow, but touching any character in the "IHDR" string
always produces the same, distinctive path, it's highly likely that
"IHDR" is an atomically-checked magic value of special significance to
the fuzzed format.

We do this here, rather than as a separate stage, because it's a nice
way to keep the operation approximately "free" (i.e., no extra execs).

Empirically, performing the check when flipping the least significant bit
is advantageous, compared to doing it at the time of more disruptive
changes, where the program flow may be affected in more violent ways.

The caveat is that we won't generate dictionaries in the -d mode or -S
mode - but that's probably a fair trade-off.

This won't work particularly well with paths that exhibit variable
behavior, but fails gracefully, so we'll carry out the checks anyway.

*/
//下面的if用于寻找token,找到就存入extra,
if (!dumb_mode && (stage_cur & 7) == 7) {//如果翻转的是最低有效位

u32 cksum = hash32(trace_bits, MAP_SIZE, HASH_CONST);

if (stage_cur == stage_max - 1 && cksum == prev_cksum) {//如果stage_cur移动到了末尾,而checksum没有变化的话,就连带最后一个字符过长度check然后执行maybe_add_auto 后续在auto extras(over)阶段拿出来使用

/* If at end of file and we are still collecting a string, grab the
final character and force output. */

if (a_len < MAX_AUTO_EXTRA) a_collect[a_len] = out_buf[stage_cur >> 3];
a_len++;

if (a_len >= MIN_AUTO_EXTRA && a_len <= MAX_AUTO_EXTRA)
maybe_add_auto(a_collect, a_len);

} else if (cksum != prev_cksum) {//如果依次翻转一段连续字节的最低有效位后,bitmap都发生了变化,afl就认为这是一段固定的token,然后进maybe_add_auto

/* Otherwise, if the checksum has changed, see if we have something
worthwhile queued up, and collect that if the answer is yes. */

if (a_len >= MIN_AUTO_EXTRA && a_len <= MAX_AUTO_EXTRA)//token的长度要求在[3,32]中
maybe_add_auto(a_collect, a_len);

a_len = 0;
prev_cksum = cksum;

}

/* Continue collecting string, but only if the bit flip actually made
any difference - we don't want no-op tokens. */

if (cksum != queue_cur->exec_cksum) {

if (a_len < MAX_AUTO_EXTRA) a_collect[a_len] = out_buf[stage_cur >> 3];
a_len++;

}

}

}
//刷新以下指标
new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_FLIP1] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_FLIP1] += stage_max;

/* Two walking bits. */
//类似与bitflip 1/1 这里是每次翻转相邻2位.这里不再考虑找token
stage_name = "bitflip 2/1";
stage_short = "flip2";
stage_max = (len << 3) - 1;

orig_hit_cnt = new_hit_cnt;

for (stage_cur = 0; stage_cur < stage_max; stage_cur++) {

stage_cur_byte = stage_cur >> 3;

FLIP_BIT(out_buf, stage_cur);
FLIP_BIT(out_buf, stage_cur + 1);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;

FLIP_BIT(out_buf, stage_cur);
FLIP_BIT(out_buf, stage_cur + 1);

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_FLIP2] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_FLIP2] += stage_max;

/* Four walking bits. */

stage_name = "bitflip 4/1";
stage_short = "flip4";
stage_max = (len << 3) - 3;

orig_hit_cnt = new_hit_cnt;

for (stage_cur = 0; stage_cur < stage_max; stage_cur++) {

stage_cur_byte = stage_cur >> 3;

FLIP_BIT(out_buf, stage_cur);
FLIP_BIT(out_buf, stage_cur + 1);
FLIP_BIT(out_buf, stage_cur + 2);
FLIP_BIT(out_buf, stage_cur + 3);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;

FLIP_BIT(out_buf, stage_cur);
FLIP_BIT(out_buf, stage_cur + 1);
FLIP_BIT(out_buf, stage_cur + 2);
FLIP_BIT(out_buf, stage_cur + 3);

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_FLIP4] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_FLIP4] += stage_max;

/* Effector map setup. These macros calculate:

EFF_APOS - position of a particular file offset in the map.
EFF_ALEN - length of a map with a particular number of bytes.
EFF_SPAN_ALEN - map span for a sequence of bytes.

*/
//在进行bytefilp前,afl生成一个effector map
//EFFAPOS:以byte为单位,在map中定位一个文件偏移
//EFF_REM:可能是remain?,(_x)&0x111,目的大概是查看文件能否恰好转换为整数个字节
//EFF_ALEN:map的长度,单位字节,EFF_APOS获取最后一位,考虑EFF_REM,如果最后有小于1字节的残留位,额外增加一字节.举例的话,假设_l=9,此时APOS(_l)=1,!!EFF_REM(_l)=1.双叹号表示,所有非零值都转换成1,否则为0
//EFF_SPAN_ALEN:
#define EFF_APOS(_p) ((_p) >> EFF_MAP_SCALE2)
#define EFF_REM(_x) ((_x) & ((1 << EFF_MAP_SCALE2) - 1))
#define EFF_ALEN(_l) (EFF_APOS(_l) + !!EFF_REM(_l))
#define EFF_SPAN_ALEN(_p, _l) (EFF_APOS((_p) + (_l) - 1) - EFF_APOS(_p) + 1)

/* Initialize effector map for the next step (see comments below). Always
flag first and last byte as doing something. */

eff_map = ck_alloc(EFF_ALEN(len));//开辟足够容纳effector map的空间
eff_map[0] = 1;//首位置1

if (EFF_APOS(len - 1) != 0) {
eff_map[EFF_APOS(len - 1)] = 1;//末位置1,不一定是末位,如果len&0x111的话,那就是倒数第二位置1
eff_cnt++;
}

/* Walking byte. */

stage_name = "bitflip 8/8";
stage_short = "flip8";
stage_max = len;

orig_hit_cnt = new_hit_cnt;

for (stage_cur = 0; stage_cur < stage_max; stage_cur++) {

stage_cur_byte = stage_cur;

out_buf[stage_cur] ^= 0xFF;//字节翻转

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;//执行common_fuzz_stuff 记录执行状态

/* We also use this stage to pull off a simple trick: we identify
bytes that seem to have no effect on the current execution path
even when fully flipped - and we skip them during more expensive
deterministic stages, such as arithmetics or known ints. */
//通过effector map,识别对当前执行路径没有影响的字节,从而跳过arithmetics和known ints
if (!eff_map[EFF_APOS(stage_cur)]) {//仅当effector map中当前字节标记为0时才进行以下代码

u32 cksum;

/* If in dumb mode or if the file is very short, just flag everything
without wasting time on checksums. */

if (!dumb_mode && len >= EFF_MIN_LEN)//如果不是dumb mode或者文件太小,就认真执行hash32,否则就将当前记录的cksum取反,作为新的cksum,直接视作checksum变了,略过高开销的hash32
cksum = hash32(trace_bits, MAP_SIZE, HASH_CONST);
else
cksum = ~queue_cur->exec_cksum;

if (cksum != queue_cur->exec_cksum) {//如果前后两次的checksum发生了变化,那么执行路径发生了变化
eff_map[EFF_APOS(stage_cur)] = 1;//将该字节在effector_map中置1,表示该字节"有效",即会影响执行路径
eff_cnt++;//eff_cnt会计数有效字节数
}

}

out_buf[stage_cur] ^= 0xFF;

}

/* If the effector map is more than EFF_MAX_PERC dense, just flag the
whole thing as worth fuzzing, since we wouldn't be saving much time
anyway. */

if (eff_cnt != EFF_ALEN(len) &&
eff_cnt * 100 / EFF_ALEN(len) > EFF_MAX_PERC) {//如果不是整个case的所有字节都有效,但是有效字节的比例超过90%,那干脆整个effector map置1,认为整个case都值得fuzzing

memset(eff_map, 1, EFF_ALEN(len));

blocks_eff_select += EFF_ALEN(len);//blocks_eff_select只用在screen上

} else {

blocks_eff_select += eff_cnt;

}

blocks_eff_total += EFF_ALEN(len);//blocks_eff_total也是应用在screen上

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_FLIP8] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_FLIP8] += stage_max;

/* Two walking bytes. */

if (len < 2) goto skip_bitflip;

stage_name = "bitflip 16/8";
stage_short = "flip16";
stage_cur = 0;
stage_max = len - 1;

orig_hit_cnt = new_hit_cnt;

for (i = 0; i < len - 1; i++) {

/* Let's consult the effector map... */
//查看effector map中相邻两位,
if (!eff_map[EFF_APOS(i)] && !eff_map[EFF_APOS(i + 1)]) {
stage_max--;//stage_max表示实际执行的双字节翻转次数,所以如果这里条件成立跳过了这一轮循环,表示节省一次翻转次数,max--
continue;
}

stage_cur_byte = i;

*(u16*)(out_buf + i) ^= 0xFFFF;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

*(u16*)(out_buf + i) ^= 0xFFFF;


}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_FLIP16] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_FLIP16] += stage_max;

if (len < 4) goto skip_bitflip;

/* Four walking bytes. */

stage_name = "bitflip 32/8";
stage_short = "flip32";
stage_cur = 0;
stage_max = len - 3;

orig_hit_cnt = new_hit_cnt;

for (i = 0; i < len - 3; i++) {

/* Let's consult the effector map... */
if (!eff_map[EFF_APOS(i)] && !eff_map[EFF_APOS(i + 1)] &&
!eff_map[EFF_APOS(i + 2)] && !eff_map[EFF_APOS(i + 3)]) {
stage_max--;
continue;
}

stage_cur_byte = i;

*(u32*)(out_buf + i) ^= 0xFFFFFFFF;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

*(u32*)(out_buf + i) ^= 0xFFFFFFFF;

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_FLIP32] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_FLIP32] += stage_max;

skip_bitflip:
//如果跳过位翻转,就直接跳到下面的arithmetic stage
if (no_arith) goto skip_arith;

/**********************
* ARITHMETIC INC/DEC *
**********************/

/* 8-bit arithmetics. */

stage_name = "arith 8/8";
stage_short = "arith8";
stage_cur = 0;
stage_max = 2 * len * ARITH_MAX;//len:每个字节都变异,2:加或减,ARITH_MAX:每个字节加减1到35

stage_val_type = STAGE_VAL_LE;

orig_hit_cnt = new_hit_cnt;

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

u8 orig = out_buf[i];

/* Let's consult the effector map... */

if (!eff_map[EFF_APOS(i)]) {
stage_max -= 2 * ARITH_MAX;
continue;
}//借助effector_map,仅探索有效位

stage_cur_byte = i;

for (j = 1; j <= ARITH_MAX; j++) {

u8 r = orig ^ (orig + j);//原始值与原始值+j作异或

/* Do arithmetic operations only if the result couldn't be a product
of a bitflip. */

if (!could_be_bitflip(r)) {//判断orig+j能否由orig通过bitsflip得来,可以的话表示bitflip阶段已经尝试过,所以可以略过这一轮循环

stage_cur_val = j;
out_buf[i] = orig + j;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

r = orig ^ (orig - j);//尝试将原始值减去一个数是否是bitflip可以实现的

if (!could_be_bitflip(r)) {

stage_cur_val = -j;
out_buf[i] = orig - j;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

out_buf[i] = orig;

}

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_ARITH8] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_ARITH8] += stage_max;

/* 16-bit arithmetics, both endians. */
//类似8位算术,但是16位开始会考虑大小端
if (len < 2) goto skip_arith;

stage_name = "arith 16/8";
stage_short = "arith16";
stage_cur = 0;
stage_max = 4 * (len - 1) * ARITH_MAX;//正负,大小端 所以是4种组合

orig_hit_cnt = new_hit_cnt;

for (i = 0; i < len - 1; i++) {

u16 orig = *(u16*)(out_buf + i);

/* Let's consult the effector map... */

if (!eff_map[EFF_APOS(i)] && !eff_map[EFF_APOS(i + 1)]) {
stage_max -= 4 * ARITH_MAX;
continue;
}

stage_cur_byte = i;

for (j = 1; j <= ARITH_MAX; j++) {

u16 r1 = orig ^ (orig + j),//小端
r2 = orig ^ (orig - j),
r3 = orig ^ SWAP16(SWAP16(orig) + j),//用SWAP16实现大小端转换,原始双字节,大小端转换后+j,再大小端转换回来,就能实现大端加减
r4 = orig ^ SWAP16(SWAP16(orig) - j);

/* Try little endian addition and subtraction first. Do it only
if the operation would affect more than one byte (hence the
& 0xff overflow checks) and if it couldn't be a product of
a bitflip. */

stage_val_type = STAGE_VAL_LE;

if ((orig & 0xff) + j > 0xff && !could_be_bitflip(r1)) {//尝试低8位+j,如果大于0xff,说明没有溢出

stage_cur_val = j;
*(u16*)(out_buf + i) = orig + j;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

if ((orig & 0xff) < j && !could_be_bitflip(r2)) {//考虑减法的时候,保证j比低8位大???????????保证下溢?

stage_cur_val = -j;
*(u16*)(out_buf + i) = orig - j;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

/* Big endian comes next. Same deal. */

stage_val_type = STAGE_VAL_BE;


if ((orig >> 8) + j > 0xff && !could_be_bitflip(r3)) {

stage_cur_val = j;
*(u16*)(out_buf + i) = SWAP16(SWAP16(orig) + j);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

if ((orig >> 8) < j && !could_be_bitflip(r4)) {

stage_cur_val = -j;
*(u16*)(out_buf + i) = SWAP16(SWAP16(orig) - j);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

*(u16*)(out_buf + i) = orig;

}

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_ARITH16] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_ARITH16] += stage_max;

/* 32-bit arithmetics, both endians. */

if (len < 4) goto skip_arith;

stage_name = "arith 32/8";
stage_short = "arith32";
stage_cur = 0;
stage_max = 4 * (len - 3) * ARITH_MAX;

orig_hit_cnt = new_hit_cnt;

for (i = 0; i < len - 3; i++) {

u32 orig = *(u32*)(out_buf + i);

/* Let's consult the effector map... */

if (!eff_map[EFF_APOS(i)] && !eff_map[EFF_APOS(i + 1)] &&
!eff_map[EFF_APOS(i + 2)] && !eff_map[EFF_APOS(i + 3)]) {
stage_max -= 4 * ARITH_MAX;
continue;
}

stage_cur_byte = i;

for (j = 1; j <= ARITH_MAX; j++) {

u32 r1 = orig ^ (orig + j),
r2 = orig ^ (orig - j),
r3 = orig ^ SWAP32(SWAP32(orig) + j),
r4 = orig ^ SWAP32(SWAP32(orig) - j);

/* Little endian first. Same deal as with 16-bit: we only want to
try if the operation would have effect on more than two bytes. */

stage_val_type = STAGE_VAL_LE;

if ((orig & 0xffff) + j > 0xffff && !could_be_bitflip(r1)) {

stage_cur_val = j;
*(u32*)(out_buf + i) = orig + j;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

if ((orig & 0xffff) < j && !could_be_bitflip(r2)) {

stage_cur_val = -j;
*(u32*)(out_buf + i) = orig - j;

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

/* Big endian next. */

stage_val_type = STAGE_VAL_BE;

if ((SWAP32(orig) & 0xffff) + j > 0xffff && !could_be_bitflip(r3)) {

stage_cur_val = j;
*(u32*)(out_buf + i) = SWAP32(SWAP32(orig) + j);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

if ((SWAP32(orig) & 0xffff) < j && !could_be_bitflip(r4)) {

stage_cur_val = -j;
*(u32*)(out_buf + i) = SWAP32(SWAP32(orig) - j);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

*(u32*)(out_buf + i) = orig;

}

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_ARITH32] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_ARITH32] += stage_max;

skip_arith:
//arithmetic阶段之后 就是直接去赋予一些interesting的值 比如interesting_8和interesting_16中
/**********************
* INTERESTING VALUES *
**********************/

stage_name = "interest 8/8";
stage_short = "int8";
stage_cur = 0;
stage_max = len * sizeof(interesting_8);

stage_val_type = STAGE_VAL_LE;

orig_hit_cnt = new_hit_cnt;

/* Setting 8-bit integers. */

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

u8 orig = out_buf[i];

/* Let's consult the effector map... */

if (!eff_map[EFF_APOS(i)]) {
stage_max -= sizeof(interesting_8);
continue;
}//依旧借助eff_map 只操作有效位

stage_cur_byte = i;

for (j = 0; j < sizeof(interesting_8); j++) {

/* Skip if the value could be a product of bitflips or arithmetics. */

if (could_be_bitflip(orig ^ (u8)interesting_8[j]) ||
could_be_arith(orig, (u8)interesting_8[j], 1)) {//类似arith stage.如果修改后的值,可以通过bitflip或arith得到,那就没有必要去尝试这个值. 但是这里有个问题,设置no_arith是可以跳过arith_stage的,那这里其实会出现:arith被跳过,而这里遇到了一个值,满足could_be_arith,于是也被跳过,那实际上这个值就没被运行
stage_max--;
continue;
}

stage_cur_val = interesting_8[j];
out_buf[i] = interesting_8[j];

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;

out_buf[i] = orig;
stage_cur++;

}

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_INTEREST8] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_INTEREST8] += stage_max;

/* Setting 16-bit integers, both endians. */

if (no_arith || len < 2) goto skip_interest;//如果选择跳过arith stage,那以下的多字节interest也跳过

stage_name = "interest 16/8";
stage_short = "int16";
stage_cur = 0;
stage_max = 2 * (len - 1) * (sizeof(interesting_16) >> 1);

orig_hit_cnt = new_hit_cnt;

for (i = 0; i < len - 1; i++) {

u16 orig = *(u16*)(out_buf + i);

/* Let's consult the effector map... */

if (!eff_map[EFF_APOS(i)] && !eff_map[EFF_APOS(i + 1)]) {
stage_max -= sizeof(interesting_16);
continue;
}

stage_cur_byte = i;

for (j = 0; j < sizeof(interesting_16) / 2; j++) {

stage_cur_val = interesting_16[j];

/* Skip if this could be a product of a bitflip, arithmetics,
or single-byte interesting value insertion. */

if (!could_be_bitflip(orig ^ (u16)interesting_16[j]) &&
!could_be_arith(orig, (u16)interesting_16[j], 2) &&
!could_be_interest(orig, (u16)interesting_16[j], 2, 0)) {//对于多字节interesting value,还考虑这是不是能通过单字节interesting value获得.

stage_val_type = STAGE_VAL_LE;

*(u16*)(out_buf + i) = interesting_16[j];

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

if ((u16)interesting_16[j] != SWAP16(interesting_16[j]) &&
!could_be_bitflip(orig ^ SWAP16(interesting_16[j])) &&
!could_be_arith(orig, SWAP16(interesting_16[j]), 2) &&
!could_be_interest(orig, SWAP16(interesting_16[j]), 2, 1)) {

stage_val_type = STAGE_VAL_BE;

*(u16*)(out_buf + i) = SWAP16(interesting_16[j]);
if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

}

*(u16*)(out_buf + i) = orig;

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_INTEREST16] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_INTEREST16] += stage_max;

if (len < 4) goto skip_interest;

/* Setting 32-bit integers, both endians. */

stage_name = "interest 32/8";
stage_short = "int32";
stage_cur = 0;
stage_max = 2 * (len - 3) * (sizeof(interesting_32) >> 2);

orig_hit_cnt = new_hit_cnt;

for (i = 0; i < len - 3; i++) {

u32 orig = *(u32*)(out_buf + i);

/* Let's consult the effector map... */

if (!eff_map[EFF_APOS(i)] && !eff_map[EFF_APOS(i + 1)] &&
!eff_map[EFF_APOS(i + 2)] && !eff_map[EFF_APOS(i + 3)]) {
stage_max -= sizeof(interesting_32) >> 1;
continue;
}

stage_cur_byte = i;

for (j = 0; j < sizeof(interesting_32) / 4; j++) {

stage_cur_val = interesting_32[j];

/* Skip if this could be a product of a bitflip, arithmetics,
or word interesting value insertion. */

if (!could_be_bitflip(orig ^ (u32)interesting_32[j]) &&
!could_be_arith(orig, interesting_32[j], 4) &&
!could_be_interest(orig, interesting_32[j], 4, 0)) {

stage_val_type = STAGE_VAL_LE;

*(u32*)(out_buf + i) = interesting_32[j];

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

if ((u32)interesting_32[j] != SWAP32(interesting_32[j]) &&
!could_be_bitflip(orig ^ SWAP32(interesting_32[j])) &&
!could_be_arith(orig, SWAP32(interesting_32[j]), 4) &&
!could_be_interest(orig, SWAP32(interesting_32[j]), 4, 1)) {

stage_val_type = STAGE_VAL_BE;

*(u32*)(out_buf + i) = SWAP32(interesting_32[j]);
if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;
stage_cur++;

} else stage_max--;

}

*(u32*)(out_buf + i) = orig;

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_INTEREST32] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_INTEREST32] += stage_max;

skip_interest:

/********************
* DICTIONARY STUFF *
********************/
//interesting阶段是afl预设了一些认为会有特殊含义的数值,dictionary环节则是由用户提供一些值
if (!extras_cnt) goto skip_user_extras;//字典如果是空的就没必要进行这个stage

/* Overwrite with user-supplied extras. */
//该环节是字典中的值覆写内存
stage_name = "user extras (over)";
stage_short = "ext_UO";
stage_cur = 0;
stage_max = extras_cnt * len;//把字典里的值再每个位置都用一遍

stage_val_type = STAGE_VAL_NONE;

orig_hit_cnt = new_hit_cnt;

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

u32 last_len = 0;

stage_cur_byte = i;

/* Extras are sorted by size, from smallest to largest. This means
that we don't have to worry about restoring the buffer in
between writes at a particular offset determined by the outer
loop. */

for (j = 0; j < extras_cnt; j++) {

/* Skip extras probabilistically if extras_cnt > MAX_DET_EXTRAS. Also
skip them if there's no room to insert the payload, if the token
is redundant, or if its entire span has no bytes set in the effector
map. */

if ((extras_cnt > MAX_DET_EXTRAS && UR(extras_cnt) >= MAX_DET_EXTRAS) ||
extras[j].len > len - i ||
!memcmp(extras[j].data, out_buf + i, extras[j].len) ||
!memchr(eff_map + EFF_APOS(i), 1, EFF_SPAN_ALEN(i, extras[j].len))) {

stage_max--;
continue;

}

last_len = extras[j].len;
memcpy(out_buf + i, extras[j].data, last_len);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;

stage_cur++;

}

/* Restore all the clobbered memory. */
memcpy(out_buf + i, in_buf + i, last_len);

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_EXTRAS_UO] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_EXTRAS_UO] += stage_max;

/* Insertion of user-supplied extras. */
//该环节是将字典值插入内存,会引起输入长度的变化
stage_name = "user extras (insert)";
stage_short = "ext_UI";
stage_cur = 0;
stage_max = extras_cnt * (len + 1);

orig_hit_cnt = new_hit_cnt;

ex_tmp = ck_alloc(len + MAX_DICT_FILE);

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

stage_cur_byte = i;

for (j = 0; j < extras_cnt; j++) {

if (len + extras[j].len > MAX_FILE) {
stage_max--;
continue;
}

/* Insert token */
memcpy(ex_tmp + i, extras[j].data, extras[j].len);

/* Copy tail */
memcpy(ex_tmp + i + extras[j].len, out_buf + i, len - i);

if (common_fuzz_stuff(argv, ex_tmp, len + extras[j].len)) {
ck_free(ex_tmp);
goto abandon_entry;
}

stage_cur++;

}

/* Copy head */
ex_tmp[i] = out_buf[i];

}

ck_free(ex_tmp);

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_EXTRAS_UI] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_EXTRAS_UI] += stage_max;

skip_user_extras:

if (!a_extras_cnt) goto skip_extras;
//这一阶段类似 user extras(over) 但这一阶段的token都是bitflip阶段自动生成的
stage_name = "auto extras (over)";
stage_short = "ext_AO";
stage_cur = 0;
stage_max = MIN(a_extras_cnt, USE_AUTO_EXTRAS) * len;

stage_val_type = STAGE_VAL_NONE;

orig_hit_cnt = new_hit_cnt;

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

u32 last_len = 0;

stage_cur_byte = i;

for (j = 0; j < MIN(a_extras_cnt, USE_AUTO_EXTRAS); j++) {

/* See the comment in the earlier code; extras are sorted by size. */

if (a_extras[j].len > len - i ||
!memcmp(a_extras[j].data, out_buf + i, a_extras[j].len) ||
!memchr(eff_map + EFF_APOS(i), 1, EFF_SPAN_ALEN(i, a_extras[j].len))) {

stage_max--;
continue;

}

last_len = a_extras[j].len;
memcpy(out_buf + i, a_extras[j].data, last_len);

if (common_fuzz_stuff(argv, out_buf, len)) goto abandon_entry;

stage_cur++;

}

/* Restore all the clobbered memory. */
memcpy(out_buf + i, in_buf + i, last_len);

}

new_hit_cnt = queued_paths + unique_crashes;

stage_finds[STAGE_EXTRAS_AO] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_EXTRAS_AO] += stage_max;

skip_extras:

/* If we made this to here without jumping to havoc_stage or abandon_entry,
we're properly done with deterministic steps and can mark it as such
in the .state/ directory. */

if (!queue_cur->passed_det) mark_as_det_done(queue_cur);//无论是跳过了det阶段还是认真经过了det阶段,这里都会在queue中标记这个case完成了deterministic

/****************
* RANDOM HAVOC *
****************/
//接下来的就是随机的破坏性变异阶段
havoc_stage:

stage_cur_byte = -1;

/* The havoc stage mutation code is also invoked when splicing files; if the
splice_cycle variable is set, generate different descriptions and such. */

if (!splice_cycle) {//拼接文件的时候也会调用havoc,为了区分这是splice_cycle还是常规的cycle,设置这个变量作为判断条件

stage_name = "havoc";
stage_short = "havoc";
stage_max = (doing_det ? HAVOC_CYCLES_INIT : HAVOC_CYCLES) *
perf_score / havoc_div / 100;//Line.5159,如果满足一些条件(比如当前case已经fuzz过,或者命令行参数带了-d等)程序就会在doing_det置位前直接跳转到havoc,所以doing_det表示会执行deterministic stage,也表示经过det stage的case,基本可以说是第一次执行random havoc stage.

} else {

static u8 tmp[32];

perf_score = orig_perf;

sprintf(tmp, "splice %u", splice_cycle);
stage_name = tmp;
stage_short = "splice";
stage_max = SPLICE_HAVOC * perf_score / havoc_div / 100;//perf_score由calculate_score()计算;havoc_div在Line.4439被赋值,与平均执行时长关联

}

if (stage_max < HAVOC_MIN) stage_max = HAVOC_MIN;//random havoc阶段最少也要进行16次

temp_len = len;

orig_hit_cnt = queued_paths + unique_crashes;

havoc_queued = queued_paths;

/* We essentially just do several thousand runs (depending on perf_score)
where we take the input file and make random stacked tweaks. */

for (stage_cur = 0; stage_cur < stage_max; stage_cur++) {

u32 use_stacking = 1 << (1 + UR(HAVOC_STACK_POW2));//use_stacking=2^8=256

stage_cur_val = use_stacking;

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

switch (UR(15 + ((extras_cnt + a_extras_cnt) ? 2 : 0))) {//switch来控制这一轮循环中采用16种havoc策略中的具体哪一种。case15/16仅当dictionary中有值时才会有可能被使用

case 0:

/* Flip a single bit somewhere. Spooky! */
//随机翻转某个bit
FLIP_BIT(out_buf, UR(temp_len << 3));
break;

case 1:

/* Set byte to interesting value. */
//设置随机某个字节为8位Interesting value
out_buf[UR(temp_len)] = interesting_8[UR(sizeof(interesting_8))];
break;

case 2:

/* Set word to interesting value, randomly choosing endian. */
//设置随机某个字为16位interesting value,随机字节序
if (temp_len < 2) break;

if (UR(2)) {

*(u16*)(out_buf + UR(temp_len - 1)) =
interesting_16[UR(sizeof(interesting_16) >> 1)];

} else {

*(u16*)(out_buf + UR(temp_len - 1)) = SWAP16(
interesting_16[UR(sizeof(interesting_16) >> 1)]);

}

break;

case 3:

/* Set dword to interesting value, randomly choosing endian. */
//设置某个随机双字为32位interesting value,随机字节序
if (temp_len < 4) break;

if (UR(2)) {

*(u32*)(out_buf + UR(temp_len - 3)) =
interesting_32[UR(sizeof(interesting_32) >> 2)];

} else {

*(u32*)(out_buf + UR(temp_len - 3)) = SWAP32(
interesting_32[UR(sizeof(interesting_32) >> 2)]);

}

break;

case 4:

/* Randomly subtract from byte. */
//某个随机字节,减去某个随机数值
out_buf[UR(temp_len)] -= 1 + UR(ARITH_MAX);
break;

case 5:

/* Randomly add to byte. */
//随机字节,加随机数
out_buf[UR(temp_len)] += 1 + UR(ARITH_MAX);
break;

case 6:

/* Randomly subtract from word, random endian. */
//随机字,减随机数,随机字节序
if (temp_len < 2) break;

if (UR(2)) {

u32 pos = UR(temp_len - 1);

*(u16*)(out_buf + pos) -= 1 + UR(ARITH_MAX);

} else {

u32 pos = UR(temp_len - 1);
u16 num = 1 + UR(ARITH_MAX);

*(u16*)(out_buf + pos) =
SWAP16(SWAP16(*(u16*)(out_buf + pos)) - num);

}

break;

case 7:

/* Randomly add to word, random endian. */
//随机字,加随机数,随机字节序
if (temp_len < 2) break;

if (UR(2)) {

u32 pos = UR(temp_len - 1);

*(u16*)(out_buf + pos) += 1 + UR(ARITH_MAX);

} else {

u32 pos = UR(temp_len - 1);
u16 num = 1 + UR(ARITH_MAX);

*(u16*)(out_buf + pos) =
SWAP16(SWAP16(*(u16*)(out_buf + pos)) + num);

}

break;

case 8:

/* Randomly subtract from dword, random endian. */
//随机双字,减随机数,随机字节序
if (temp_len < 4) break;

if (UR(2)) {

u32 pos = UR(temp_len - 3);

*(u32*)(out_buf + pos) -= 1 + UR(ARITH_MAX);

} else {

u32 pos = UR(temp_len - 3);
u32 num = 1 + UR(ARITH_MAX);

*(u32*)(out_buf + pos) =
SWAP32(SWAP32(*(u32*)(out_buf + pos)) - num);

}

break;

case 9:

/* Randomly add to dword, random endian. */
// 随机双字,加随机数,随机字节序
if (temp_len < 4) break;

if (UR(2)) {

u32 pos = UR(temp_len - 3);

*(u32*)(out_buf + pos) += 1 + UR(ARITH_MAX);

} else {

u32 pos = UR(temp_len - 3);
u32 num = 1 + UR(ARITH_MAX);

*(u32*)(out_buf + pos) =
SWAP32(SWAP32(*(u32*)(out_buf + pos)) + num);

}

break;

case 10:

/* Just set a random byte to a random value. Because,
why not. We use XOR with 1-255 to eliminate the
possibility of a no-op. */
//随机字节设置为随机数。原理是原数值异或1~255的一个随机数,这样能避免无效操作的可能性,即随机数就是原数值
out_buf[UR(temp_len)] ^= 1 + UR(255);
break;

case 11 ... 12: {

/* Delete bytes. We're making this a bit more likely
than insertion (the next option) in hopes of keeping
files reasonably small. */
//随机位置删除连续的若干字节,设置case11...12都是这个逻辑,目的是提高删减case的概率,保持case较小
u32 del_from, del_len;

if (temp_len < 2) break;

/* Don't delete too much. */

del_len = choose_block_len(temp_len - 1);//生成一个随机数,作为删除字节的长度

del_from = UR(temp_len - del_len + 1);

memmove(out_buf + del_from, out_buf + del_from + del_len,
temp_len - del_from - del_len);

temp_len -= del_len;

break;

}

case 13:
//随机位置插入一段字节。75%概率克隆原case中一段内容;25%概率插入一段固定的随机值(e.g. 0x44444444),随机值的选取,50%概率选取0x00~0xFF中随机值,50%概率取out_buf中随机某位
if (temp_len + HAVOC_BLK_XL < MAX_FILE) {//

/* Clone bytes (75%) or insert a block of constant bytes (25%). */

u8 actually_clone = UR(4);
u32 clone_from, clone_to, clone_len;
u8* new_buf;

if (actually_clone) {

clone_len = choose_block_len(temp_len);
clone_from = UR(temp_len - clone_len + 1);

} else {

clone_len = choose_block_len(HAVOC_BLK_XL);
clone_from = 0;

}

clone_to = UR(temp_len);

new_buf = ck_alloc_nozero(temp_len + clone_len);

/* Head */

memcpy(new_buf, out_buf, clone_to);

/* Inserted part */

if (actually_clone)
memcpy(new_buf + clone_to, out_buf + clone_from, clone_len);
else
memset(new_buf + clone_to,
UR(2) ? UR(256) : out_buf[UR(temp_len)], clone_len);

/* Tail */
memcpy(new_buf + clone_to + clone_len, out_buf + clone_to,
temp_len - clone_to);

ck_free(out_buf);
out_buf = new_buf;
temp_len += clone_len;

}

break;

case 14: {

/* Overwrite bytes with a randomly selected chunk (75%) or fixed
bytes (25%). */
//随机位置覆盖一段字节。75%克隆一段内容,25%用随机的相同数值填充
u32 copy_from, copy_to, copy_len;

if (temp_len < 2) break;

copy_len = choose_block_len(temp_len - 1);

copy_from = UR(temp_len - copy_len + 1);
copy_to = UR(temp_len - copy_len + 1);

if (UR(4)) {

if (copy_from != copy_to)
memmove(out_buf + copy_to, out_buf + copy_from, copy_len);

} else memset(out_buf + copy_to,
UR(2) ? UR(256) : out_buf[UR(temp_len)], copy_len);

break;

}

/* Values 15 and 16 can be selected only if there are any extras
present in the dictionaries. */

case 15: {

/* Overwrite bytes with an extra. */
//随机位置用extra覆盖若干字节
if (!extras_cnt || (a_extras_cnt && UR(2))) {
//如果没有用户指定的extras(提供100%概率通过条件判断),或者可用的token为基数个(50%概率通过条件判断,因为UR(2)),使用auto extras
/* No user-specified extras or odds in our favor. Let's use an
auto-detected one. */

u32 use_extra = UR(a_extras_cnt);
u32 extra_len = a_extras[use_extra].len;
u32 insert_at;

if (extra_len > temp_len) break;

insert_at = UR(temp_len - extra_len + 1);
memcpy(out_buf + insert_at, a_extras[use_extra].data, extra_len);

} else {

/* No auto extras or odds in our favor. Use the dictionary. */

u32 use_extra = UR(extras_cnt);
u32 extra_len = extras[use_extra].len;
u32 insert_at;

if (extra_len > temp_len) break;

insert_at = UR(temp_len - extra_len + 1);
memcpy(out_buf + insert_at, extras[use_extra].data, extra_len);

}

break;

}

case 16: {
//随机位置用extra插入若干字节
u32 use_extra, extra_len, insert_at = UR(temp_len + 1);
u8* new_buf;

/* Insert an extra. Do the same dice-rolling stuff as for the
previous case. */

if (!extras_cnt || (a_extras_cnt && UR(2))) {

use_extra = UR(a_extras_cnt);
extra_len = a_extras[use_extra].len;

if (temp_len + extra_len >= MAX_FILE) break;

new_buf = ck_alloc_nozero(temp_len + extra_len);

/* Head */
memcpy(new_buf, out_buf, insert_at);

/* Inserted part */
memcpy(new_buf + insert_at, a_extras[use_extra].data, extra_len);

} else {

use_extra = UR(extras_cnt);
extra_len = extras[use_extra].len;

if (temp_len + extra_len >= MAX_FILE) break;

new_buf = ck_alloc_nozero(temp_len + extra_len);

/* Head */
memcpy(new_buf, out_buf, insert_at);

/* Inserted part */
memcpy(new_buf + insert_at, extras[use_extra].data, extra_len);

}

/* Tail */
memcpy(new_buf + insert_at + extra_len, out_buf + insert_at,
temp_len - insert_at);

ck_free(out_buf);
out_buf = new_buf;
temp_len += extra_len;

break;

}

}

}

if (common_fuzz_stuff(argv, out_buf, temp_len))
goto abandon_entry;

/* out_buf might have been mangled a bit, so let's restore it to its
original size and shape. */

if (temp_len < len) out_buf = ck_realloc(out_buf, len);
temp_len = len;
memcpy(out_buf, in_buf, len);

/* If we're finding new stuff, let's run for a bit longer, limits
permitting. */

if (queued_paths != havoc_queued) {

if (perf_score <= HAVOC_MAX_MULT * 100) {
stage_max *= 2;
perf_score *= 2;
}

havoc_queued = queued_paths;

}

}

new_hit_cnt = queued_paths + unique_crashes;

if (!splice_cycle) {
stage_finds[STAGE_HAVOC] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_HAVOC] += stage_max;
} else {
stage_finds[STAGE_SPLICE] += new_hit_cnt - orig_hit_cnt;
stage_cycles[STAGE_SPLICE] += stage_max;
}

#ifndef IGNORE_FINDS

/************
* SPLICING *
************/

/* This is a last-resort strategy triggered by a full round with no findings.
It takes the current input file, randomly selects another input, and
splices them together at some offset, then relies on the havoc
code to mutate that blob. */
//如果一整轮都没有收获,就会触发这最后一个策略。随机选择另一个输入文件,以一定的偏移与当前的输入文件进行拼接,然后依靠havoc进行变异
retry_splicing:

if (use_splicing && splice_cycle++ < SPLICE_CYCLES &&
queued_paths > 1 && queue_cur->len > 1) {

struct queue_entry* target;
u32 tid, split_at;
u8* new_buf;
s32 f_diff, l_diff;

/* First of all, if we've modified in_buf for havoc, let's clean that
up... */

if (in_buf != orig_in) {//这个阶段拼接的两个case要求是未做过修改的,所以检查in_buf是否作过改动,然后还原成origin_input
ck_free(in_buf);
in_buf = orig_in;
len = queue_cur->len;
}

/* Pick a random queue entry and seek to it. Don't splice with yourself. */

do { tid = UR(queued_paths); } while (tid == current_entry);//根据testcase队列长度随机生成一个数作为tid。while()中的条件保证tid不是当前的currrent_entry

splicing_with = tid;
target = queue;

while (tid >= 100) { target = target->next_100; tid -= 100; }
while (tid--) target = target->next;//快速找到target target即为作为拼接材料的"另一个输入文件"

/* Make sure that the target has a reasonable length. */

while (target && (target->len < 2 || target == queue_cur)) {
target = target->next;
splicing_with++;
}

if (!target) goto retry_splicing;

/* Read the testcase into a new buffer. */

fd = open(target->fname, O_RDONLY);

if (fd < 0) PFATAL("Unable to open '%s'", target->fname);

new_buf = ck_alloc_nozero(target->len);

ck_read(fd, new_buf, target->len, target->fname);//testcase读进new_buf

close(fd);

/* Find a suitable splicing location, somewhere between the first and
the last differing byte. Bail out if the difference is just a single
byte or so. */

locate_diffs(in_buf, new_buf, MIN(len, target->len), &f_diff, &l_diff);//这个函数定位in_buf和new_buf的第一个差异偏移和最后一个差异偏移。但是这个函数有改进空间吗。比如头尾都带token的testcase,一个是ABCDEEEABCD,另一个是ABCDFFFFABCD,f_diff在4,l_diff在10,按照下面的步骤,如果我选择从pos=9开始拼接,那我就会把BCD拼接过去形成ABCDEEEABBCD,这样token就被破坏了。这样可能算是一些小概率事件,但是是不是可以用一些其他策略去保护token,或者设计一些更优雅的拼接方式(虽然动用splicing已经不应该考虑优雅了)

if (f_diff < 0 || l_diff < 2 || f_diff == l_diff) {
ck_free(new_buf);//f_diff:在locate_diffs()中,first和last初始值为-1,表示未找到差异位,如果f_diff<0表示该值仍为-1,即没有差异,retry;l_diff<2:TODO 无法理解,只在头部出现差异就放弃拼接?;f_diff == l_diff:表示两者只有1位差异,retry
goto retry_splicing;
}

/* Split somewhere between the first and last differing byte. */

split_at = f_diff + UR(l_diff - f_diff);

/* Do the thing. */

len = target->len;
memcpy(new_buf, in_buf, split_at);
in_buf = new_buf;

ck_free(out_buf);
out_buf = ck_alloc_nozero(len);
memcpy(out_buf, in_buf, len);

goto havoc_stage;

}

#endif /* !IGNORE_FINDS */

ret_val = 0;

abandon_entry:

splicing_with = -1;

/* Update pending_not_fuzzed count if we made it through the calibration
cycle and have not seen this entry before. */

if (!stop_soon && !queue_cur->cal_failed && !queue_cur->was_fuzzed) {
queue_cur->was_fuzzed = 1;
pending_not_fuzzed--;
if (queue_cur->favored) pending_favored--;
}

munmap(orig_in, queue_cur->len);

if (in_buf != orig_in) ck_free(in_buf);
ck_free(out_buf);
ck_free(eff_map);

return ret_val;

#undef FLIP_BIT

}


/* Grab interesting test cases from other fuzzers. */

static void sync_fuzzers(char** argv) {

DIR* sd;
struct dirent* sd_ent;
u32 sync_cnt = 0;

sd = opendir(sync_dir);
if (!sd) PFATAL("Unable to open '%s'", sync_dir);

stage_max = stage_cur = 0;
cur_depth = 0;

/* Look at the entries created for every other fuzzer in the sync directory. */

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

static u8 stage_tmp[128];

DIR* qd;
struct dirent* qd_ent;
u8 *qd_path, *qd_synced_path;
u32 min_accept = 0, next_min_accept;

s32 id_fd;

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

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

/* Skip anything that doesn't have a queue/ subdirectory. */

qd_path = alloc_printf("%s/%s/queue", sync_dir, sd_ent->d_name);

if (!(qd = opendir(qd_path))) {
ck_free(qd_path);
continue;
}

/* Retrieve the ID of the last seen test case. */

qd_synced_path = alloc_printf("%s/.synced/%s", out_dir, sd_ent->d_name);

id_fd = open(qd_synced_path, O_RDWR | O_CREAT, 0600);

if (id_fd < 0) PFATAL("Unable to create '%s'", qd_synced_path);

if (read(id_fd, &min_accept, sizeof(u32)) > 0)
lseek(id_fd, 0, SEEK_SET);

next_min_accept = min_accept;

/* Show stats */

sprintf(stage_tmp, "sync %u", ++sync_cnt);
stage_name = stage_tmp;
stage_cur = 0;
stage_max = 0;

/* For every file queued by this fuzzer, parse ID and see if we have looked at
it before; exec a test case if not. */

while ((qd_ent = readdir(qd))) {

u8* path;
s32 fd;
struct stat st;

if (qd_ent->d_name[0] == '.' ||
sscanf(qd_ent->d_name, CASE_PREFIX "%06u", &syncing_case) != 1 ||
syncing_case < min_accept) continue;

/* OK, sounds like a new one. Let's give it a try. */

if (syncing_case >= next_min_accept)
next_min_accept = syncing_case + 1;

path = alloc_printf("%s/%s", qd_path, qd_ent->d_name);

/* Allow this to fail in case the other fuzzer is resuming or so... */

fd = open(path, O_RDONLY);

if (fd < 0) {
ck_free(path);
continue;
}

if (fstat(fd, &st)) PFATAL("fstat() failed");

/* Ignore zero-sized or oversized files. */

if (st.st_size && st.st_size <= MAX_FILE) {

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

if (mem == MAP_FAILED) PFATAL("Unable to mmap '%s'", path);

/* See what happens. We rely on save_if_interesting() to catch major
errors and save the test case. */

write_to_testcase(mem, st.st_size);

fault = run_target(argv, exec_tmout);//执行这个target,获取fault状态

if (stop_soon) return;

syncing_party = sd_ent->d_name;
queued_imported += save_if_interesting(argv, mem, st.st_size, fault);//根据收集到的相关执行状态等信息判断这个case是否interesting,如果有趣则保存,返回1
syncing_party = 0;

munmap(mem, st.st_size);

if (!(stage_cur++ % stats_update_freq)) show_stats();//每执行stats_update_freq次,更新一次stats

}

ck_free(path);
close(fd);

}

ck_write(id_fd, &next_min_accept, sizeof(u32), qd_synced_path);

close(id_fd);
closedir(qd);
ck_free(qd_path);
ck_free(qd_synced_path);

}

closedir(sd);

}


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

static void handle_stop_sig(int sig) {

stop_soon = 1;

if (child_pid > 0) kill(child_pid, SIGKILL);
if (forksrv_pid > 0) kill(forksrv_pid, SIGKILL);

}


/* Handle skip request (SIGUSR1). */

static void handle_skipreq(int sig) {

skip_requested = 1;

}

/* Handle timeout (SIGALRM). */

static void handle_timeout(int sig) {

if (child_pid > 0) {

child_timed_out = 1;
kill(child_pid, SIGKILL);

} else if (child_pid == -1 && forksrv_pid > 0) {

child_timed_out = 1;
kill(forksrv_pid, SIGKILL);

}

}


/* 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. */

EXP_ST void check_binary(u8* fname) {

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"))) {

target_path = ck_strdup(fname);
if (stat(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);
//存在文件,文件正常,可执行,target binary的size必须大于等于4bytes
} else {

while (env_path) {

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

if (delim) {

cur_elem = ck_alloc(delim - env_path + 1);
memcpy(cur_elem, env_path, delim - env_path);
delim++;

} else cur_elem = ck_strdup(env_path);

env_path = delim;

if (cur_elem[0])
target_path = alloc_printf("%s/%s", cur_elem, fname);
else
target_path = ck_strdup(fname);

ck_free(cur_elem);

if (!stat(target_path, &st) && S_ISREG(st.st_mode) &&
(st.st_mode & 0111) && (f_len = st.st_size) >= 4) break;

ck_free(target_path);
target_path = 0;

}

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

}

if (getenv("AFL_SKIP_BIN_CHECK")) return;

/* Check for blatant user errors. */

if ((!strncmp(target_path, "/tmp/", 5) && !strchr(target_path + 5, '/')) ||
(!strncmp(target_path, "/var/tmp/", 9) && !strchr(target_path + 9, '/')))
FATAL("Please don't keep binaries in /tmp or /var/tmp");

fd = open(target_path, O_RDONLY);

if (fd < 0) PFATAL("Unable to open '%s'", 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'", target_path);

close(fd);

if (f_data[0] == '#' && f_data[1] == '!') {
//识别target是否是脚本。
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", target_path);

}

#ifndef __APPLE__

if (f_data[0] != 0x7f || memcmp(f_data + 1, "ELF", 3))
FATAL("Program '%s' is not an ELF binary", target_path);

#else

if (f_data[0] != 0xCF || f_data[1] != 0xFA || f_data[2] != 0xED)
FATAL("Program '%s' is not a 64-bit Mach-O binary", target_path);

#endif /* ^!__APPLE__ */

if (!qemu_mode && !dumb_mode &&
!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.\n\n"

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

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

FATAL("No instrumentation detected");

}

if (qemu_mode &&
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 - this setup will be\n"
" slow and offer no practical benefits.\n");

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

}

if (memmem(f_data, f_len, "libasan.so", 10) ||
memmem(f_data, f_len, "__msan_init", 11)) uses_asan = 1;

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

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

OKF(cPIN "Persistent mode binary detected.");
setenv(PERSIST_ENV_VAR, "1", 1);
persistent_mode = 1;

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

WARNF("AFL_PERSISTENT is no longer supported and may misbehave!");

}

if (memmem(f_data, f_len, DEFER_SIG, strlen(DEFER_SIG) + 1)) {

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

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

WARNF("AFL_DEFER_FORKSRV is no longer supported and may misbehave!");

}

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

}


/* Trim and possibly create a banner for the run. */

static void fix_up_banner(u8* name) {

if (!use_banner) {

if (sync_id) {

use_banner = sync_id;

} else {

u8* trim = strrchr(name, '/');
if (!trim) use_banner = name; else use_banner = trim + 1;

}

}

if (strlen(use_banner) > 40) {

u8* tmp = ck_alloc(44);
sprintf(tmp, "%.40s...", use_banner);
use_banner = tmp;

}

}


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

static void check_if_tty(void) {

struct winsize ws;

if (getenv("AFL_NO_UI")) {
OKF("Disabling the UI because AFL_NO_UI is set.");
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.");
not_on_tty = 1;
}

return;
}

}


/* Check terminal dimensions after resize. */

static void check_term_size(void) {

struct winsize ws;

term_too_small = 0;

if (ioctl(1, TIOCGWINSZ, &ws)) return;

if (ws.ws_row == 0 && ws.ws_col == 0) return;
if (ws.ws_row < 25 || ws.ws_col < 80) term_too_small = 1;

}



/* Display usage hints. */

static void usage(u8* argv0) {

SAYF("\n%s [ options ] -- /path/to/fuzzed_app [ ... ]\n\n"

"Required parameters:\n\n"

" -i dir - input directory with test cases\n"
" -o dir - output directory for fuzzer findings\n\n"

"Execution control settings:\n\n"

" -f file - location read by the fuzzed program (stdin)\n"
" -t msec - timeout for each run (auto-scaled, 50-%u ms)\n"
" -m megs - memory limit for child process (%u MB)\n"
" -Q - use binary-only instrumentation (QEMU mode)\n\n"

"Fuzzing behavior settings:\n\n"

" -d - quick & dirty mode (skips deterministic steps)\n"
" -n - fuzz without instrumentation (dumb mode)\n"
" -x dir - optional fuzzer dictionary (see README)\n\n"

"Other stuff:\n\n"

" -T text - text banner to show on the screen\n"
" -M / -S id - distributed mode (see parallel_fuzzing.txt)\n"
" -C - crash exploration mode (the peruvian rabbit thing)\n"
" -V - show version number and exit\n\n"
" -b cpu_id - bind the fuzzing process to the specified CPU core\n\n"

"For additional tips, please consult %s/README.\n\n",

argv0, EXEC_TIMEOUT, MEM_LIMIT, doc_path);

exit(1);

}


/* Prepare output directories and fds. */

EXP_ST void setup_dirs_fds(void) {

u8* tmp;
s32 fd;

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

if (sync_id && mkdir(sync_dir, 0700) && errno != EEXIST)
PFATAL("Unable to create '%s'", sync_dir);

if (mkdir(out_dir, 0700)) {

if (errno != EEXIST) PFATAL("Unable to create '%s'", out_dir);

maybe_delete_out_dir();

} else {

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

out_dir_fd = open(out_dir, O_RDONLY);

#ifndef __sun

if (out_dir_fd < 0 || flock(out_dir_fd, LOCK_EX | LOCK_NB))
PFATAL("Unable to flock() output directory.");

#endif /* !__sun */

}

/* Queue directory for any starting & discovered paths. */
//queue目录存放起始和发现的路径。路径?
tmp = alloc_printf("%s/queue", 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/", 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/", 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/", 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/", 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/", out_dir);
if (mkdir(tmp, 0700)) PFATAL("Unable to create '%s'", tmp);
ck_free(tmp);

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

if (sync_id) {

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

if (mkdir(tmp, 0700) && (!in_place_resume || errno != EEXIST))
PFATAL("Unable to create '%s'", tmp);

ck_free(tmp);

}

/* All recorded crashes. */

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

/* All recorded hangs. */

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

/* Generally useful file descriptors. */

dev_null_fd = open("/dev/null", O_RDWR);
if (dev_null_fd < 0) PFATAL("Unable to open /dev/null");

dev_urandom_fd = open("/dev/urandom", O_RDONLY);
if (dev_urandom_fd < 0) PFATAL("Unable to open /dev/urandom");

/* Gnuplot output file. */

tmp = alloc_printf("%s/plot_data", out_dir);
fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) PFATAL("Unable to create '%s'", tmp);
ck_free(tmp);

plot_file = fdopen(fd, "w");
if (!plot_file) PFATAL("fdopen() failed");

fprintf(plot_file, "# unix_time, cycles_done, cur_path, paths_total, "
"pending_total, pending_favs, map_size, unique_crashes, "
"unique_hangs, max_depth, execs_per_sec\n");
/* ignore errors */

}


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

EXP_ST void setup_stdio_file(void) {

u8* fn = alloc_printf("%s/.cur_input", out_dir);

unlink(fn); /* Ignore errors */

out_fd = open(fn, O_RDWR | O_CREAT | O_EXCL, 0600);

if (out_fd < 0) PFATAL("Unable to create '%s'", fn);

ck_free(fn);

}


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

static 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 (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");

if (!getenv("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\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. */

static void check_cpu_governor(void) {
//reference:https://zhuanlan.zhihu.com/p/33753019
FILE* f;
u8 tmp[128];
u64 min = 0, max = 0;

if (getenv("AFL_SKIP_CPUFREQ")) return;

f = fopen("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", "r");
if (!f) 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' with\n"
" 'ondemand'. If you don't want to change the 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");

}


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

static void get_core_count(void) {

u32 cur_runnable = 0;

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

size_t s = sizeof(cpu_core_count);

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

#ifdef __APPLE__

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

#else

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

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

#endif /* ^__APPLE__ */

#else

#ifdef HAVE_AFFINITY

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])) cpu_core_count++;

fclose(f);

#endif /* ^HAVE_AFFINITY */

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

if (cpu_core_count > 0) {

cur_runnable = (u32)get_runnable_processes();

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

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

cur_runnable++;

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

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

if (cpu_core_count > 1) {

if (cur_runnable > cpu_core_count * 1.5) {

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

} else if (cur_runnable + 1 <= cpu_core_count) {

OKF("Try parallel jobs - see %s/parallel_fuzzing.txt.", doc_path);

}

}

} else {

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

}

}


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

static void fix_up_sync(void) {

u8* x = sync_id;

if (dumb_mode)
FATAL("-S / -M and -n are mutually exclusive");//并行fuzzing 不允许非插桩模式

if (skip_deterministic) {

if (force_deterministic)
FATAL("use -S instead of -M -d");//Master强制开启deterministic 因此不能对Master附加skip_deterministic
else
FATAL("-S already implies -d");//从fuzzer暗含了skip_deterministic

}

while (*x) {

if (!isalnum(*x) && *x != '_' && *x != '-')//限制fuzzer_id仅能使用字母数字和'_','-'
FATAL("Non-alphanumeric fuzzer ID specified via -S or -M");

x++;

}

if (strlen(sync_id) > 32) FATAL("Fuzzer ID too long");//id长度不超过32位

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

sync_dir = out_dir;
out_dir = x;//原来预设的out_dir作为同步目录sync_dir 将out_dir/sync_id作为当前主/从fuzzer各自的输出目录

if (!force_deterministic) {
skip_deterministic = 1;
use_splicing = 1;
}

}


/* Handle screen resize (SIGWINCH). */

static void handle_resize(int sig) {
clear_screen = 1;
}


/* Check ASAN options. */

static void check_asan_opts(void) {
u8* x = getenv("ASAN_OPTIONS");

if (x) {

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

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

}

x = getenv("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 (!strstr(x, "symbolize=0"))
FATAL("Custom MSAN_OPTIONS set without symbolize=0 - please fix!");

}

}


/* Detect @@ in args. */

EXP_ST void detect_file_args(char** argv) {

u32 i = 0;
u8* cwd = getcwd(NULL, 0);//current working direction

if (!cwd) PFATAL("getcwd() failed");

while (argv[i]) {

u8* aa_loc = strstr(argv[i], "@@");

if (aa_loc) {

u8 *aa_subst, *n_arg;

/* If we don't have a file name chosen yet, use a safe default. */

if (!out_file)//和-f参数相关联,如果没有给输出文件的名称,就使用".cur_input"作为默认名称
out_file = alloc_printf("%s/.cur_input", out_dir);

/* Be sure that we're always using fully-qualified paths. */

if (out_file[0] == '/') aa_subst = out_file;//检测out_file[0]是否是绝对路径
else aa_subst = alloc_printf("%s/%s", cwd, out_file);//如果不是的话就用cwd作为路径

/* Construct a replacement argv value. */

*aa_loc = 0;
n_arg = alloc_printf("%s%s%s", argv[i], aa_subst, aa_loc + 2);
argv[i] = n_arg;//把@@替换成aa_subst
*aa_loc = '@';

if (out_file[0] != '/') ck_free(aa_subst);

}

i++;

}

free(cwd); /* not tracked */

}


/* 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 unnecessary things. */

EXP_ST void setup_signal_handlers(void) {

struct sigaction sa;
// struct sigaction
// {
// void (*sa_handler)(int);
// void (*sa_sigaction)(int, siginfo_t *, void *);
// sigset_t sa_mask;
// int sa_flags;
// void (*sa_restorer)(void);
// };
//reference:https://www.cnblogs.com/wblyuyang/archive/2012/11/13/2768923.html
sa.sa_handler = NULL;
sa.sa_flags = SA_RESTART;
sa.sa_sigaction = NULL;

sigemptyset(&sa.sa_mask);//将信号集初始化为空

/* Various ways of saying "stop". */
// #include <signal.h>
// int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
// signum:要操作的信号 act:要设置的对该信号的处理方法 oldact:该信号的原处理方法

//reference:https://zh.wikipedia.org/wiki/Unix%E4%BF%A1%E5%8F%B7
sa.sa_handler = handle_stop_sig;
sigaction(SIGHUP, &sa, NULL);//挂起
sigaction(SIGINT, &sa, NULL);//终端中断信号
sigaction(SIGTERM, &sa, NULL);//终止信号
//为SIGHUP,SIGINT,SIGTERM注册handle_stop_sig处理函数
/* Exec timeout notifications. */

sa.sa_handler = handle_timeout;
sigaction(SIGALRM, &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);//用户自定义信号1 此处为忽略入口

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

sa.sa_handler = SIG_IGN;
sigaction(SIGTSTP, &sa, NULL);//终端中止信号
sigaction(SIGPIPE, &sa, NULL);//写入一个没有连接另一端的管道

}


/* Rewrite argv for QEMU. */

static char** get_qemu_argv(u8* own_loc, char** argv, int argc) {

char** new_argv = ck_alloc(sizeof(char*) * (argc + 4));
u8 *tmp, *cp, *rsl, *own_copy;

/* Workaround for a QEMU stability glitch. */

setenv("QEMU_LOG", "nochain", 1);

memcpy(new_argv + 3, argv + 1, sizeof(char*) * argc);

new_argv[2] = target_path;
new_argv[1] = "--";

/* Now we need to actually find the QEMU binary to put in argv[0]. */

tmp = getenv("AFL_PATH");

if (tmp) {

cp = alloc_printf("%s/afl-qemu-trace", tmp);//尝试从AFL_PATH里找qemu

if (access(cp, X_OK))
FATAL("Unable to find '%s'", tmp);

target_path = new_argv[0] = cp;
return new_argv;

}

own_copy = ck_strdup(own_loc);
rsl = strrchr(own_copy, '/');

if (rsl) {

*rsl = 0;

cp = alloc_printf("%s/afl-qemu-trace", own_copy);
ck_free(own_copy);

if (!access(cp, X_OK)) {

target_path = new_argv[0] = cp;
return new_argv;

}

} else ck_free(own_copy);

if (!access(BIN_PATH "/afl-qemu-trace", X_OK)) {

target_path = new_argv[0] = ck_strdup(BIN_PATH "/afl-qemu-trace");
return new_argv;

}

SAYF("\n" cLRD "[-] " cRST
"Oops, unable to find the 'afl-qemu-trace' binary. The binary must be built\n"
" separately by following the instructions in qemu_mode/README.qemu. If you\n"
" already have the binary installed, you may need to specify AFL_PATH in the\n"
" environment.\n\n"

" Of course, even without QEMU, afl-fuzz can still work with binaries that are\n"
" instrumented at compile time with afl-gcc. It is also possible to use it as a\n"
" traditional \"dumb\" fuzzer by specifying '-n' in the command line.\n");

FATAL("Failed to locate 'afl-qemu-trace'.");

}


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

static void save_cmdline(u32 argc, char** argv) {

u32 len = 1, i;
u8* buf;

for (i = 0; i < argc; i++)
len += strlen(argv[i]) + 1;

buf = orig_cmdline = ck_alloc(len);

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

u32 l = strlen(argv[i]);

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

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

}

*buf = 0;

}


#ifndef AFL_LIB

/* Main entry point */

int main(int argc, char** argv) {

s32 opt;
u64 prev_queued = 0;
u32 sync_interval_cnt = 0, seek_to;
u8 *extras_dir = 0;
u8 mem_limit_given = 0;
u8 exit_1 = !!getenv("AFL_BENCH_JUST_ONE");
char** use_argv;

struct timeval tv;
struct timezone tz;

SAYF(cCYA "afl-fuzz " cBRI VERSION cRST " by <lcamtuf@google.com>\n");

doc_path = access(DOC_PATH, F_OK) ? "docs" : DOC_PATH;

gettimeofday(&tv, &tz);
srandom(tv.tv_sec ^ tv.tv_usec ^ getpid());

while ((opt = getopt(argc, argv, "+i:o:f:m:b:t:T:dnCB:S:M:x:QV")) > 0)//分析命令行参数 第三个参数为选项字符串optstring,"o:"表示"o"后必须带参数,中间有无空格都接受;两个冒号表示参数可选,但有参数时,参数和选项之间不能带空格;optstring如果以'+'起始,表示不能包含optstring以外的参数,否则getopt停止,并返回-1
//reference:http://www.cnitblog.com/zouzheng/archive/2007/04/02/25034.aspx
//reference:https://www.cnblogs.com/yusenwu/p/4756219.html

switch (opt) {

case 'i': /* input dir */

if (in_dir) FATAL("Multiple -i options not supported");
in_dir = optarg;

if (!strcmp(in_dir, "-")) in_place_resume = 1;//resume?恢复?继续执行上一次fuzzing?

break;

case 'o': /* output dir */

if (out_dir) FATAL("Multiple -o options not supported");
out_dir = optarg;
break;

case 'M': { /* master sync ID */
//并行fuzzing,通过-M设置主fuzzer
u8* c;

if (sync_id) FATAL("Multiple -S or -M options not supported");
sync_id = ck_strdup(optarg);//ck_strdup:分配一个chunk,并将optarg copy进chunk

if ((c = strchr(sync_id, ':'))) {//sync_id中第一次搜索到':'的位置

*c = 0;

if (sscanf(c + 1, "%u/%u", &master_id, &master_max) != 2 ||
!master_id || !master_max || master_id > master_max ||
master_max > 1000000) FATAL("Bogus master ID passed to -M");//从c+1(即sync_id的':'后一位)读取两个数值,master_id(当前主fuzzer的id)和master_max(允许的主fuzzer最大数量,难道还能复数个master的吗),同时id和max都为非零,id必须不大于max,max不能超过100,0000
//这里有一点,很多博客上写的-M -S的用法比如"-M fuzzer1",也不会导致afl-fuzz报错,只是会跳过这一段check
}

force_deterministic = 1;//强制开启deterministic阶段

}

break;

case 'S':
//并行fuzzing 设置从fuzzer slave
if (sync_id) FATAL("Multiple -S or -M options not supported");
sync_id = ck_strdup(optarg);
break;

case 'f': /* target file */

if (out_file) FATAL("Multiple -f options not supported");
out_file = optarg;
break;

case 'x': /* dictionary */

if (extras_dir) FATAL("Multiple -x options not supported");
extras_dir = optarg;
break;

case 't': { /* timeout */
//设置afl-fuzz对测试程序每次执行判定超时的阈值
u8 suffix = 0;

if (timeout_given) FATAL("Multiple -t options not supported");

if (sscanf(optarg, "%u%c", &exec_tmout, &suffix) < 1 ||
optarg[0] == '-') FATAL("Bad syntax used for -t");//从optarg中读取一个数值作为timeout的数值,再读取一个字符作为后缀

if (exec_tmout < 5) FATAL("Dangerously low value of -t");

if (suffix == '+') timeout_given = 2; else timeout_given = 1;//具体可以看line 2792 后缀'+'表示依旧设置timeout,但是忽略这一事件,不把这一输入放入输入队列

break;

}

case 'm': { /* mem limit */
//设置afl-fuzz允许使用的内存上限
u8 suffix = 'M';

if (mem_limit_given) FATAL("Multiple -m options not supported");
mem_limit_given = 1;

if (!strcmp(optarg, "none")) {
//参数none表示不限制内存限制
mem_limit = 0;
break;

}

if (sscanf(optarg, "%llu%c", &mem_limit, &suffix) < 1 ||
optarg[0] == '-') FATAL("Bad syntax used for -m");//允许内存大小带后缀,afl-fuzz识别K,M,G,T四个后缀,默认为M

switch (suffix) {

case 'T': mem_limit *= 1024 * 1024; break;
case 'G': mem_limit *= 1024; break;
case 'k': mem_limit /= 1024; break;
case 'M': break;

default: FATAL("Unsupported suffix or bad syntax for -m");

}

if (mem_limit < 5) FATAL("Dangerously low value of -m");

if (sizeof(rlim_t) == 4 && mem_limit > 2000)//sizeof(rlim_t)用来判断当前系统是32位还是64位,32位系统下限制内存资源不超过2000M
FATAL("Value of -m out of range on 32-bit systems");

}

break;

case 'b': { /* bind CPU core */
//绑定空闲的CPU核心
if (cpu_to_bind_given) FATAL("Multiple -b options not supported");
cpu_to_bind_given = 1;

if (sscanf(optarg, "%u", &cpu_to_bind) < 1 ||
optarg[0] == '-') FATAL("Bad syntax used for -b");

break;

}

case 'd': /* skip deterministic */
//选择跳过deterministic阶段,直接进行havoc stage
//deterministic阶段包括 bit/byte flips, arithmetics, interesting values, dictionary, extra这几个阶段
if (skip_deterministic) FATAL("Multiple -d options not supported");
skip_deterministic = 1;
use_splicing = 1;//mutation中激活splicing拼接方式
break;

case 'B': /* load bitmap */

/* This is a secret undocumented option! It is useful if you find
an interesting test case during a normal fuzzing process, and want
to mutate it without rediscovering any of the test cases already
found during an earlier run.

To use this mode, you need to point -B to the fuzz_bitmap produced
by an earlier run for the exact same binary... and that's it.

I only used this once or twice to get variants of a particular
file, so I'm not making this an official setting. */
//没写进文档里的一个选项,有趣。
//直接导入一个早先测试中得到的bitmap,这样就能在本次测试中避免从头开始fuzzing
if (in_bitmap) FATAL("Multiple -B options not supported");

in_bitmap = optarg;
read_bitmap(in_bitmap);//把bitmap写进virgin_bits
break;

case 'C': /* crash mode */
//crash mode具体可以看https://lcamtuf.blogspot.com/2014/11/afl-fuzz-crash-exploration-mode.html
//允许使用crash作为testcase进行测试,这样可以在短时间内生成少量相关但略有不同的crash
if (crash_mode) FATAL("Multiple -C options not supported");
crash_mode = FAULT_CRASH;//这里会给crash_mode赋值2,后续逻辑中时常会出现fault==crash_mode 就是考虑是否出现了crash,同时afl开启了crash mode
break;

case 'n': /* dumb mode */
//不插桩模式
if (dumb_mode) FATAL("Multiple -n options not supported");
if (getenv("AFL_DUMB_FORKSRV")) dumb_mode = 2; else dumb_mode = 1;//1为不插桩不开启forkserver;2为不插桩,启动forkserver

break;

case 'T': /* banner */

if (use_banner) FATAL("Multiple -T options not supported");
use_banner = optarg;
break;

case 'Q': /* QEMU mode */

if (qemu_mode) FATAL("Multiple -Q options not supported");
qemu_mode = 1;

if (!mem_limit_given) mem_limit = MEM_LIMIT_QEMU;//如果没有设置-m 此处默认内存限制 #define MEM_LIMIT_QEMU 200

break;

case 'V': /* Show version number */

/* Version number has been printed already, just quit. */
exit(0);

default:

usage(argv[0]);

}

if (optind == argc || !in_dir || !out_dir) usage(argv[0]);//optind argv的当前索引值

setup_signal_handlers();//设置信号处理函数
check_asan_opts();//检查ASAN选项是否正确设置

if (sync_id) fix_up_sync();//如果参数带了-M或-S 就去设置输出和同步目录

if (!strcmp(in_dir, out_dir))
FATAL("Input and output directories can't be the same");

if (dumb_mode) {

if (crash_mode) FATAL("-C and -n are mutually exclusive");
if (qemu_mode) FATAL("-Q and -n are mutually exclusive");//不插桩用不了crash mode和qemu mode

}

if (getenv("AFL_NO_FORKSRV")) no_forkserver = 1;
if (getenv("AFL_NO_CPU_RED")) no_cpu_meter_red = 1;
if (getenv("AFL_NO_ARITH")) no_arith = 1;//跳过deterministic stage里的arithmetic stage
if (getenv("AFL_SHUFFLE_QUEUE")) shuffle_queue = 1;//对输入队列进行洗牌
if (getenv("AFL_FAST_CAL")) fast_cal = 1;//快速校准

if (getenv("AFL_HANG_TMOUT")) {
hang_tmout = atoi(getenv("AFL_HANG_TMOUT"));
if (!hang_tmout) FATAL("Invalid value of AFL_HANG_TMOUT");
}

if (dumb_mode == 2 && no_forkserver)
FATAL("AFL_DUMB_FORKSRV and AFL_NO_FORKSRV are mutually exclusive");

if (getenv("AFL_PRELOAD")) {
setenv("LD_PRELOAD", getenv("AFL_PRELOAD"), 1);//可以使用AFL_PRELOAD来设置LD_PRELOAD
//动态库加载顺序 LD_PRELOAD > LD_LIBRARY_PATH > /etc/ld.so.cache > /lib>/usr/lib
setenv("DYLD_INSERT_LIBRARIES", getenv("AFL_PRELOAD"), 1);
}

if (getenv("AFL_LD_PRELOAD"))
FATAL("Use AFL_PRELOAD instead of AFL_LD_PRELOAD");

save_cmdline(argc, argv);//copy一份当前的命令行

fix_up_banner(argv[optind]);

check_if_tty();//查看当前是否在tty中。如果不在tty中的话,AFL会将输出信息作精简

get_core_count();//获取cpu核心数量

#ifdef HAVE_AFFINITY
bind_to_free_cpu();
#endif /* HAVE_AFFINITY */

check_crash_handling();//设置core dump,检查/proc/sys/kernel/core_pattern
check_cpu_governor();//检查CPU调频策略。ondemand策略算法不完善,可能会错过afl-fuzz产生的短暂进程

setup_post();//加载postprocessor
setup_shm();//分配shared memory和virgin_bits空间
init_count_class16();//根据ount_class_lookup8创建一个ount_class_lookup16

setup_dirs_fds();//设置输出目录out_dir,包括该目录下的若干子目录
read_testcases();//从input_dir读取所有测试用例,放入队列
load_auto();//加载自动生成的extras

pivot_inputs();//设置输出目录里的测试用例的硬链接

if (extras_dir) load_extras(extras_dir);//加载extra目录里的extras

if (!timeout_given) find_timeout();//如果没有设置timeout,如果先前已经有对目标进行过fuzzing,就去in_dir和out_dir里的fuzzer_stats里找exec_timeout

detect_file_args(argv + optind + 1);//检测命令行中的@@

if (!out_file) setup_stdio_file();//没有设置-f的话,就用.cur_input作默认stdio文件名

check_binary(argv[optind]);//检查target binary:确保其存在且不是shell script;文件存在且可执行;文件路径不是/tmp或/var/tmp;非qemu mode或dumb mode下,target binary已经完成插桩

start_time = get_cur_time();

if (qemu_mode)
use_argv = get_qemu_argv(argv[0], argv + optind, argc - optind);//qemu模式下 为QEMU重写命令行参数
else
use_argv = argv + optind;

perform_dry_run(use_argv);//测试执行in_dir中所有testcase

cull_queue();//精简队列,遍历top_rate中的条目,依次获取先前未见过的字节(temp_v)中的winner并标记位favored,favored条目在fuzzing过程中会得到更多的air time

show_init_stats();//在处理input_dir的最后显示一些快速的统计信息和一些warning.一些校准的东西和一些硬编码的常数也都在这里结束.

seek_to = find_start_position();//如果是first run,直接返回0,如果是resuming fuzz,就从out_dir的stats中找开始点

write_stats_file(0, 0, 0);//更新stats_file
save_auto();//保存自动生成的extras

if (stop_soon) goto stop_fuzzing;

/* Woop woop woop */

if (!not_on_tty) {//确认一下在不在tty上
sleep(4);
start_time += 4000;
if (stop_soon) goto stop_fuzzing;
}

while (1) {//主循环

u8 skipped_fuzz;

cull_queue();//精简队列

if (!queue_cur) {//如果queue_cur当前队列中的偏移为0,认为队列已空,那就开启新的一轮

queue_cycle++;//queue_cycle表示已完成的轮数
current_entry = 0;//复位当前的队列条目ID
cur_skipped_paths = 0;//复位当前cycle中舍弃的输入
queue_cur = queue;//复位,回到queue的头部

while (seek_to) {//seek_to = find_start_position() 这个循环就是把current_entry和queue_cur定位到start_position
current_entry++;
seek_to--;
queue_cur = queue_cur->next;
}

show_stats();//显示经典的数据统计窗口.此外该函数中每分钟会更新fuzzer stats,auto tokens,保存bitmap

if (not_on_tty) {
ACTF("Entering queue cycle %llu.", queue_cycle);
fflush(stdout);
}

/* If we had a full queue cycle with no new finds, try
recombination strategies next. */

if (queued_paths == prev_queued) {//如果当前队列中的测试用例数与上一轮中队列中测试用例数相等

if (use_splicing) cycles_wo_finds++; else use_splicing = 1;//如果用了splicing,但还是没新发现,那就cycles_wo_finds++,否则就启用splicing,尝试找新发现

} else cycles_wo_finds = 0;//两轮测试用例数不等,说明有新发现,那cycles_wo_finds复位

prev_queued = queued_paths;

if (sync_id && queue_cycle == 1 && getenv("AFL_IMPORT_FIRST"))//如果设置了-M或-S,afl会在执行操作之前先从其他instance中获取测试用例
sync_fuzzers(use_argv);//从同步目录sync_dir中获取有趣的测试用例

}

skipped_fuzz = fuzz_one(use_argv);//最核心的fuzz_one 包括testcase的变异策略都在这其中进行.如果成功fuzz,返回0;如果被跳过或者bailed out,返回1

if (!stop_soon && sync_id && !skipped_fuzz) {

if (!(sync_interval_cnt++ % SYNC_INTERVAL))
sync_fuzzers(use_argv);

}

if (!stop_soon && exit_1) stop_soon = 2;

if (stop_soon) break;

queue_cur = queue_cur->next;
current_entry++;

}

if (queue_cur) show_stats();

/* If we stopped programmatically, we kill the forkserver and the current runner.
If we stopped manually, this is done by the signal handler. */
if (stop_soon == 2) {
if (child_pid > 0) kill(child_pid, SIGKILL);
if (forksrv_pid > 0) kill(forksrv_pid, SIGKILL);
}
/* Now that we've killed the forkserver, we wait for it to be able to get rusage stats. */
if (waitpid(forksrv_pid, NULL, 0) <= 0) {
WARNF("error waitpid\n");
}

write_bitmap();
write_stats_file(0, 0, 0);
save_auto();

stop_fuzzing:

SAYF(CURSOR_SHOW cLRD "\n\n+++ Testing aborted %s +++\n" cRST,
stop_soon == 2 ? "programmatically" : "by user");

/* Running for more than 30 minutes but still doing first cycle? */

if (queue_cycle == 1 && get_cur_time() - start_time > 30 * 60 * 1000) {

SAYF("\n" cYEL "[!] " cRST
"Stopped during the first cycle, results may be incomplete.\n"
" (For info on resuming, see %s/README.)\n", doc_path);

}

fclose(plot_file);
destroy_queue();
destroy_extras();
ck_free(target_path);
ck_free(sync_id);

alloc_report();

OKF("We're done here. Have a nice day!\n");

exit(0);

}

#endif /* !AFL_LIB */