blob: a0c9f185f7c9f3e5727d8382392403c67a3a7af0 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +00001//===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===//
2//
chandlerc40284492019-01-19 08:50:56 +00003// 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
george.karpenkov29efa6d2017-08-21 23:25:50 +00006//
7//===----------------------------------------------------------------------===//
8// FuzzerDriver and flag parsing.
9//===----------------------------------------------------------------------===//
10
morehousea80f6452017-12-04 19:25:59 +000011#include "FuzzerCommand.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000012#include "FuzzerCorpus.h"
13#include "FuzzerIO.h"
14#include "FuzzerInterface.h"
15#include "FuzzerInternal.h"
16#include "FuzzerMutate.h"
17#include "FuzzerRandom.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000018#include "FuzzerTracePC.h"
kcca3815862019-02-08 21:27:23 +000019#include "FuzzerMerge.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000020#include <algorithm>
21#include <atomic>
22#include <chrono>
23#include <cstdlib>
24#include <cstring>
25#include <mutex>
26#include <string>
27#include <thread>
kcca3815862019-02-08 21:27:23 +000028#include <fstream>
george.karpenkov29efa6d2017-08-21 23:25:50 +000029
30// This function should be present in the libFuzzer so that the client
31// binary can test for its existence.
metzman2fe66e62019-01-17 16:36:05 +000032#if LIBFUZZER_MSVC
33extern "C" void __libfuzzer_is_present() {}
34#pragma comment(linker, "/include:__libfuzzer_is_present")
35#else
george.karpenkov29efa6d2017-08-21 23:25:50 +000036extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
metzman2fe66e62019-01-17 16:36:05 +000037#endif // LIBFUZZER_MSVC
george.karpenkov29efa6d2017-08-21 23:25:50 +000038
39namespace fuzzer {
40
41// Program arguments.
42struct FlagDescription {
43 const char *Name;
44 const char *Description;
45 int Default;
46 int *IntFlag;
47 const char **StrFlag;
48 unsigned int *UIntFlag;
49};
50
51struct {
52#define FUZZER_DEPRECATED_FLAG(Name)
53#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
54#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
55#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
56#include "FuzzerFlags.def"
57#undef FUZZER_DEPRECATED_FLAG
58#undef FUZZER_FLAG_INT
59#undef FUZZER_FLAG_UNSIGNED
60#undef FUZZER_FLAG_STRING
61} Flags;
62
63static const FlagDescription FlagDescriptions [] {
64#define FUZZER_DEPRECATED_FLAG(Name) \
65 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
66#define FUZZER_FLAG_INT(Name, Default, Description) \
67 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
68#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
69 {#Name, Description, static_cast<int>(Default), \
70 nullptr, nullptr, &Flags.Name},
71#define FUZZER_FLAG_STRING(Name, Description) \
72 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
73#include "FuzzerFlags.def"
74#undef FUZZER_DEPRECATED_FLAG
75#undef FUZZER_FLAG_INT
76#undef FUZZER_FLAG_UNSIGNED
77#undef FUZZER_FLAG_STRING
78};
79
80static const size_t kNumFlags =
81 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
82
george.karpenkovfbfa45c2017-08-27 23:20:09 +000083static Vector<std::string> *Inputs;
george.karpenkov29efa6d2017-08-21 23:25:50 +000084static std::string *ProgName;
85
86static void PrintHelp() {
87 Printf("Usage:\n");
88 auto Prog = ProgName->c_str();
89 Printf("\nTo run fuzzing pass 0 or more directories.\n");
90 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
91
92 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
93 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
94
95 Printf("\nFlags: (strictly in form -flag=value)\n");
96 size_t MaxFlagLen = 0;
97 for (size_t F = 0; F < kNumFlags; F++)
98 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
99
100 for (size_t F = 0; F < kNumFlags; F++) {
101 const auto &D = FlagDescriptions[F];
102 if (strstr(D.Description, "internal flag") == D.Description) continue;
103 Printf(" %s", D.Name);
104 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
105 Printf(" ");
106 Printf("\t");
107 Printf("%d\t%s\n", D.Default, D.Description);
108 }
109 Printf("\nFlags starting with '--' will be ignored and "
dor1se6729cb2018-07-16 15:15:34 +0000110 "will be passed verbatim to subprocesses.\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000111}
112
113static const char *FlagValue(const char *Param, const char *Name) {
114 size_t Len = strlen(Name);
115 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
116 Param[Len + 1] == '=')
dor1se6729cb2018-07-16 15:15:34 +0000117 return &Param[Len + 2];
george.karpenkov29efa6d2017-08-21 23:25:50 +0000118 return nullptr;
119}
120
121// Avoid calling stol as it triggers a bug in clang/glibc build.
122static long MyStol(const char *Str) {
123 long Res = 0;
124 long Sign = 1;
125 if (*Str == '-') {
126 Str++;
127 Sign = -1;
128 }
129 for (size_t i = 0; Str[i]; i++) {
130 char Ch = Str[i];
131 if (Ch < '0' || Ch > '9')
132 return Res;
133 Res = Res * 10 + (Ch - '0');
134 }
135 return Res * Sign;
136}
137
138static bool ParseOneFlag(const char *Param) {
139 if (Param[0] != '-') return false;
140 if (Param[1] == '-') {
141 static bool PrintedWarning = false;
142 if (!PrintedWarning) {
143 PrintedWarning = true;
144 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
145 }
146 for (size_t F = 0; F < kNumFlags; F++)
147 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
148 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
149 return true;
150 }
151 for (size_t F = 0; F < kNumFlags; F++) {
152 const char *Name = FlagDescriptions[F].Name;
153 const char *Str = FlagValue(Param, Name);
154 if (Str) {
155 if (FlagDescriptions[F].IntFlag) {
156 int Val = MyStol(Str);
157 *FlagDescriptions[F].IntFlag = Val;
158 if (Flags.verbosity >= 2)
159 Printf("Flag: %s %d\n", Name, Val);
160 return true;
161 } else if (FlagDescriptions[F].UIntFlag) {
162 unsigned int Val = std::stoul(Str);
163 *FlagDescriptions[F].UIntFlag = Val;
164 if (Flags.verbosity >= 2)
165 Printf("Flag: %s %u\n", Name, Val);
166 return true;
167 } else if (FlagDescriptions[F].StrFlag) {
168 *FlagDescriptions[F].StrFlag = Str;
169 if (Flags.verbosity >= 2)
170 Printf("Flag: %s %s\n", Name, Str);
171 return true;
172 } else { // Deprecated flag.
173 Printf("Flag: %s: deprecated, don't use\n", Name);
174 return true;
175 }
176 }
177 }
178 Printf("\n\nWARNING: unrecognized flag '%s'; "
179 "use -help=1 to list all flags\n\n", Param);
180 return true;
181}
182
183// We don't use any library to minimize dependencies.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000184static void ParseFlags(const Vector<std::string> &Args) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000185 for (size_t F = 0; F < kNumFlags; F++) {
186 if (FlagDescriptions[F].IntFlag)
187 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
188 if (FlagDescriptions[F].UIntFlag)
189 *FlagDescriptions[F].UIntFlag =
190 static_cast<unsigned int>(FlagDescriptions[F].Default);
191 if (FlagDescriptions[F].StrFlag)
192 *FlagDescriptions[F].StrFlag = nullptr;
193 }
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000194 Inputs = new Vector<std::string>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000195 for (size_t A = 1; A < Args.size(); A++) {
196 if (ParseOneFlag(Args[A].c_str())) {
197 if (Flags.ignore_remaining_args)
198 break;
199 continue;
200 }
201 Inputs->push_back(Args[A]);
202 }
203}
204
205static std::mutex Mu;
206
207static void PulseThread() {
208 while (true) {
209 SleepSeconds(600);
210 std::lock_guard<std::mutex> Lock(Mu);
211 Printf("pulse...\n");
212 }
213}
214
morehousea80f6452017-12-04 19:25:59 +0000215static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000216 unsigned NumJobs, std::atomic<bool> *HasErrors) {
217 while (true) {
218 unsigned C = (*Counter)++;
219 if (C >= NumJobs) break;
220 std::string Log = "fuzz-" + std::to_string(C) + ".log";
morehousea80f6452017-12-04 19:25:59 +0000221 Command Cmd(BaseCmd);
222 Cmd.setOutputFile(Log);
223 Cmd.combineOutAndErr();
224 if (Flags.verbosity) {
225 std::string CommandLine = Cmd.toString();
kccf5628b32017-12-06 22:12:24 +0000226 Printf("%s\n", CommandLine.c_str());
morehousea80f6452017-12-04 19:25:59 +0000227 }
228 int ExitCode = ExecuteCommand(Cmd);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000229 if (ExitCode != 0)
230 *HasErrors = true;
231 std::lock_guard<std::mutex> Lock(Mu);
232 Printf("================== Job %u exited with exit code %d ============\n",
233 C, ExitCode);
234 fuzzer::CopyFileToErr(Log);
235 }
236}
237
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000238std::string CloneArgsWithoutX(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000239 const char *X1, const char *X2) {
240 std::string Cmd;
241 for (auto &S : Args) {
242 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
243 continue;
244 Cmd += S + " ";
245 }
246 return Cmd;
247}
248
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000249static int RunInMultipleProcesses(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000250 unsigned NumWorkers, unsigned NumJobs) {
251 std::atomic<unsigned> Counter(0);
252 std::atomic<bool> HasErrors(false);
morehousea80f6452017-12-04 19:25:59 +0000253 Command Cmd(Args);
254 Cmd.removeFlag("jobs");
255 Cmd.removeFlag("workers");
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000256 Vector<std::thread> V;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000257 std::thread Pulse(PulseThread);
258 Pulse.detach();
259 for (unsigned i = 0; i < NumWorkers; i++)
morehousea80f6452017-12-04 19:25:59 +0000260 V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors));
george.karpenkov29efa6d2017-08-21 23:25:50 +0000261 for (auto &T : V)
262 T.join();
263 return HasErrors ? 1 : 0;
264}
265
266static void RssThread(Fuzzer *F, size_t RssLimitMb) {
267 while (true) {
268 SleepSeconds(1);
269 size_t Peak = GetPeakRSSMb();
270 if (Peak > RssLimitMb)
271 F->RssLimitCallback();
272 }
273}
274
275static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
276 if (!RssLimitMb) return;
277 std::thread T(RssThread, F, RssLimitMb);
278 T.detach();
279}
280
281int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
282 Unit U = FileToVector(InputFilePath);
283 if (MaxLen && MaxLen < U.size())
284 U.resize(MaxLen);
285 F->ExecuteCallback(U.data(), U.size());
286 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
287 return 0;
288}
289
290static bool AllInputsAreFiles() {
291 if (Inputs->empty()) return false;
292 for (auto &Path : *Inputs)
293 if (!IsFile(Path))
294 return false;
295 return true;
296}
297
298static std::string GetDedupTokenFromFile(const std::string &Path) {
299 auto S = FileToString(Path);
300 auto Beg = S.find("DEDUP_TOKEN:");
301 if (Beg == std::string::npos)
302 return "";
303 auto End = S.find('\n', Beg);
304 if (End == std::string::npos)
305 return "";
306 return S.substr(Beg, End - Beg);
307}
308
kcca3815862019-02-08 21:27:23 +0000309static std::string TempPath(const char *Extension) {
310 return DirPlusFile(TmpDir(),
311 "libFuzzerTemp." + std::to_string(GetPid()) + Extension);
312}
313
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000314int CleanseCrashInput(const Vector<std::string> &Args,
dor1se6729cb2018-07-16 15:15:34 +0000315 const FuzzingOptions &Options) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000316 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
317 Printf("ERROR: -cleanse_crash should be given one input file and"
dor1se6729cb2018-07-16 15:15:34 +0000318 " -exact_artifact_path\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000319 exit(1);
320 }
321 std::string InputFilePath = Inputs->at(0);
322 std::string OutputFilePath = Flags.exact_artifact_path;
morehousea80f6452017-12-04 19:25:59 +0000323 Command Cmd(Args);
324 Cmd.removeFlag("cleanse_crash");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000325
morehousea80f6452017-12-04 19:25:59 +0000326 assert(Cmd.hasArgument(InputFilePath));
327 Cmd.removeArgument(InputFilePath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000328
kcca3815862019-02-08 21:27:23 +0000329 auto LogFilePath = TempPath(".txt");
330 auto TmpFilePath = TempPath(".repro");
morehousea80f6452017-12-04 19:25:59 +0000331 Cmd.addArgument(TmpFilePath);
332 Cmd.setOutputFile(LogFilePath);
333 Cmd.combineOutAndErr();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000334
335 std::string CurrentFilePath = InputFilePath;
336 auto U = FileToVector(CurrentFilePath);
337 size_t Size = U.size();
338
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000339 const Vector<uint8_t> ReplacementBytes = {' ', 0xff};
george.karpenkov29efa6d2017-08-21 23:25:50 +0000340 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
341 bool Changed = false;
342 for (size_t Idx = 0; Idx < Size; Idx++) {
343 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
344 Idx, Size);
345 uint8_t OriginalByte = U[Idx];
346 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
347 ReplacementBytes.end(),
348 OriginalByte))
349 continue;
350 for (auto NewByte : ReplacementBytes) {
351 U[Idx] = NewByte;
352 WriteToFile(U, TmpFilePath);
353 auto ExitCode = ExecuteCommand(Cmd);
354 RemoveFile(TmpFilePath);
355 if (!ExitCode) {
356 U[Idx] = OriginalByte;
357 } else {
358 Changed = true;
359 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
360 WriteToFile(U, OutputFilePath);
361 break;
362 }
363 }
364 }
365 if (!Changed) break;
366 }
367 RemoveFile(LogFilePath);
368 return 0;
369}
370
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000371int MinimizeCrashInput(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000372 const FuzzingOptions &Options) {
373 if (Inputs->size() != 1) {
374 Printf("ERROR: -minimize_crash should be given one input file\n");
375 exit(1);
376 }
377 std::string InputFilePath = Inputs->at(0);
morehousea80f6452017-12-04 19:25:59 +0000378 Command BaseCmd(Args);
379 BaseCmd.removeFlag("minimize_crash");
380 BaseCmd.removeFlag("exact_artifact_path");
381 assert(BaseCmd.hasArgument(InputFilePath));
382 BaseCmd.removeArgument(InputFilePath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000383 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
384 Printf("INFO: you need to specify -runs=N or "
385 "-max_total_time=N with -minimize_crash=1\n"
386 "INFO: defaulting to -max_total_time=600\n");
morehousea80f6452017-12-04 19:25:59 +0000387 BaseCmd.addFlag("max_total_time", "600");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000388 }
389
kcca3815862019-02-08 21:27:23 +0000390 auto LogFilePath = TempPath(".txt");
morehousea80f6452017-12-04 19:25:59 +0000391 BaseCmd.setOutputFile(LogFilePath);
392 BaseCmd.combineOutAndErr();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000393
394 std::string CurrentFilePath = InputFilePath;
395 while (true) {
396 Unit U = FileToVector(CurrentFilePath);
397 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
398 CurrentFilePath.c_str(), U.size());
399
morehousea80f6452017-12-04 19:25:59 +0000400 Command Cmd(BaseCmd);
401 Cmd.addArgument(CurrentFilePath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000402
morehousea80f6452017-12-04 19:25:59 +0000403 std::string CommandLine = Cmd.toString();
404 Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000405 int ExitCode = ExecuteCommand(Cmd);
406 if (ExitCode == 0) {
407 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
408 exit(1);
409 }
410 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
411 "it further\n",
412 CurrentFilePath.c_str(), U.size());
413 auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
414 if (!DedupToken1.empty())
415 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
416
417 std::string ArtifactPath =
418 Flags.exact_artifact_path
419 ? Flags.exact_artifact_path
420 : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
morehousea80f6452017-12-04 19:25:59 +0000421 Cmd.addFlag("minimize_crash_internal_step", "1");
422 Cmd.addFlag("exact_artifact_path", ArtifactPath);
423 CommandLine = Cmd.toString();
424 Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000425 ExitCode = ExecuteCommand(Cmd);
426 CopyFileToErr(LogFilePath);
427 if (ExitCode == 0) {
428 if (Flags.exact_artifact_path) {
429 CurrentFilePath = Flags.exact_artifact_path;
430 WriteToFile(U, CurrentFilePath);
431 }
432 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
433 CurrentFilePath.c_str(), U.size());
434 break;
435 }
436 auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
437 if (!DedupToken2.empty())
438 Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
439
440 if (DedupToken1 != DedupToken2) {
441 if (Flags.exact_artifact_path) {
442 CurrentFilePath = Flags.exact_artifact_path;
443 WriteToFile(U, CurrentFilePath);
444 }
445 Printf("CRASH_MIN: mismatch in dedup tokens"
446 " (looks like a different bug). Won't minimize further\n");
447 break;
448 }
449
450 CurrentFilePath = ArtifactPath;
451 Printf("*********************************\n");
452 }
453 RemoveFile(LogFilePath);
454 return 0;
455}
456
457int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
458 assert(Inputs->size() == 1);
459 std::string InputFilePath = Inputs->at(0);
460 Unit U = FileToVector(InputFilePath);
461 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
462 if (U.size() < 2) {
463 Printf("INFO: The input is small enough, exiting\n");
464 exit(0);
465 }
466 F->SetMaxInputLen(U.size());
467 F->SetMaxMutationLen(U.size() - 1);
468 F->MinimizeCrashLoop(U);
469 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
470 exit(0);
471 return 0;
472}
473
kcca3815862019-02-08 21:27:23 +0000474// This is just a sceleton of an experimental -fork=1 feature.
475void FuzzWithFork(const FuzzingOptions &Options,
476 const Vector<std::string> &Args,
477 const Vector<std::string> &Corpora) {
478 auto CFPath = TempPath(".fork");
479 Printf("INFO: -fork=1: doing fuzzing in a separate process in order to "
480 "be more resistant to crashes, timeouts, and OOMs\n");
kccf2593592019-02-08 22:02:37 +0000481 auto Files = CrashResistantMerge(Args, Corpora, CFPath);
kcca3815862019-02-08 21:27:23 +0000482 Printf("INFO: -fork=1: seed corpus analyzed, %zd seeds chosen, starting to "
483 "fuzz in separate processes\n", Files.size());
484
485 Command Cmd(Args);
486 Cmd.removeFlag("fork");
487 if (Files.size() >= 2)
488 Cmd.addFlag("seed_inputs",
489 Files.back() + "," + Files[Files.size() - 2]);
490 Cmd.addFlag("runs", "1000000");
491 Cmd.addFlag("max_total_time", "30");
492 for (size_t i = 0; i < 1000; i++) {
493 Printf("RUN %s\n", Cmd.toString().c_str());
494 int ExitCode = ExecuteCommand(Cmd);
495 // TODO: sniff the crash, ignore OOMs and timeouts.
496 if (ExitCode != 0) break;
497 }
498
499 RemoveFile(CFPath);
500 exit(0);
501}
502
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000503int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000504 UnitVector& Corpus) {
505 Printf("Started dictionary minimization (up to %d tests)\n",
506 Dict.size() * Corpus.size() * 2);
507
508 // Scores and usage count for each dictionary unit.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000509 Vector<int> Scores(Dict.size());
510 Vector<int> Usages(Dict.size());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000511
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000512 Vector<size_t> InitialFeatures;
513 Vector<size_t> ModifiedFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000514 for (auto &C : Corpus) {
515 // Get coverage for the testcase without modifications.
516 F->ExecuteCallback(C.data(), C.size());
517 InitialFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000518 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000519 InitialFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000520 });
521
522 for (size_t i = 0; i < Dict.size(); ++i) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000523 Vector<uint8_t> Data = C;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000524 auto StartPos = std::search(Data.begin(), Data.end(),
525 Dict[i].begin(), Dict[i].end());
526 // Skip dictionary unit, if the testcase does not contain it.
527 if (StartPos == Data.end())
528 continue;
529
530 ++Usages[i];
531 while (StartPos != Data.end()) {
532 // Replace all occurrences of dictionary unit in the testcase.
533 auto EndPos = StartPos + Dict[i].size();
534 for (auto It = StartPos; It != EndPos; ++It)
535 *It ^= 0xFF;
536
537 StartPos = std::search(EndPos, Data.end(),
538 Dict[i].begin(), Dict[i].end());
539 }
540
541 // Get coverage for testcase with masked occurrences of dictionary unit.
542 F->ExecuteCallback(Data.data(), Data.size());
543 ModifiedFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000544 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000545 ModifiedFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000546 });
547
548 if (InitialFeatures == ModifiedFeatures)
549 --Scores[i];
550 else
551 Scores[i] += 2;
552 }
553 }
554
555 Printf("###### Useless dictionary elements. ######\n");
556 for (size_t i = 0; i < Dict.size(); ++i) {
557 // Dictionary units with positive score are treated as useful ones.
558 if (Scores[i] > 0)
dor1se6729cb2018-07-16 15:15:34 +0000559 continue;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000560
561 Printf("\"");
562 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
563 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
564 }
565 Printf("###### End of useless dictionary elements. ######\n");
566 return 0;
567}
568
569int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
570 using namespace fuzzer;
571 assert(argc && argv && "Argument pointers cannot be nullptr");
572 std::string Argv0((*argv)[0]);
573 EF = new ExternalFunctions();
574 if (EF->LLVMFuzzerInitialize)
575 EF->LLVMFuzzerInitialize(argc, argv);
morehouse1467b792018-07-09 23:51:08 +0000576 if (EF->__msan_scoped_disable_interceptor_checks)
577 EF->__msan_scoped_disable_interceptor_checks();
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000578 const Vector<std::string> Args(*argv, *argv + *argc);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000579 assert(!Args.empty());
580 ProgName = new std::string(Args[0]);
581 if (Argv0 != *ProgName) {
582 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
583 exit(1);
584 }
585 ParseFlags(Args);
586 if (Flags.help) {
587 PrintHelp();
588 return 0;
589 }
590
591 if (Flags.close_fd_mask & 2)
592 DupAndCloseStderr();
593 if (Flags.close_fd_mask & 1)
594 CloseStdout();
595
596 if (Flags.jobs > 0 && Flags.workers == 0) {
597 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
598 if (Flags.workers > 1)
599 Printf("Running %u workers\n", Flags.workers);
600 }
601
602 if (Flags.workers > 0 && Flags.jobs > 0)
603 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
604
george.karpenkov29efa6d2017-08-21 23:25:50 +0000605 FuzzingOptions Options;
606 Options.Verbosity = Flags.verbosity;
607 Options.MaxLen = Flags.max_len;
morehouse8c42ada2018-02-13 20:52:15 +0000608 Options.LenControl = Flags.len_control;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000609 Options.UnitTimeoutSec = Flags.timeout;
610 Options.ErrorExitCode = Flags.error_exitcode;
611 Options.TimeoutExitCode = Flags.timeout_exitcode;
612 Options.MaxTotalTimeSec = Flags.max_total_time;
613 Options.DoCrossOver = Flags.cross_over;
614 Options.MutateDepth = Flags.mutate_depth;
kccb6836be2017-12-01 19:18:38 +0000615 Options.ReduceDepth = Flags.reduce_depth;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000616 Options.UseCounters = Flags.use_counters;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000617 Options.UseMemmem = Flags.use_memmem;
618 Options.UseCmp = Flags.use_cmp;
619 Options.UseValueProfile = Flags.use_value_profile;
620 Options.Shrink = Flags.shrink;
621 Options.ReduceInputs = Flags.reduce_inputs;
622 Options.ShuffleAtStartUp = Flags.shuffle;
623 Options.PreferSmall = Flags.prefer_small;
624 Options.ReloadIntervalSec = Flags.reload;
625 Options.OnlyASCII = Flags.only_ascii;
626 Options.DetectLeaks = Flags.detect_leaks;
alekseyshld995b552017-10-23 22:04:30 +0000627 Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000628 Options.TraceMalloc = Flags.trace_malloc;
629 Options.RssLimitMb = Flags.rss_limit_mb;
kcc120e40b2017-12-01 22:12:04 +0000630 Options.MallocLimitMb = Flags.malloc_limit_mb;
631 if (!Options.MallocLimitMb)
632 Options.MallocLimitMb = Options.RssLimitMb;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000633 if (Flags.runs >= 0)
634 Options.MaxNumberOfRuns = Flags.runs;
635 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
636 Options.OutputCorpus = (*Inputs)[0];
637 Options.ReportSlowUnits = Flags.report_slow_units;
638 if (Flags.artifact_prefix)
639 Options.ArtifactPrefix = Flags.artifact_prefix;
640 if (Flags.exact_artifact_path)
641 Options.ExactArtifactPath = Flags.exact_artifact_path;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000642 Vector<Unit> Dictionary;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000643 if (Flags.dict)
644 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
645 return 1;
646 if (Flags.verbosity > 0 && !Dictionary.empty())
647 Printf("Dictionary: %zd entries\n", Dictionary.size());
648 bool DoPlainRun = AllInputsAreFiles();
649 Options.SaveArtifacts =
650 !DoPlainRun || Flags.minimize_crash_internal_step;
651 Options.PrintNewCovPcs = Flags.print_pcs;
kcc00da6482017-08-25 20:09:25 +0000652 Options.PrintNewCovFuncs = Flags.print_funcs;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000653 Options.PrintFinalStats = Flags.print_final_stats;
654 Options.PrintCorpusStats = Flags.print_corpus_stats;
655 Options.PrintCoverage = Flags.print_coverage;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000656 if (Flags.exit_on_src_pos)
657 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
658 if (Flags.exit_on_item)
659 Options.ExitOnItem = Flags.exit_on_item;
kcc3acbe072018-05-16 23:26:37 +0000660 if (Flags.focus_function)
661 Options.FocusFunction = Flags.focus_function;
kcc86e43882018-06-06 01:23:29 +0000662 if (Flags.data_flow_trace)
663 Options.DataFlowTrace = Flags.data_flow_trace;
kccc0a0b1f2019-01-31 01:40:14 +0000664 Options.LazyCounters = Flags.lazy_counters;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000665
666 unsigned Seed = Flags.seed;
667 // Initialize Seed.
668 if (Seed == 0)
669 Seed =
670 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
671 if (Flags.verbosity)
672 Printf("INFO: Seed: %u\n", Seed);
673
674 Random Rand(Seed);
675 auto *MD = new MutationDispatcher(Rand, Options);
676 auto *Corpus = new InputCorpus(Options.OutputCorpus);
677 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
678
679 for (auto &U: Dictionary)
680 if (U.size() <= Word::GetMaxSize())
681 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
682
683 StartRssThread(F, Flags.rss_limit_mb);
684
685 Options.HandleAbrt = Flags.handle_abrt;
686 Options.HandleBus = Flags.handle_bus;
687 Options.HandleFpe = Flags.handle_fpe;
688 Options.HandleIll = Flags.handle_ill;
689 Options.HandleInt = Flags.handle_int;
690 Options.HandleSegv = Flags.handle_segv;
691 Options.HandleTerm = Flags.handle_term;
692 Options.HandleXfsz = Flags.handle_xfsz;
kcc1239a992017-11-09 20:30:19 +0000693 Options.HandleUsr1 = Flags.handle_usr1;
694 Options.HandleUsr2 = Flags.handle_usr2;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000695 SetSignalHandler(Options);
696
697 std::atexit(Fuzzer::StaticExitCallback);
698
699 if (Flags.minimize_crash)
700 return MinimizeCrashInput(Args, Options);
701
702 if (Flags.minimize_crash_internal_step)
703 return MinimizeCrashInputInternalStep(F, Corpus);
704
705 if (Flags.cleanse_crash)
706 return CleanseCrashInput(Args, Options);
707
george.karpenkov29efa6d2017-08-21 23:25:50 +0000708 if (DoPlainRun) {
709 Options.SaveArtifacts = false;
710 int Runs = std::max(1, Flags.runs);
711 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
712 Inputs->size(), Runs);
713 for (auto &Path : *Inputs) {
714 auto StartTime = system_clock::now();
715 Printf("Running: %s\n", Path.c_str());
716 for (int Iter = 0; Iter < Runs; Iter++)
717 RunOneTest(F, Path.c_str(), Options.MaxLen);
718 auto StopTime = system_clock::now();
719 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
720 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
721 }
722 Printf("***\n"
723 "*** NOTE: fuzzing was not performed, you have only\n"
724 "*** executed the target code on a fixed set of inputs.\n"
725 "***\n");
726 F->PrintFinalStats();
727 exit(0);
728 }
729
kcca3815862019-02-08 21:27:23 +0000730 if (Flags.fork)
731 FuzzWithFork(Options, Args, *Inputs);
732
george.karpenkov29efa6d2017-08-21 23:25:50 +0000733 if (Flags.merge) {
kcca3815862019-02-08 21:27:23 +0000734 if (Inputs->size() < 2) {
735 Printf("INFO: Merge requires two or more corpus dirs\n");
736 exit(0);
737 }
738 std::string CFPath =
739 Flags.merge_control_file ? Flags.merge_control_file : TempPath(".txt");
kccf2593592019-02-08 22:02:37 +0000740 auto Files = CrashResistantMerge(Args, *Inputs, CFPath);
kcca3815862019-02-08 21:27:23 +0000741 for (auto &Path : Files)
742 F->WriteToOutputCorpus(FileToVector(Path, Options.MaxLen));
743 // We are done, delete the control file if it was a temporary one.
744 if (!Flags.merge_control_file)
745 RemoveFile(CFPath);
746
george.karpenkov29efa6d2017-08-21 23:25:50 +0000747 exit(0);
748 }
749
kccc51afd72017-11-09 01:05:29 +0000750 if (Flags.merge_inner) {
751 const size_t kDefaultMaxMergeLen = 1 << 20;
752 if (Options.MaxLen == 0)
753 F->SetMaxInputLen(kDefaultMaxMergeLen);
754 assert(Flags.merge_control_file);
755 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
756 exit(0);
757 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000758
759 if (Flags.analyze_dict) {
kcc2e93b3f2017-08-29 02:05:01 +0000760 size_t MaxLen = INT_MAX; // Large max length.
761 UnitVector InitialCorpus;
762 for (auto &Inp : *Inputs) {
763 Printf("Loading corpus dir: %s\n", Inp.c_str());
764 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
765 MaxLen, /*ExitOnError=*/false);
766 }
767
george.karpenkov29efa6d2017-08-21 23:25:50 +0000768 if (Dictionary.empty() || Inputs->empty()) {
769 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
770 return 1;
771 }
772 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
773 Printf("Dictionary analysis failed\n");
774 exit(1);
775 }
sylvestrea9eb8572018-03-13 14:35:10 +0000776 Printf("Dictionary analysis succeeded\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000777 exit(0);
778 }
779
kcc0c34c832019-02-08 01:20:54 +0000780 // Parse -seed_inputs=file1,file2,...
781 Vector<std::string> ExtraSeedFiles;
782 if (Flags.seed_inputs) {
783 std::string s = Flags.seed_inputs;
784 size_t comma_pos;
785 while ((comma_pos = s.find_last_of(',')) != std::string::npos) {
786 ExtraSeedFiles.push_back(s.substr(comma_pos + 1));
787 s = s.substr(0, comma_pos);
788 }
789 ExtraSeedFiles.push_back(s);
790 }
791
792 F->Loop(*Inputs, ExtraSeedFiles);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000793
794 if (Flags.verbosity)
795 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
796 F->secondsSinceProcessStartUp());
797 F->PrintFinalStats();
798
799 exit(0); // Don't let F destroy itself.
800}
801
802// Storage for global ExternalFunctions object.
803ExternalFunctions *EF = nullptr;
804
805} // namespace fuzzer