blob: 7a963ad6668fa8c450d14a716a5d429c1fce576b [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"
kcc2e6ca5c2019-02-12 22:48:55 +000013#include "FuzzerFork.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000014#include "FuzzerIO.h"
15#include "FuzzerInterface.h"
16#include "FuzzerInternal.h"
kcc2e6ca5c2019-02-12 22:48:55 +000017#include "FuzzerMerge.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000018#include "FuzzerMutate.h"
19#include "FuzzerRandom.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000020#include "FuzzerTracePC.h"
21#include <algorithm>
22#include <atomic>
23#include <chrono>
24#include <cstdlib>
25#include <cstring>
26#include <mutex>
27#include <string>
28#include <thread>
kcca3815862019-02-08 21:27:23 +000029#include <fstream>
george.karpenkov29efa6d2017-08-21 23:25:50 +000030
31// This function should be present in the libFuzzer so that the client
32// binary can test for its existence.
metzman2fe66e62019-01-17 16:36:05 +000033#if LIBFUZZER_MSVC
34extern "C" void __libfuzzer_is_present() {}
35#pragma comment(linker, "/include:__libfuzzer_is_present")
36#else
george.karpenkov29efa6d2017-08-21 23:25:50 +000037extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
metzman2fe66e62019-01-17 16:36:05 +000038#endif // LIBFUZZER_MSVC
george.karpenkov29efa6d2017-08-21 23:25:50 +000039
40namespace fuzzer {
41
42// Program arguments.
43struct FlagDescription {
44 const char *Name;
45 const char *Description;
46 int Default;
47 int *IntFlag;
48 const char **StrFlag;
49 unsigned int *UIntFlag;
50};
51
52struct {
53#define FUZZER_DEPRECATED_FLAG(Name)
54#define FUZZER_FLAG_INT(Name, Default, Description) int Name;
55#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
56#define FUZZER_FLAG_STRING(Name, Description) const char *Name;
57#include "FuzzerFlags.def"
58#undef FUZZER_DEPRECATED_FLAG
59#undef FUZZER_FLAG_INT
60#undef FUZZER_FLAG_UNSIGNED
61#undef FUZZER_FLAG_STRING
62} Flags;
63
64static const FlagDescription FlagDescriptions [] {
65#define FUZZER_DEPRECATED_FLAG(Name) \
66 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
67#define FUZZER_FLAG_INT(Name, Default, Description) \
68 {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
69#define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
70 {#Name, Description, static_cast<int>(Default), \
71 nullptr, nullptr, &Flags.Name},
72#define FUZZER_FLAG_STRING(Name, Description) \
73 {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
74#include "FuzzerFlags.def"
75#undef FUZZER_DEPRECATED_FLAG
76#undef FUZZER_FLAG_INT
77#undef FUZZER_FLAG_UNSIGNED
78#undef FUZZER_FLAG_STRING
79};
80
81static const size_t kNumFlags =
82 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
83
george.karpenkovfbfa45c2017-08-27 23:20:09 +000084static Vector<std::string> *Inputs;
george.karpenkov29efa6d2017-08-21 23:25:50 +000085static std::string *ProgName;
86
87static void PrintHelp() {
88 Printf("Usage:\n");
89 auto Prog = ProgName->c_str();
90 Printf("\nTo run fuzzing pass 0 or more directories.\n");
91 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
92
93 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
94 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
95
96 Printf("\nFlags: (strictly in form -flag=value)\n");
97 size_t MaxFlagLen = 0;
98 for (size_t F = 0; F < kNumFlags; F++)
99 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
100
101 for (size_t F = 0; F < kNumFlags; F++) {
102 const auto &D = FlagDescriptions[F];
103 if (strstr(D.Description, "internal flag") == D.Description) continue;
104 Printf(" %s", D.Name);
105 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
106 Printf(" ");
107 Printf("\t");
108 Printf("%d\t%s\n", D.Default, D.Description);
109 }
110 Printf("\nFlags starting with '--' will be ignored and "
dor1se6729cb2018-07-16 15:15:34 +0000111 "will be passed verbatim to subprocesses.\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000112}
113
114static const char *FlagValue(const char *Param, const char *Name) {
115 size_t Len = strlen(Name);
116 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
117 Param[Len + 1] == '=')
dor1se6729cb2018-07-16 15:15:34 +0000118 return &Param[Len + 2];
george.karpenkov29efa6d2017-08-21 23:25:50 +0000119 return nullptr;
120}
121
122// Avoid calling stol as it triggers a bug in clang/glibc build.
123static long MyStol(const char *Str) {
124 long Res = 0;
125 long Sign = 1;
126 if (*Str == '-') {
127 Str++;
128 Sign = -1;
129 }
130 for (size_t i = 0; Str[i]; i++) {
131 char Ch = Str[i];
132 if (Ch < '0' || Ch > '9')
133 return Res;
134 Res = Res * 10 + (Ch - '0');
135 }
136 return Res * Sign;
137}
138
139static bool ParseOneFlag(const char *Param) {
140 if (Param[0] != '-') return false;
141 if (Param[1] == '-') {
142 static bool PrintedWarning = false;
143 if (!PrintedWarning) {
144 PrintedWarning = true;
145 Printf("INFO: libFuzzer ignores flags that start with '--'\n");
146 }
147 for (size_t F = 0; F < kNumFlags; F++)
148 if (FlagValue(Param + 1, FlagDescriptions[F].Name))
149 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
150 return true;
151 }
152 for (size_t F = 0; F < kNumFlags; F++) {
153 const char *Name = FlagDescriptions[F].Name;
154 const char *Str = FlagValue(Param, Name);
155 if (Str) {
156 if (FlagDescriptions[F].IntFlag) {
157 int Val = MyStol(Str);
158 *FlagDescriptions[F].IntFlag = Val;
159 if (Flags.verbosity >= 2)
160 Printf("Flag: %s %d\n", Name, Val);
161 return true;
162 } else if (FlagDescriptions[F].UIntFlag) {
163 unsigned int Val = std::stoul(Str);
164 *FlagDescriptions[F].UIntFlag = Val;
165 if (Flags.verbosity >= 2)
166 Printf("Flag: %s %u\n", Name, Val);
167 return true;
168 } else if (FlagDescriptions[F].StrFlag) {
169 *FlagDescriptions[F].StrFlag = Str;
170 if (Flags.verbosity >= 2)
171 Printf("Flag: %s %s\n", Name, Str);
172 return true;
173 } else { // Deprecated flag.
174 Printf("Flag: %s: deprecated, don't use\n", Name);
175 return true;
176 }
177 }
178 }
179 Printf("\n\nWARNING: unrecognized flag '%s'; "
180 "use -help=1 to list all flags\n\n", Param);
181 return true;
182}
183
184// We don't use any library to minimize dependencies.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000185static void ParseFlags(const Vector<std::string> &Args) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000186 for (size_t F = 0; F < kNumFlags; F++) {
187 if (FlagDescriptions[F].IntFlag)
188 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
189 if (FlagDescriptions[F].UIntFlag)
190 *FlagDescriptions[F].UIntFlag =
191 static_cast<unsigned int>(FlagDescriptions[F].Default);
192 if (FlagDescriptions[F].StrFlag)
193 *FlagDescriptions[F].StrFlag = nullptr;
194 }
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000195 Inputs = new Vector<std::string>;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000196 for (size_t A = 1; A < Args.size(); A++) {
197 if (ParseOneFlag(Args[A].c_str())) {
198 if (Flags.ignore_remaining_args)
199 break;
200 continue;
201 }
202 Inputs->push_back(Args[A]);
203 }
204}
205
206static std::mutex Mu;
207
208static void PulseThread() {
209 while (true) {
210 SleepSeconds(600);
211 std::lock_guard<std::mutex> Lock(Mu);
212 Printf("pulse...\n");
213 }
214}
215
morehousea80f6452017-12-04 19:25:59 +0000216static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000217 unsigned NumJobs, std::atomic<bool> *HasErrors) {
218 while (true) {
219 unsigned C = (*Counter)++;
220 if (C >= NumJobs) break;
221 std::string Log = "fuzz-" + std::to_string(C) + ".log";
morehousea80f6452017-12-04 19:25:59 +0000222 Command Cmd(BaseCmd);
223 Cmd.setOutputFile(Log);
224 Cmd.combineOutAndErr();
225 if (Flags.verbosity) {
226 std::string CommandLine = Cmd.toString();
kccf5628b32017-12-06 22:12:24 +0000227 Printf("%s\n", CommandLine.c_str());
morehousea80f6452017-12-04 19:25:59 +0000228 }
229 int ExitCode = ExecuteCommand(Cmd);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000230 if (ExitCode != 0)
231 *HasErrors = true;
232 std::lock_guard<std::mutex> Lock(Mu);
233 Printf("================== Job %u exited with exit code %d ============\n",
234 C, ExitCode);
235 fuzzer::CopyFileToErr(Log);
236 }
237}
238
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000239std::string CloneArgsWithoutX(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000240 const char *X1, const char *X2) {
241 std::string Cmd;
242 for (auto &S : Args) {
243 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
244 continue;
245 Cmd += S + " ";
246 }
247 return Cmd;
248}
249
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000250static int RunInMultipleProcesses(const Vector<std::string> &Args,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000251 unsigned NumWorkers, unsigned NumJobs) {
252 std::atomic<unsigned> Counter(0);
253 std::atomic<bool> HasErrors(false);
morehousea80f6452017-12-04 19:25:59 +0000254 Command Cmd(Args);
255 Cmd.removeFlag("jobs");
256 Cmd.removeFlag("workers");
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000257 Vector<std::thread> V;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000258 std::thread Pulse(PulseThread);
259 Pulse.detach();
260 for (unsigned i = 0; i < NumWorkers; i++)
morehousea80f6452017-12-04 19:25:59 +0000261 V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors));
george.karpenkov29efa6d2017-08-21 23:25:50 +0000262 for (auto &T : V)
263 T.join();
264 return HasErrors ? 1 : 0;
265}
266
267static void RssThread(Fuzzer *F, size_t RssLimitMb) {
268 while (true) {
269 SleepSeconds(1);
270 size_t Peak = GetPeakRSSMb();
271 if (Peak > RssLimitMb)
272 F->RssLimitCallback();
273 }
274}
275
276static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
277 if (!RssLimitMb) return;
278 std::thread T(RssThread, F, RssLimitMb);
279 T.detach();
280}
281
282int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
283 Unit U = FileToVector(InputFilePath);
284 if (MaxLen && MaxLen < U.size())
285 U.resize(MaxLen);
286 F->ExecuteCallback(U.data(), U.size());
287 F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
288 return 0;
289}
290
291static bool AllInputsAreFiles() {
292 if (Inputs->empty()) return false;
293 for (auto &Path : *Inputs)
294 if (!IsFile(Path))
295 return false;
296 return true;
297}
298
299static std::string GetDedupTokenFromFile(const std::string &Path) {
300 auto S = FileToString(Path);
301 auto Beg = S.find("DEDUP_TOKEN:");
302 if (Beg == std::string::npos)
303 return "";
304 auto End = S.find('\n', Beg);
305 if (End == std::string::npos)
306 return "";
307 return S.substr(Beg, End - Beg);
308}
309
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000310int CleanseCrashInput(const Vector<std::string> &Args,
dor1se6729cb2018-07-16 15:15:34 +0000311 const FuzzingOptions &Options) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000312 if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
313 Printf("ERROR: -cleanse_crash should be given one input file and"
dor1se6729cb2018-07-16 15:15:34 +0000314 " -exact_artifact_path\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000315 exit(1);
316 }
317 std::string InputFilePath = Inputs->at(0);
318 std::string OutputFilePath = Flags.exact_artifact_path;
morehousea80f6452017-12-04 19:25:59 +0000319 Command Cmd(Args);
320 Cmd.removeFlag("cleanse_crash");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000321
morehousea80f6452017-12-04 19:25:59 +0000322 assert(Cmd.hasArgument(InputFilePath));
323 Cmd.removeArgument(InputFilePath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000324
kcca3815862019-02-08 21:27:23 +0000325 auto LogFilePath = TempPath(".txt");
326 auto TmpFilePath = TempPath(".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
kcca3815862019-02-08 21:27:23 +0000386 auto LogFilePath = TempPath(".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
kccd1449be2019-02-08 22:59:03 +0000470void Merge(Fuzzer *F, FuzzingOptions &Options, const Vector<std::string> &Args,
471 const Vector<std::string> &Corpora, const char *CFPathOrNull) {
472 if (Corpora.size() < 2) {
473 Printf("INFO: Merge requires two or more corpus dirs\n");
474 exit(0);
475 }
476
477 Vector<SizedFile> OldCorpus, NewCorpus;
478 GetSizedFilesFromDir(Corpora[0], &OldCorpus);
479 for (size_t i = 1; i < Corpora.size(); i++)
480 GetSizedFilesFromDir(Corpora[i], &NewCorpus);
481 std::sort(OldCorpus.begin(), OldCorpus.end());
482 std::sort(NewCorpus.begin(), NewCorpus.end());
483
484 std::string CFPath = CFPathOrNull ? CFPathOrNull : TempPath(".txt");
kcc4b5aa122019-02-09 00:16:21 +0000485 Vector<std::string> NewFiles;
kcc98a86242019-02-15 00:08:16 +0000486 Set<uint32_t> NewFeatures, NewCov;
kcc4b5aa122019-02-09 00:16:21 +0000487 CrashResistantMerge(Args, OldCorpus, NewCorpus, &NewFiles, {}, &NewFeatures,
kcc98a86242019-02-15 00:08:16 +0000488 {}, &NewCov, CFPath, true);
kcc4b5aa122019-02-09 00:16:21 +0000489 for (auto &Path : NewFiles)
kccd1449be2019-02-08 22:59:03 +0000490 F->WriteToOutputCorpus(FileToVector(Path, Options.MaxLen));
491 // We are done, delete the control file if it was a temporary one.
492 if (!Flags.merge_control_file)
493 RemoveFile(CFPath);
494
495 exit(0);
496}
497
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000498int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict,
george.karpenkov29efa6d2017-08-21 23:25:50 +0000499 UnitVector& Corpus) {
500 Printf("Started dictionary minimization (up to %d tests)\n",
501 Dict.size() * Corpus.size() * 2);
502
503 // Scores and usage count for each dictionary unit.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000504 Vector<int> Scores(Dict.size());
505 Vector<int> Usages(Dict.size());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000506
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000507 Vector<size_t> InitialFeatures;
508 Vector<size_t> ModifiedFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000509 for (auto &C : Corpus) {
510 // Get coverage for the testcase without modifications.
511 F->ExecuteCallback(C.data(), C.size());
512 InitialFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000513 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000514 InitialFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000515 });
516
517 for (size_t i = 0; i < Dict.size(); ++i) {
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000518 Vector<uint8_t> Data = C;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000519 auto StartPos = std::search(Data.begin(), Data.end(),
520 Dict[i].begin(), Dict[i].end());
521 // Skip dictionary unit, if the testcase does not contain it.
522 if (StartPos == Data.end())
523 continue;
524
525 ++Usages[i];
526 while (StartPos != Data.end()) {
527 // Replace all occurrences of dictionary unit in the testcase.
528 auto EndPos = StartPos + Dict[i].size();
529 for (auto It = StartPos; It != EndPos; ++It)
530 *It ^= 0xFF;
531
532 StartPos = std::search(EndPos, Data.end(),
533 Dict[i].begin(), Dict[i].end());
534 }
535
536 // Get coverage for testcase with masked occurrences of dictionary unit.
537 F->ExecuteCallback(Data.data(), Data.size());
538 ModifiedFeatures.clear();
kccc924e382017-09-15 22:10:36 +0000539 TPC.CollectFeatures([&](size_t Feature) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000540 ModifiedFeatures.push_back(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000541 });
542
543 if (InitialFeatures == ModifiedFeatures)
544 --Scores[i];
545 else
546 Scores[i] += 2;
547 }
548 }
549
550 Printf("###### Useless dictionary elements. ######\n");
551 for (size_t i = 0; i < Dict.size(); ++i) {
552 // Dictionary units with positive score are treated as useful ones.
553 if (Scores[i] > 0)
dor1se6729cb2018-07-16 15:15:34 +0000554 continue;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000555
556 Printf("\"");
557 PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
558 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
559 }
560 Printf("###### End of useless dictionary elements. ######\n");
561 return 0;
562}
563
kcc908220a2019-05-10 00:59:32 +0000564Vector<std::string> ParseSeedInuts(const char *seed_inputs) {
565 // Parse -seed_inputs=file1,file2,... or -seed_inputs=@seed_inputs_file
566 Vector<std::string> Files;
567 if (!seed_inputs) return Files;
568 std::string SeedInputs;
569 if (Flags.seed_inputs[0] == '@')
570 SeedInputs = FileToString(Flags.seed_inputs + 1); // File contains list.
571 else
572 SeedInputs = Flags.seed_inputs; // seed_inputs contains the list.
573 if (SeedInputs.empty()) {
574 Printf("seed_inputs is empty or @file does not exist.\n");
575 exit(1);
576 }
577 // Parse SeedInputs.
578 size_t comma_pos = 0;
579 while ((comma_pos = SeedInputs.find_last_of(',')) != std::string::npos) {
580 Files.push_back(SeedInputs.substr(comma_pos + 1));
581 SeedInputs = SeedInputs.substr(0, comma_pos);
582 }
583 Files.push_back(SeedInputs);
584 return Files;
585}
586
george.karpenkov29efa6d2017-08-21 23:25:50 +0000587int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
588 using namespace fuzzer;
589 assert(argc && argv && "Argument pointers cannot be nullptr");
590 std::string Argv0((*argv)[0]);
591 EF = new ExternalFunctions();
592 if (EF->LLVMFuzzerInitialize)
593 EF->LLVMFuzzerInitialize(argc, argv);
morehouse1467b792018-07-09 23:51:08 +0000594 if (EF->__msan_scoped_disable_interceptor_checks)
595 EF->__msan_scoped_disable_interceptor_checks();
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000596 const Vector<std::string> Args(*argv, *argv + *argc);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000597 assert(!Args.empty());
598 ProgName = new std::string(Args[0]);
599 if (Argv0 != *ProgName) {
600 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
601 exit(1);
602 }
603 ParseFlags(Args);
604 if (Flags.help) {
605 PrintHelp();
606 return 0;
607 }
608
609 if (Flags.close_fd_mask & 2)
610 DupAndCloseStderr();
611 if (Flags.close_fd_mask & 1)
612 CloseStdout();
613
614 if (Flags.jobs > 0 && Flags.workers == 0) {
615 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
616 if (Flags.workers > 1)
617 Printf("Running %u workers\n", Flags.workers);
618 }
619
620 if (Flags.workers > 0 && Flags.jobs > 0)
621 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
622
george.karpenkov29efa6d2017-08-21 23:25:50 +0000623 FuzzingOptions Options;
624 Options.Verbosity = Flags.verbosity;
625 Options.MaxLen = Flags.max_len;
morehouse8c42ada2018-02-13 20:52:15 +0000626 Options.LenControl = Flags.len_control;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000627 Options.UnitTimeoutSec = Flags.timeout;
628 Options.ErrorExitCode = Flags.error_exitcode;
629 Options.TimeoutExitCode = Flags.timeout_exitcode;
kcca7b741c2019-02-12 02:18:53 +0000630 Options.IgnoreTimeouts = Flags.ignore_timeouts;
631 Options.IgnoreOOMs = Flags.ignore_ooms;
kcc55e54ed2019-02-15 21:51:15 +0000632 Options.IgnoreCrashes = Flags.ignore_crashes;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000633 Options.MaxTotalTimeSec = Flags.max_total_time;
634 Options.DoCrossOver = Flags.cross_over;
635 Options.MutateDepth = Flags.mutate_depth;
kccb6836be2017-12-01 19:18:38 +0000636 Options.ReduceDepth = Flags.reduce_depth;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000637 Options.UseCounters = Flags.use_counters;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000638 Options.UseMemmem = Flags.use_memmem;
639 Options.UseCmp = Flags.use_cmp;
640 Options.UseValueProfile = Flags.use_value_profile;
641 Options.Shrink = Flags.shrink;
642 Options.ReduceInputs = Flags.reduce_inputs;
643 Options.ShuffleAtStartUp = Flags.shuffle;
644 Options.PreferSmall = Flags.prefer_small;
645 Options.ReloadIntervalSec = Flags.reload;
646 Options.OnlyASCII = Flags.only_ascii;
647 Options.DetectLeaks = Flags.detect_leaks;
alekseyshld995b552017-10-23 22:04:30 +0000648 Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000649 Options.TraceMalloc = Flags.trace_malloc;
650 Options.RssLimitMb = Flags.rss_limit_mb;
kcc120e40b2017-12-01 22:12:04 +0000651 Options.MallocLimitMb = Flags.malloc_limit_mb;
652 if (!Options.MallocLimitMb)
653 Options.MallocLimitMb = Options.RssLimitMb;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000654 if (Flags.runs >= 0)
655 Options.MaxNumberOfRuns = Flags.runs;
656 if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
657 Options.OutputCorpus = (*Inputs)[0];
658 Options.ReportSlowUnits = Flags.report_slow_units;
659 if (Flags.artifact_prefix)
660 Options.ArtifactPrefix = Flags.artifact_prefix;
661 if (Flags.exact_artifact_path)
662 Options.ExactArtifactPath = Flags.exact_artifact_path;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000663 Vector<Unit> Dictionary;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000664 if (Flags.dict)
665 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary))
666 return 1;
667 if (Flags.verbosity > 0 && !Dictionary.empty())
668 Printf("Dictionary: %zd entries\n", Dictionary.size());
669 bool DoPlainRun = AllInputsAreFiles();
670 Options.SaveArtifacts =
671 !DoPlainRun || Flags.minimize_crash_internal_step;
672 Options.PrintNewCovPcs = Flags.print_pcs;
kcc00da6482017-08-25 20:09:25 +0000673 Options.PrintNewCovFuncs = Flags.print_funcs;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000674 Options.PrintFinalStats = Flags.print_final_stats;
675 Options.PrintCorpusStats = Flags.print_corpus_stats;
676 Options.PrintCoverage = Flags.print_coverage;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000677 if (Flags.exit_on_src_pos)
678 Options.ExitOnSrcPos = Flags.exit_on_src_pos;
679 if (Flags.exit_on_item)
680 Options.ExitOnItem = Flags.exit_on_item;
kcc3acbe072018-05-16 23:26:37 +0000681 if (Flags.focus_function)
682 Options.FocusFunction = Flags.focus_function;
kcc86e43882018-06-06 01:23:29 +0000683 if (Flags.data_flow_trace)
684 Options.DataFlowTrace = Flags.data_flow_trace;
kcc6f1e9bc2019-04-13 00:20:31 +0000685 if (Flags.features_dir)
686 Options.FeaturesDir = Flags.features_dir;
kccc0a0b1f2019-01-31 01:40:14 +0000687 Options.LazyCounters = Flags.lazy_counters;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000688
kcc908220a2019-05-10 00:59:32 +0000689 auto ExtraSeedFiles = ParseSeedInuts(Flags.seed_inputs);
690
george.karpenkov29efa6d2017-08-21 23:25:50 +0000691 unsigned Seed = Flags.seed;
692 // Initialize Seed.
693 if (Seed == 0)
694 Seed =
695 std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
696 if (Flags.verbosity)
697 Printf("INFO: Seed: %u\n", Seed);
698
kcc908220a2019-05-10 00:59:32 +0000699 if (Flags.collect_data_flow)
700 return CollectDataFlow(Flags.collect_data_flow, Flags.data_flow_trace,
701 *Inputs, ExtraSeedFiles);
702
george.karpenkov29efa6d2017-08-21 23:25:50 +0000703 Random Rand(Seed);
704 auto *MD = new MutationDispatcher(Rand, Options);
705 auto *Corpus = new InputCorpus(Options.OutputCorpus);
706 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
707
708 for (auto &U: Dictionary)
709 if (U.size() <= Word::GetMaxSize())
710 MD->AddWordToManualDictionary(Word(U.data(), U.size()));
711
712 StartRssThread(F, Flags.rss_limit_mb);
713
714 Options.HandleAbrt = Flags.handle_abrt;
715 Options.HandleBus = Flags.handle_bus;
716 Options.HandleFpe = Flags.handle_fpe;
717 Options.HandleIll = Flags.handle_ill;
718 Options.HandleInt = Flags.handle_int;
719 Options.HandleSegv = Flags.handle_segv;
720 Options.HandleTerm = Flags.handle_term;
721 Options.HandleXfsz = Flags.handle_xfsz;
kcc1239a992017-11-09 20:30:19 +0000722 Options.HandleUsr1 = Flags.handle_usr1;
723 Options.HandleUsr2 = Flags.handle_usr2;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000724 SetSignalHandler(Options);
725
726 std::atexit(Fuzzer::StaticExitCallback);
727
728 if (Flags.minimize_crash)
729 return MinimizeCrashInput(Args, Options);
730
731 if (Flags.minimize_crash_internal_step)
732 return MinimizeCrashInputInternalStep(F, Corpus);
733
734 if (Flags.cleanse_crash)
735 return CleanseCrashInput(Args, Options);
736
george.karpenkov29efa6d2017-08-21 23:25:50 +0000737 if (DoPlainRun) {
738 Options.SaveArtifacts = false;
739 int Runs = std::max(1, Flags.runs);
740 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
741 Inputs->size(), Runs);
742 for (auto &Path : *Inputs) {
743 auto StartTime = system_clock::now();
744 Printf("Running: %s\n", Path.c_str());
745 for (int Iter = 0; Iter < Runs; Iter++)
746 RunOneTest(F, Path.c_str(), Options.MaxLen);
747 auto StopTime = system_clock::now();
748 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
749 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
750 }
751 Printf("***\n"
752 "*** NOTE: fuzzing was not performed, you have only\n"
753 "*** executed the target code on a fixed set of inputs.\n"
754 "***\n");
755 F->PrintFinalStats();
756 exit(0);
757 }
758
kcca3815862019-02-08 21:27:23 +0000759 if (Flags.fork)
kcc6526f1d2019-02-14 00:25:43 +0000760 FuzzWithFork(F->GetMD().GetRand(), Options, Args, *Inputs, Flags.fork);
kcca3815862019-02-08 21:27:23 +0000761
kccd1449be2019-02-08 22:59:03 +0000762 if (Flags.merge)
763 Merge(F, Options, Args, *Inputs, Flags.merge_control_file);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000764
kccc51afd72017-11-09 01:05:29 +0000765 if (Flags.merge_inner) {
766 const size_t kDefaultMaxMergeLen = 1 << 20;
767 if (Options.MaxLen == 0)
768 F->SetMaxInputLen(kDefaultMaxMergeLen);
769 assert(Flags.merge_control_file);
770 F->CrashResistantMergeInternalStep(Flags.merge_control_file);
771 exit(0);
772 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000773
774 if (Flags.analyze_dict) {
kcc2e93b3f2017-08-29 02:05:01 +0000775 size_t MaxLen = INT_MAX; // Large max length.
776 UnitVector InitialCorpus;
777 for (auto &Inp : *Inputs) {
778 Printf("Loading corpus dir: %s\n", Inp.c_str());
779 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr,
780 MaxLen, /*ExitOnError=*/false);
781 }
782
george.karpenkov29efa6d2017-08-21 23:25:50 +0000783 if (Dictionary.empty() || Inputs->empty()) {
784 Printf("ERROR: can't analyze dict without dict and corpus provided\n");
785 return 1;
786 }
787 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
788 Printf("Dictionary analysis failed\n");
789 exit(1);
790 }
sylvestrea9eb8572018-03-13 14:35:10 +0000791 Printf("Dictionary analysis succeeded\n");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000792 exit(0);
793 }
794
kcc0c34c832019-02-08 01:20:54 +0000795 F->Loop(*Inputs, ExtraSeedFiles);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000796
797 if (Flags.verbosity)
798 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
799 F->secondsSinceProcessStartUp());
800 F->PrintFinalStats();
801
802 exit(0); // Don't let F destroy itself.
803}
804
805// Storage for global ExternalFunctions object.
806ExternalFunctions *EF = nullptr;
807
808} // namespace fuzzer