1 | //===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // FuzzerDriver and flag parsing. |
9 | //===----------------------------------------------------------------------===// |
10 | |
11 | #include "FuzzerCommand.h" |
12 | #include "FuzzerCorpus.h" |
13 | #include "FuzzerFork.h" |
14 | #include "FuzzerIO.h" |
15 | #include "FuzzerInterface.h" |
16 | #include "FuzzerInternal.h" |
17 | #include "FuzzerMerge.h" |
18 | #include "FuzzerMutate.h" |
19 | #include "FuzzerPlatform.h" |
20 | #include "FuzzerRandom.h" |
21 | #include "FuzzerTracePC.h" |
22 | #include <algorithm> |
23 | #include <atomic> |
24 | #include <chrono> |
25 | #include <cstdlib> |
26 | #include <cstring> |
27 | #include <mutex> |
28 | #include <string> |
29 | #include <thread> |
30 | #include <fstream> |
31 | |
32 | // This function should be present in the libFuzzer so that the client |
33 | // binary can test for its existence. |
34 | #if LIBFUZZER_MSVC |
35 | extern "C" void __libfuzzer_is_present() {} |
36 | #if defined(_M_IX86) || defined(__i386__) |
37 | #pragma comment(linker, "/include:___libfuzzer_is_present") |
38 | #else |
39 | #pragma comment(linker, "/include:__libfuzzer_is_present") |
40 | #endif |
41 | #else |
42 | extern "C" __attribute__((used)) void __libfuzzer_is_present() {} |
43 | #endif // LIBFUZZER_MSVC |
44 | |
45 | namespace fuzzer { |
46 | |
47 | // Program arguments. |
48 | struct FlagDescription { |
49 | const char *Name; |
50 | const char *Description; |
51 | int Default; |
52 | int *IntFlag; |
53 | const char **StrFlag; |
54 | unsigned int *UIntFlag; |
55 | }; |
56 | |
57 | struct { |
58 | #define FUZZER_DEPRECATED_FLAG(Name) |
59 | #define FUZZER_FLAG_INT(Name, Default, Description) int Name; |
60 | #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name; |
61 | #define FUZZER_FLAG_STRING(Name, Description) const char *Name; |
62 | #include "FuzzerFlags.def" |
63 | #undef FUZZER_DEPRECATED_FLAG |
64 | #undef FUZZER_FLAG_INT |
65 | #undef FUZZER_FLAG_UNSIGNED |
66 | #undef FUZZER_FLAG_STRING |
67 | } Flags; |
68 | |
69 | static const FlagDescription FlagDescriptions [] { |
70 | #define FUZZER_DEPRECATED_FLAG(Name) \ |
71 | {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr}, |
72 | #define FUZZER_FLAG_INT(Name, Default, Description) \ |
73 | {#Name, Description, Default, &Flags.Name, nullptr, nullptr}, |
74 | #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \ |
75 | {#Name, Description, static_cast<int>(Default), \ |
76 | nullptr, nullptr, &Flags.Name}, |
77 | #define FUZZER_FLAG_STRING(Name, Description) \ |
78 | {#Name, Description, 0, nullptr, &Flags.Name, nullptr}, |
79 | #include "FuzzerFlags.def" |
80 | #undef FUZZER_DEPRECATED_FLAG |
81 | #undef FUZZER_FLAG_INT |
82 | #undef FUZZER_FLAG_UNSIGNED |
83 | #undef FUZZER_FLAG_STRING |
84 | }; |
85 | |
86 | static const size_t kNumFlags = |
87 | sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]); |
88 | |
89 | static std::vector<std::string> *Inputs; |
90 | static std::string *ProgName; |
91 | |
92 | static void PrintHelp() { |
93 | Printf(Fmt: "Usage:\n" ); |
94 | auto Prog = ProgName->c_str(); |
95 | Printf(Fmt: "\nTo run fuzzing pass 0 or more directories.\n" ); |
96 | Printf(Fmt: "%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n" , Prog); |
97 | |
98 | Printf(Fmt: "\nTo run individual tests without fuzzing pass 1 or more files:\n" ); |
99 | Printf(Fmt: "%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n" , Prog); |
100 | |
101 | Printf(Fmt: "\nFlags: (strictly in form -flag=value)\n" ); |
102 | size_t MaxFlagLen = 0; |
103 | for (size_t F = 0; F < kNumFlags; F++) |
104 | MaxFlagLen = std::max(a: strlen(s: FlagDescriptions[F].Name), b: MaxFlagLen); |
105 | |
106 | for (size_t F = 0; F < kNumFlags; F++) { |
107 | const auto &D = FlagDescriptions[F]; |
108 | if (strstr(haystack: D.Description, needle: "internal flag" ) == D.Description) continue; |
109 | Printf(Fmt: " %s" , D.Name); |
110 | for (size_t i = 0, n = MaxFlagLen - strlen(s: D.Name); i < n; i++) |
111 | Printf(Fmt: " " ); |
112 | Printf(Fmt: "\t" ); |
113 | Printf(Fmt: "%d\t%s\n" , D.Default, D.Description); |
114 | } |
115 | Printf(Fmt: "\nFlags starting with '--' will be ignored and " |
116 | "will be passed verbatim to subprocesses.\n" ); |
117 | } |
118 | |
119 | static const char *FlagValue(const char *Param, const char *Name) { |
120 | size_t Len = strlen(s: Name); |
121 | if (Param[0] == '-' && strstr(haystack: Param + 1, needle: Name) == Param + 1 && |
122 | Param[Len + 1] == '=') |
123 | return &Param[Len + 2]; |
124 | return nullptr; |
125 | } |
126 | |
127 | // Avoid calling stol as it triggers a bug in clang/glibc build. |
128 | static long MyStol(const char *Str) { |
129 | long Res = 0; |
130 | long Sign = 1; |
131 | if (*Str == '-') { |
132 | Str++; |
133 | Sign = -1; |
134 | } |
135 | for (size_t i = 0; Str[i]; i++) { |
136 | char Ch = Str[i]; |
137 | if (Ch < '0' || Ch > '9') |
138 | return Res; |
139 | Res = Res * 10 + (Ch - '0'); |
140 | } |
141 | return Res * Sign; |
142 | } |
143 | |
144 | static bool ParseOneFlag(const char *Param) { |
145 | if (Param[0] != '-') return false; |
146 | if (Param[1] == '-') { |
147 | static bool PrintedWarning = false; |
148 | if (!PrintedWarning) { |
149 | PrintedWarning = true; |
150 | Printf(Fmt: "INFO: libFuzzer ignores flags that start with '--'\n" ); |
151 | } |
152 | for (size_t F = 0; F < kNumFlags; F++) |
153 | if (FlagValue(Param: Param + 1, Name: FlagDescriptions[F].Name)) |
154 | Printf(Fmt: "WARNING: did you mean '%s' (single dash)?\n" , Param + 1); |
155 | return true; |
156 | } |
157 | for (size_t F = 0; F < kNumFlags; F++) { |
158 | const char *Name = FlagDescriptions[F].Name; |
159 | const char *Str = FlagValue(Param, Name); |
160 | if (Str) { |
161 | if (FlagDescriptions[F].IntFlag) { |
162 | auto Val = MyStol(Str); |
163 | *FlagDescriptions[F].IntFlag = static_cast<int>(Val); |
164 | if (Flags.verbosity >= 2) |
165 | Printf(Fmt: "Flag: %s %d\n" , Name, Val); |
166 | return true; |
167 | } else if (FlagDescriptions[F].UIntFlag) { |
168 | auto Val = std::stoul(str: Str); |
169 | *FlagDescriptions[F].UIntFlag = static_cast<unsigned int>(Val); |
170 | if (Flags.verbosity >= 2) |
171 | Printf(Fmt: "Flag: %s %u\n" , Name, Val); |
172 | return true; |
173 | } else if (FlagDescriptions[F].StrFlag) { |
174 | *FlagDescriptions[F].StrFlag = Str; |
175 | if (Flags.verbosity >= 2) |
176 | Printf(Fmt: "Flag: %s %s\n" , Name, Str); |
177 | return true; |
178 | } else { // Deprecated flag. |
179 | Printf(Fmt: "Flag: %s: deprecated, don't use\n" , Name); |
180 | return true; |
181 | } |
182 | } |
183 | } |
184 | Printf(Fmt: "\n\nWARNING: unrecognized flag '%s'; " |
185 | "use -help=1 to list all flags\n\n" , Param); |
186 | return true; |
187 | } |
188 | |
189 | // We don't use any library to minimize dependencies. |
190 | static void ParseFlags(const std::vector<std::string> &Args, |
191 | const ExternalFunctions *EF) { |
192 | for (size_t F = 0; F < kNumFlags; F++) { |
193 | if (FlagDescriptions[F].IntFlag) |
194 | *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default; |
195 | if (FlagDescriptions[F].UIntFlag) |
196 | *FlagDescriptions[F].UIntFlag = |
197 | static_cast<unsigned int>(FlagDescriptions[F].Default); |
198 | if (FlagDescriptions[F].StrFlag) |
199 | *FlagDescriptions[F].StrFlag = nullptr; |
200 | } |
201 | |
202 | // Disable len_control by default, if LLVMFuzzerCustomMutator is used. |
203 | if (EF->LLVMFuzzerCustomMutator) { |
204 | Flags.len_control = 0; |
205 | Printf(Fmt: "INFO: found LLVMFuzzerCustomMutator (%p). " |
206 | "Disabling -len_control by default.\n" , EF->LLVMFuzzerCustomMutator); |
207 | } |
208 | |
209 | Inputs = new std::vector<std::string>; |
210 | for (size_t A = 1; A < Args.size(); A++) { |
211 | if (ParseOneFlag(Param: Args[A].c_str())) { |
212 | if (Flags.ignore_remaining_args) |
213 | break; |
214 | continue; |
215 | } |
216 | Inputs->push_back(x: Args[A]); |
217 | } |
218 | } |
219 | |
220 | static std::mutex Mu; |
221 | |
222 | static void PulseThread() { |
223 | while (true) { |
224 | SleepSeconds(Seconds: 600); |
225 | std::lock_guard<std::mutex> Lock(Mu); |
226 | Printf(Fmt: "pulse...\n" ); |
227 | } |
228 | } |
229 | |
230 | static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter, |
231 | unsigned NumJobs, std::atomic<bool> *HasErrors) { |
232 | while (true) { |
233 | unsigned C = (*Counter)++; |
234 | if (C >= NumJobs) break; |
235 | std::string Log = "fuzz-" + std::to_string(val: C) + ".log" ; |
236 | Command Cmd(BaseCmd); |
237 | Cmd.setOutputFile(Log); |
238 | Cmd.combineOutAndErr(); |
239 | if (Flags.verbosity) { |
240 | std::string CommandLine = Cmd.toString(); |
241 | Printf(Fmt: "%s\n" , CommandLine.c_str()); |
242 | } |
243 | int ExitCode = ExecuteCommand(Cmd); |
244 | if (ExitCode != 0) |
245 | *HasErrors = true; |
246 | std::lock_guard<std::mutex> Lock(Mu); |
247 | Printf(Fmt: "================== Job %u exited with exit code %d ============\n" , |
248 | C, ExitCode); |
249 | fuzzer::CopyFileToErr(Path: Log); |
250 | } |
251 | } |
252 | |
253 | static void ValidateDirectoryExists(const std::string &Path, |
254 | bool CreateDirectory) { |
255 | if (Path.empty()) { |
256 | Printf(Fmt: "ERROR: Provided directory path is an empty string\n" ); |
257 | exit(status: 1); |
258 | } |
259 | |
260 | if (IsDirectory(Path)) |
261 | return; |
262 | |
263 | if (CreateDirectory) { |
264 | if (!MkDirRecursive(Dir: Path)) { |
265 | Printf(Fmt: "ERROR: Failed to create directory \"%s\"\n" , Path.c_str()); |
266 | exit(status: 1); |
267 | } |
268 | return; |
269 | } |
270 | |
271 | Printf(Fmt: "ERROR: The required directory \"%s\" does not exist\n" , Path.c_str()); |
272 | exit(status: 1); |
273 | } |
274 | |
275 | std::string CloneArgsWithoutX(const std::vector<std::string> &Args, |
276 | const char *X1, const char *X2) { |
277 | std::string Cmd; |
278 | for (auto &S : Args) { |
279 | if (FlagValue(Param: S.c_str(), Name: X1) || FlagValue(Param: S.c_str(), Name: X2)) |
280 | continue; |
281 | Cmd += S + " " ; |
282 | } |
283 | return Cmd; |
284 | } |
285 | |
286 | static int RunInMultipleProcesses(const std::vector<std::string> &Args, |
287 | unsigned NumWorkers, unsigned NumJobs) { |
288 | std::atomic<unsigned> Counter(0); |
289 | std::atomic<bool> HasErrors(false); |
290 | Command Cmd(Args); |
291 | Cmd.removeFlag(Flag: "jobs" ); |
292 | Cmd.removeFlag(Flag: "workers" ); |
293 | std::vector<std::thread> V; |
294 | std::thread Pulse(PulseThread); |
295 | Pulse.detach(); |
296 | V.resize(new_size: NumWorkers); |
297 | for (unsigned i = 0; i < NumWorkers; i++) { |
298 | V[i] = std::thread(WorkerThread, std::ref(t&: Cmd), &Counter, NumJobs, |
299 | &HasErrors); |
300 | SetThreadName(thread&: V[i], name: "FuzzerWorker" ); |
301 | } |
302 | for (auto &T : V) |
303 | T.join(); |
304 | return HasErrors ? 1 : 0; |
305 | } |
306 | |
307 | static void (Fuzzer *F, size_t ) { |
308 | while (true) { |
309 | SleepSeconds(Seconds: 1); |
310 | size_t Peak = GetPeakRSSMb(); |
311 | if (Peak > RssLimitMb) |
312 | F->RssLimitCallback(); |
313 | } |
314 | } |
315 | |
316 | static void (Fuzzer *F, size_t ) { |
317 | if (!RssLimitMb) |
318 | return; |
319 | std::thread T(RssThread, F, RssLimitMb); |
320 | T.detach(); |
321 | } |
322 | |
323 | int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) { |
324 | Unit U = FileToVector(Path: InputFilePath); |
325 | if (MaxLen && MaxLen < U.size()) |
326 | U.resize(new_size: MaxLen); |
327 | F->ExecuteCallback(Data: U.data(), Size: U.size()); |
328 | if (Flags.print_full_coverage) { |
329 | // Leak detection is not needed when collecting full coverage data. |
330 | F->TPCUpdateObservedPCs(); |
331 | } else { |
332 | F->TryDetectingAMemoryLeak(Data: U.data(), Size: U.size(), DuringInitialCorpusExecution: true); |
333 | } |
334 | return 0; |
335 | } |
336 | |
337 | static bool AllInputsAreFiles() { |
338 | if (Inputs->empty()) return false; |
339 | for (auto &Path : *Inputs) |
340 | if (!IsFile(Path)) |
341 | return false; |
342 | return true; |
343 | } |
344 | |
345 | static std::string GetDedupTokenFromCmdOutput(const std::string &S) { |
346 | auto Beg = S.find(s: "DEDUP_TOKEN:" ); |
347 | if (Beg == std::string::npos) |
348 | return "" ; |
349 | auto End = S.find(c: '\n', pos: Beg); |
350 | if (End == std::string::npos) |
351 | return "" ; |
352 | return S.substr(pos: Beg, n: End - Beg); |
353 | } |
354 | |
355 | int CleanseCrashInput(const std::vector<std::string> &Args, |
356 | const FuzzingOptions &Options) { |
357 | if (Inputs->size() != 1 || !Flags.exact_artifact_path) { |
358 | Printf(Fmt: "ERROR: -cleanse_crash should be given one input file and" |
359 | " -exact_artifact_path\n" ); |
360 | exit(status: 1); |
361 | } |
362 | std::string InputFilePath = Inputs->at(n: 0); |
363 | std::string OutputFilePath = Flags.exact_artifact_path; |
364 | Command Cmd(Args); |
365 | Cmd.removeFlag(Flag: "cleanse_crash" ); |
366 | |
367 | assert(Cmd.hasArgument(InputFilePath)); |
368 | Cmd.removeArgument(Arg: InputFilePath); |
369 | |
370 | auto TmpFilePath = TempPath(Prefix: "CleanseCrashInput" , Extension: ".repro" ); |
371 | Cmd.addArgument(Arg: TmpFilePath); |
372 | Cmd.setOutputFile(getDevNull()); |
373 | Cmd.combineOutAndErr(); |
374 | |
375 | std::string CurrentFilePath = InputFilePath; |
376 | auto U = FileToVector(Path: CurrentFilePath); |
377 | size_t Size = U.size(); |
378 | |
379 | const std::vector<uint8_t> ReplacementBytes = {' ', 0xff}; |
380 | for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) { |
381 | bool Changed = false; |
382 | for (size_t Idx = 0; Idx < Size; Idx++) { |
383 | Printf(Fmt: "CLEANSE[%d]: Trying to replace byte %zd of %zd\n" , NumAttempts, |
384 | Idx, Size); |
385 | uint8_t OriginalByte = U[Idx]; |
386 | if (ReplacementBytes.end() != std::find(first: ReplacementBytes.begin(), |
387 | last: ReplacementBytes.end(), |
388 | val: OriginalByte)) |
389 | continue; |
390 | for (auto NewByte : ReplacementBytes) { |
391 | U[Idx] = NewByte; |
392 | WriteToFile(U, Path: TmpFilePath); |
393 | auto ExitCode = ExecuteCommand(Cmd); |
394 | RemoveFile(Path: TmpFilePath); |
395 | if (!ExitCode) { |
396 | U[Idx] = OriginalByte; |
397 | } else { |
398 | Changed = true; |
399 | Printf(Fmt: "CLEANSE: Replaced byte %zd with 0x%x\n" , Idx, NewByte); |
400 | WriteToFile(U, Path: OutputFilePath); |
401 | break; |
402 | } |
403 | } |
404 | } |
405 | if (!Changed) break; |
406 | } |
407 | return 0; |
408 | } |
409 | |
410 | int MinimizeCrashInput(const std::vector<std::string> &Args, |
411 | const FuzzingOptions &Options) { |
412 | if (Inputs->size() != 1) { |
413 | Printf(Fmt: "ERROR: -minimize_crash should be given one input file\n" ); |
414 | exit(status: 1); |
415 | } |
416 | std::string InputFilePath = Inputs->at(n: 0); |
417 | Command BaseCmd(Args); |
418 | BaseCmd.removeFlag(Flag: "minimize_crash" ); |
419 | BaseCmd.removeFlag(Flag: "exact_artifact_path" ); |
420 | assert(BaseCmd.hasArgument(InputFilePath)); |
421 | BaseCmd.removeArgument(Arg: InputFilePath); |
422 | if (Flags.runs <= 0 && Flags.max_total_time == 0) { |
423 | Printf(Fmt: "INFO: you need to specify -runs=N or " |
424 | "-max_total_time=N with -minimize_crash=1\n" |
425 | "INFO: defaulting to -max_total_time=600\n" ); |
426 | BaseCmd.addFlag(Flag: "max_total_time" , Value: "600" ); |
427 | } |
428 | |
429 | BaseCmd.combineOutAndErr(); |
430 | |
431 | std::string CurrentFilePath = InputFilePath; |
432 | while (true) { |
433 | Unit U = FileToVector(Path: CurrentFilePath); |
434 | Printf(Fmt: "CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n" , |
435 | CurrentFilePath.c_str(), U.size()); |
436 | |
437 | Command Cmd(BaseCmd); |
438 | Cmd.addArgument(Arg: CurrentFilePath); |
439 | |
440 | Printf(Fmt: "CRASH_MIN: executing: %s\n" , Cmd.toString().c_str()); |
441 | std::string CmdOutput; |
442 | bool Success = ExecuteCommand(Cmd, CmdOutput: &CmdOutput); |
443 | if (Success) { |
444 | Printf(Fmt: "ERROR: the input %s did not crash\n" , CurrentFilePath.c_str()); |
445 | exit(status: 1); |
446 | } |
447 | Printf(Fmt: "CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize " |
448 | "it further\n" , |
449 | CurrentFilePath.c_str(), U.size()); |
450 | auto DedupToken1 = GetDedupTokenFromCmdOutput(S: CmdOutput); |
451 | if (!DedupToken1.empty()) |
452 | Printf(Fmt: "CRASH_MIN: DedupToken1: %s\n" , DedupToken1.c_str()); |
453 | |
454 | std::string ArtifactPath = |
455 | Flags.exact_artifact_path |
456 | ? Flags.exact_artifact_path |
457 | : Options.ArtifactPrefix + "minimized-from-" + Hash(U); |
458 | Cmd.addFlag(Flag: "minimize_crash_internal_step" , Value: "1" ); |
459 | Cmd.addFlag(Flag: "exact_artifact_path" , Value: ArtifactPath); |
460 | Printf(Fmt: "CRASH_MIN: executing: %s\n" , Cmd.toString().c_str()); |
461 | CmdOutput.clear(); |
462 | Success = ExecuteCommand(Cmd, CmdOutput: &CmdOutput); |
463 | Printf(Fmt: "%s" , CmdOutput.c_str()); |
464 | if (Success) { |
465 | if (Flags.exact_artifact_path) { |
466 | CurrentFilePath = Flags.exact_artifact_path; |
467 | WriteToFile(U, Path: CurrentFilePath); |
468 | } |
469 | Printf(Fmt: "CRASH_MIN: failed to minimize beyond %s (%zu bytes), exiting\n" , |
470 | CurrentFilePath.c_str(), U.size()); |
471 | break; |
472 | } |
473 | auto DedupToken2 = GetDedupTokenFromCmdOutput(S: CmdOutput); |
474 | if (!DedupToken2.empty()) |
475 | Printf(Fmt: "CRASH_MIN: DedupToken2: %s\n" , DedupToken2.c_str()); |
476 | |
477 | if (DedupToken1 != DedupToken2) { |
478 | if (Flags.exact_artifact_path) { |
479 | CurrentFilePath = Flags.exact_artifact_path; |
480 | WriteToFile(U, Path: CurrentFilePath); |
481 | } |
482 | Printf(Fmt: "CRASH_MIN: mismatch in dedup tokens" |
483 | " (looks like a different bug). Won't minimize further\n" ); |
484 | break; |
485 | } |
486 | |
487 | CurrentFilePath = ArtifactPath; |
488 | Printf(Fmt: "*********************************\n" ); |
489 | } |
490 | return 0; |
491 | } |
492 | |
493 | int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) { |
494 | assert(Inputs->size() == 1); |
495 | std::string InputFilePath = Inputs->at(n: 0); |
496 | Unit U = FileToVector(Path: InputFilePath); |
497 | Printf(Fmt: "INFO: Starting MinimizeCrashInputInternalStep: %zd\n" , U.size()); |
498 | if (U.size() < 2) { |
499 | Printf(Fmt: "INFO: The input is small enough, exiting\n" ); |
500 | exit(status: 0); |
501 | } |
502 | F->SetMaxInputLen(U.size()); |
503 | F->SetMaxMutationLen(U.size() - 1); |
504 | F->MinimizeCrashLoop(U); |
505 | Printf(Fmt: "INFO: Done MinimizeCrashInputInternalStep, no crashes found\n" ); |
506 | exit(status: 0); |
507 | } |
508 | |
509 | void Merge(Fuzzer *F, FuzzingOptions &Options, |
510 | const std::vector<std::string> &Args, |
511 | const std::vector<std::string> &Corpora, const char *CFPathOrNull) { |
512 | if (Corpora.size() < 2) { |
513 | Printf(Fmt: "INFO: Merge requires two or more corpus dirs\n" ); |
514 | exit(status: 0); |
515 | } |
516 | |
517 | std::vector<SizedFile> OldCorpus, NewCorpus; |
518 | GetSizedFilesFromDir(Dir: Corpora[0], V: &OldCorpus); |
519 | for (size_t i = 1; i < Corpora.size(); i++) |
520 | GetSizedFilesFromDir(Dir: Corpora[i], V: &NewCorpus); |
521 | std::sort(first: OldCorpus.begin(), last: OldCorpus.end()); |
522 | std::sort(first: NewCorpus.begin(), last: NewCorpus.end()); |
523 | |
524 | std::string CFPath = CFPathOrNull ? CFPathOrNull : TempPath(Prefix: "Merge" , Extension: ".txt" ); |
525 | std::vector<std::string> NewFiles; |
526 | std::set<uint32_t> NewFeatures, NewCov; |
527 | CrashResistantMerge(Args, OldCorpus, NewCorpus, NewFiles: &NewFiles, InitialFeatures: {}, NewFeatures: &NewFeatures, |
528 | InitialCov: {}, NewCov: &NewCov, CFPath, Verbose: true, IsSetCoverMerge: Flags.set_cover_merge); |
529 | for (auto &Path : NewFiles) |
530 | F->WriteToOutputCorpus(U: FileToVector(Path, MaxSize: Options.MaxLen)); |
531 | // We are done, delete the control file if it was a temporary one. |
532 | if (!Flags.merge_control_file) |
533 | RemoveFile(Path: CFPath); |
534 | |
535 | exit(status: 0); |
536 | } |
537 | |
538 | int AnalyzeDictionary(Fuzzer *F, const std::vector<Unit> &Dict, |
539 | UnitVector &Corpus) { |
540 | Printf(Fmt: "Started dictionary minimization (up to %zu tests)\n" , |
541 | Dict.size() * Corpus.size() * 2); |
542 | |
543 | // Scores and usage count for each dictionary unit. |
544 | std::vector<int> Scores(Dict.size()); |
545 | std::vector<int> Usages(Dict.size()); |
546 | |
547 | std::vector<size_t> InitialFeatures; |
548 | std::vector<size_t> ModifiedFeatures; |
549 | for (auto &C : Corpus) { |
550 | // Get coverage for the testcase without modifications. |
551 | F->ExecuteCallback(Data: C.data(), Size: C.size()); |
552 | InitialFeatures.clear(); |
553 | TPC.CollectFeatures(HandleFeature: [&](size_t Feature) { |
554 | InitialFeatures.push_back(x: Feature); |
555 | }); |
556 | |
557 | for (size_t i = 0; i < Dict.size(); ++i) { |
558 | std::vector<uint8_t> Data = C; |
559 | auto StartPos = std::search(first1: Data.begin(), last1: Data.end(), |
560 | first2: Dict[i].begin(), last2: Dict[i].end()); |
561 | // Skip dictionary unit, if the testcase does not contain it. |
562 | if (StartPos == Data.end()) |
563 | continue; |
564 | |
565 | ++Usages[i]; |
566 | while (StartPos != Data.end()) { |
567 | // Replace all occurrences of dictionary unit in the testcase. |
568 | auto EndPos = StartPos + Dict[i].size(); |
569 | for (auto It = StartPos; It != EndPos; ++It) |
570 | *It ^= 0xFF; |
571 | |
572 | StartPos = std::search(first1: EndPos, last1: Data.end(), |
573 | first2: Dict[i].begin(), last2: Dict[i].end()); |
574 | } |
575 | |
576 | // Get coverage for testcase with masked occurrences of dictionary unit. |
577 | F->ExecuteCallback(Data: Data.data(), Size: Data.size()); |
578 | ModifiedFeatures.clear(); |
579 | TPC.CollectFeatures(HandleFeature: [&](size_t Feature) { |
580 | ModifiedFeatures.push_back(x: Feature); |
581 | }); |
582 | |
583 | if (InitialFeatures == ModifiedFeatures) |
584 | --Scores[i]; |
585 | else |
586 | Scores[i] += 2; |
587 | } |
588 | } |
589 | |
590 | Printf(Fmt: "###### Useless dictionary elements. ######\n" ); |
591 | for (size_t i = 0; i < Dict.size(); ++i) { |
592 | // Dictionary units with positive score are treated as useful ones. |
593 | if (Scores[i] > 0) |
594 | continue; |
595 | |
596 | Printf(Fmt: "\"" ); |
597 | PrintASCII(Data: Dict[i].data(), Size: Dict[i].size(), PrintAfter: "\"" ); |
598 | Printf(Fmt: " # Score: %d, Used: %d\n" , Scores[i], Usages[i]); |
599 | } |
600 | Printf(Fmt: "###### End of useless dictionary elements. ######\n" ); |
601 | return 0; |
602 | } |
603 | |
604 | std::vector<std::string> ParseSeedInuts(const char *seed_inputs) { |
605 | // Parse -seed_inputs=file1,file2,... or -seed_inputs=@seed_inputs_file |
606 | std::vector<std::string> Files; |
607 | if (!seed_inputs) return Files; |
608 | std::string SeedInputs; |
609 | if (Flags.seed_inputs[0] == '@') |
610 | SeedInputs = FileToString(Path: Flags.seed_inputs + 1); // File contains list. |
611 | else |
612 | SeedInputs = Flags.seed_inputs; // seed_inputs contains the list. |
613 | if (SeedInputs.empty()) { |
614 | Printf(Fmt: "seed_inputs is empty or @file does not exist.\n" ); |
615 | exit(status: 1); |
616 | } |
617 | // Parse SeedInputs. |
618 | size_t comma_pos = 0; |
619 | while ((comma_pos = SeedInputs.find_last_of(c: ',')) != std::string::npos) { |
620 | Files.push_back(x: SeedInputs.substr(pos: comma_pos + 1)); |
621 | SeedInputs = SeedInputs.substr(pos: 0, n: comma_pos); |
622 | } |
623 | Files.push_back(x: SeedInputs); |
624 | return Files; |
625 | } |
626 | |
627 | static std::vector<SizedFile> |
628 | ReadCorpora(const std::vector<std::string> &CorpusDirs, |
629 | const std::vector<std::string> &) { |
630 | std::vector<SizedFile> SizedFiles; |
631 | size_t LastNumFiles = 0; |
632 | for (auto &Dir : CorpusDirs) { |
633 | GetSizedFilesFromDir(Dir, V: &SizedFiles); |
634 | Printf(Fmt: "INFO: % 8zd files found in %s\n" , SizedFiles.size() - LastNumFiles, |
635 | Dir.c_str()); |
636 | LastNumFiles = SizedFiles.size(); |
637 | } |
638 | for (auto &File : ExtraSeedFiles) |
639 | if (auto Size = FileSize(Path: File)) |
640 | SizedFiles.push_back(x: {.File: File, .Size: Size}); |
641 | return SizedFiles; |
642 | } |
643 | |
644 | int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) { |
645 | using namespace fuzzer; |
646 | assert(argc && argv && "Argument pointers cannot be nullptr" ); |
647 | std::string Argv0((*argv)[0]); |
648 | EF = new ExternalFunctions(); |
649 | if (EF->LLVMFuzzerInitialize) |
650 | EF->LLVMFuzzerInitialize(argc, argv); |
651 | if (EF->__msan_scoped_disable_interceptor_checks) |
652 | EF->__msan_scoped_disable_interceptor_checks(); |
653 | const std::vector<std::string> Args(*argv, *argv + *argc); |
654 | assert(!Args.empty()); |
655 | ProgName = new std::string(Args[0]); |
656 | if (Argv0 != *ProgName) { |
657 | Printf(Fmt: "ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n" ); |
658 | exit(status: 1); |
659 | } |
660 | ParseFlags(Args, EF); |
661 | if (Flags.help) { |
662 | PrintHelp(); |
663 | return 0; |
664 | } |
665 | |
666 | if (Flags.close_fd_mask & 2) |
667 | DupAndCloseStderr(); |
668 | if (Flags.close_fd_mask & 1) |
669 | CloseStdout(); |
670 | |
671 | if (Flags.jobs > 0 && Flags.workers == 0) { |
672 | Flags.workers = std::min(a: NumberOfCpuCores() / 2, b: Flags.jobs); |
673 | if (Flags.workers > 1) |
674 | Printf(Fmt: "Running %u workers\n" , Flags.workers); |
675 | } |
676 | |
677 | if (Flags.workers > 0 && Flags.jobs > 0) |
678 | return RunInMultipleProcesses(Args, NumWorkers: Flags.workers, NumJobs: Flags.jobs); |
679 | |
680 | FuzzingOptions Options; |
681 | Options.Verbosity = Flags.verbosity; |
682 | Options.MaxLen = Flags.max_len; |
683 | Options.LenControl = Flags.len_control; |
684 | Options.KeepSeed = Flags.keep_seed; |
685 | Options.UnitTimeoutSec = Flags.timeout; |
686 | Options.ErrorExitCode = Flags.error_exitcode; |
687 | Options.TimeoutExitCode = Flags.timeout_exitcode; |
688 | Options.IgnoreTimeouts = Flags.ignore_timeouts; |
689 | Options.IgnoreOOMs = Flags.ignore_ooms; |
690 | Options.IgnoreCrashes = Flags.ignore_crashes; |
691 | Options.MaxTotalTimeSec = Flags.max_total_time; |
692 | Options.DoCrossOver = Flags.cross_over; |
693 | Options.CrossOverUniformDist = Flags.cross_over_uniform_dist; |
694 | Options.MutateDepth = Flags.mutate_depth; |
695 | Options.ReduceDepth = Flags.reduce_depth; |
696 | Options.UseCounters = Flags.use_counters; |
697 | Options.UseMemmem = Flags.use_memmem; |
698 | Options.UseCmp = Flags.use_cmp; |
699 | Options.UseValueProfile = Flags.use_value_profile; |
700 | Options.Shrink = Flags.shrink; |
701 | Options.ReduceInputs = Flags.reduce_inputs; |
702 | Options.ShuffleAtStartUp = Flags.shuffle; |
703 | Options.PreferSmall = Flags.prefer_small; |
704 | Options.ReloadIntervalSec = Flags.reload; |
705 | Options.OnlyASCII = Flags.only_ascii; |
706 | Options.DetectLeaks = Flags.detect_leaks; |
707 | Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval; |
708 | Options.TraceMalloc = Flags.trace_malloc; |
709 | Options.RssLimitMb = Flags.rss_limit_mb; |
710 | Options.MallocLimitMb = Flags.malloc_limit_mb; |
711 | if (!Options.MallocLimitMb) |
712 | Options.MallocLimitMb = Options.RssLimitMb; |
713 | if (Flags.runs >= 0) |
714 | Options.MaxNumberOfRuns = Flags.runs; |
715 | if (!Inputs->empty() && !Flags.minimize_crash_internal_step) { |
716 | // Ensure output corpus assumed to be the first arbitrary argument input |
717 | // is not a path to an existing file. |
718 | std::string OutputCorpusDir = (*Inputs)[0]; |
719 | if (!IsFile(Path: OutputCorpusDir)) { |
720 | Options.OutputCorpus = OutputCorpusDir; |
721 | ValidateDirectoryExists(Path: Options.OutputCorpus, CreateDirectory: Flags.create_missing_dirs); |
722 | } |
723 | } |
724 | Options.ReportSlowUnits = Flags.report_slow_units; |
725 | if (Flags.artifact_prefix) { |
726 | Options.ArtifactPrefix = Flags.artifact_prefix; |
727 | |
728 | // Since the prefix could be a full path to a file name prefix, assume |
729 | // that if the path ends with the platform's separator that a directory |
730 | // is desired |
731 | std::string ArtifactPathDir = Options.ArtifactPrefix; |
732 | if (!IsSeparator(C: ArtifactPathDir[ArtifactPathDir.length() - 1])) { |
733 | ArtifactPathDir = DirName(FileName: ArtifactPathDir); |
734 | } |
735 | ValidateDirectoryExists(Path: ArtifactPathDir, CreateDirectory: Flags.create_missing_dirs); |
736 | } |
737 | if (Flags.exact_artifact_path) { |
738 | Options.ExactArtifactPath = Flags.exact_artifact_path; |
739 | ValidateDirectoryExists(Path: DirName(FileName: Options.ExactArtifactPath), |
740 | CreateDirectory: Flags.create_missing_dirs); |
741 | } |
742 | std::vector<Unit> Dictionary; |
743 | if (Flags.dict) |
744 | if (!ParseDictionaryFile(Text: FileToString(Path: Flags.dict), Units: &Dictionary)) |
745 | return 1; |
746 | if (Flags.verbosity > 0 && !Dictionary.empty()) |
747 | Printf(Fmt: "Dictionary: %zd entries\n" , Dictionary.size()); |
748 | bool RunIndividualFiles = AllInputsAreFiles(); |
749 | Options.SaveArtifacts = |
750 | !RunIndividualFiles || Flags.minimize_crash_internal_step; |
751 | Options.PrintNewCovPcs = Flags.print_pcs; |
752 | Options.PrintNewCovFuncs = Flags.print_funcs; |
753 | Options.PrintFinalStats = Flags.print_final_stats; |
754 | Options.PrintCorpusStats = Flags.print_corpus_stats; |
755 | Options.PrintCoverage = Flags.print_coverage; |
756 | Options.PrintFullCoverage = Flags.print_full_coverage; |
757 | if (Flags.exit_on_src_pos) |
758 | Options.ExitOnSrcPos = Flags.exit_on_src_pos; |
759 | if (Flags.exit_on_item) |
760 | Options.ExitOnItem = Flags.exit_on_item; |
761 | if (Flags.focus_function) |
762 | Options.FocusFunction = Flags.focus_function; |
763 | if (Flags.data_flow_trace) |
764 | Options.DataFlowTrace = Flags.data_flow_trace; |
765 | if (Flags.features_dir) { |
766 | Options.FeaturesDir = Flags.features_dir; |
767 | ValidateDirectoryExists(Path: Options.FeaturesDir, CreateDirectory: Flags.create_missing_dirs); |
768 | } |
769 | if (Flags.mutation_graph_file) |
770 | Options.MutationGraphFile = Flags.mutation_graph_file; |
771 | if (Flags.collect_data_flow) |
772 | Options.CollectDataFlow = Flags.collect_data_flow; |
773 | if (Flags.stop_file) |
774 | Options.StopFile = Flags.stop_file; |
775 | Options.Entropic = Flags.entropic; |
776 | Options.EntropicFeatureFrequencyThreshold = |
777 | (size_t)Flags.entropic_feature_frequency_threshold; |
778 | Options.EntropicNumberOfRarestFeatures = |
779 | (size_t)Flags.entropic_number_of_rarest_features; |
780 | Options.EntropicScalePerExecTime = Flags.entropic_scale_per_exec_time; |
781 | if (!Options.FocusFunction.empty()) |
782 | Options.Entropic = false; // FocusFunction overrides entropic scheduling. |
783 | if (Options.Entropic) |
784 | Printf(Fmt: "INFO: Running with entropic power schedule (0x%zX, %zu).\n" , |
785 | Options.EntropicFeatureFrequencyThreshold, |
786 | Options.EntropicNumberOfRarestFeatures); |
787 | struct EntropicOptions Entropic; |
788 | Entropic.Enabled = Options.Entropic; |
789 | Entropic.FeatureFrequencyThreshold = |
790 | Options.EntropicFeatureFrequencyThreshold; |
791 | Entropic.NumberOfRarestFeatures = Options.EntropicNumberOfRarestFeatures; |
792 | Entropic.ScalePerExecTime = Options.EntropicScalePerExecTime; |
793 | |
794 | unsigned Seed = Flags.seed; |
795 | // Initialize Seed. |
796 | if (Seed == 0) |
797 | Seed = static_cast<unsigned>( |
798 | std::chrono::system_clock::now().time_since_epoch().count() + GetPid()); |
799 | if (Flags.verbosity) |
800 | Printf(Fmt: "INFO: Seed: %u\n" , Seed); |
801 | |
802 | if (Flags.collect_data_flow && Flags.data_flow_trace && !Flags.fork && |
803 | !(Flags.merge || Flags.set_cover_merge)) { |
804 | if (RunIndividualFiles) |
805 | return CollectDataFlow(DFTBinary: Flags.collect_data_flow, DirPath: Flags.data_flow_trace, |
806 | CorporaFiles: ReadCorpora(CorpusDirs: {}, ExtraSeedFiles: *Inputs)); |
807 | else |
808 | return CollectDataFlow(DFTBinary: Flags.collect_data_flow, DirPath: Flags.data_flow_trace, |
809 | CorporaFiles: ReadCorpora(CorpusDirs: *Inputs, ExtraSeedFiles: {})); |
810 | } |
811 | |
812 | Random Rand(Seed); |
813 | auto *MD = new MutationDispatcher(Rand, Options); |
814 | auto *Corpus = new InputCorpus(Options.OutputCorpus, Entropic); |
815 | auto *F = new Fuzzer(Callback, *Corpus, *MD, Options); |
816 | |
817 | for (auto &U: Dictionary) |
818 | if (U.size() <= Word::GetMaxSize()) |
819 | MD->AddWordToManualDictionary(W: Word(U.data(), U.size())); |
820 | |
821 | // Threads are only supported by Chrome. Don't use them with emscripten |
822 | // for now. |
823 | #if !LIBFUZZER_EMSCRIPTEN |
824 | StartRssThread(F, RssLimitMb: Flags.rss_limit_mb); |
825 | #endif // LIBFUZZER_EMSCRIPTEN |
826 | |
827 | Options.HandleAbrt = Flags.handle_abrt; |
828 | Options.HandleAlrm = !Flags.minimize_crash; |
829 | Options.HandleBus = Flags.handle_bus; |
830 | Options.HandleFpe = Flags.handle_fpe; |
831 | Options.HandleIll = Flags.handle_ill; |
832 | Options.HandleInt = Flags.handle_int; |
833 | Options.HandleSegv = Flags.handle_segv; |
834 | Options.HandleTerm = Flags.handle_term; |
835 | Options.HandleXfsz = Flags.handle_xfsz; |
836 | Options.HandleUsr1 = Flags.handle_usr1; |
837 | Options.HandleUsr2 = Flags.handle_usr2; |
838 | Options.HandleWinExcept = Flags.handle_winexcept; |
839 | |
840 | SetSignalHandler(Options); |
841 | |
842 | std::atexit(func: Fuzzer::StaticExitCallback); |
843 | |
844 | if (Flags.minimize_crash) |
845 | return MinimizeCrashInput(Args, Options); |
846 | |
847 | if (Flags.minimize_crash_internal_step) |
848 | return MinimizeCrashInputInternalStep(F, Corpus); |
849 | |
850 | if (Flags.cleanse_crash) |
851 | return CleanseCrashInput(Args, Options); |
852 | |
853 | if (RunIndividualFiles) { |
854 | Options.SaveArtifacts = false; |
855 | int Runs = std::max(a: 1, b: Flags.runs); |
856 | Printf(Fmt: "%s: Running %zd inputs %d time(s) each.\n" , ProgName->c_str(), |
857 | Inputs->size(), Runs); |
858 | for (auto &Path : *Inputs) { |
859 | auto StartTime = system_clock::now(); |
860 | Printf(Fmt: "Running: %s\n" , Path.c_str()); |
861 | for (int Iter = 0; Iter < Runs; Iter++) |
862 | RunOneTest(F, InputFilePath: Path.c_str(), MaxLen: Options.MaxLen); |
863 | auto StopTime = system_clock::now(); |
864 | auto MS = duration_cast<milliseconds>(d: StopTime - StartTime).count(); |
865 | Printf(Fmt: "Executed %s in %ld ms\n" , Path.c_str(), (long)MS); |
866 | } |
867 | Printf(Fmt: "***\n" |
868 | "*** NOTE: fuzzing was not performed, you have only\n" |
869 | "*** executed the target code on a fixed set of inputs.\n" |
870 | "***\n" ); |
871 | F->PrintFinalStats(); |
872 | exit(status: 0); |
873 | } |
874 | |
875 | Options.ForkCorpusGroups = Flags.fork_corpus_groups; |
876 | if (Flags.fork) |
877 | FuzzWithFork(Rand&: F->GetMD().GetRand(), Options, Args, CorpusDirs: *Inputs, NumJobs: Flags.fork); |
878 | |
879 | if (Flags.merge || Flags.set_cover_merge) |
880 | Merge(F, Options, Args, Corpora: *Inputs, CFPathOrNull: Flags.merge_control_file); |
881 | |
882 | if (Flags.merge_inner) { |
883 | const size_t kDefaultMaxMergeLen = 1 << 20; |
884 | if (Options.MaxLen == 0) |
885 | F->SetMaxInputLen(kDefaultMaxMergeLen); |
886 | assert(Flags.merge_control_file); |
887 | F->CrashResistantMergeInternalStep(ControlFilePath: Flags.merge_control_file, |
888 | IsSetCoverMerge: !strncmp(s1: Flags.merge_inner, s2: "2" , n: 1)); |
889 | exit(status: 0); |
890 | } |
891 | |
892 | if (Flags.analyze_dict) { |
893 | size_t MaxLen = INT_MAX; // Large max length. |
894 | UnitVector InitialCorpus; |
895 | for (auto &Inp : *Inputs) { |
896 | Printf(Fmt: "Loading corpus dir: %s\n" , Inp.c_str()); |
897 | ReadDirToVectorOfUnits(Path: Inp.c_str(), V: &InitialCorpus, Epoch: nullptr, |
898 | MaxSize: MaxLen, /*ExitOnError=*/false); |
899 | } |
900 | |
901 | if (Dictionary.empty() || Inputs->empty()) { |
902 | Printf(Fmt: "ERROR: can't analyze dict without dict and corpus provided\n" ); |
903 | return 1; |
904 | } |
905 | if (AnalyzeDictionary(F, Dict: Dictionary, Corpus&: InitialCorpus)) { |
906 | Printf(Fmt: "Dictionary analysis failed\n" ); |
907 | exit(status: 1); |
908 | } |
909 | Printf(Fmt: "Dictionary analysis succeeded\n" ); |
910 | exit(status: 0); |
911 | } |
912 | |
913 | auto CorporaFiles = ReadCorpora(CorpusDirs: *Inputs, ExtraSeedFiles: ParseSeedInuts(seed_inputs: Flags.seed_inputs)); |
914 | F->Loop(CorporaFiles); |
915 | |
916 | if (Flags.verbosity) |
917 | Printf(Fmt: "Done %zd runs in %zd second(s)\n" , F->getTotalNumberOfRuns(), |
918 | F->secondsSinceProcessStartUp()); |
919 | F->PrintFinalStats(); |
920 | |
921 | exit(status: 0); // Don't let F destroy itself. |
922 | } |
923 | |
924 | extern "C" ATTRIBUTE_INTERFACE int |
925 | LLVMFuzzerRunDriver(int *argc, char ***argv, |
926 | int (*UserCb)(const uint8_t *Data, size_t Size)) { |
927 | return FuzzerDriver(argc, argv, Callback: UserCb); |
928 | } |
929 | |
930 | // Storage for global ExternalFunctions object. |
931 | ExternalFunctions *EF = nullptr; |
932 | |
933 | } // namespace fuzzer |
934 | |