/
afl_state.hpp
1857 lines (1457 loc) · 63.3 KB
/
afl_state.hpp
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
/*
* fuzzuf
* Copyright (C) 2021 Ricerca Security
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
#pragma once
#include <sys/ioctl.h>
#include <vector>
#include <string>
#include <memory>
#include "fuzzuf/logger/logger.hpp"
#include "fuzzuf/utils/common.hpp"
#include "fuzzuf/utils/filesystem.hpp"
#include "fuzzuf/exec_input/exec_input.hpp"
#include "fuzzuf/exec_input/exec_input_set.hpp"
#include "fuzzuf/executor/native_linux_executor.hpp"
#include "fuzzuf/feedback/inplace_memory_feedback.hpp"
#include "fuzzuf/feedback/exit_status_feedback.hpp"
#include "fuzzuf/algorithms/afl/afl_option.hpp"
#include "fuzzuf/algorithms/afl/afl_setting.hpp"
#include "fuzzuf/algorithms/afl/afl_util.hpp"
#include "fuzzuf/algorithms/afl/afl_macro.hpp"
#include "fuzzuf/algorithms/afl/afl_dict_data.hpp"
#include "fuzzuf/algorithms/afl/afl_update_hierarflow_routines.hpp"
namespace fuzzuf::algorithm::afl {
// FIXME: check if we are initializing all the members that need to be initialized
template<class Testcase>
AFLStateTemplate<Testcase>::AFLStateTemplate(
std::shared_ptr<const AFLSetting> setting,
std::shared_ptr<NativeLinuxExecutor> executor
)
: setting( setting ),
executor( executor ),
input_set(),
rand_fd( Util::OpenFile("/dev/urandom", O_RDONLY | O_CLOEXEC) ),
should_construct_auto_dict(false)
{
if (in_bitmap.empty()) virgin_bits.assign(option::GetMapSize<Tag>(), 255);
else {
ReadBitmap(in_bitmap);
}
/* Gnuplot output file. */
auto plot_fn = setting->out_dir / "plot_data";
plot_file = fopen(plot_fn.c_str(), "w");
if (!plot_file) ERROR("Unable to create '%s'", plot_fn.c_str());
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");
}
template<class Testcase>
AFLStateTemplate<Testcase>::~AFLStateTemplate() {
if (rand_fd != -1) {
Util::CloseFile(rand_fd);
rand_fd = -1;
}
fclose(plot_file);
}
template<class Testcase>
InplaceMemoryFeedback AFLStateTemplate<Testcase>::RunExecutorWithClassifyCounts(
const u8* buf,
u32 len,
ExitStatusFeedback &exit_status,
u32 tmout
) {
total_execs++;
if (tmout == 0) {
executor->Run(buf, len);
} else {
executor->Run(buf, len, tmout);
}
auto inp_feed = executor->GetAFLFeedback();
exit_status = executor->GetExitStatusFeedback();
if constexpr (sizeof(size_t) == 8) {
inp_feed.ModifyMemoryWithFunc(
[](u8* trace_bits, u32 map_size) {
afl::util::ClassifyCounts<u64>((u64*)trace_bits, map_size);
}
);
} else {
inp_feed.ModifyMemoryWithFunc(
[](u8* trace_bits, u32 map_size) {
afl::util::ClassifyCounts<u32>((u32*)trace_bits, map_size);
}
);
}
return InplaceMemoryFeedback(std::move(inp_feed));
}
template<class Testcase>
PUTExitReasonType AFLStateTemplate<Testcase>::CalibrateCaseWithFeedDestroyed(
Testcase &testcase,
const u8 *buf,
u32 len,
InplaceMemoryFeedback &inp_feed,
ExitStatusFeedback &exit_status,
u32 handicap,
bool from_queue
) {
std::array<u8, option::GetMapSize<Tag>()> first_trace;
bool first_run = testcase.exec_cksum == 0;
s32 old_sc = stage_cur;
s32 old_sm = stage_max;
std::string old_sn = std::move(stage_name);
u32 use_tmout;
if (!from_queue || resuming_fuzz) {
use_tmout = std::max(setting->exec_timelimit_ms + option::GetCalTmoutAdd(*this),
setting->exec_timelimit_ms * option::GetCalTmoutPerc(*this) / 100);
} else {
use_tmout = setting->exec_timelimit_ms;
}
testcase.cal_failed++;
stage_name = "calibration";
stage_max = fast_cal ? 3 : option::GetCalCycles(*this);
u8 hnb = 0;
u8 new_bits = 0;
if (testcase.exec_cksum) {
inp_feed.ShowMemoryToFunc(
[this, &first_trace, &hnb](const u8* trace_bits, u32 map_size) {
std::memcpy(first_trace.data(), trace_bits, map_size);
hnb = HasNewBits(trace_bits, &virgin_bits[0], map_size);
}
);
if (hnb > new_bits) new_bits = hnb;
}
bool var_detected = false;
u64 start_us = Util::GetCurTimeUs();
u64 stop_us;
for (stage_cur=0; stage_cur < stage_max; stage_cur++) {
if (!first_run && stage_cur % stats_update_freq == 0) {
ShowStats();
}
InplaceMemoryFeedback::DiscardActive(std::move(inp_feed));
inp_feed =
RunExecutorWithClassifyCounts(buf, len, exit_status, use_tmout);
/* stop_soon is set by the handler for Ctrl+C. When it's pressed,
we want to bail out quickly. */
if (stop_soon || exit_status.exit_reason != crash_mode)
goto abort_calibration; // FIXME: goto
if (!setting->dumb_mode && !stage_cur && !inp_feed.CountNonZeroBytes()) {
exit_status.exit_reason = PUTExitReasonType::FAULT_NOINST;
goto abort_calibration; // FIXME: goto
}
u32 cksum = inp_feed.CalcCksum32();
if (testcase.exec_cksum != cksum) {
inp_feed.ShowMemoryToFunc(
[this, &hnb](const u8* trace_bits, u32 map_size) {
hnb = HasNewBits(trace_bits, &virgin_bits[0], map_size);
}
);
if (hnb > new_bits) new_bits = hnb;
if (testcase.exec_cksum) {
inp_feed.ShowMemoryToFunc(
[this, &first_trace](const u8* trace_bits, u32 map_size) {
for (u32 i=0; i < map_size; i++) {
if (!var_bytes[i] && first_trace[i] != trace_bits[i]) {
var_bytes[i] = 1;
stage_max = option::GetCalCyclesLong(*this);
}
}
}
);
var_detected = true;
} else {
testcase.exec_cksum = cksum;
inp_feed.ShowMemoryToFunc(
[&first_trace](const u8* trace_bits, u32 map_size) {
std::memcpy(first_trace.data(), trace_bits, map_size);
}
);
}
}
}
stop_us = Util::GetCurTimeUs();
total_cal_us += stop_us - start_us;
total_cal_cycles += stage_max;
testcase.exec_us = (stop_us - start_us) / stage_max;
testcase.bitmap_size = inp_feed.CountNonZeroBytes();
testcase.handicap = handicap;
testcase.cal_failed = 0;
total_bitmap_size += testcase.bitmap_size;
total_bitmap_entries++;
UpdateBitmapScore(testcase, inp_feed);
/* 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 ( !setting->dumb_mode
&& first_run
&& exit_status.exit_reason == PUTExitReasonType::FAULT_NONE
&& new_bits == 0) {
exit_status.exit_reason = PUTExitReasonType::FAULT_NOBITS;
}
abort_calibration:
if (new_bits == 2 && !testcase.has_new_cov) {
testcase.has_new_cov = true;
queued_with_cov++;
}
/* Mark variable paths. */
if (var_detected) {
var_byte_count = Util::CountBytes(&var_bytes[0], var_bytes.size());
if (!testcase.var_behavior) {
MarkAsVariable(testcase);
queued_variable++;
}
}
stage_name = old_sn;
stage_cur = old_sc;
stage_max = old_sm;
if (!first_run) ShowStats();
return exit_status.exit_reason;
}
// Difference with AFL's add_to_queue:
// if buf is not nullptr, then this function saves "buf" in a file specified by "fn"
template<class Testcase>
std::shared_ptr<Testcase> AFLStateTemplate<Testcase>::AddToQueue(
const std::string &fn,
const u8 *buf,
u32 len,
bool passed_det
) {
auto input = input_set.CreateOnDisk(fn);
if (buf) {
input->OverwriteThenUnload(buf, len);
}
std::shared_ptr<Testcase> testcase( new Testcase(std::move(input)) );
testcase->depth = cur_depth + 1;
testcase->passed_det = passed_det;
if (testcase->depth > max_depth) max_depth = testcase->depth;
case_queue.emplace_back(testcase);
queued_paths++;
pending_not_fuzzed++;
cycles_wo_finds = 0;
last_path_time = Util::GetCurTimeMs();
return testcase;
}
template<class Testcase>
void AFLStateTemplate<Testcase>::UpdateBitmapScoreWithRawTrace(
Testcase &testcase,
const u8 *trace_bits,
u32 map_size
) {
u64 fav_factor = testcase.exec_us * testcase.input->GetLen();
for (u32 i=0; i<map_size; i++) {
if (trace_bits[i]) {
if (top_rated[i]) {
auto &top_testcase = top_rated[i].value().get();
u64 factor = top_testcase.exec_us * top_testcase.input->GetLen();
if (fav_factor > factor) continue;
/* Looks like we're going to win. Decrease ref count for the
previous winner, discard its trace_bits[] if necessary. */
--top_testcase.tc_ref;
if (top_testcase.tc_ref == 0) {
top_testcase.trace_mini.reset();
}
}
/* Insert ourselves as the new winner. */
top_rated[i] = std::ref(testcase);
testcase.tc_ref++;
if (!testcase.trace_mini) {
testcase.trace_mini.reset(
new std::bitset<option::GetMapSize<Tag>()>()
);
auto& trace_mini = *testcase.trace_mini;
for (u32 j=0; j < option::GetMapSize<Tag>(); j++) {
trace_mini[j] = trace_bits[j] != 0;
}
}
score_changed = true;
}
}
}
template<class Testcase>
void AFLStateTemplate<Testcase>::UpdateBitmapScore(
Testcase &testcase,
const InplaceMemoryFeedback &inp_feed
) {
inp_feed.ShowMemoryToFunc(
[this, &testcase](const u8* trace_bits, u32 map_size) {
UpdateBitmapScoreWithRawTrace(testcase, trace_bits, map_size);
}
);
}
template<class Testcase>
bool AFLStateTemplate<Testcase>::SaveIfInteresting(
const u8 *buf,
u32 len,
InplaceMemoryFeedback &inp_feed,
ExitStatusFeedback &exit_status
) {
bool keeping = false;
std::string fn;
if (exit_status.exit_reason == crash_mode) {
/* Keep only if there are new bits in the map, add to queue for
future fuzzing, etc. */
u8 hnb;
inp_feed.ShowMemoryToFunc(
[this, &hnb](const u8* trace_bits, u32 map_size) {
hnb = HasNewBits(trace_bits, &virgin_bits[0], map_size);
}
);
if (!hnb) {
if (crash_mode == PUTExitReasonType::FAULT_CRASH) {
total_crashes++;
}
return false;
}
if (!setting->simple_files) {
fn = Util::StrPrintf("%s/queue/id:%06u,%s",
setting->out_dir.c_str(),
queued_paths,
routine::update::DescribeOp(*this, hnb).c_str()
);
} else {
fn = Util::StrPrintf("%s/queue/id_%06u",
setting->out_dir.c_str(),
queued_paths
);
}
auto testcase = AddToQueue(fn, buf, len, false);
if (hnb == 2) {
testcase->has_new_cov = 1;
queued_with_cov++;
}
testcase->exec_cksum = inp_feed.CalcCksum32();
// inp_feed will may be discard to start a new execution
// in that case inp_feed will receive the new feedback
PUTExitReasonType res = CalibrateCaseWithFeedDestroyed(
*testcase,
buf, len,
inp_feed,
exit_status,
queue_cycle - 1,
false);
if (res == PUTExitReasonType::FAULT_ERROR) {
ERROR("Unable to execute target application");
}
keeping = true;
}
switch (exit_status.exit_reason) {
case PUTExitReasonType::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 >= option::GetKeepUniqueHang(*this)) {
// originally here "return keeping" is used, but this is clearer right?
return false;
}
if (!setting->dumb_mode) {
if constexpr (sizeof(size_t) == 8) {
inp_feed.ModifyMemoryWithFunc(
[](u8* trace_bits, u32 map_size) {
afl::util::SimplifyTrace<u64>((u64*)trace_bits, map_size);
}
);
} else {
inp_feed.ModifyMemoryWithFunc(
[](u8* trace_bits, u32 map_size) {
afl::util::SimplifyTrace<u32>((u32*)trace_bits, map_size);
}
);
}
u8 res;
inp_feed.ShowMemoryToFunc(
[this, &res](const u8* trace_bits, u32 map_size) {
res = HasNewBits(trace_bits, &virgin_tmout[0], map_size);
}
);
if (!res) {
// originally here "return keeping" is used, but this is clearer right?
return false;
}
}
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 (setting->exec_timelimit_ms < hang_tmout) {
// discard inp_feed here because we will use executor
InplaceMemoryFeedback::DiscardActive(std::move(inp_feed));
inp_feed = RunExecutorWithClassifyCounts(
buf, len, exit_status, hang_tmout);
/* 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 && exit_status.exit_reason == PUTExitReasonType::FAULT_CRASH) {
goto keep_as_crash; // FIXME: goto
}
if ( stop_soon
|| exit_status.exit_reason != PUTExitReasonType::FAULT_TMOUT) {
return false;
}
}
if (!setting->simple_files) {
fn = Util::StrPrintf("%s/hangs/id:%06llu,%s",
setting->out_dir.c_str(),
unique_hangs,
routine::update::DescribeOp(*this, 0).c_str()
);
} else {
fn = Util::StrPrintf("%s/hangs/id_%06llu",
setting->out_dir.c_str(),
unique_hangs
);
}
unique_hangs++;
last_hang_time = Util::GetCurTimeMs();
break;
case PUTExitReasonType::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 >= option::GetKeepUniqueCrash(*this)) {
// unlike FAULT_TMOUT case, keeping can be true when "crash mode" is enabled
return keeping;
}
if (!setting->dumb_mode) {
if constexpr (sizeof(size_t) == 8) {
inp_feed.ModifyMemoryWithFunc(
[](u8* trace_bits, u32 map_size) {
afl::util::SimplifyTrace<u64>((u64*)trace_bits, map_size);
}
);
} else {
inp_feed.ModifyMemoryWithFunc(
[](u8* trace_bits, u32 map_size) {
afl::util::SimplifyTrace<u32>((u32*)trace_bits, map_size);
}
);
}
u8 res;
inp_feed.ShowMemoryToFunc(
[this, &res](const u8* trace_bits, u32 map_size) {
res = HasNewBits(trace_bits, &virgin_crash[0], map_size);
}
);
if (!res) {
// unlike FAULT_TMOUT case, keeping can be true when "crash mode" is enabled
return keeping;
}
}
#if 0
if (!unique_crashes) WriteCrashReadme(); // FIXME?
#endif
if (!setting->simple_files) {
fn = Util::StrPrintf("%s/crashes/id:%06llu,sig:%02u,%s",
setting->out_dir.c_str(),
unique_crashes,
exit_status.signal,
routine::update::DescribeOp(*this, 0).c_str()
);
} else {
fn = Util::StrPrintf("%s/hangs/id_%06llu_%02u",
setting->out_dir.c_str(),
unique_crashes,
exit_status.signal
);
}
unique_crashes++;
last_crash_time = Util::GetCurTimeMs();
last_crash_execs = total_execs;
break;
case PUTExitReasonType::FAULT_ERROR:
ERROR("Unable to execute target application");
default:
return keeping;
}
/* If we're here, we apparently want to save the crash or hang
test case, too. */
int fd = Util::OpenFile(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
Util::WriteFile(fd, buf, len);
Util::CloseFile(fd);
return keeping;
}
template<class Testcase>
u32 AFLStateTemplate<Testcase>::DoCalcScore(Testcase &testcase) {
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 (testcase.exec_us * 0.1 > avg_exec_us) perf_score = 10;
else if (testcase.exec_us * 0.25 > avg_exec_us) perf_score = 25;
else if (testcase.exec_us * 0.5 > avg_exec_us) perf_score = 50;
else if (testcase.exec_us * 0.75 > avg_exec_us) perf_score = 75;
else if (testcase.exec_us * 4 < avg_exec_us) perf_score = 300;
else if (testcase.exec_us * 3 < avg_exec_us) perf_score = 200;
else if (testcase.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 (testcase.bitmap_size * 0.3 > avg_bitmap_size) perf_score *= 3;
else if (testcase.bitmap_size * 0.5 > avg_bitmap_size) perf_score *= 2;
else if (testcase.bitmap_size * 0.75 > avg_bitmap_size) perf_score *= 1.5;
else if (testcase.bitmap_size * 3 < avg_bitmap_size) perf_score *= 0.25;
else if (testcase.bitmap_size * 2 < avg_bitmap_size) perf_score *= 0.5;
else if (testcase.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 (testcase.handicap >= 4) {
perf_score *= 4;
testcase.handicap -= 4;
} else if (testcase.handicap) {
perf_score *= 2;
testcase.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 (testcase.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;
break;
}
/* Make sure that we don't go over limit. */
if (perf_score > option::GetHavocMaxMult(*this) * 100) {
perf_score = option::GetHavocMaxMult(*this) * 100;
}
return perf_score;
}
/* 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. */
template<class Testcase>
u8 AFLStateTemplate<Testcase>::HasNewBits(const u8 *trace_bits, u8 *virgin_map, u32 map_size) {
// we assume the word size is the same as sizeof(size_t)
static_assert( sizeof(size_t) == 4 || sizeof(size_t) == 8 );
using UInt = std::conditional_t<sizeof(size_t) == 4, u32, u64>;
constexpr int width = sizeof(UInt);
constexpr int wlog = width == 4 ? 2 :
/* width == 8 */ 3 ;
UInt* virgin = (UInt*)virgin_map;
const UInt* current = (const UInt*)trace_bits;
u32 i = map_size >> wlog;
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[]. */
for (int j=0; j < width; j++) {
if (cur[j] && vir[j] == 0xff) {
ret = 2;
break;
}
}
if (ret != 2) ret = 1;
}
*virgin &= ~*current;
}
current++;
virgin++;
}
if (ret && virgin_map == &virgin_bits[0]) bitmap_changed = 1;
return ret;
}
template<class Testcase>
void AFLStateTemplate<Testcase>::MarkAsDetDone(Testcase &testcase) {
const auto& input = *testcase.input;
std::string fn = input.GetPath().filename().string();
fn = Util::StrPrintf("%s/queue/.state/deterministic_done/%s",
setting->out_dir.c_str(), fn.c_str());
int fd = Util::OpenFile(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
Util::CloseFile(fd);
testcase.passed_det = true;
}
template<class Testcase>
void AFLStateTemplate<Testcase>::MarkAsVariable(Testcase &testcase) {
const auto& input = *testcase.input;
std::string fn = input.GetPath().filename().string();
std::string ldest = Util::StrPrintf("../../%s", fn.c_str());
fn = Util::StrPrintf("%s/queue/.state/variable_behavior/%s",
setting->out_dir.c_str(), fn.c_str());
if (symlink(ldest.c_str(), fn.c_str()) == -1) {
int fd = Util::OpenFile(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
Util::CloseFile(fd);
}
testcase.var_behavior = true;
}
template<class Testcase>
void AFLStateTemplate<Testcase>::MarkAsRedundant(Testcase &testcase, bool val) {
const auto& input = *testcase.input;
if (val == testcase.fs_redundant) return;
testcase.fs_redundant = val;
std::string fn = input.GetPath().filename().string();
fn = Util::StrPrintf("%s/queue/.state/redundant_edges/%s",
setting->out_dir.c_str(), fn.c_str());
if (val) {
int fd = Util::OpenFile(fn, O_WRONLY | O_CREAT | O_EXCL, 0600);
Util::CloseFile(fd);
} else {
if (unlink(fn.c_str())) ERROR("Unable to remove '%s'", fn.c_str());
}
}
/* Get the number of runnable processes, with some simple smoothing. */
template<class State>
static double GetRunnableProcesses(State &state) {
// FIXME: static variable
static double res = 0;
#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");
char 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 / option::GetAvgSmoothing(state)) +
((double)val) * (1.0 / option::GetAvgSmoothing(state));
}
#endif /* ^(__APPLE__ || __FreeBSD__ || __OpenBSD__) */
return res;
}
/* Update stats file for unattended monitoring. */
template<class Testcase>
void AFLStateTemplate<Testcase>::WriteStatsFile(double bitmap_cvg, double stability, double eps) {
auto fn = setting->out_dir / "fuzzer_stats";
int fd = Util::OpenFile(fn.string(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0) ERROR("Unable to create '%s'", fn.c_str());
FILE* f = fdopen(fd, "w");
if (!f) ERROR("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 : %s\n"
"target_mode : %s%s%s%s%s%s%s\n"
"command_line : %s\n"
"slowest_exec_ms : %llu\n",
start_time / 1000, Util::GetCurTimeMs() / 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,
setting->exec_timelimit_ms, use_banner.c_str(), option::GetVersion(*this),
qemu_mode ? "qemu " : "", setting->dumb_mode ? " dumb " : "",
no_forkserver ? "no_forksrv " : "",
crash_mode != PUTExitReasonType::FAULT_NONE ? "crash " : "",
persistent_mode ? "persistent " : "", deferred_mode ? "deferred " : "",
(qemu_mode || setting->dumb_mode || no_forkserver ||
crash_mode != PUTExitReasonType::FAULT_NONE ||
persistent_mode || deferred_mode) ? "" : "default",
orig_cmdline.c_str(), slowest_exec_ms);
/* ignore errors */
/* Get rss value from the children
We must have killed the forkserver process and called waitpid
before calling getrusage */
struct rusage usage;
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);
}
template<class Testcase>
void AFLStateTemplate<Testcase>::SaveAuto(void) {
if (!auto_changed) return;
auto_changed = false;
u32 lim = std::min<u32>(option::GetUseAutoExtras(*this), a_extras.size());
for (u32 i=0; i<lim; i++) {
auto fn = setting->out_dir
/ "queue/.state/auto_extras"
/ Util::StrPrintf("auto_%06u", i);
int fd = Util::OpenFile(fn.string(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0) ERROR("Unable to create '%s'", fn.c_str());
Util::WriteFile(fd, &a_extras[i].data[0], a_extras[i].data.size());
Util::CloseFile(fd);
}
}
/* 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. */
template<class Testcase>
void AFLStateTemplate<Testcase>::WriteBitmap(void) {
if (!bitmap_changed) return;
bitmap_changed = false;
auto fn = setting->out_dir / "fuzz_bitmap";
int fd = Util::OpenFile(fn.string(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0) ERROR("Unable to create '%s'", fn.c_str());
Util::WriteFile(fd, virgin_bits.data(), option::GetMapSize<Tag>());
Util::CloseFile(fd);
}
/* Read bitmap from file. This is for the -B option again. */
template<class Testcase>
void AFLStateTemplate<Testcase>::ReadBitmap(fs::path fname) {
int fd = Util::OpenFile(fname.string(), O_RDONLY);
if (fd < 0) ERROR("Unable to open '%s'", fname.c_str());
virgin_bits.resize(option::GetMapSize<Tag>());
Util::ReadFile(fd, virgin_bits.data(), option::GetMapSize<Tag>());
Util::CloseFile(fd);
}
template<class Testcase>
void AFLStateTemplate<Testcase>::MaybeUpdatePlotFile(double bitmap_cvg, double eps) {
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",
Util::GetCurTimeMs() / 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);
}
template<class Testcase>
void AFLStateTemplate<Testcase>::SaveCmdline(const std::vector<std::string> &argv) {
for (u32 i=0; i < argv.size(); i++) {
if (i > 0) orig_cmdline += ' ';
orig_cmdline += argv[i];
}
}