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