FuzzerDriver.cpp 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. #include "FuzzerInterface.h"
  12. #include "FuzzerInternal.h"
  13. #include <cstring>
  14. #include <chrono>
  15. #include <unistd.h>
  16. #include <thread>
  17. #include <atomic>
  18. #include <mutex>
  19. #include <string>
  20. #include <sstream>
  21. #include <algorithm>
  22. #include <iterator>
  23. namespace fuzzer {
  24. // Program arguments.
  25. struct FlagDescription {
  26. const char *Name;
  27. const char *Description;
  28. int Default;
  29. int *IntFlag;
  30. const char **StrFlag;
  31. };
  32. struct {
  33. #define FUZZER_FLAG_INT(Name, Default, Description) int Name;
  34. #define FUZZER_FLAG_STRING(Name, Description) const char *Name;
  35. #include "FuzzerFlags.def"
  36. #undef FUZZER_FLAG_INT
  37. #undef FUZZER_FLAG_STRING
  38. } Flags;
  39. static FlagDescription FlagDescriptions [] {
  40. #define FUZZER_FLAG_INT(Name, Default, Description) \
  41. { #Name, Description, Default, &Flags.Name, nullptr},
  42. #define FUZZER_FLAG_STRING(Name, Description) \
  43. { #Name, Description, 0, nullptr, &Flags.Name },
  44. #include "FuzzerFlags.def"
  45. #undef FUZZER_FLAG_INT
  46. #undef FUZZER_FLAG_STRING
  47. };
  48. static const size_t kNumFlags =
  49. sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]);
  50. static std::vector<std::string> inputs;
  51. static const char *ProgName;
  52. static void PrintHelp() {
  53. Printf("Usage: %s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n",
  54. ProgName);
  55. Printf("\nFlags: (strictly in form -flag=value)\n");
  56. size_t MaxFlagLen = 0;
  57. for (size_t F = 0; F < kNumFlags; F++)
  58. MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen);
  59. for (size_t F = 0; F < kNumFlags; F++) {
  60. const auto &D = FlagDescriptions[F];
  61. Printf(" %s", D.Name);
  62. for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++)
  63. Printf(" ");
  64. Printf("\t");
  65. Printf("%d\t%s\n", D.Default, D.Description);
  66. }
  67. Printf("\nFlags starting with '--' will be ignored and "
  68. "will be passed verbatim to subprocesses.\n");
  69. }
  70. static const char *FlagValue(const char *Param, const char *Name) {
  71. size_t Len = strlen(Name);
  72. if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 &&
  73. Param[Len + 1] == '=')
  74. return &Param[Len + 2];
  75. return nullptr;
  76. }
  77. static bool ParseOneFlag(const char *Param) {
  78. if (Param[0] != '-') return false;
  79. if (Param[1] == '-') {
  80. static bool PrintedWarning = false;
  81. if (!PrintedWarning) {
  82. PrintedWarning = true;
  83. Printf("WARNING: libFuzzer ignores flags that start with '--'\n");
  84. }
  85. return true;
  86. }
  87. for (size_t F = 0; F < kNumFlags; F++) {
  88. const char *Name = FlagDescriptions[F].Name;
  89. const char *Str = FlagValue(Param, Name);
  90. if (Str) {
  91. if (FlagDescriptions[F].IntFlag) {
  92. int Val = std::stol(Str);
  93. *FlagDescriptions[F].IntFlag = Val;
  94. if (Flags.verbosity >= 2)
  95. Printf("Flag: %s %d\n", Name, Val);;
  96. return true;
  97. } else if (FlagDescriptions[F].StrFlag) {
  98. *FlagDescriptions[F].StrFlag = Str;
  99. if (Flags.verbosity >= 2)
  100. Printf("Flag: %s %s\n", Name, Str);
  101. return true;
  102. }
  103. }
  104. }
  105. PrintHelp();
  106. exit(1);
  107. }
  108. // We don't use any library to minimize dependencies.
  109. static void ParseFlags(int argc, char **argv) {
  110. for (size_t F = 0; F < kNumFlags; F++) {
  111. if (FlagDescriptions[F].IntFlag)
  112. *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default;
  113. if (FlagDescriptions[F].StrFlag)
  114. *FlagDescriptions[F].StrFlag = nullptr;
  115. }
  116. for (int A = 1; A < argc; A++) {
  117. if (ParseOneFlag(argv[A])) continue;
  118. inputs.push_back(argv[A]);
  119. }
  120. }
  121. static std::mutex Mu;
  122. static void PulseThread() {
  123. while (true) {
  124. std::this_thread::sleep_for(std::chrono::seconds(600));
  125. std::lock_guard<std::mutex> Lock(Mu);
  126. Printf("pulse...\n");
  127. }
  128. }
  129. static void WorkerThread(const std::string &Cmd, std::atomic<int> *Counter,
  130. int NumJobs, std::atomic<bool> *HasErrors) {
  131. while (true) {
  132. int C = (*Counter)++;
  133. if (C >= NumJobs) break;
  134. std::string Log = "fuzz-" + std::to_string(C) + ".log";
  135. std::string ToRun = Cmd + " > " + Log + " 2>&1\n";
  136. if (Flags.verbosity)
  137. Printf("%s", ToRun.c_str());
  138. int ExitCode = system(ToRun.c_str());
  139. if (ExitCode != 0)
  140. *HasErrors = true;
  141. std::lock_guard<std::mutex> Lock(Mu);
  142. Printf("================== Job %d exited with exit code %d ============\n",
  143. C, ExitCode);
  144. fuzzer::CopyFileToErr(Log);
  145. }
  146. }
  147. static int RunInMultipleProcesses(int argc, char **argv, int NumWorkers,
  148. int NumJobs) {
  149. std::atomic<int> Counter(0);
  150. std::atomic<bool> HasErrors(false);
  151. std::string Cmd;
  152. for (int i = 0; i < argc; i++) {
  153. if (FlagValue(argv[i], "jobs") || FlagValue(argv[i], "workers")) continue;
  154. Cmd += argv[i];
  155. Cmd += " ";
  156. }
  157. std::vector<std::thread> V;
  158. std::thread Pulse(PulseThread);
  159. Pulse.detach();
  160. for (int i = 0; i < NumWorkers; i++)
  161. V.push_back(std::thread(WorkerThread, Cmd, &Counter, NumJobs, &HasErrors));
  162. for (auto &T : V)
  163. T.join();
  164. return HasErrors ? 1 : 0;
  165. }
  166. std::vector<std::string> ReadTokensFile(const char *TokensFilePath) {
  167. if (!TokensFilePath) return {};
  168. std::string TokensFileContents = FileToString(TokensFilePath);
  169. std::istringstream ISS(TokensFileContents);
  170. std::vector<std::string> Res = {std::istream_iterator<std::string>{ISS},
  171. std::istream_iterator<std::string>{}};
  172. Res.push_back(" ");
  173. Res.push_back("\t");
  174. Res.push_back("\n");
  175. return Res;
  176. }
  177. int ApplyTokens(const Fuzzer &F, const char *InputFilePath) {
  178. Unit U = FileToVector(InputFilePath);
  179. auto T = F.SubstituteTokens(U);
  180. T.push_back(0);
  181. Printf("%s", T.data());
  182. return 0;
  183. }
  184. int FuzzerDriver(int argc, char **argv, UserCallback Callback) {
  185. SimpleUserSuppliedFuzzer SUSF(Callback);
  186. return FuzzerDriver(argc, argv, SUSF);
  187. }
  188. int FuzzerDriver(int argc, char **argv, UserSuppliedFuzzer &USF) {
  189. using namespace fuzzer;
  190. ProgName = argv[0];
  191. ParseFlags(argc, argv);
  192. if (Flags.help) {
  193. PrintHelp();
  194. return 0;
  195. }
  196. if (Flags.jobs > 0 && Flags.workers == 0) {
  197. Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs);
  198. if (Flags.workers > 1)
  199. Printf("Running %d workers\n", Flags.workers);
  200. }
  201. if (Flags.workers > 0 && Flags.jobs > 0)
  202. return RunInMultipleProcesses(argc, argv, Flags.workers, Flags.jobs);
  203. Fuzzer::FuzzingOptions Options;
  204. Options.Verbosity = Flags.verbosity;
  205. Options.MaxLen = Flags.max_len;
  206. Options.UnitTimeoutSec = Flags.timeout;
  207. Options.DoCrossOver = Flags.cross_over;
  208. Options.MutateDepth = Flags.mutate_depth;
  209. Options.ExitOnFirst = Flags.exit_on_first;
  210. Options.UseCounters = Flags.use_counters;
  211. Options.UseTraces = Flags.use_traces;
  212. Options.UseFullCoverageSet = Flags.use_full_coverage_set;
  213. Options.PreferSmallDuringInitialShuffle =
  214. Flags.prefer_small_during_initial_shuffle;
  215. Options.Tokens = ReadTokensFile(Flags.tokens);
  216. Options.Reload = Flags.reload;
  217. if (Flags.runs >= 0)
  218. Options.MaxNumberOfRuns = Flags.runs;
  219. if (!inputs.empty())
  220. Options.OutputCorpus = inputs[0];
  221. if (Flags.sync_command)
  222. Options.SyncCommand = Flags.sync_command;
  223. Options.SyncTimeout = Flags.sync_timeout;
  224. Fuzzer F(USF, Options);
  225. if (Flags.apply_tokens)
  226. return ApplyTokens(F, Flags.apply_tokens);
  227. unsigned Seed = Flags.seed;
  228. // Initialize Seed.
  229. if (Seed == 0)
  230. Seed = time(0) * 10000 + getpid();
  231. if (Flags.verbosity)
  232. Printf("Seed: %u\n", Seed);
  233. srand(Seed);
  234. // Timer
  235. if (Flags.timeout > 0)
  236. SetTimer(Flags.timeout / 2 + 1);
  237. if (Flags.verbosity >= 2) {
  238. Printf("Tokens: {");
  239. for (auto &T : Options.Tokens)
  240. Printf("%s,", T.c_str());
  241. Printf("}\n");
  242. }
  243. F.RereadOutputCorpus();
  244. for (auto &inp : inputs)
  245. if (inp != Options.OutputCorpus)
  246. F.ReadDir(inp, nullptr);
  247. if (F.CorpusSize() == 0)
  248. F.AddToCorpus(Unit()); // Can't fuzz empty corpus, so add an empty input.
  249. F.ShuffleAndMinimize();
  250. if (Flags.save_minimized_corpus)
  251. F.SaveCorpus();
  252. F.Loop(Flags.iterations < 0 ? INT_MAX : Flags.iterations);
  253. if (Flags.verbosity)
  254. Printf("Done %d runs in %zd second(s)\n", F.getTotalNumberOfRuns(),
  255. F.secondsSinceProcessStartUp());
  256. return 0;
  257. }
  258. } // namespace fuzzer