blob: 8ad99d0a3c2e7e91756b71cb2a637ad43fa486d4 [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
kccd1449be2019-02-08 22:59:03 +0000474// This is just a skeleton of an experimental -fork=1 feature.
kcc243006d2019-02-12 00:12:33 +0000475void FuzzWithFork(Fuzzer *F, const FuzzingOptions &Options,
kcca3815862019-02-08 21:27:23 +0000476 const Vector<std::string> &Args,
477 const Vector<std::string> &Corpora) {
kcca3815862019-02-08 21:27:23 +0000478 Printf("INFO: -fork=1: doing fuzzing in a separate process in order to "
479 "be more resistant to crashes, timeouts, and OOMs\n");
kcc243006d2019-02-12 00:12:33 +0000480 auto Rand = F->GetMD().GetRand();
kccd1449be2019-02-08 22:59:03 +0000481
kccd1449be2019-02-08 22:59:03 +0000482 Vector<SizedFile> Corpus;
483 for (auto &Dir : Corpora)
484 GetSizedFilesFromDir(Dir, &Corpus);
485 std::sort(Corpus.begin(), Corpus.end());
kcc243006d2019-02-12 00:12:33 +0000486 auto CFPath = TempPath(".fork");
kccd1449be2019-02-08 22:59:03 +0000487
kcc4b5aa122019-02-09 00:16:21 +0000488 Vector<std::string> Files;
489 Set<uint32_t> Features;
490 if (!Corpus.empty()) {
kcc4b5aa122019-02-09 00:16:21 +0000491 CrashResistantMerge(Args, {}, Corpus, &Files, {}, &Features, CFPath);
492 RemoveFile(CFPath);
493 }
kcc243006d2019-02-12 00:12:33 +0000494 auto TempDir = TempPath("Dir");
495 MkDir(TempDir);
496 Printf("INFO: -fork=1: %zd seeds, starting to fuzz; scratch: %s\n",
497 Files.size(), TempDir.c_str());
kcca3815862019-02-08 21:27:23 +0000498
kcc243006d2019-02-12 00:12:33 +0000499 Command BaseCmd(Args);
500 BaseCmd.removeFlag("fork");
kcc4b5aa122019-02-09 00:16:21 +0000501 for (auto &C : Corpora) // Remove all corpora from the args.
kcc243006d2019-02-12 00:12:33 +0000502 BaseCmd.removeArgument(C);
503 BaseCmd.addFlag("runs", "1000000");
504 BaseCmd.addFlag("max_total_time", "30");
505 BaseCmd.addArgument(TempDir);
506 int ExitCode = 0;
507 for (size_t i = 0; i < 1000000; i++) {
508 // TODO: take new files from disk e.g. those generated by another process.
509 Command Cmd(BaseCmd);
510 if (Files.size() >= 2)
511 Cmd.addFlag("seed_inputs",
512 Files[Rand.SkewTowardsLast(Files.size())] + "," +
513 Files[Rand.SkewTowardsLast(Files.size())]);
kcca3815862019-02-08 21:27:23 +0000514 Printf("RUN %s\n", Cmd.toString().c_str());
kcc243006d2019-02-12 00:12:33 +0000515 RmFilesInDir(TempDir);
516 ExitCode = ExecuteCommand(Cmd);
517 Printf("Exit code: %d\n", ExitCode);
kcc4b5aa122019-02-09 00:16:21 +0000518 if (ExitCode == Options.InterruptExitCode)
kcc243006d2019-02-12 00:12:33 +0000519 break;
520 Vector<SizedFile> TempFiles;
521 Vector<std::string>FilesToAdd;
522 Set<uint32_t> NewFeatures;
523 GetSizedFilesFromDir(TempDir, &TempFiles);
524 CrashResistantMerge(Args, {}, TempFiles, &FilesToAdd, Features,
525 &NewFeatures, CFPath);
526 RemoveFile(CFPath);
527 for (auto &Path : FilesToAdd) {
528 auto NewPath = F->WriteToOutputCorpus(FileToVector(Path, Options.MaxLen));
529 if (!NewPath.empty())
530 Files.push_back(NewPath);
531 }
532 Features.insert(NewFeatures.begin(), NewFeatures.end());
533 Printf("INFO: temp_files: %zd files_added: %zd newft: %zd ft: %zd\n",
534 TempFiles.size(), FilesToAdd.size(), NewFeatures.size(),
535 Features.size());
kcca7b741c2019-02-12 02:18:53 +0000536 // Continue if our crash is one of the ignorred ones.
537 if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
538 continue;
539 if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
540 continue;
541 // And exit if we don't ignore this crash.
kcca3815862019-02-08 21:27:23 +0000542 if (ExitCode != 0) break;
543 }
544
kcc243006d2019-02-12 00:12:33 +0000545 RmFilesInDir(TempDir);
546 RmDir(TempDir);
547
548 // Use the exit code from the last child process.
549 Printf("Fork: exiting: %d\n", ExitCode);
550 exit(ExitCode);
kcca3815862019-02-08 21:27:23 +0000551}
552
kccd1449be2019-02-08 22:59:03 +0000553void Merge(Fuzzer *F, FuzzingOptions &Options, const Vector<std::string> &Args,
554 const Vector<std::string> &Corpora, const char *CFPathOrNull) {
555 if (Corpora.size() < 2) {
556 Printf("INFO: Merge requires two or more corpus dirs\n");
557 exit(0);
558 }
559
560 Vector<SizedFile> OldCorpus, NewCorpus;
561 GetSizedFilesFromDir(Corpora[0], &OldCorpus);
562 for (size_t i = 1; i < Corpora.size(); i++)
563 GetSizedFilesFromDir(Corpora[i], &NewCorpus);
564 std::sort(OldCorpus.begin(), OldCorpus.end());
565 std::sort(NewCorpus.begin(), NewCorpus.end());
566
567 std::string CFPath = CFPathOrNull ? CFPathOrNull : TempPath(".txt");
kcc4b5aa122019-02-09 00:16:21 +0000568 Vector<std::string> NewFiles;
569 Set<uint32_t> NewFeatures;
570 CrashResistantMerge(Args, OldCorpus, NewCorpus, &NewFiles, {}, &NewFeatures,
571 CFPath);
572 for (auto &Path : NewFiles)
kccd1449be2019-02-08 22:59:03 +0000573 F->WriteToOutputCorpus(FileToVector(Path, Options.MaxLen));
574 // We are done, delete the control file if it was a temporary one.
575 if (!Flags.merge_control_file)
576 RemoveFile(CFPath);
577
578 exit(0);
579}
580
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000581int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000582 UnitVector& Corpus) {
583 Printf("Started dictionary minimization (up to %d tests)\n",
584 Dict.size() * Corpus.size() * 2);
585
586 // Scores and usage count for each dictionary unit.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000587 Vector<int> Scores(Dict.size());
588 Vector<int> Usages(Dict.size());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000589
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000590 Vector<size_t> InitialFeatures;
591 Vector<size_t> ModifiedFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000592 for (auto &C : Corpus) {
593 // Get coverage for the testcase without modifications.
594 F->ExecuteCallback(C.data(), C.size());
595 InitialFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000596 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000597 InitialFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000598 });
599
600 for (size_t i = 0; i < Dict.size(); ++i) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000601 Vector<uint8_t> Data = C;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000602 auto StartPos = std::search(Data.begin(), Data.end(),
603 Dict[i].begin(), Dict[i].end());
604 // Skip dictionary unit, if the testcase does not contain it.
605 if (StartPos == Data.end())
606 continue;
607
608 ++Usages[i];
609 while (StartPos != Data.end()) {
610 // Replace all occurrences of dictionary unit in the testcase.
611 auto EndPos = StartPos + Dict[i].size();
612 for (auto It = StartPos; It != EndPos; ++It)
613 *It ^= 0xFF;
614
615 StartPos = std::search(EndPos, Data.end(),
616 Dict[i].begin(), Dict[i].end());
617 }
618
619 // Get coverage for testcase with masked occurrences of dictionary unit.
620 F->ExecuteCallback(Data.data(), Data.size());
621 ModifiedFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000622 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000623 ModifiedFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000624 });
625
626 if (InitialFeatures == ModifiedFeatures)
627 --Scores[i];
628 else
629 Scores[i] += 2;
630 }
631 }
632
633 Printf("###### Useless dictionary elements. ######\n");
634 for (size_t i = 0; i < Dict.size(); ++i) {
635 // Dictionary units with positive score are treated as useful ones.
636 if (Scores[i] > 0)
dor1se6729cb2018-07-16 15:15:34 +0000637 continue;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000638
639 Printf("\"");
640 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
641 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
642 }
643 Printf("###### End of useless dictionary elements. ######\n");
644 return 0;
645}
646
647int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
648 using namespace fuzzer;
649 assert(argc && argv && "Argument pointers cannot be nullptr");
650 std::string Argv0((*argv)[0]);
651 EF = new ExternalFunctions();
652 if (EF->LLVMFuzzerInitialize)
653 EF->LLVMFuzzerInitialize(argc, argv);
morehouse1467b792018-07-09 23:51:08 +0000654 if (EF->__msan_scoped_disable_interceptor_checks)
655 EF->__msan_scoped_disable_interceptor_checks();
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000656 const Vector<std::string> Args(*argv, *argv + *argc);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000657 assert(!Args.empty());
658 ProgName = new std::string(Args[0]);
659 if (Argv0 != *ProgName) {
660 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
661 exit(1);
662 }
663 ParseFlags(Args);
664 if (Flags.help) {
665 PrintHelp();
666 return 0;
667 }
668
669 if (Flags.close_fd_mask & 2)
670 DupAndCloseStderr();
671 if (Flags.close_fd_mask & 1)
672 CloseStdout();
673
674 if (Flags.jobs > 0 && Flags.workers == 0) {
675 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
676 if (Flags.workers > 1)
677 Printf("Running %u workers\n", Flags.workers);
678 }
679
680 if (Flags.workers > 0 && Flags.jobs > 0)
681 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
682
george.karpenkov29efa6d2017-08-21 23:25:50 +0000683 FuzzingOptions Options;
684 Options.Verbosity = Flags.verbosity;
685 Options.MaxLen = Flags.max_len;
morehouse8c42ada2018-02-13 20:52:15 +0000686 Options.LenControl = Flags.len_control;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000687 Options.UnitTimeoutSec = Flags.timeout;
688 Options.ErrorExitCode = Flags.error_exitcode;
689 Options.TimeoutExitCode = Flags.timeout_exitcode;
kcca7b741c2019-02-12 02:18:53 +0000690 Options.IgnoreTimeouts = Flags.ignore_timeouts;
691 Options.IgnoreOOMs = Flags.ignore_ooms;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000692 Options.MaxTotalTimeSec = Flags.max_total_time;
693 Options.DoCrossOver = Flags.cross_over;
694 Options.MutateDepth = Flags.mutate_depth;
kccb6836be2017-12-01 19:18:38 +0000695 Options.ReduceDepth = Flags.reduce_depth;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000696 Options.UseCounters = Flags.use_counters;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000697 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;
alekseyshld995b552017-10-23 22:04:30 +0000707 Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000708 Options.TraceMalloc = Flags.trace_malloc;
709 Options.RssLimitMb = Flags.rss_limit_mb;
kcc120e40b2017-12-01 22:12:04 +0000710 Options.MallocLimitMb = Flags.malloc_limit_mb;
711 if (!Options.MallocLimitMb)
712 Options.MallocLimitMb = Options.RssLimitMb;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000713 if (Flags.runs >= 0)
714 Options.MaxNumberOfRuns = Flags.runs;
715 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
716 Options.OutputCorpus = (*Inputs)[0];
717 Options.ReportSlowUnits = Flags.report_slow_units;
718 if (Flags.artifact_prefix)
719 Options.ArtifactPrefix = Flags.artifact_prefix;
720 if (Flags.exact_artifact_path)
721 Options.ExactArtifactPath = Flags.exact_artifact_path;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000722 Vector<Unit> Dictionary;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000723 if (Flags.dict)
724 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
725 return 1;
726 if (Flags.verbosity > 0 && !Dictionary.empty())
727 Printf("Dictionary: %zd entries\n", Dictionary.size());
728 bool DoPlainRun = AllInputsAreFiles();
729 Options.SaveArtifacts =
730 !DoPlainRun || Flags.minimize_crash_internal_step;
731 Options.PrintNewCovPcs = Flags.print_pcs;
kcc00da6482017-08-25 20:09:25 +0000732 Options.PrintNewCovFuncs = Flags.print_funcs;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000733 Options.PrintFinalStats = Flags.print_final_stats;
734 Options.PrintCorpusStats = Flags.print_corpus_stats;
735 Options.PrintCoverage = Flags.print_coverage;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000736 if (Flags.exit_on_src_pos)
737 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
738 if (Flags.exit_on_item)
739 Options.ExitOnItem = Flags.exit_on_item;
kcc3acbe072018-05-16 23:26:37 +0000740 if (Flags.focus_function)
741 Options.FocusFunction = Flags.focus_function;
kcc86e43882018-06-06 01:23:29 +0000742 if (Flags.data_flow_trace)
743 Options.DataFlowTrace = Flags.data_flow_trace;
kccc0a0b1f2019-01-31 01:40:14 +0000744 Options.LazyCounters = Flags.lazy_counters;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000745
746 unsigned Seed = Flags.seed;
747 // Initialize Seed.
748 if (Seed == 0)
749 Seed =
750 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
751 if (Flags.verbosity)
752 Printf("INFO: Seed: %u\n", Seed);
753
754 Random Rand(Seed);
755 auto *MD = new MutationDispatcher(Rand, Options);
756 auto *Corpus = new InputCorpus(Options.OutputCorpus);
757 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
758
759 for (auto &U: Dictionary)
760 if (U.size() <= Word::GetMaxSize())
761 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
762
763 StartRssThread(F, Flags.rss_limit_mb);
764
765 Options.HandleAbrt = Flags.handle_abrt;
766 Options.HandleBus = Flags.handle_bus;
767 Options.HandleFpe = Flags.handle_fpe;
768 Options.HandleIll = Flags.handle_ill;
769 Options.HandleInt = Flags.handle_int;
770 Options.HandleSegv = Flags.handle_segv;
771 Options.HandleTerm = Flags.handle_term;
772 Options.HandleXfsz = Flags.handle_xfsz;
kcc1239a992017-11-09 20:30:19 +0000773 Options.HandleUsr1 = Flags.handle_usr1;
774 Options.HandleUsr2 = Flags.handle_usr2;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000775 SetSignalHandler(Options);
776
777 std::atexit(Fuzzer::StaticExitCallback);
778
779 if (Flags.minimize_crash)
780 return MinimizeCrashInput(Args, Options);
781
782 if (Flags.minimize_crash_internal_step)
783 return MinimizeCrashInputInternalStep(F, Corpus);
784
785 if (Flags.cleanse_crash)
786 return CleanseCrashInput(Args, Options);
787
george.karpenkov29efa6d2017-08-21 23:25:50 +0000788 if (DoPlainRun) {
789 Options.SaveArtifacts = false;
790 int Runs = std::max(1, Flags.runs);
791 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
792 Inputs->size(), Runs);
793 for (auto &Path : *Inputs) {
794 auto StartTime = system_clock::now();
795 Printf("Running: %s\n", Path.c_str());
796 for (int Iter = 0; Iter < Runs; Iter++)
797 RunOneTest(F, Path.c_str(), Options.MaxLen);
798 auto StopTime = system_clock::now();
799 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
800 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
801 }
802 Printf("***\n"
803 "*** NOTE: fuzzing was not performed, you have only\n"
804 "*** executed the target code on a fixed set of inputs.\n"
805 "***\n");
806 F->PrintFinalStats();
807 exit(0);
808 }
809
kcca3815862019-02-08 21:27:23 +0000810 if (Flags.fork)
kcc243006d2019-02-12 00:12:33 +0000811 FuzzWithFork(F, Options, Args, *Inputs);
kcca3815862019-02-08 21:27:23 +0000812
kccd1449be2019-02-08 22:59:03 +0000813 if (Flags.merge)
814 Merge(F, Options, Args, *Inputs, Flags.merge_control_file);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000815
kccc51afd72017-11-09 01:05:29 +0000816 if (Flags.merge_inner) {
817 const size_t kDefaultMaxMergeLen = 1 << 20;
818 if (Options.MaxLen == 0)
819 F->SetMaxInputLen(kDefaultMaxMergeLen);
820 assert(Flags.merge_control_file);
821 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
822 exit(0);
823 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000824
825 if (Flags.analyze_dict) {
kcc2e93b3f2017-08-29 02:05:01 +0000826 size_t MaxLen = INT_MAX; // Large max length.
827 UnitVector InitialCorpus;
828 for (auto &Inp : *Inputs) {
829 Printf("Loading corpus dir: %s\n", Inp.c_str());
830 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
831 MaxLen, /*ExitOnError=*/false);
832 }
833
george.karpenkov29efa6d2017-08-21 23:25:50 +0000834 if (Dictionary.empty() || Inputs->empty()) {
835 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
836 return 1;
837 }
838 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
839 Printf("Dictionary analysis failed\n");
840 exit(1);
841 }
sylvestrea9eb8572018-03-13 14:35:10 +0000842 Printf("Dictionary analysis succeeded\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000843 exit(0);
844 }
845
kcc0c34c832019-02-08 01:20:54 +0000846 // Parse -seed_inputs=file1,file2,...
847 Vector<std::string> ExtraSeedFiles;
848 if (Flags.seed_inputs) {
849 std::string s = Flags.seed_inputs;
850 size_t comma_pos;
851 while ((comma_pos = s.find_last_of(',')) != std::string::npos) {
852 ExtraSeedFiles.push_back(s.substr(comma_pos + 1));
853 s = s.substr(0, comma_pos);
854 }
855 ExtraSeedFiles.push_back(s);
856 }
857
858 F->Loop(*Inputs, ExtraSeedFiles);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000859
860 if (Flags.verbosity)
861 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
862 F->secondsSinceProcessStartUp());
863 F->PrintFinalStats();
864
865 exit(0); // Don't let F destroy itself.
866}
867
868// Storage for global ExternalFunctions object.
869ExternalFunctions *EF = nullptr;
870
871} // namespace fuzzer