forked from googleprojectzero/winafl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
afl-tmin.c
1473 lines (1000 loc) · 33 KB
/
afl-tmin.c
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
/*
american fuzzy lop - test case minimizer
----------------------------------------
Written and maintained by Michal Zalewski <[email protected]>
Windows fork written by Axel "0vercl0k" Souchet <[email protected]>
Copyright 2017 Google Inc. 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
A simple test case minimizer that takes an input file and tries to remove
as much data as possible while keeping the binary in a crashing state
*or* producing consistent instrumentation output (the mode is auto-selected
based on the initially observed behavior).
*/
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_RAND_S
#define AFL_MAIN
#define VERSION "2.51b"
#include <windows.h>
#include "config.h"
#include "types.h"
#include "debug.h"
#include "alloc-inl.h"
#include "hash.h"
#include <io.h>
#include <direct.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
static s32 child_pid; /* PID of the tested program */
static HANDLE child_handle,
child_thread_handle;
static char *dynamorio_dir;
static char *client_params;
int fuzz_iterations_max = 1, fuzz_iterations_current;
static CRITICAL_SECTION critical_section;
static u64 watchdog_timeout_time;
static u8 watchdog_enabled;
static u8 *target_cmd; /* command line of target */
static u8 *trace_bits, /* SHM with instrumentation bitmap */
*mask_bitmap; /* Mask for trace bits (-B) */
static u8 *in_file, /* Minimizer input test case */
*out_file, /* Minimizer output file */
*prog_in, /* Targeted program input file */
*target_path, /* Path to target binary */
*doc_path, /* Path to docs */
*at_file; /* Substitution string for @@ */
static u8* in_data; /* Input data for trimming */
static u32 in_len, /* Input data length */
orig_cksum, /* Original checksum */
total_execs, /* Total number of execs */
missed_hangs, /* Misses due to hangs */
missed_crashes, /* Misses due to crashes */
missed_paths, /* Misses due to exec path diffs */
exec_tmout = EXEC_TIMEOUT; /* Exec timeout (ms) */
static u64 mem_limit = MEM_LIMIT; /* Memory limit (MB) */
static HANDLE shm_handle; /* Handle of the SHM region */
static HANDLE pipe_handle; /* Handle of the name pipe */
static u64 name_seed; /* Random integer to have a unique shm/pipe name */
static HANDLE devnul_handle; /* Handle of the nul device */
static u8 sinkhole_stds = 1; /* Sink-hole stdout/stderr messages?*/
static char *fuzzer_id = NULL; /* The fuzzer ID or a randomized
seed allowing multiple instances */
static u8 crash_mode, /* Crash-centric mode? */
exit_crash, /* Treat non-zero exit as crash? */
edges_only, /* Ignore hit counts? */
exact_mode, /* Require path match for crashes? */
use_stdin = 1, /* Use stdin for program input? */
drioless = 0;
static volatile u8
stop_soon, /* Ctrl-C pressed? */
child_timed_out; /* Child timed out? */
/* Classify tuple counts. This is a slow & naive version, but good enough here. */
#define AREP4(_sym) (_sym), (_sym), (_sym), (_sym)
#define AREP8(_sym) AREP4(_sym), AREP4(_sym)
#define AREP16(_sym) AREP8(_sym), AREP8(_sym)
#define AREP32(_sym) AREP16(_sym), AREP16(_sym)
#define AREP64(_sym) AREP32(_sym), AREP32(_sym)
#define AREP128(_sym) AREP64(_sym), AREP64(_sym)
static const u8 count_class_lookup[256] = {
/* 0 - 3: 4 */ 0, 1, 2, 4,
/* 4 - 7: +4 */ AREP4(8),
/* 8 - 15: +8 */ AREP8(16),
/* 16 - 31: +16 */ AREP16(32),
/* 32 - 127: +96 */ AREP64(64), AREP32(64),
/* 128+: +128 */ AREP128(128)
};
static void classify_counts(u8* mem) {
u32 i = MAP_SIZE;
if (edges_only) {
while (i--) {
if (*mem) *mem = 1;
mem++;
}
} else {
while (i--) {
*mem = count_class_lookup[*mem];
mem++;
}
}
}
/* Apply mask to classified bitmap (if set). */
static void apply_mask(u32* mem, u32* mask) {
u32 i = (MAP_SIZE >> 2);
if (!mask) return;
while (i--) {
*mem &= ~*mask;
mem++;
mask++;
}
}
/* See if any bytes are set in the bitmap. */
static inline u8 anything_set(void) {
u32* ptr = (u32*)trace_bits;
u32 i = (MAP_SIZE >> 2);
while (i--) if (*(ptr++)) return 1;
return 0;
}
/* Get unix time in milliseconds */
static u64 get_cur_time(void) {
u64 ret;
FILETIME filetime;
GetSystemTimeAsFileTime(&filetime);
ret = (((u64)filetime.dwHighDateTime)<<32) + (u64)filetime.dwLowDateTime;
return ret / 10000;
}
/* Get unix time in microseconds */
static u64 get_cur_time_us(void) {
u64 ret;
FILETIME filetime;
GetSystemTimeAsFileTime(&filetime);
ret = (((u64)filetime.dwHighDateTime)<<32) + (u64)filetime.dwLowDateTime;
return ret / 10;
}
char *alloc_printf(const char *_str, ...) {
va_list argptr;
char* _tmp;
s32 _len;
va_start(argptr, _str);
_len = vsnprintf(NULL, 0, _str, argptr);
if (_len < 0) FATAL("Whoa, snprintf() fails?!");
_tmp = ck_alloc(_len + 1);
vsnprintf(_tmp, _len + 1, _str, argptr);
va_end(argptr);
return _tmp;
}
/* Get rid of shared memory and temp files (atexit handler). */
static void remove_shm(void) {
UnmapViewOfFile(trace_bits);
CloseHandle(shm_handle);
if (prog_in) unlink(prog_in); /* Ignore errors */
}
/* Configure shared memory. */
static void setup_shm(void) {
char* shm_str = NULL;
unsigned int seeds[2];
u64 name_seed;
u8 attempts = 0;
while(attempts < 5) {
if(fuzzer_id == NULL) {
// If it is null, it means we have to generate a random seed to name the instance
rand_s(&seeds[0]);
rand_s(&seeds[1]);
name_seed = ((u64)seeds[0] << 32) | seeds[1];
fuzzer_id = (char *)alloc_printf("%I64x", name_seed);
}
shm_str = (char *)alloc_printf("afl_shm_%s", fuzzer_id);
shm_handle = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
MAP_SIZE, // maximum object size (low-order DWORD)
(char *)shm_str); // name of mapping object
if(shm_handle == NULL) {
if(GetLastError() == ERROR_ALREADY_EXISTS) {
// We need another attempt to find a unique section name
attempts++;
ck_free(shm_str);
ck_free(fuzzer_id);
fuzzer_id = NULL;
continue;
}
else {
PFATAL("CreateFileMapping failed");
}
}
// We found a section name that works!
break;
}
if(attempts == 5) {
FATAL("Could not find a section name.\n");
}
atexit(remove_shm);
ck_free(shm_str);
trace_bits = (u8 *)MapViewOfFile(
shm_handle, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
MAP_SIZE
);
if (!trace_bits) PFATAL("MapViewOfFile() failed");
}
/* Read initial file. */
static void read_initial_file(void) {
struct stat st;
s32 fd = _open(in_file, O_RDONLY | O_BINARY);
if (fd < 0) PFATAL("Unable to open '%s'", in_file);
if (fstat(fd, &st) || !st.st_size)
FATAL("Zero-sized input file.");
if (st.st_size >= TMIN_MAX_FILE)
FATAL("Input file is too large (%u MB max)", TMIN_MAX_FILE / 1024 / 1024);
in_len = st.st_size;
in_data = ck_alloc_nozero(in_len);
ck_read(fd, in_data, in_len, in_file);
_close(fd);
OKF("Read %u byte%s from '%s'.", in_len, in_len == 1 ? "" : "s", in_file);
}
/* Write output file. */
static void write_to_file(u8* path, u8* mem, u32 len) {
s32 ret;
_unlink(path); /* Ignore errors */
ret = _open(path, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
if (ret < 0) PFATAL("Unable to create '%s'", path);
ck_write(ret, mem, len, path);
_lseek(ret, 0, SEEK_SET);
_close(ret);
}
//quoting on Windows is weird
size_t ArgvQuote(char *in, char *out) {
int needs_quoting = 0;
size_t size = 0;
char *p = in;
size_t i;
//check if quoting is necessary
if(strchr(in, ' ')) needs_quoting = 1;
if(strchr(in, '\"')) needs_quoting = 1;
if(strchr(in, '\t')) needs_quoting = 1;
if(strchr(in, '\n')) needs_quoting = 1;
if(strchr(in, '\v')) needs_quoting = 1;
if(!needs_quoting) {
size = strlen(in);
if(out) memcpy(out, in, size);
return size;
}
if(out) out[size] = '\"';
size++;
while(*p) {
size_t num_backslashes = 0;
while((*p) && (*p == '\\')) {
p++;
num_backslashes++;
}
if(*p == 0) {
for(i = 0; i < (num_backslashes*2); i++) {
if(out) out[size] = '\\';
size++;
}
break;
} else if(*p == '\"') {
for(i = 0; i < (num_backslashes*2 + 1); i++) {
if(out) out[size] = '\\';
size++;
}
if(out) out[size] = *p;
size++;
} else {
for(i = 0; i < num_backslashes; i++) {
if(out) out[size] = '\\';
size++;
}
if(out) out[size] = *p;
size++;
}
p++;
}
if(out) out[size] = '\"';
size++;
return size;
}
char *argv_to_cmd(char** argv) {
u32 len = 0, i;
u8* buf, *ret;
//todo shell-escape
for (i = 0; argv[i]; i++)
len += ArgvQuote(argv[i], NULL) + 1;
if(!len) FATAL("Error creating command line");
buf = ret = ck_alloc(len);
for (i = 0; argv[i]; i++) {
u32 l = ArgvQuote(argv[i], buf);
buf += l;
*(buf++) = ' ';
}
ret[len-1] = 0;
return ret;
}
static void create_target_process(char** argv) {
char* cmd;
char* pipe_name;
char *buf;
char *pidfile = NULL;
FILE *fp;
size_t pidsize;
BOOL inherit_handles = TRUE;
HANDLE hJob = NULL;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_limit;
STARTUPINFO si;
PROCESS_INFORMATION pi;
pipe_name = (char *)alloc_printf("\\\\.\\pipe\\afl_pipe_%s", fuzzer_id);
pipe_handle = CreateNamedPipe(
pipe_name, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
0,
1, // max. instances
512, // output buffer size
512, // input buffer size
20000, // client time-out
NULL); // default security attribute
if (pipe_handle == INVALID_HANDLE_VALUE) {
FATAL("CreateNamedPipe failed, GLE=%d.\n", GetLastError());
}
target_cmd = argv_to_cmd(argv);
if (drioless) {
char *static_config = alloc_printf("%s:1", fuzzer_id);
if (static_config == NULL) {
FATAL("Cannot allocate static_config.");
}
SetEnvironmentVariable("AFL_STATIC_CONFIG", static_config);
cmd = alloc_printf("%s", target_cmd);
ck_free(static_config);
} else {
pidfile = alloc_printf("childpid_%s.txt", fuzzer_id);
cmd = alloc_printf(
"%s\\drrun.exe -pidfile %s -no_follow_children -c winafl.dll %s -fuzz_iterations 1 -fuzzer_id %s -- %s",
dynamorio_dir, pidfile, client_params, fuzzer_id, target_cmd
);
}
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
if (sinkhole_stds) {
si.hStdOutput = si.hStdError = devnul_handle;
si.dwFlags |= STARTF_USESTDHANDLES;
} else {
inherit_handles = FALSE;
}
if (mem_limit != 0) {
hJob = CreateJobObject(NULL, NULL);
if (hJob == NULL) {
FATAL("CreateJobObject failed, GLE=%d.\n", GetLastError());
}
ZeroMemory(&job_limit, sizeof(job_limit));
job_limit.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
job_limit.ProcessMemoryLimit = mem_limit * 1024 * 1024;
if (!SetInformationJobObject(
hJob,
JobObjectExtendedLimitInformation,
&job_limit,
sizeof(job_limit)
)) {
FATAL("SetInformationJobObject failed, GLE=%d.\n", GetLastError());
}
}
if (!CreateProcess(NULL, cmd, NULL, NULL, inherit_handles, CREATE_SUSPENDED, NULL, NULL, &si, &pi)) {
FATAL("CreateProcess failed, GLE=%d.\n", GetLastError());
}
child_handle = pi.hProcess;
child_thread_handle = pi.hThread;
if (mem_limit != 0) {
if (!AssignProcessToJobObject(hJob, child_handle)) {
FATAL("AssignProcessToJobObject failed, GLE=%d.\n", GetLastError());
}
}
ResumeThread(child_thread_handle);
watchdog_timeout_time = get_cur_time() + exec_tmout;
watchdog_enabled = 1;
if (!ConnectNamedPipe(pipe_handle, NULL)) {
if (GetLastError() != ERROR_PIPE_CONNECTED) {
FATAL("ConnectNamedPipe failed, GLE=%d.\n", GetLastError());
}
}
watchdog_enabled = 0;
if (drioless == 0) {
//by the time pipe has connected the pidfile must have been created
fp = fopen(pidfile, "rb");
if (!fp) {
FATAL("Error opening pidfile.txt");
}
fseek(fp,0,SEEK_END);
pidsize = ftell(fp);
fseek(fp,0,SEEK_SET);
buf = (char *)malloc(pidsize+1);
fread(buf, pidsize, 1, fp);
buf[pidsize] = 0;
fclose(fp);
remove(pidfile);
child_pid = atoi(buf);
free(buf);
ck_free(pidfile);
}
else {
child_pid = pi.dwProcessId;
}
ck_free(target_cmd);
ck_free(cmd);
ck_free(pipe_name);
}
static void destroy_target_process(int wait_exit) {
char* kill_cmd;
BOOL still_alive = TRUE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
EnterCriticalSection(&critical_section);
if(!child_handle) {
goto leave;
}
if(WaitForSingleObject(child_handle, wait_exit) != WAIT_TIMEOUT) {
goto done;
}
// nudge the child process only if dynamorio is used
if(drioless) {
TerminateProcess(child_handle, 0);
} else {
kill_cmd = alloc_printf("%s\\drconfig.exe -nudge_pid %d 0 1", dynamorio_dir, child_pid);
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if(!CreateProcess(NULL, kill_cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
FATAL("CreateProcess failed, GLE=%d.\n", GetLastError());
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
ck_free(kill_cmd);
}
still_alive = WaitForSingleObject(child_handle, 2000) == WAIT_TIMEOUT;
if(still_alive) {
//wait until the child process exits
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
kill_cmd = alloc_printf("taskkill /PID %d /F", child_pid);
if(!CreateProcess(NULL, kill_cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
FATAL("CreateProcess failed, GLE=%d.\n", GetLastError());
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
ck_free(kill_cmd);
if(WaitForSingleObject(child_handle, 20000) == WAIT_TIMEOUT) {
FATAL("Cannot kill child process\n");
}
}
done:
CloseHandle(child_handle);
CloseHandle(child_thread_handle);
child_handle = NULL;
child_thread_handle = NULL;
leave:
//close the pipe
if(pipe_handle) {
DisconnectNamedPipe(pipe_handle);
CloseHandle(pipe_handle);
pipe_handle = NULL;
}
LeaveCriticalSection(&critical_section);
}
DWORD WINAPI watchdog_timer( LPVOID lpParam ) {
u64 current_time;
while(1) {
Sleep(1000);
current_time = get_cur_time();
if(watchdog_enabled && (current_time > watchdog_timeout_time)) {
child_timed_out = 1;
destroy_target_process(0);
}
}
}
static void setup_watchdog_timer() {
watchdog_enabled = 0;
InitializeCriticalSection(&critical_section);
CreateThread(NULL, 0, watchdog_timer, 0, 0, NULL);
}
static int is_child_running() {
return (child_handle && (WaitForSingleObject(child_handle, 0 ) == WAIT_TIMEOUT));
}
/* Execute target application. Returns 0 if the changes are a dud, or
1 if they should be kept. */
static u8 run_target(char** argv, u8* mem, u32 len, u8 first_run) {
char command[] = "F";
DWORD num_read;
char result = 0;
u8 child_crashed;
u32 cksum;
write_to_file(prog_in, mem, len);
if(!is_child_running()) {
destroy_target_process(0);
create_target_process(argv);
fuzz_iterations_current = 0;
}
child_timed_out = 0;
memset(trace_bits, 0, MAP_SIZE);
MemoryBarrier();
//TEMPORARY FIX FOR REGULAR USAGE OF AFL-TMIN
ReadFile(pipe_handle, &result, 1, &num_read, NULL);
if (result == 'K')
{
//a workaround for first cycle
ReadFile(pipe_handle, &result, 1, &num_read, NULL);
}
if (result != 'P')
{
FATAL("Unexpected result from pipe! expected 'P', instead received '%c'\n", result);
}
//END OF TEMPORARY FIX FOR REGULAR USAGE OF AFL-TMIN
WriteFile(
pipe_handle, // handle to pipe
command, // buffer to write from
1, // number of bytes to write
&num_read, // number of bytes written
NULL); // not overlapped I/O
watchdog_timeout_time = get_cur_time() + exec_tmout;
if(exec_tmout) {
watchdog_enabled = 1;
}
ReadFile(pipe_handle, &result, 1, &num_read, NULL);
if(exec_tmout) {
watchdog_enabled = 0;
}
MemoryBarrier();
/* Clean up bitmap, analyze exit condition, etc. */
classify_counts(trace_bits);
apply_mask((u32*)trace_bits, (u32*)mask_bitmap);
total_execs++;
fuzz_iterations_current++;
if(fuzz_iterations_current == fuzz_iterations_max) {
destroy_target_process(2000);
}
if (stop_soon) {
SAYF(cRST cLRD "\n+++ Minimization aborted by user +++\n" cRST);
exit(1);
}
child_crashed = result == 'C';
/* Always discard inputs that time out. */
if (child_timed_out) {
missed_hangs++;
return 0;
}
/* Handle crashing inputs depending on current mode. */
if (child_crashed) {
if (first_run) crash_mode = 1;
if (crash_mode) {
if (!exact_mode) return 1;
} else {
missed_crashes++;
return 0;
}
} else
/* Handle non-crashing inputs appropriately. */
if (crash_mode) {
missed_paths++;
return 0;
}
cksum = hash32(trace_bits, MAP_SIZE, HASH_CONST);
if (first_run) orig_cksum = cksum;
if (orig_cksum == cksum) return 1;
missed_paths++;
return 0;
}
/* Find first power of two greater or equal to val. */
static u32 next_p2(u32 val) {
u32 ret = 1;
while (val > ret) ret <<= 1;
return ret;
}
/* Actually minimize! */
static void minimize(char** argv) {
static u32 alpha_map[256];
u8* tmp_buf = ck_alloc_nozero(in_len);
u32 orig_len = in_len, stage_o_len;
u32 del_len, set_len, del_pos, set_pos, i, alpha_size, cur_pass = 0;
u32 syms_removed, alpha_del0 = 0, alpha_del1, alpha_del2, alpha_d_total = 0;
u8 changed_any, prev_del;
/***********************
* BLOCK NORMALIZATION *
***********************/
set_len = next_p2(in_len / TMIN_SET_STEPS);
set_pos = 0;
if (set_len < TMIN_SET_MIN_SIZE) set_len = TMIN_SET_MIN_SIZE;
ACTF(cBRI "Stage #0: " cRST "One-time block normalization...");
while (set_pos < in_len) {
u8 res;
u32 use_len = MIN(set_len, in_len - set_pos);
for (i = 0; i < use_len; i++)
if (in_data[set_pos + i] != '0') break;
if (i != use_len) {
memcpy(tmp_buf, in_data, in_len);
memset(tmp_buf + set_pos, '0', use_len);
res = run_target(argv, tmp_buf, in_len, 0);
if (res) {
memset(in_data + set_pos, '0', use_len);
changed_any = 1;
alpha_del0 += use_len;
}
}
set_pos += set_len;
}
alpha_d_total += alpha_del0;
OKF("Block normalization complete, %u byte%s replaced.", alpha_del0,
alpha_del0 == 1 ? "" : "s");
next_pass:
ACTF(cYEL "--- " cBRI "Pass #%u " cYEL "---", ++cur_pass);
changed_any = 0;
/******************
* BLOCK DELETION *
******************/
del_len = next_p2(in_len / TRIM_START_STEPS);
stage_o_len = in_len;
ACTF(cBRI "Stage #1: " cRST "Removing blocks of data...");
next_del_blksize:
if (!del_len) del_len = 1;
del_pos = 0;
prev_del = 1;
SAYF(cGRA " Block length = %u, remaining size = %u\n" cRST,
del_len, in_len);
while (del_pos < in_len) {
u8 res;
s32 tail_len;
tail_len = in_len - del_pos - del_len;
if (tail_len < 0) tail_len = 0;
/* If we have processed at least one full block (initially, prev_del == 1),
and we did so without deleting the previous one, and we aren't at the
very end of the buffer (tail_len > 0), and the current block is the same
as the previous one... skip this step as a no-op. */
if (!prev_del && tail_len && !memcmp(in_data + del_pos - del_len,
in_data + del_pos, del_len)) {
del_pos += del_len;
continue;
}
prev_del = 0;
/* Head */
memcpy(tmp_buf, in_data, del_pos);
/* Tail */
memcpy(tmp_buf + del_pos, in_data + del_pos + del_len, tail_len);
res = run_target(argv, tmp_buf, del_pos + tail_len, 0);
if (res) {
memcpy(in_data, tmp_buf, del_pos + tail_len);
prev_del = 1;
in_len = del_pos + tail_len;
changed_any = 1;
} else del_pos += del_len;
}
if (del_len > 1 && in_len >= 1) {
del_len /= 2;
goto next_del_blksize;
}
OKF("Block removal complete, %u bytes deleted.", stage_o_len - in_len);
if (!in_len && changed_any)
WARNF(cLRD "Down to zero bytes - check the command line and mem limit!" cRST);
if (cur_pass > 1 && !changed_any) goto finalize_all;
/*************************
* ALPHABET MINIMIZATION *
*************************/
alpha_size = 0;
alpha_del1 = 0;
syms_removed = 0;
memset(alpha_map, 0, 256 * sizeof(u32));
for (i = 0; i < in_len; i++) {
if (!alpha_map[in_data[i]]) alpha_size++;
alpha_map[in_data[i]]++;
}
ACTF(cBRI "Stage #2: " cRST "Minimizing symbols (%u code point%s)...",
alpha_size, alpha_size == 1 ? "" : "s");
for (i = 0; i < 256; i++) {
u32 r;
u8 res;
if (i == '0' || !alpha_map[i]) continue;
memcpy(tmp_buf, in_data, in_len);
for (r = 0; r < in_len; r++)
if (tmp_buf[r] == i) tmp_buf[r] = '0';
res = run_target(argv, tmp_buf, in_len, 0);
if (res) {
memcpy(in_data, tmp_buf, in_len);
syms_removed++;
alpha_del1 += alpha_map[i];
changed_any = 1;
}
}
alpha_d_total += alpha_del1;
OKF("Symbol minimization finished, %u symbol%s (%u byte%s) replaced.",
syms_removed, syms_removed == 1 ? "" : "s",
alpha_del1, alpha_del1 == 1 ? "" : "s");
/**************************
* CHARACTER MINIMIZATION *