blob: 306e644277cc5106056c799149e9535d0a1b0676 [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"
18#include "FuzzerShmem.h"
19#include "FuzzerTracePC.h"
20#include <algorithm>
21#include <atomic>
22#include <chrono>
23#include <cstdlib>
24#include <cstring>
25#include <mutex>
26#include <string>
27#include <thread>
28
29// This function should be present in the libFuzzer so that the client
30// binary can test for its existence.
metzman2fe66e62019-01-17 16:36:05 +000031#if LIBFUZZER_MSVC
32extern "C" void __libfuzzer_is_present() {}
33#pragma comment(linker, "/include:__libfuzzer_is_present")
34#else
george.karpenkov29efa6d2017-08-21 23:25:50 +000035extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
metzman2fe66e62019-01-17 16:36:05 +000036#endif // LIBFUZZER_MSVC
george.karpenkov29efa6d2017-08-21 23:25:50 +000037
38namespace fuzzer {
39
40// Program arguments.
41struct FlagDescription {
42 const char *Name;
43 const char *Description;
44 int Default;
45 int *IntFlag;
46 const char **StrFlag;
47 unsigned int *UIntFlag;
48};
49
50struct {
51#define FUZZER_DEPRECATED_FLAG(Name)
52#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
53#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
54#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
55#include "FuzzerFlags.def"
56#undef FUZZER_DEPRECATED_FLAG
57#undef FUZZER_FLAG_INT
58#undef FUZZER_FLAG_UNSIGNED
59#undef FUZZER_FLAG_STRING
60} Flags;
61
62static const FlagDescription FlagDescriptions [] {
63#define FUZZER_DEPRECATED_FLAG(Name) \
64 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
65#define FUZZER_FLAG_INT(Name, Default, Description) \
66 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
67#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
68 {#Name, Description, static_cast<int>(Default), \
69 nullptr, nullptr, &Flags.Name},
70#define FUZZER_FLAG_STRING(Name, Description) \
71 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
72#include "FuzzerFlags.def"
73#undef FUZZER_DEPRECATED_FLAG
74#undef FUZZER_FLAG_INT
75#undef FUZZER_FLAG_UNSIGNED
76#undef FUZZER_FLAG_STRING
77};
78
79static const size_t kNumFlags =
80 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
81
george.karpenkovfbfa45c2017-08-27 23:20:09 +000082static Vector<std::string> *Inputs;
george.karpenkov29efa6d2017-08-21 23:25:50 +000083static std::string *ProgName;
84
85static void PrintHelp() {
86 Printf("Usage:\n");
87 auto Prog = ProgName->c_str();
88 Printf("\nTo run fuzzing pass 0 or more directories.\n");
89 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
90
91 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
92 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
93
94 Printf("\nFlags: (strictly in form -flag=value)\n");
95 size_t MaxFlagLen = 0;
96 for (size_t F = 0; F < kNumFlags; F++)
97 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
98
99 for (size_t F = 0; F < kNumFlags; F++) {
100 const auto &D = FlagDescriptions[F];
101 if (strstr(D.Description, "internal flag") == D.Description) continue;
102 Printf(" %s", D.Name);
103 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
104 Printf(" ");
105 Printf("\t");
106 Printf("%d\t%s\n", D.Default, D.Description);
107 }
108 Printf("\nFlags starting with '--' will be ignored and "
dor1se6729cb2018-07-16 15:15:34 +0000109 "will be passed verbatim to subprocesses.\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000110}
111
112static const char *FlagValue(const char *Param, const char *Name) {
113 size_t Len = strlen(Name);
114 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
115 Param[Len + 1] == '=')
dor1se6729cb2018-07-16 15:15:34 +0000116 return &Param[Len + 2];
george.karpenkov29efa6d2017-08-21 23:25:50 +0000117 return nullptr;
118}
119
120// Avoid calling stol as it triggers a bug in clang/glibc build.
121static long MyStol(const char *Str) {
122 long Res = 0;
123 long Sign = 1;
124 if (*Str == '-') {
125 Str++;
126 Sign = -1;
127 }
128 for (size_t i = 0; Str[i]; i++) {
129 char Ch = Str[i];
130 if (Ch < '0' || Ch > '9')
131 return Res;
132 Res = Res * 10 + (Ch - '0');
133 }
134 return Res * Sign;
135}
136
137static bool ParseOneFlag(const char *Param) {
138 if (Param[0] != '-') return false;
139 if (Param[1] == '-') {
140 static bool PrintedWarning = false;
141 if (!PrintedWarning) {
142 PrintedWarning = true;
143 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
144 }
145 for (size_t F = 0; F < kNumFlags; F++)
146 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
147 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
148 return true;
149 }
150 for (size_t F = 0; F < kNumFlags; F++) {
151 const char *Name = FlagDescriptions[F].Name;
152 const char *Str = FlagValue(Param, Name);
153 if (Str) {
154 if (FlagDescriptions[F].IntFlag) {
155 int Val = MyStol(Str);
156 *FlagDescriptions[F].IntFlag = Val;
157 if (Flags.verbosity >= 2)
158 Printf("Flag: %s %d\n", Name, Val);
159 return true;
160 } else if (FlagDescriptions[F].UIntFlag) {
161 unsigned int Val = std::stoul(Str);
162 *FlagDescriptions[F].UIntFlag = Val;
163 if (Flags.verbosity >= 2)
164 Printf("Flag: %s %u\n", Name, Val);
165 return true;
166 } else if (FlagDescriptions[F].StrFlag) {
167 *FlagDescriptions[F].StrFlag = Str;
168 if (Flags.verbosity >= 2)
169 Printf("Flag: %s %s\n", Name, Str);
170 return true;
171 } else { // Deprecated flag.
172 Printf("Flag: %s: deprecated, don't use\n", Name);
173 return true;
174 }
175 }
176 }
177 Printf("\n\nWARNING: unrecognized flag '%s'; "
178 "use -help=1 to list all flags\n\n", Param);
179 return true;
180}
181
182// We don't use any library to minimize dependencies.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000183static void ParseFlags(const Vector<std::string> &Args) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000184 for (size_t F = 0; F < kNumFlags; F++) {
185 if (FlagDescriptions[F].IntFlag)
186 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
187 if (FlagDescriptions[F].UIntFlag)
188 *FlagDescriptions[F].UIntFlag =
189 static_cast<unsigned int>(FlagDescriptions[F].Default);
190 if (FlagDescriptions[F].StrFlag)
191 *FlagDescriptions[F].StrFlag = nullptr;
192 }
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000193 Inputs = new Vector<std::string>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000194 for (size_t A = 1; A < Args.size(); A++) {
195 if (ParseOneFlag(Args[A].c_str())) {
196 if (Flags.ignore_remaining_args)
197 break;
198 continue;
199 }
200 Inputs->push_back(Args[A]);
201 }
202}
203
204static std::mutex Mu;
205
206static void PulseThread() {
207 while (true) {
208 SleepSeconds(600);
209 std::lock_guard<std::mutex> Lock(Mu);
210 Printf("pulse...\n");
211 }
212}
213
morehousea80f6452017-12-04 19:25:59 +0000214static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000215 unsigned NumJobs, std::atomic<bool> *HasErrors) {
216 while (true) {
217 unsigned C = (*Counter)++;
218 if (C >= NumJobs) break;
219 std::string Log = "fuzz-" + std::to_string(C) + ".log";
morehousea80f6452017-12-04 19:25:59 +0000220 Command Cmd(BaseCmd);
221 Cmd.setOutputFile(Log);
222 Cmd.combineOutAndErr();
223 if (Flags.verbosity) {
224 std::string CommandLine = Cmd.toString();
kccf5628b32017-12-06 22:12:24 +0000225 Printf("%s\n", CommandLine.c_str());
morehousea80f6452017-12-04 19:25:59 +0000226 }
227 int ExitCode = ExecuteCommand(Cmd);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000228 if (ExitCode != 0)
229 *HasErrors = true;
230 std::lock_guard<std::mutex> Lock(Mu);
231 Printf("================== Job %u exited with exit code %d ============\n",
232 C, ExitCode);
233 fuzzer::CopyFileToErr(Log);
234 }
235}
236
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000237std::string CloneArgsWithoutX(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000238 const char *X1, const char *X2) {
239 std::string Cmd;
240 for (auto &S : Args) {
241 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
242 continue;
243 Cmd += S + " ";
244 }
245 return Cmd;
246}
247
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000248static int RunInMultipleProcesses(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000249 unsigned NumWorkers, unsigned NumJobs) {
250 std::atomic<unsigned> Counter(0);
251 std::atomic<bool> HasErrors(false);
morehousea80f6452017-12-04 19:25:59 +0000252 Command Cmd(Args);
253 Cmd.removeFlag("jobs");
254 Cmd.removeFlag("workers");
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000255 Vector<std::thread> V;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000256 std::thread Pulse(PulseThread);
257 Pulse.detach();
258 for (unsigned i = 0; i < NumWorkers; i++)
morehousea80f6452017-12-04 19:25:59 +0000259 V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors));
george.karpenkov29efa6d2017-08-21 23:25:50 +0000260 for (auto &T : V)
261 T.join();
262 return HasErrors ? 1 : 0;
263}
264
265static void RssThread(Fuzzer *F, size_t RssLimitMb) {
266 while (true) {
267 SleepSeconds(1);
268 size_t Peak = GetPeakRSSMb();
269 if (Peak > RssLimitMb)
270 F->RssLimitCallback();
271 }
272}
273
274static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
275 if (!RssLimitMb) return;
276 std::thread T(RssThread, F, RssLimitMb);
277 T.detach();
278}
279
280int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
281 Unit U = FileToVector(InputFilePath);
282 if (MaxLen && MaxLen < U.size())
283 U.resize(MaxLen);
284 F->ExecuteCallback(U.data(), U.size());
285 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
286 return 0;
287}
288
289static bool AllInputsAreFiles() {
290 if (Inputs->empty()) return false;
291 for (auto &Path : *Inputs)
292 if (!IsFile(Path))
293 return false;
294 return true;
295}
296
297static std::string GetDedupTokenFromFile(const std::string &Path) {
298 auto S = FileToString(Path);
299 auto Beg = S.find("DEDUP_TOKEN:");
300 if (Beg == std::string::npos)
301 return "";
302 auto End = S.find('\n', Beg);
303 if (End == std::string::npos)
304 return "";
305 return S.substr(Beg, End - Beg);
306}
307
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000308int CleanseCrashInput(const Vector<std::string> &Args,
dor1se6729cb2018-07-16 15:15:34 +0000309 const FuzzingOptions &Options) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000310 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
311 Printf("ERROR: -cleanse_crash should be given one input file and"
dor1se6729cb2018-07-16 15:15:34 +0000312 " -exact_artifact_path\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000313 exit(1);
314 }
315 std::string InputFilePath = Inputs->at(0);
316 std::string OutputFilePath = Flags.exact_artifact_path;
morehousea80f6452017-12-04 19:25:59 +0000317 Command Cmd(Args);
318 Cmd.removeFlag("cleanse_crash");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000319
morehousea80f6452017-12-04 19:25:59 +0000320 assert(Cmd.hasArgument(InputFilePath));
321 Cmd.removeArgument(InputFilePath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000322
323 auto LogFilePath = DirPlusFile(
324 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
325 auto TmpFilePath = DirPlusFile(
326 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".repro");
morehousea80f6452017-12-04 19:25:59 +0000327 Cmd.addArgument(TmpFilePath);
328 Cmd.setOutputFile(LogFilePath);
329 Cmd.combineOutAndErr();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000330
331 std::string CurrentFilePath = InputFilePath;
332 auto U = FileToVector(CurrentFilePath);
333 size_t Size = U.size();
334
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000335 const Vector<uint8_t> ReplacementBytes = {' ', 0xff};
george.karpenkov29efa6d2017-08-21 23:25:50 +0000336 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
337 bool Changed = false;
338 for (size_t Idx = 0; Idx < Size; Idx++) {
339 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
340 Idx, Size);
341 uint8_t OriginalByte = U[Idx];
342 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
343 ReplacementBytes.end(),
344 OriginalByte))
345 continue;
346 for (auto NewByte : ReplacementBytes) {
347 U[Idx] = NewByte;
348 WriteToFile(U, TmpFilePath);
349 auto ExitCode = ExecuteCommand(Cmd);
350 RemoveFile(TmpFilePath);
351 if (!ExitCode) {
352 U[Idx] = OriginalByte;
353 } else {
354 Changed = true;
355 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
356 WriteToFile(U, OutputFilePath);
357 break;
358 }
359 }
360 }
361 if (!Changed) break;
362 }
363 RemoveFile(LogFilePath);
364 return 0;
365}
366
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000367int MinimizeCrashInput(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000368 const FuzzingOptions &Options) {
369 if (Inputs->size() != 1) {
370 Printf("ERROR: -minimize_crash should be given one input file\n");
371 exit(1);
372 }
373 std::string InputFilePath = Inputs->at(0);
morehousea80f6452017-12-04 19:25:59 +0000374 Command BaseCmd(Args);
375 BaseCmd.removeFlag("minimize_crash");
376 BaseCmd.removeFlag("exact_artifact_path");
377 assert(BaseCmd.hasArgument(InputFilePath));
378 BaseCmd.removeArgument(InputFilePath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000379 if (Flags.runs <= 0 && Flags.max_total_time == 0) {
380 Printf("INFO: you need to specify -runs=N or "
381 "-max_total_time=N with -minimize_crash=1\n"
382 "INFO: defaulting to -max_total_time=600\n");
morehousea80f6452017-12-04 19:25:59 +0000383 BaseCmd.addFlag("max_total_time", "600");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000384 }
385
386 auto LogFilePath = DirPlusFile(
387 TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
morehousea80f6452017-12-04 19:25:59 +0000388 BaseCmd.setOutputFile(LogFilePath);
389 BaseCmd.combineOutAndErr();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000390
391 std::string CurrentFilePath = InputFilePath;
392 while (true) {
393 Unit U = FileToVector(CurrentFilePath);
394 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
395 CurrentFilePath.c_str(), U.size());
396
morehousea80f6452017-12-04 19:25:59 +0000397 Command Cmd(BaseCmd);
398 Cmd.addArgument(CurrentFilePath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000399
morehousea80f6452017-12-04 19:25:59 +0000400 std::string CommandLine = Cmd.toString();
401 Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000402 int ExitCode = ExecuteCommand(Cmd);
403 if (ExitCode == 0) {
404 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
405 exit(1);
406 }
407 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
408 "it further\n",
409 CurrentFilePath.c_str(), U.size());
410 auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
411 if (!DedupToken1.empty())
412 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
413
414 std::string ArtifactPath =
415 Flags.exact_artifact_path
416 ? Flags.exact_artifact_path
417 : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
morehousea80f6452017-12-04 19:25:59 +0000418 Cmd.addFlag("minimize_crash_internal_step", "1");
419 Cmd.addFlag("exact_artifact_path", ArtifactPath);
420 CommandLine = Cmd.toString();
421 Printf("CRASH_MIN: executing: %s\n", CommandLine.c_str());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000422 ExitCode = ExecuteCommand(Cmd);
423 CopyFileToErr(LogFilePath);
424 if (ExitCode == 0) {
425 if (Flags.exact_artifact_path) {
426 CurrentFilePath = Flags.exact_artifact_path;
427 WriteToFile(U, CurrentFilePath);
428 }
429 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
430 CurrentFilePath.c_str(), U.size());
431 break;
432 }
433 auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
434 if (!DedupToken2.empty())
435 Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
436
437 if (DedupToken1 != DedupToken2) {
438 if (Flags.exact_artifact_path) {
439 CurrentFilePath = Flags.exact_artifact_path;
440 WriteToFile(U, CurrentFilePath);
441 }
442 Printf("CRASH_MIN: mismatch in dedup tokens"
443 " (looks like a different bug). Won't minimize further\n");
444 break;
445 }
446
447 CurrentFilePath = ArtifactPath;
448 Printf("*********************************\n");
449 }
450 RemoveFile(LogFilePath);
451 return 0;
452}
453
454int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
455 assert(Inputs->size() == 1);
456 std::string InputFilePath = Inputs->at(0);
457 Unit U = FileToVector(InputFilePath);
458 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
459 if (U.size() < 2) {
460 Printf("INFO: The input is small enough, exiting\n");
461 exit(0);
462 }
463 F->SetMaxInputLen(U.size());
464 F->SetMaxMutationLen(U.size() - 1);
465 F->MinimizeCrashLoop(U);
466 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
467 exit(0);
468 return 0;
469}
470
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000471int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000472 UnitVector& Corpus) {
473 Printf("Started dictionary minimization (up to %d tests)\n",
474 Dict.size() * Corpus.size() * 2);
475
476 // Scores and usage count for each dictionary unit.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000477 Vector<int> Scores(Dict.size());
478 Vector<int> Usages(Dict.size());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000479
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000480 Vector<size_t> InitialFeatures;
481 Vector<size_t> ModifiedFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000482 for (auto &C : Corpus) {
483 // Get coverage for the testcase without modifications.
484 F->ExecuteCallback(C.data(), C.size());
485 InitialFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000486 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000487 InitialFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000488 });
489
490 for (size_t i = 0; i < Dict.size(); ++i) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000491 Vector<uint8_t> Data = C;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000492 auto StartPos = std::search(Data.begin(), Data.end(),
493 Dict[i].begin(), Dict[i].end());
494 // Skip dictionary unit, if the testcase does not contain it.
495 if (StartPos == Data.end())
496 continue;
497
498 ++Usages[i];
499 while (StartPos != Data.end()) {
500 // Replace all occurrences of dictionary unit in the testcase.
501 auto EndPos = StartPos + Dict[i].size();
502 for (auto It = StartPos; It != EndPos; ++It)
503 *It ^= 0xFF;
504
505 StartPos = std::search(EndPos, Data.end(),
506 Dict[i].begin(), Dict[i].end());
507 }
508
509 // Get coverage for testcase with masked occurrences of dictionary unit.
510 F->ExecuteCallback(Data.data(), Data.size());
511 ModifiedFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000512 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000513 ModifiedFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000514 });
515
516 if (InitialFeatures == ModifiedFeatures)
517 --Scores[i];
518 else
519 Scores[i] += 2;
520 }
521 }
522
523 Printf("###### Useless dictionary elements. ######\n");
524 for (size_t i = 0; i < Dict.size(); ++i) {
525 // Dictionary units with positive score are treated as useful ones.
526 if (Scores[i] > 0)
dor1se6729cb2018-07-16 15:15:34 +0000527 continue;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000528
529 Printf("\"");
530 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
531 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
532 }
533 Printf("###### End of useless dictionary elements. ######\n");
534 return 0;
535}
536
537int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
538 using namespace fuzzer;
539 assert(argc && argv && "Argument pointers cannot be nullptr");
540 std::string Argv0((*argv)[0]);
541 EF = new ExternalFunctions();
542 if (EF->LLVMFuzzerInitialize)
543 EF->LLVMFuzzerInitialize(argc, argv);
morehouse1467b792018-07-09 23:51:08 +0000544 if (EF->__msan_scoped_disable_interceptor_checks)
545 EF->__msan_scoped_disable_interceptor_checks();
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000546 const Vector<std::string> Args(*argv, *argv + *argc);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000547 assert(!Args.empty());
548 ProgName = new std::string(Args[0]);
549 if (Argv0 != *ProgName) {
550 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
551 exit(1);
552 }
553 ParseFlags(Args);
554 if (Flags.help) {
555 PrintHelp();
556 return 0;
557 }
558
559 if (Flags.close_fd_mask & 2)
560 DupAndCloseStderr();
561 if (Flags.close_fd_mask & 1)
562 CloseStdout();
563
564 if (Flags.jobs > 0 && Flags.workers == 0) {
565 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
566 if (Flags.workers > 1)
567 Printf("Running %u workers\n", Flags.workers);
568 }
569
570 if (Flags.workers > 0 && Flags.jobs > 0)
571 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
572
george.karpenkov29efa6d2017-08-21 23:25:50 +0000573 FuzzingOptions Options;
574 Options.Verbosity = Flags.verbosity;
575 Options.MaxLen = Flags.max_len;
morehouse8c42ada2018-02-13 20:52:15 +0000576 Options.LenControl = Flags.len_control;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000577 Options.UnitTimeoutSec = Flags.timeout;
578 Options.ErrorExitCode = Flags.error_exitcode;
579 Options.TimeoutExitCode = Flags.timeout_exitcode;
580 Options.MaxTotalTimeSec = Flags.max_total_time;
581 Options.DoCrossOver = Flags.cross_over;
582 Options.MutateDepth = Flags.mutate_depth;
kccb6836be2017-12-01 19:18:38 +0000583 Options.ReduceDepth = Flags.reduce_depth;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000584 Options.UseCounters = Flags.use_counters;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000585 Options.UseMemmem = Flags.use_memmem;
586 Options.UseCmp = Flags.use_cmp;
587 Options.UseValueProfile = Flags.use_value_profile;
588 Options.Shrink = Flags.shrink;
589 Options.ReduceInputs = Flags.reduce_inputs;
590 Options.ShuffleAtStartUp = Flags.shuffle;
591 Options.PreferSmall = Flags.prefer_small;
592 Options.ReloadIntervalSec = Flags.reload;
593 Options.OnlyASCII = Flags.only_ascii;
594 Options.DetectLeaks = Flags.detect_leaks;
alekseyshld995b552017-10-23 22:04:30 +0000595 Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000596 Options.TraceMalloc = Flags.trace_malloc;
597 Options.RssLimitMb = Flags.rss_limit_mb;
kcc120e40b2017-12-01 22:12:04 +0000598 Options.MallocLimitMb = Flags.malloc_limit_mb;
599 if (!Options.MallocLimitMb)
600 Options.MallocLimitMb = Options.RssLimitMb;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000601 if (Flags.runs >= 0)
602 Options.MaxNumberOfRuns = Flags.runs;
603 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
604 Options.OutputCorpus = (*Inputs)[0];
605 Options.ReportSlowUnits = Flags.report_slow_units;
606 if (Flags.artifact_prefix)
607 Options.ArtifactPrefix = Flags.artifact_prefix;
608 if (Flags.exact_artifact_path)
609 Options.ExactArtifactPath = Flags.exact_artifact_path;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000610 Vector<Unit> Dictionary;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000611 if (Flags.dict)
612 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
613 return 1;
614 if (Flags.verbosity > 0 && !Dictionary.empty())
615 Printf("Dictionary: %zd entries\n", Dictionary.size());
616 bool DoPlainRun = AllInputsAreFiles();
617 Options.SaveArtifacts =
618 !DoPlainRun || Flags.minimize_crash_internal_step;
619 Options.PrintNewCovPcs = Flags.print_pcs;
kcc00da6482017-08-25 20:09:25 +0000620 Options.PrintNewCovFuncs = Flags.print_funcs;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000621 Options.PrintFinalStats = Flags.print_final_stats;
622 Options.PrintCorpusStats = Flags.print_corpus_stats;
623 Options.PrintCoverage = Flags.print_coverage;
kcca7dd2a92018-05-21 19:47:00 +0000624 Options.DumpCoverage = Flags.dump_coverage;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000625 if (Flags.exit_on_src_pos)
626 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
627 if (Flags.exit_on_item)
628 Options.ExitOnItem = Flags.exit_on_item;
kcc3acbe072018-05-16 23:26:37 +0000629 if (Flags.focus_function)
630 Options.FocusFunction = Flags.focus_function;
kcc86e43882018-06-06 01:23:29 +0000631 if (Flags.data_flow_trace)
632 Options.DataFlowTrace = Flags.data_flow_trace;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000633
634 unsigned Seed = Flags.seed;
635 // Initialize Seed.
636 if (Seed == 0)
637 Seed =
638 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
639 if (Flags.verbosity)
640 Printf("INFO: Seed: %u\n", Seed);
641
642 Random Rand(Seed);
643 auto *MD = new MutationDispatcher(Rand, Options);
644 auto *Corpus = new InputCorpus(Options.OutputCorpus);
645 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
646
647 for (auto &U: Dictionary)
648 if (U.size() <= Word::GetMaxSize())
649 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
650
651 StartRssThread(F, Flags.rss_limit_mb);
652
653 Options.HandleAbrt = Flags.handle_abrt;
654 Options.HandleBus = Flags.handle_bus;
655 Options.HandleFpe = Flags.handle_fpe;
656 Options.HandleIll = Flags.handle_ill;
657 Options.HandleInt = Flags.handle_int;
658 Options.HandleSegv = Flags.handle_segv;
659 Options.HandleTerm = Flags.handle_term;
660 Options.HandleXfsz = Flags.handle_xfsz;
kcc1239a992017-11-09 20:30:19 +0000661 Options.HandleUsr1 = Flags.handle_usr1;
662 Options.HandleUsr2 = Flags.handle_usr2;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000663 SetSignalHandler(Options);
664
665 std::atexit(Fuzzer::StaticExitCallback);
666
667 if (Flags.minimize_crash)
668 return MinimizeCrashInput(Args, Options);
669
670 if (Flags.minimize_crash_internal_step)
671 return MinimizeCrashInputInternalStep(F, Corpus);
672
673 if (Flags.cleanse_crash)
674 return CleanseCrashInput(Args, Options);
675
kcc275c9f02018-05-15 01:15:47 +0000676#if 0 // deprecated, to be removed.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000677 if (auto Name = Flags.run_equivalence_server) {
678 SMR.Destroy(Name);
679 if (!SMR.Create(Name)) {
680 Printf("ERROR: can't create shared memory region\n");
681 return 1;
682 }
683 Printf("INFO: EQUIVALENCE SERVER UP\n");
684 while (true) {
685 SMR.WaitClient();
686 size_t Size = SMR.ReadByteArraySize();
687 SMR.WriteByteArray(nullptr, 0);
688 const Unit tmp(SMR.GetByteArray(), SMR.GetByteArray() + Size);
689 F->ExecuteCallback(tmp.data(), tmp.size());
690 SMR.PostServer();
691 }
692 return 0;
693 }
694
695 if (auto Name = Flags.use_equivalence_server) {
696 if (!SMR.Open(Name)) {
697 Printf("ERROR: can't open shared memory region\n");
698 return 1;
699 }
700 Printf("INFO: EQUIVALENCE CLIENT UP\n");
701 }
kcc275c9f02018-05-15 01:15:47 +0000702#endif
george.karpenkov29efa6d2017-08-21 23:25:50 +0000703
704 if (DoPlainRun) {
705 Options.SaveArtifacts = false;
706 int Runs = std::max(1, Flags.runs);
707 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
708 Inputs->size(), Runs);
709 for (auto &Path : *Inputs) {
710 auto StartTime = system_clock::now();
711 Printf("Running: %s\n", Path.c_str());
712 for (int Iter = 0; Iter < Runs; Iter++)
713 RunOneTest(F, Path.c_str(), Options.MaxLen);
714 auto StopTime = system_clock::now();
715 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
716 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
717 }
718 Printf("***\n"
719 "*** NOTE: fuzzing was not performed, you have only\n"
720 "*** executed the target code on a fixed set of inputs.\n"
721 "***\n");
722 F->PrintFinalStats();
723 exit(0);
724 }
725
726 if (Flags.merge) {
kccc51afd72017-11-09 01:05:29 +0000727 F->CrashResistantMerge(Args, *Inputs,
728 Flags.load_coverage_summary,
729 Flags.save_coverage_summary,
730 Flags.merge_control_file);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000731 exit(0);
732 }
733
kccc51afd72017-11-09 01:05:29 +0000734 if (Flags.merge_inner) {
735 const size_t kDefaultMaxMergeLen = 1 << 20;
736 if (Options.MaxLen == 0)
737 F->SetMaxInputLen(kDefaultMaxMergeLen);
738 assert(Flags.merge_control_file);
739 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
740 exit(0);
741 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000742
743 if (Flags.analyze_dict) {
kcc2e93b3f2017-08-29 02:05:01 +0000744 size_t MaxLen = INT_MAX; // Large max length.
745 UnitVector InitialCorpus;
746 for (auto &Inp : *Inputs) {
747 Printf("Loading corpus dir: %s\n", Inp.c_str());
748 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
749 MaxLen, /*ExitOnError=*/false);
750 }
751
george.karpenkov29efa6d2017-08-21 23:25:50 +0000752 if (Dictionary.empty() || Inputs->empty()) {
753 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
754 return 1;
755 }
756 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
757 Printf("Dictionary analysis failed\n");
758 exit(1);
759 }
sylvestrea9eb8572018-03-13 14:35:10 +0000760 Printf("Dictionary analysis succeeded\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000761 exit(0);
762 }
763
kcc2e93b3f2017-08-29 02:05:01 +0000764 F->Loop(*Inputs);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000765
766 if (Flags.verbosity)
767 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
768 F->secondsSinceProcessStartUp());
769 F->PrintFinalStats();
770
771 exit(0); // Don't let F destroy itself.
772}
773
774// Storage for global ExternalFunctions object.
775ExternalFunctions *EF = nullptr;
776
777} // namespace fuzzer