LLVM  5.0.0
FuzzerDriver.cpp
Go to the documentation of this file.
1 //===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 // FuzzerDriver and flag parsing.
10 //===----------------------------------------------------------------------===//
11 
12 #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 <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.
30 extern "C" __attribute__((used)) void __libfuzzer_is_present() {}
31 
32 namespace fuzzer {
33 
34 // Program arguments.
36  const char *Name;
37  const char *Description;
38  int Default;
39  int *IntFlag;
40  const char **StrFlag;
41  unsigned int *UIntFlag;
42 };
43 
44 struct {
45 #define FUZZER_DEPRECATED_FLAG(Name)
46 #define FUZZER_FLAG_INT(Name, Default, Description) int Name;
47 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name;
48 #define FUZZER_FLAG_STRING(Name, Description) const char *Name;
49 #include "FuzzerFlags.def"
50 #undef FUZZER_DEPRECATED_FLAG
51 #undef FUZZER_FLAG_INT
52 #undef FUZZER_FLAG_UNSIGNED
53 #undef FUZZER_FLAG_STRING
54 } Flags;
55 
56 static const FlagDescription FlagDescriptions [] {
57 #define FUZZER_DEPRECATED_FLAG(Name) \
58  {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr},
59 #define FUZZER_FLAG_INT(Name, Default, Description) \
60  {#Name, Description, Default, &Flags.Name, nullptr, nullptr},
61 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \
62  {#Name, Description, static_cast<int>(Default), \
63  nullptr, nullptr, &Flags.Name},
64 #define FUZZER_FLAG_STRING(Name, Description) \
65  {#Name, Description, 0, nullptr, &Flags.Name, nullptr},
66 #include "FuzzerFlags.def"
67 #undef FUZZER_DEPRECATED_FLAG
68 #undef FUZZER_FLAG_INT
69 #undef FUZZER_FLAG_UNSIGNED
70 #undef FUZZER_FLAG_STRING
71 };
72 
73 static const size_t kNumFlags =
74  sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
75 
76 static std::vector<std::string> *Inputs;
77 static std::string *ProgName;
78 
79 static void PrintHelp() {
80  Printf("Usage:\n");
81  auto Prog = ProgName->c_str();
82  Printf("\nTo run fuzzing pass 0 or more directories.\n");
83  Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog);
84 
85  Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n");
86  Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog);
87 
88  Printf("\nFlags: (strictly in form -flag=value)\n");
89  size_t MaxFlagLen = 0;
90  for (size_t F = 0; F < kNumFlags; F++)
91  MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
92 
93  for (size_t F = 0; F < kNumFlags; F++) {
94  const auto &D = FlagDescriptions[F];
95  if (strstr(D.Description, "internal flag") == D.Description) continue;
96  Printf(" %s", D.Name);
97  for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
98  Printf(" ");
99  Printf("\t");
100  Printf("%d\t%s\n", D.Default, D.Description);
101  }
102  Printf("\nFlags starting with '--' will be ignored and "
103  "will be passed verbatim to subprocesses.\n");
104 }
105 
106 static const char *FlagValue(const char *Param, const char *Name) {
107  size_t Len = strlen(Name);
108  if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
109  Param[Len + 1] == '=')
110  return &Param[Len + 2];
111  return nullptr;
112 }
113 
114 // Avoid calling stol as it triggers a bug in clang/glibc build.
115 static long MyStol(const char *Str) {
116  long Res = 0;
117  long Sign = 1;
118  if (*Str == '-') {
119  Str++;
120  Sign = -1;
121  }
122  for (size_t i = 0; Str[i]; i++) {
123  char Ch = Str[i];
124  if (Ch < '0' || Ch > '9')
125  return Res;
126  Res = Res * 10 + (Ch - '0');
127  }
128  return Res * Sign;
129 }
130 
131 static bool ParseOneFlag(const char *Param) {
132  if (Param[0] != '-') return false;
133  if (Param[1] == '-') {
134  static bool PrintedWarning = false;
135  if (!PrintedWarning) {
136  PrintedWarning = true;
137  Printf("INFO: libFuzzer ignores flags that start with '--'\n");
138  }
139  for (size_t F = 0; F < kNumFlags; F++)
140  if (FlagValue(Param + 1, FlagDescriptions[F].Name))
141  Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1);
142  return true;
143  }
144  for (size_t F = 0; F < kNumFlags; F++) {
145  const char *Name = FlagDescriptions[F].Name;
146  const char *Str = FlagValue(Param, Name);
147  if (Str) {
148  if (FlagDescriptions[F].IntFlag) {
149  int Val = MyStol(Str);
150  *FlagDescriptions[F].IntFlag = Val;
151  if (Flags.verbosity >= 2)
152  Printf("Flag: %s %d\n", Name, Val);
153  return true;
154  } else if (FlagDescriptions[F].UIntFlag) {
155  unsigned int Val = std::stoul(Str);
156  *FlagDescriptions[F].UIntFlag = Val;
157  if (Flags.verbosity >= 2)
158  Printf("Flag: %s %u\n", Name, Val);
159  return true;
160  } else if (FlagDescriptions[F].StrFlag) {
161  *FlagDescriptions[F].StrFlag = Str;
162  if (Flags.verbosity >= 2)
163  Printf("Flag: %s %s\n", Name, Str);
164  return true;
165  } else { // Deprecated flag.
166  Printf("Flag: %s: deprecated, don't use\n", Name);
167  return true;
168  }
169  }
170  }
171  Printf("\n\nWARNING: unrecognized flag '%s'; "
172  "use -help=1 to list all flags\n\n", Param);
173  return true;
174 }
175 
176 // We don't use any library to minimize dependencies.
177 static void ParseFlags(const std::vector<std::string> &Args) {
178  for (size_t F = 0; F < kNumFlags; F++) {
179  if (FlagDescriptions[F].IntFlag)
180  *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
181  if (FlagDescriptions[F].UIntFlag)
182  *FlagDescriptions[F].UIntFlag =
183  static_cast<unsigned int>(FlagDescriptions[F].Default);
184  if (FlagDescriptions[F].StrFlag)
185  *FlagDescriptions[F].StrFlag = nullptr;
186  }
187  Inputs = new std::vector<std::string>;
188  for (size_t A = 1; A < Args.size(); A++) {
189  if (ParseOneFlag(Args[A].c_str())) {
190  if (Flags.ignore_remaining_args)
191  break;
192  continue;
193  }
194  Inputs->push_back(Args[A]);
195  }
196 }
197 
198 static std::mutex Mu;
199 
200 static void PulseThread() {
201  while (true) {
202  SleepSeconds(600);
203  std::lock_guard<std::mutex> Lock(Mu);
204  Printf("pulse...\n");
205  }
206 }
207 
208 static void WorkerThread(const std::string &Cmd, std::atomic<unsigned> *Counter,
209  unsigned NumJobs, std::atomic<bool> *HasErrors) {
210  while (true) {
211  unsigned C = (*Counter)++;
212  if (C >= NumJobs) break;
213  std::string Log = "fuzz-" + std::to_string(C) + ".log";
214  std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
215  if (Flags.verbosity)
216  Printf("%s", ToRun.c_str());
217  int ExitCode = ExecuteCommand(ToRun);
218  if (ExitCode != 0)
219  *HasErrors = true;
220  std::lock_guard<std::mutex> Lock(Mu);
221  Printf("================== Job %u exited with exit code %d ============\n",
222  C, ExitCode);
224  }
225 }
226 
227 std::string CloneArgsWithoutX(const std::vector<std::string> &Args,
228  const char *X1, const char *X2) {
229  std::string Cmd;
230  for (auto &S : Args) {
231  if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2))
232  continue;
233  Cmd += S + " ";
234  }
235  return Cmd;
236 }
237 
238 static int RunInMultipleProcesses(const std::vector<std::string> &Args,
239  unsigned NumWorkers, unsigned NumJobs) {
240  std::atomic<unsigned> Counter(0);
241  std::atomic<bool> HasErrors(false);
242  std::string Cmd = CloneArgsWithoutX(Args, "jobs", "workers");
243  std::vector<std::thread> V;
244  std::thread Pulse(PulseThread);
245  Pulse.detach();
246  for (unsigned i = 0; i < NumWorkers; i++)
247  V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
248  for (auto &T : V)
249  T.join();
250  return HasErrors ? 1 : 0;
251 }
252 
253 static void RssThread(Fuzzer *F, size_t RssLimitMb) {
254  while (true) {
255  SleepSeconds(1);
256  size_t Peak = GetPeakRSSMb();
257  if (Peak > RssLimitMb)
258  F->RssLimitCallback();
259  }
260 }
261 
262 static void StartRssThread(Fuzzer *F, size_t RssLimitMb) {
263  if (!RssLimitMb) return;
264  std::thread T(RssThread, F, RssLimitMb);
265  T.detach();
266 }
267 
268 int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) {
269  Unit U = FileToVector(InputFilePath);
270  if (MaxLen && MaxLen < U.size())
271  U.resize(MaxLen);
272  F->ExecuteCallback(U.data(), U.size());
273  F->TryDetectingAMemoryLeak(U.data(), U.size(), true);
274  return 0;
275 }
276 
277 static bool AllInputsAreFiles() {
278  if (Inputs->empty()) return false;
279  for (auto &Path : *Inputs)
280  if (!IsFile(Path))
281  return false;
282  return true;
283 }
284 
285 static std::string GetDedupTokenFromFile(const std::string &Path) {
286  auto S = FileToString(Path);
287  auto Beg = S.find("DEDUP_TOKEN:");
288  if (Beg == std::string::npos)
289  return "";
290  auto End = S.find('\n', Beg);
291  if (End == std::string::npos)
292  return "";
293  return S.substr(Beg, End - Beg);
294 }
295 
296 int CleanseCrashInput(const std::vector<std::string> &Args,
297  const FuzzingOptions &Options) {
298  if (Inputs->size() != 1 || !Flags.exact_artifact_path) {
299  Printf("ERROR: -cleanse_crash should be given one input file and"
300  " -exact_artifact_path\n");
301  exit(1);
302  }
303  std::string InputFilePath = Inputs->at(0);
304  std::string OutputFilePath = Flags.exact_artifact_path;
305  std::string BaseCmd =
306  CloneArgsWithoutX(Args, "cleanse_crash", "cleanse_crash");
307 
308  auto InputPos = BaseCmd.find(" " + InputFilePath + " ");
309  assert(InputPos != std::string::npos);
310  BaseCmd.erase(InputPos, InputFilePath.size() + 1);
311 
312  auto LogFilePath = DirPlusFile(
313  TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
314  auto TmpFilePath = DirPlusFile(
315  TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".repro");
316  auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
317 
318  auto Cmd = BaseCmd + " " + TmpFilePath + LogFileRedirect;
319 
320  std::string CurrentFilePath = InputFilePath;
321  auto U = FileToVector(CurrentFilePath);
322  size_t Size = U.size();
323 
324  const std::vector<uint8_t> ReplacementBytes = {' ', 0xff};
325  for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) {
326  bool Changed = false;
327  for (size_t Idx = 0; Idx < Size; Idx++) {
328  Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts,
329  Idx, Size);
330  uint8_t OriginalByte = U[Idx];
331  if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(),
332  ReplacementBytes.end(),
333  OriginalByte))
334  continue;
335  for (auto NewByte : ReplacementBytes) {
336  U[Idx] = NewByte;
337  WriteToFile(U, TmpFilePath);
338  auto ExitCode = ExecuteCommand(Cmd);
339  RemoveFile(TmpFilePath);
340  if (!ExitCode) {
341  U[Idx] = OriginalByte;
342  } else {
343  Changed = true;
344  Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte);
345  WriteToFile(U, OutputFilePath);
346  break;
347  }
348  }
349  }
350  if (!Changed) break;
351  }
352  RemoveFile(LogFilePath);
353  return 0;
354 }
355 
356 int MinimizeCrashInput(const std::vector<std::string> &Args,
357  const FuzzingOptions &Options) {
358  if (Inputs->size() != 1) {
359  Printf("ERROR: -minimize_crash should be given one input file\n");
360  exit(1);
361  }
362  std::string InputFilePath = Inputs->at(0);
363  auto BaseCmd = SplitBefore(
364  "-ignore_remaining_args=1",
365  CloneArgsWithoutX(Args, "minimize_crash", "exact_artifact_path"));
366  auto InputPos = BaseCmd.first.find(" " + InputFilePath + " ");
367  assert(InputPos != std::string::npos);
368  BaseCmd.first.erase(InputPos, InputFilePath.size() + 1);
369  if (Flags.runs <= 0 && Flags.max_total_time == 0) {
370  Printf("INFO: you need to specify -runs=N or "
371  "-max_total_time=N with -minimize_crash=1\n"
372  "INFO: defaulting to -max_total_time=600\n");
373  BaseCmd.first += " -max_total_time=600";
374  }
375 
376  auto LogFilePath = DirPlusFile(
377  TmpDir(), "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
378  auto LogFileRedirect = " > " + LogFilePath + " 2>&1 ";
379 
380  std::string CurrentFilePath = InputFilePath;
381  while (true) {
382  Unit U = FileToVector(CurrentFilePath);
383  Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n",
384  CurrentFilePath.c_str(), U.size());
385 
386  auto Cmd = BaseCmd.first + " " + CurrentFilePath + LogFileRedirect + " " +
387  BaseCmd.second;
388 
389  Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
390  int ExitCode = ExecuteCommand(Cmd);
391  if (ExitCode == 0) {
392  Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str());
393  exit(1);
394  }
395  Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize "
396  "it further\n",
397  CurrentFilePath.c_str(), U.size());
398  auto DedupToken1 = GetDedupTokenFromFile(LogFilePath);
399  if (!DedupToken1.empty())
400  Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str());
401 
402  std::string ArtifactPath =
403  Flags.exact_artifact_path
404  ? Flags.exact_artifact_path
405  : Options.ArtifactPrefix + "minimized-from-" + Hash(U);
406  Cmd += " -minimize_crash_internal_step=1 -exact_artifact_path=" +
407  ArtifactPath;
408  Printf("CRASH_MIN: executing: %s\n", Cmd.c_str());
409  ExitCode = ExecuteCommand(Cmd);
410  CopyFileToErr(LogFilePath);
411  if (ExitCode == 0) {
412  if (Flags.exact_artifact_path) {
413  CurrentFilePath = Flags.exact_artifact_path;
414  WriteToFile(U, CurrentFilePath);
415  }
416  Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n",
417  CurrentFilePath.c_str(), U.size());
418  break;
419  }
420  auto DedupToken2 = GetDedupTokenFromFile(LogFilePath);
421  if (!DedupToken2.empty())
422  Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str());
423 
424  if (DedupToken1 != DedupToken2) {
425  if (Flags.exact_artifact_path) {
426  CurrentFilePath = Flags.exact_artifact_path;
427  WriteToFile(U, CurrentFilePath);
428  }
429  Printf("CRASH_MIN: mismatch in dedup tokens"
430  " (looks like a different bug). Won't minimize further\n");
431  break;
432  }
433 
434  CurrentFilePath = ArtifactPath;
435  Printf("*********************************\n");
436  }
437  RemoveFile(LogFilePath);
438  return 0;
439 }
440 
441 int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) {
442  assert(Inputs->size() == 1);
443  std::string InputFilePath = Inputs->at(0);
444  Unit U = FileToVector(InputFilePath);
445  Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size());
446  if (U.size() < 2) {
447  Printf("INFO: The input is small enough, exiting\n");
448  exit(0);
449  }
450  F->SetMaxInputLen(U.size());
451  F->SetMaxMutationLen(U.size() - 1);
452  F->MinimizeCrashLoop(U);
453  Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n");
454  exit(0);
455  return 0;
456 }
457 
458 int AnalyzeDictionary(Fuzzer *F, const std::vector<Unit>& Dict,
459  UnitVector& Corpus) {
460  Printf("Started dictionary minimization (up to %d tests)\n",
461  Dict.size() * Corpus.size() * 2);
462 
463  // Scores and usage count for each dictionary unit.
464  std::vector<int> Scores(Dict.size());
465  std::vector<int> Usages(Dict.size());
466 
467  std::vector<size_t> InitialFeatures;
468  std::vector<size_t> ModifiedFeatures;
469  for (auto &C : Corpus) {
470  // Get coverage for the testcase without modifications.
471  F->ExecuteCallback(C.data(), C.size());
472  InitialFeatures.clear();
473  TPC.CollectFeatures([&](size_t Feature) -> bool {
474  InitialFeatures.push_back(Feature);
475  return true;
476  });
477 
478  for (size_t i = 0; i < Dict.size(); ++i) {
479  auto Data = C;
480  auto StartPos = std::search(Data.begin(), Data.end(),
481  Dict[i].begin(), Dict[i].end());
482  // Skip dictionary unit, if the testcase does not contain it.
483  if (StartPos == Data.end())
484  continue;
485 
486  ++Usages[i];
487  while (StartPos != Data.end()) {
488  // Replace all occurrences of dictionary unit in the testcase.
489  auto EndPos = StartPos + Dict[i].size();
490  for (auto It = StartPos; It != EndPos; ++It)
491  *It ^= 0xFF;
492 
493  StartPos = std::search(EndPos, Data.end(),
494  Dict[i].begin(), Dict[i].end());
495  }
496 
497  // Get coverage for testcase with masked occurrences of dictionary unit.
498  F->ExecuteCallback(Data.data(), Data.size());
499  ModifiedFeatures.clear();
500  TPC.CollectFeatures([&](size_t Feature) -> bool {
501  ModifiedFeatures.push_back(Feature);
502  return true;
503  });
504 
505  if (InitialFeatures == ModifiedFeatures)
506  --Scores[i];
507  else
508  Scores[i] += 2;
509  }
510  }
511 
512  Printf("###### Useless dictionary elements. ######\n");
513  for (size_t i = 0; i < Dict.size(); ++i) {
514  // Dictionary units with positive score are treated as useful ones.
515  if (Scores[i] > 0)
516  continue;
517 
518  Printf("\"");
519  PrintASCII(Dict[i].data(), Dict[i].size(), "\"");
520  Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]);
521  }
522  Printf("###### End of useless dictionary elements. ######\n");
523  return 0;
524 }
525 
526 int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) {
527  using namespace fuzzer;
528  assert(argc && argv && "Argument pointers cannot be nullptr");
529  std::string Argv0((*argv)[0]);
530  EF = new ExternalFunctions();
531  if (EF->LLVMFuzzerInitialize)
532  EF->LLVMFuzzerInitialize(argc, argv);
533  const std::vector<std::string> Args(*argv, *argv + *argc);
534  assert(!Args.empty());
535  ProgName = new std::string(Args[0]);
536  if (Argv0 != *ProgName) {
537  Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n");
538  exit(1);
539  }
540  ParseFlags(Args);
541  if (Flags.help) {
542  PrintHelp();
543  return 0;
544  }
545 
546  if (Flags.close_fd_mask & 2)
548  if (Flags.close_fd_mask & 1)
549  CloseStdout();
550 
551  if (Flags.jobs > 0 && Flags.workers == 0) {
552  Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
553  if (Flags.workers > 1)
554  Printf("Running %u workers\n", Flags.workers);
555  }
556 
557  if (Flags.workers > 0 && Flags.jobs > 0)
558  return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs);
559 
560  const size_t kMaxSaneLen = 1 << 20;
561  const size_t kMinDefaultLen = 4096;
562  FuzzingOptions Options;
563  Options.Verbosity = Flags.verbosity;
564  Options.MaxLen = Flags.max_len;
565  Options.ExperimentalLenControl = Flags.experimental_len_control;
566  if (Flags.experimental_len_control && Flags.max_len == kMinDefaultLen)
567  Options.MaxLen = 1 << 20;
568  Options.UnitTimeoutSec = Flags.timeout;
569  Options.ErrorExitCode = Flags.error_exitcode;
570  Options.TimeoutExitCode = Flags.timeout_exitcode;
571  Options.MaxTotalTimeSec = Flags.max_total_time;
572  Options.DoCrossOver = Flags.cross_over;
573  Options.MutateDepth = Flags.mutate_depth;
574  Options.UseCounters = Flags.use_counters;
575  Options.UseIndirCalls = Flags.use_indir_calls;
576  Options.UseMemmem = Flags.use_memmem;
577  Options.UseCmp = Flags.use_cmp;
578  Options.UseValueProfile = Flags.use_value_profile;
579  Options.Shrink = Flags.shrink;
580  Options.ReduceInputs = Flags.reduce_inputs;
581  Options.ShuffleAtStartUp = Flags.shuffle;
582  Options.PreferSmall = Flags.prefer_small;
583  Options.ReloadIntervalSec = Flags.reload;
584  Options.OnlyASCII = Flags.only_ascii;
585  Options.DetectLeaks = Flags.detect_leaks;
586  Options.TraceMalloc = Flags.trace_malloc;
587  Options.RssLimitMb = Flags.rss_limit_mb;
588  if (Flags.runs >= 0)
589  Options.MaxNumberOfRuns = Flags.runs;
590  if (!Inputs->empty() && !Flags.minimize_crash_internal_step)
591  Options.OutputCorpus = (*Inputs)[0];
592  Options.ReportSlowUnits = Flags.report_slow_units;
593  if (Flags.artifact_prefix)
594  Options.ArtifactPrefix = Flags.artifact_prefix;
595  if (Flags.exact_artifact_path)
596  Options.ExactArtifactPath = Flags.exact_artifact_path;
597  std::vector<Unit> Dictionary;
598  if (Flags.dict)
600  return 1;
601  if (Flags.verbosity > 0 && !Dictionary.empty())
602  Printf("Dictionary: %zd entries\n", Dictionary.size());
603  bool DoPlainRun = AllInputsAreFiles();
604  Options.SaveArtifacts =
605  !DoPlainRun || Flags.minimize_crash_internal_step;
606  Options.PrintNewCovPcs = Flags.print_pcs;
607  Options.PrintFinalStats = Flags.print_final_stats;
608  Options.PrintCorpusStats = Flags.print_corpus_stats;
609  Options.PrintCoverage = Flags.print_coverage;
610  Options.DumpCoverage = Flags.dump_coverage;
611  if (Flags.exit_on_src_pos)
612  Options.ExitOnSrcPos = Flags.exit_on_src_pos;
613  if (Flags.exit_on_item)
614  Options.ExitOnItem = Flags.exit_on_item;
615 
616  unsigned Seed = Flags.seed;
617  // Initialize Seed.
618  if (Seed == 0)
619  Seed =
620  std::chrono::system_clock::now().time_since_epoch().count() + GetPid();
621  if (Flags.verbosity)
622  Printf("INFO: Seed: %u\n", Seed);
623 
624  Random Rand(Seed);
625  auto *MD = new MutationDispatcher(Rand, Options);
626  auto *Corpus = new InputCorpus(Options.OutputCorpus);
627  auto *F = new Fuzzer(Callback, *Corpus, *MD, Options);
628 
629  for (auto &U: Dictionary)
630  if (U.size() <= Word::GetMaxSize())
631  MD->AddWordToManualDictionary(Word(U.data(), U.size()));
632 
633  StartRssThread(F, Flags.rss_limit_mb);
634 
635  Options.HandleAbrt = Flags.handle_abrt;
636  Options.HandleBus = Flags.handle_bus;
637  Options.HandleFpe = Flags.handle_fpe;
638  Options.HandleIll = Flags.handle_ill;
639  Options.HandleInt = Flags.handle_int;
640  Options.HandleSegv = Flags.handle_segv;
641  Options.HandleTerm = Flags.handle_term;
642  Options.HandleXfsz = Flags.handle_xfsz;
643  SetSignalHandler(Options);
644 
645  if (Flags.minimize_crash)
646  return MinimizeCrashInput(Args, Options);
647 
648  if (Flags.minimize_crash_internal_step)
649  return MinimizeCrashInputInternalStep(F, Corpus);
650 
651  if (Flags.cleanse_crash)
652  return CleanseCrashInput(Args, Options);
653 
654  if (auto Name = Flags.run_equivalence_server) {
655  SMR.Destroy(Name);
656  if (!SMR.Create(Name)) {
657  Printf("ERROR: can't create shared memory region\n");
658  return 1;
659  }
660  Printf("INFO: EQUIVALENCE SERVER UP\n");
661  while (true) {
662  SMR.WaitClient();
663  size_t Size = SMR.ReadByteArraySize();
664  SMR.WriteByteArray(nullptr, 0);
665  const Unit tmp(SMR.GetByteArray(), SMR.GetByteArray() + Size);
666  F->ExecuteCallback(tmp.data(), tmp.size());
667  SMR.PostServer();
668  }
669  return 0;
670  }
671 
672  if (auto Name = Flags.use_equivalence_server) {
673  if (!SMR.Open(Name)) {
674  Printf("ERROR: can't open shared memory region\n");
675  return 1;
676  }
677  Printf("INFO: EQUIVALENCE CLIENT UP\n");
678  }
679 
680  if (DoPlainRun) {
681  Options.SaveArtifacts = false;
682  int Runs = std::max(1, Flags.runs);
683  Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(),
684  Inputs->size(), Runs);
685  for (auto &Path : *Inputs) {
686  auto StartTime = system_clock::now();
687  Printf("Running: %s\n", Path.c_str());
688  for (int Iter = 0; Iter < Runs; Iter++)
689  RunOneTest(F, Path.c_str(), Options.MaxLen);
690  auto StopTime = system_clock::now();
691  auto MS = duration_cast<milliseconds>(StopTime - StartTime).count();
692  Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS);
693  }
694  Printf("***\n"
695  "*** NOTE: fuzzing was not performed, you have only\n"
696  "*** executed the target code on a fixed set of inputs.\n"
697  "***\n");
698  F->PrintFinalStats();
699  exit(0);
700  }
701 
702  if (Flags.merge) {
703  if (Options.MaxLen == 0)
704  F->SetMaxInputLen(kMaxSaneLen);
705  if (Flags.merge_control_file)
706  F->CrashResistantMergeInternalStep(Flags.merge_control_file);
707  else
708  F->CrashResistantMerge(Args, *Inputs,
709  Flags.load_coverage_summary,
710  Flags.save_coverage_summary);
711  exit(0);
712  }
713 
714  size_t TemporaryMaxLen = Options.MaxLen ? Options.MaxLen : kMaxSaneLen;
715 
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  TemporaryMaxLen, /*ExitOnError=*/false);
721  }
722 
723  if (Flags.analyze_dict) {
724  if (Dictionary.empty() || Inputs->empty()) {
725  Printf("ERROR: can't analyze dict without dict and corpus provided\n");
726  return 1;
727  }
728  if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) {
729  Printf("Dictionary analysis failed\n");
730  exit(1);
731  }
732  Printf("Dictionary analysis suceeded\n");
733  exit(0);
734  }
735 
736  if (Options.MaxLen == 0) {
737  size_t MaxLen = 0;
738  for (auto &U : InitialCorpus)
739  MaxLen = std::max(U.size(), MaxLen);
740  F->SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxLen), kMaxSaneLen));
741  }
742 
743  if (InitialCorpus.empty()) {
744  InitialCorpus.push_back(Unit({'\n'})); // Valid ASCII input.
745  if (Options.Verbosity)
746  Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
747  }
748  F->ShuffleAndMinimize(&InitialCorpus);
749  InitialCorpus.clear(); // Don't need this memory any more.
750  F->Loop();
751 
752  if (Flags.verbosity)
753  Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(),
754  F->secondsSinceProcessStartUp());
755  F->PrintFinalStats();
756 
757  exit(0); // Don't let F destroy itself.
758 }
759 
760 // Storage for global ExternalFunctions object.
761 ExternalFunctions *EF = nullptr;
762 
763 } // namespace fuzzer
bool Create(const char *Name)
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static cl::opt< unsigned long long > Seed("rng-seed", cl::value_desc("seed"), cl::desc("Seed for the random number generator"), cl::init(0))
size_t WriteByteArray(const uint8_t *Bytes, size_t N)
Definition: FuzzerShmem.h:34
int(* UserCallback)(const uint8_t *Data, size_t Size)
Definition: FuzzerDefs.h:107
size_t size() const
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
bool Open(const char *Name)
std::pair< std::string, std::string > SplitBefore(std::string X, std::string S)
Definition: FuzzerUtil.h:70
unsigned int * UIntFlag
static int Counter
static sys::Mutex Lock
void SleepSeconds(int Seconds)
SharedMemoryRegion SMR
Definition: FuzzerLoop.cpp:43
struct fuzzer::@301 Flags
static Fuzzer * F
Definition: FuzzerLoop.cpp:46
bool IsFile(const std::string &Path)
void CloseStdout()
Definition: FuzzerIO.cpp:106
void DupAndCloseStderr()
Definition: FuzzerIO.cpp:92
std::string FileToString(const std::string &Path)
Definition: FuzzerIO.cpp:51
ExternalFunctions * EF
void ReadDirToVectorOfUnits(const char *Path, std::vector< Unit > *V, long *Epoch, size_t MaxSize, bool ExitOnError)
Definition: FuzzerIO.cpp:69
__attribute__((used)) void __libfuzzer_is_present()
#define T
int FuzzerDriver(int *argc, char ***argv, UserCallback Callback)
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:880
const char * Name
TracePC TPC
PrintASCII(Dict[i].data(), Dict[i].size(),"\"")
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
bool ParseDictionaryFile(const std::string &Text, std::vector< Unit > *Units)
Definition: FuzzerUtil.cpp:127
#define A
Definition: LargeTest.cpp:12
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
std::string DirPlusFile(const std::string &DirPath, const std::string &FileName)
Definition: FuzzerIO.cpp:87
static const unsigned End
void SetSignalHandler(const FuzzingOptions &Options)
void CollectFeatures(Callback CB) const
void CopyFileToErr(const std::string &Path)
Definition: FuzzerIO.cpp:57
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:839
bool Destroy(const char *Name)
char *** argv
Definition: afl_driver.cpp:92
void WriteToFile(const Unit &U, const std::string &Path)
Definition: FuzzerIO.cpp:61
Unit FileToVector(const std::string &Path, size_t MaxSize, bool ExitOnError)
Definition: FuzzerIO.cpp:33
unsigned long GetPid()
size_t GetPeakRSSMb()
Definition: afl_driver.cpp:118
void RemoveFile(const std::string &Path)
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
std::string TmpDir()
std::vector< Unit > UnitVector
Definition: FuzzerDefs.h:106
#define C
Definition: LargeTest.cpp:25
const std::string to_string(const T &Value)
Definition: ScopedPrinter.h:62
std::vector< uint8_t > Unit
Definition: FuzzerDefs.h:105
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::string Hash(const Unit &U)
Definition: FuzzerSHA1.cpp:216
unsigned NumberOfCpuCores()
Definition: FuzzerUtil.cpp:198
Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i])
int ExecuteCommand(const std::string &Command)
std::thread thread
Definition: thread.h:27
#define D
Definition: LargeTest.cpp:26
std::string CloneArgsWithoutX(const std::vector< std::string > &Args, const char *X1, const char *X2)
static size_t GetMaxSize()