FuzzerLoop.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. //===- FuzzerLoop.cpp - Fuzzer's main loop --------------------------------===//
  2. //
  3. // 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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // Fuzzer's main loop.
  9. //===----------------------------------------------------------------------===//
  10. #include "FuzzerCorpus.h"
  11. #include "FuzzerIO.h"
  12. #include "FuzzerInternal.h"
  13. #include "FuzzerMutate.h"
  14. #include "FuzzerPlatform.h"
  15. #include "FuzzerRandom.h"
  16. #include "FuzzerTracePC.h"
  17. #include <algorithm>
  18. #include <cstring>
  19. #include <memory>
  20. #include <mutex>
  21. #include <set>
  22. #if defined(__has_include)
  23. #if __has_include(<sanitizer / lsan_interface.h>)
  24. #include <sanitizer/lsan_interface.h>
  25. #endif
  26. #endif
  27. #define NO_SANITIZE_MEMORY
  28. #if defined(__has_feature)
  29. #if __has_feature(memory_sanitizer)
  30. #undef NO_SANITIZE_MEMORY
  31. #define NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
  32. #endif
  33. #endif
  34. namespace fuzzer {
  35. static const size_t kMaxUnitSizeToPrint = 256;
  36. thread_local bool Fuzzer::IsMyThread;
  37. bool RunningUserCallback = false;
  38. // Only one Fuzzer per process.
  39. static Fuzzer *F;
  40. // Leak detection is expensive, so we first check if there were more mallocs
  41. // than frees (using the sanitizer malloc hooks) and only then try to call lsan.
  42. struct MallocFreeTracer {
  43. void Start(int TraceLevel) {
  44. this->TraceLevel = TraceLevel;
  45. if (TraceLevel)
  46. Printf("MallocFreeTracer: START\n");
  47. Mallocs = 0;
  48. Frees = 0;
  49. }
  50. // Returns true if there were more mallocs than frees.
  51. bool Stop() {
  52. if (TraceLevel)
  53. Printf("MallocFreeTracer: STOP %zd %zd (%s)\n", Mallocs.load(),
  54. Frees.load(), Mallocs == Frees ? "same" : "DIFFERENT");
  55. bool Result = Mallocs > Frees;
  56. Mallocs = 0;
  57. Frees = 0;
  58. TraceLevel = 0;
  59. return Result;
  60. }
  61. std::atomic<size_t> Mallocs;
  62. std::atomic<size_t> Frees;
  63. int TraceLevel = 0;
  64. std::recursive_mutex TraceMutex;
  65. bool TraceDisabled = false;
  66. };
  67. static MallocFreeTracer AllocTracer;
  68. // Locks printing and avoids nested hooks triggered from mallocs/frees in
  69. // sanitizer.
  70. class TraceLock {
  71. public:
  72. TraceLock() : Lock(AllocTracer.TraceMutex) {
  73. AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled;
  74. }
  75. ~TraceLock() { AllocTracer.TraceDisabled = !AllocTracer.TraceDisabled; }
  76. bool IsDisabled() const {
  77. // This is already inverted value.
  78. return !AllocTracer.TraceDisabled;
  79. }
  80. private:
  81. std::lock_guard<std::recursive_mutex> Lock;
  82. };
  83. ATTRIBUTE_NO_SANITIZE_MEMORY
  84. void MallocHook(const volatile void *ptr, size_t size) {
  85. size_t N = AllocTracer.Mallocs++;
  86. F->HandleMalloc(size);
  87. if (int TraceLevel = AllocTracer.TraceLevel) {
  88. TraceLock Lock;
  89. if (Lock.IsDisabled())
  90. return;
  91. Printf("MALLOC[%zd] %p %zd\n", N, ptr, size);
  92. if (TraceLevel >= 2 && EF)
  93. PrintStackTrace();
  94. }
  95. }
  96. ATTRIBUTE_NO_SANITIZE_MEMORY
  97. void FreeHook(const volatile void *ptr) {
  98. size_t N = AllocTracer.Frees++;
  99. if (int TraceLevel = AllocTracer.TraceLevel) {
  100. TraceLock Lock;
  101. if (Lock.IsDisabled())
  102. return;
  103. Printf("FREE[%zd] %p\n", N, ptr);
  104. if (TraceLevel >= 2 && EF)
  105. PrintStackTrace();
  106. }
  107. }
  108. // Crash on a single malloc that exceeds the rss limit.
  109. void Fuzzer::HandleMalloc(size_t Size) {
  110. if (!Options.MallocLimitMb || (Size >> 20) < (size_t)Options.MallocLimitMb)
  111. return;
  112. Printf("==%d== ERROR: libFuzzer: out-of-memory (malloc(%zd))\n", GetPid(),
  113. Size);
  114. Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
  115. PrintStackTrace();
  116. DumpCurrentUnit("oom-");
  117. Printf("SUMMARY: libFuzzer: out-of-memory\n");
  118. PrintFinalStats();
  119. _Exit(Options.OOMExitCode); // Stop right now.
  120. }
  121. Fuzzer::Fuzzer(UserCallback CB, InputCorpus &Corpus, MutationDispatcher &MD,
  122. FuzzingOptions Options)
  123. : CB(CB), Corpus(Corpus), MD(MD), Options(Options) {
  124. if (EF->__sanitizer_set_death_callback)
  125. EF->__sanitizer_set_death_callback(StaticDeathCallback);
  126. assert(!F);
  127. F = this;
  128. TPC.ResetMaps();
  129. IsMyThread = true;
  130. if (Options.DetectLeaks && EF->__sanitizer_install_malloc_and_free_hooks)
  131. EF->__sanitizer_install_malloc_and_free_hooks(MallocHook, FreeHook);
  132. TPC.SetUseCounters(Options.UseCounters);
  133. TPC.SetUseValueProfileMask(Options.UseValueProfile);
  134. if (Options.Verbosity)
  135. TPC.PrintModuleInfo();
  136. if (!Options.OutputCorpus.empty() && Options.ReloadIntervalSec)
  137. EpochOfLastReadOfOutputCorpus = GetEpoch(Options.OutputCorpus);
  138. MaxInputLen = MaxMutationLen = Options.MaxLen;
  139. TmpMaxMutationLen = 0; // Will be set once we load the corpus.
  140. AllocateCurrentUnitData();
  141. CurrentUnitSize = 0;
  142. memset(BaseSha1, 0, sizeof(BaseSha1));
  143. }
  144. Fuzzer::~Fuzzer() {}
  145. void Fuzzer::AllocateCurrentUnitData() {
  146. if (CurrentUnitData || MaxInputLen == 0)
  147. return;
  148. CurrentUnitData = new uint8_t[MaxInputLen];
  149. }
  150. void Fuzzer::StaticDeathCallback() {
  151. assert(F);
  152. F->DeathCallback();
  153. }
  154. void Fuzzer::DumpCurrentUnit(const char *Prefix) {
  155. if (!CurrentUnitData)
  156. return; // Happens when running individual inputs.
  157. ScopedDisableMsanInterceptorChecks S;
  158. MD.PrintMutationSequence();
  159. Printf("; base unit: %s\n", Sha1ToString(BaseSha1).c_str());
  160. size_t UnitSize = CurrentUnitSize;
  161. if (UnitSize <= kMaxUnitSizeToPrint) {
  162. PrintHexArray(CurrentUnitData, UnitSize, "\n");
  163. PrintASCII(CurrentUnitData, UnitSize, "\n");
  164. }
  165. WriteUnitToFileWithPrefix({CurrentUnitData, CurrentUnitData + UnitSize},
  166. Prefix);
  167. }
  168. NO_SANITIZE_MEMORY
  169. void Fuzzer::DeathCallback() {
  170. DumpCurrentUnit("crash-");
  171. PrintFinalStats();
  172. }
  173. void Fuzzer::StaticAlarmCallback() {
  174. assert(F);
  175. F->AlarmCallback();
  176. }
  177. void Fuzzer::StaticCrashSignalCallback() {
  178. assert(F);
  179. F->CrashCallback();
  180. }
  181. void Fuzzer::StaticExitCallback() {
  182. assert(F);
  183. F->ExitCallback();
  184. }
  185. void Fuzzer::StaticInterruptCallback() {
  186. assert(F);
  187. F->InterruptCallback();
  188. }
  189. void Fuzzer::StaticGracefulExitCallback() {
  190. assert(F);
  191. F->GracefulExitRequested = true;
  192. Printf("INFO: signal received, trying to exit gracefully\n");
  193. }
  194. void Fuzzer::StaticFileSizeExceedCallback() {
  195. Printf("==%lu== ERROR: libFuzzer: file size exceeded\n", GetPid());
  196. exit(1);
  197. }
  198. void Fuzzer::CrashCallback() {
  199. if (EF->__sanitizer_acquire_crash_state &&
  200. !EF->__sanitizer_acquire_crash_state())
  201. return;
  202. Printf("==%lu== ERROR: libFuzzer: deadly signal\n", GetPid());
  203. PrintStackTrace();
  204. Printf("NOTE: libFuzzer has rudimentary signal handlers.\n"
  205. " Combine libFuzzer with AddressSanitizer or similar for better "
  206. "crash reports.\n");
  207. Printf("SUMMARY: libFuzzer: deadly signal\n");
  208. DumpCurrentUnit("crash-");
  209. PrintFinalStats();
  210. _Exit(Options.ErrorExitCode); // Stop right now.
  211. }
  212. void Fuzzer::ExitCallback() {
  213. if (!RunningUserCallback)
  214. return; // This exit did not come from the user callback
  215. if (EF->__sanitizer_acquire_crash_state &&
  216. !EF->__sanitizer_acquire_crash_state())
  217. return;
  218. Printf("==%lu== ERROR: libFuzzer: fuzz target exited\n", GetPid());
  219. PrintStackTrace();
  220. Printf("SUMMARY: libFuzzer: fuzz target exited\n");
  221. DumpCurrentUnit("crash-");
  222. PrintFinalStats();
  223. _Exit(Options.ErrorExitCode);
  224. }
  225. void Fuzzer::MaybeExitGracefully() {
  226. if (!F->GracefulExitRequested) return;
  227. Printf("==%lu== INFO: libFuzzer: exiting as requested\n", GetPid());
  228. RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
  229. F->PrintFinalStats();
  230. _Exit(0);
  231. }
  232. void Fuzzer::InterruptCallback() {
  233. if (Options.DumpInterrupted)
  234. DumpCurrentUnit("interrupted-");
  235. Printf("==%lu== libFuzzer: run interrupted; exiting\n", GetPid());
  236. PrintFinalStats();
  237. ScopedDisableMsanInterceptorChecks S; // RmDirRecursive may call opendir().
  238. RmDirRecursive(TempPath("FuzzWithFork", ".dir"));
  239. // Stop right now, don't perform any at-exit actions.
  240. _Exit(Options.InterruptExitCode);
  241. }
  242. NO_SANITIZE_MEMORY
  243. void Fuzzer::AlarmCallback() {
  244. assert(Options.UnitTimeoutSec > 0);
  245. // In Windows and Fuchsia, Alarm callback is executed by a different thread.
  246. // NetBSD's current behavior needs this change too.
  247. #if !LIBFUZZER_WINDOWS && !LIBFUZZER_NETBSD && !LIBFUZZER_FUCHSIA
  248. if (!InFuzzingThread())
  249. return;
  250. #endif
  251. if (!RunningUserCallback)
  252. return; // We have not started running units yet.
  253. size_t Seconds =
  254. duration_cast<seconds>(system_clock::now() - UnitStartTime).count();
  255. if (Seconds == 0)
  256. return;
  257. if (Options.Verbosity >= 2)
  258. Printf("AlarmCallback %zd\n", Seconds);
  259. if (Seconds >= (size_t)Options.UnitTimeoutSec) {
  260. if (EF->__sanitizer_acquire_crash_state &&
  261. !EF->__sanitizer_acquire_crash_state())
  262. return;
  263. Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds);
  264. Printf(" and the timeout value is %d (use -timeout=N to change)\n",
  265. Options.UnitTimeoutSec);
  266. DumpCurrentUnit("timeout-");
  267. Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(),
  268. Seconds);
  269. PrintStackTrace();
  270. Printf("SUMMARY: libFuzzer: timeout\n");
  271. PrintFinalStats();
  272. _Exit(Options.TimeoutExitCode); // Stop right now.
  273. }
  274. }
  275. void Fuzzer::RssLimitCallback() {
  276. if (EF->__sanitizer_acquire_crash_state &&
  277. !EF->__sanitizer_acquire_crash_state())
  278. return;
  279. Printf(
  280. "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n",
  281. GetPid(), GetPeakRSSMb(), Options.RssLimitMb);
  282. Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n");
  283. PrintMemoryProfile();
  284. DumpCurrentUnit("oom-");
  285. Printf("SUMMARY: libFuzzer: out-of-memory\n");
  286. PrintFinalStats();
  287. _Exit(Options.OOMExitCode); // Stop right now.
  288. }
  289. void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units,
  290. size_t Features) {
  291. size_t ExecPerSec = execPerSec();
  292. if (!Options.Verbosity)
  293. return;
  294. Printf("#%zd\t%s", TotalNumberOfRuns, Where);
  295. if (size_t N = TPC.GetTotalPCCoverage())
  296. Printf(" cov: %zd", N);
  297. if (size_t N = Features ? Features : Corpus.NumFeatures())
  298. Printf(" ft: %zd", N);
  299. if (!Corpus.empty()) {
  300. Printf(" corp: %zd", Corpus.NumActiveUnits());
  301. if (size_t N = Corpus.SizeInBytes()) {
  302. if (N < (1 << 14))
  303. Printf("/%zdb", N);
  304. else if (N < (1 << 24))
  305. Printf("/%zdKb", N >> 10);
  306. else
  307. Printf("/%zdMb", N >> 20);
  308. }
  309. if (size_t FF = Corpus.NumInputsThatTouchFocusFunction())
  310. Printf(" focus: %zd", FF);
  311. }
  312. if (TmpMaxMutationLen)
  313. Printf(" lim: %zd", TmpMaxMutationLen);
  314. if (Units)
  315. Printf(" units: %zd", Units);
  316. Printf(" exec/s: %zd", ExecPerSec);
  317. Printf(" rss: %zdMb", GetPeakRSSMb());
  318. Printf("%s", End);
  319. }
  320. void Fuzzer::PrintFinalStats() {
  321. if (Options.PrintFullCoverage)
  322. TPC.PrintCoverage(/*PrintAllCounters=*/true);
  323. if (Options.PrintCoverage)
  324. TPC.PrintCoverage(/*PrintAllCounters=*/false);
  325. if (Options.PrintCorpusStats)
  326. Corpus.PrintStats();
  327. if (!Options.PrintFinalStats)
  328. return;
  329. size_t ExecPerSec = execPerSec();
  330. Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns);
  331. Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec);
  332. Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded);
  333. Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds);
  334. Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb());
  335. }
  336. void Fuzzer::SetMaxInputLen(size_t MaxInputLen) {
  337. assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0.
  338. assert(MaxInputLen);
  339. this->MaxInputLen = MaxInputLen;
  340. this->MaxMutationLen = MaxInputLen;
  341. AllocateCurrentUnitData();
  342. Printf("INFO: -max_len is not provided; "
  343. "libFuzzer will not generate inputs larger than %zd bytes\n",
  344. MaxInputLen);
  345. }
  346. void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) {
  347. assert(MaxMutationLen && MaxMutationLen <= MaxInputLen);
  348. this->MaxMutationLen = MaxMutationLen;
  349. }
  350. void Fuzzer::CheckExitOnSrcPosOrItem() {
  351. if (!Options.ExitOnSrcPos.empty()) {
  352. static auto *PCsSet = new std::set<uintptr_t>;
  353. auto HandlePC = [&](const TracePC::PCTableEntry *TE) {
  354. if (!PCsSet->insert(TE->PC).second)
  355. return;
  356. std::string Descr = DescribePC("%F %L", TE->PC + 1);
  357. if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) {
  358. Printf("INFO: found line matching '%s', exiting.\n",
  359. Options.ExitOnSrcPos.c_str());
  360. _Exit(0);
  361. }
  362. };
  363. TPC.ForEachObservedPC(HandlePC);
  364. }
  365. if (!Options.ExitOnItem.empty()) {
  366. if (Corpus.HasUnit(Options.ExitOnItem)) {
  367. Printf("INFO: found item with checksum '%s', exiting.\n",
  368. Options.ExitOnItem.c_str());
  369. _Exit(0);
  370. }
  371. }
  372. }
  373. void Fuzzer::RereadOutputCorpus(size_t MaxSize) {
  374. if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec)
  375. return;
  376. std::vector<Unit> AdditionalCorpus;
  377. std::vector<std::string> AdditionalCorpusPaths;
  378. ReadDirToVectorOfUnits(
  379. Options.OutputCorpus.c_str(), &AdditionalCorpus,
  380. &EpochOfLastReadOfOutputCorpus, MaxSize,
  381. /*ExitOnError*/ false,
  382. (Options.Verbosity >= 2 ? &AdditionalCorpusPaths : nullptr));
  383. if (Options.Verbosity >= 2)
  384. Printf("Reload: read %zd new units.\n", AdditionalCorpus.size());
  385. bool Reloaded = false;
  386. for (size_t i = 0; i != AdditionalCorpus.size(); ++i) {
  387. auto &U = AdditionalCorpus[i];
  388. if (U.size() > MaxSize)
  389. U.resize(MaxSize);
  390. if (!Corpus.HasUnit(U)) {
  391. if (RunOne(U.data(), U.size())) {
  392. CheckExitOnSrcPosOrItem();
  393. Reloaded = true;
  394. if (Options.Verbosity >= 2)
  395. Printf("Reloaded %s\n", AdditionalCorpusPaths[i].c_str());
  396. }
  397. }
  398. }
  399. if (Reloaded)
  400. PrintStats("RELOAD");
  401. }
  402. void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) {
  403. auto TimeOfUnit =
  404. duration_cast<seconds>(UnitStopTime - UnitStartTime).count();
  405. if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) &&
  406. secondsSinceProcessStartUp() >= 2)
  407. PrintStats("pulse ");
  408. auto Threshhold =
  409. static_cast<long>(static_cast<double>(TimeOfLongestUnitInSeconds) * 1.1);
  410. if (TimeOfUnit > Threshhold && TimeOfUnit >= Options.ReportSlowUnits) {
  411. TimeOfLongestUnitInSeconds = TimeOfUnit;
  412. Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds);
  413. WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-");
  414. }
  415. }
  416. static void WriteFeatureSetToFile(const std::string &FeaturesDir,
  417. const std::string &FileName,
  418. const std::vector<uint32_t> &FeatureSet) {
  419. if (FeaturesDir.empty() || FeatureSet.empty()) return;
  420. WriteToFile(reinterpret_cast<const uint8_t *>(FeatureSet.data()),
  421. FeatureSet.size() * sizeof(FeatureSet[0]),
  422. DirPlusFile(FeaturesDir, FileName));
  423. }
  424. static void RenameFeatureSetFile(const std::string &FeaturesDir,
  425. const std::string &OldFile,
  426. const std::string &NewFile) {
  427. if (FeaturesDir.empty()) return;
  428. RenameFile(DirPlusFile(FeaturesDir, OldFile),
  429. DirPlusFile(FeaturesDir, NewFile));
  430. }
  431. static void WriteEdgeToMutationGraphFile(const std::string &MutationGraphFile,
  432. const InputInfo *II,
  433. const InputInfo *BaseII,
  434. const std::string &MS) {
  435. if (MutationGraphFile.empty())
  436. return;
  437. std::string Sha1 = Sha1ToString(II->Sha1);
  438. std::string OutputString;
  439. // Add a new vertex.
  440. OutputString.append("\"");
  441. OutputString.append(Sha1);
  442. OutputString.append("\"\n");
  443. // Add a new edge if there is base input.
  444. if (BaseII) {
  445. std::string BaseSha1 = Sha1ToString(BaseII->Sha1);
  446. OutputString.append("\"");
  447. OutputString.append(BaseSha1);
  448. OutputString.append("\" -> \"");
  449. OutputString.append(Sha1);
  450. OutputString.append("\" [label=\"");
  451. OutputString.append(MS);
  452. OutputString.append("\"];\n");
  453. }
  454. AppendToFile(OutputString, MutationGraphFile);
  455. }
  456. bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile,
  457. InputInfo *II, bool ForceAddToCorpus,
  458. bool *FoundUniqFeatures) {
  459. if (!Size)
  460. return false;
  461. // Largest input length should be INT_MAX.
  462. assert(Size < std::numeric_limits<uint32_t>::max());
  463. if(!ExecuteCallback(Data, Size)) return false;
  464. auto TimeOfUnit = duration_cast<microseconds>(UnitStopTime - UnitStartTime);
  465. UniqFeatureSetTmp.clear();
  466. size_t FoundUniqFeaturesOfII = 0;
  467. size_t NumUpdatesBefore = Corpus.NumFeatureUpdates();
  468. TPC.CollectFeatures([&](uint32_t Feature) {
  469. if (Corpus.AddFeature(Feature, static_cast<uint32_t>(Size), Options.Shrink))
  470. UniqFeatureSetTmp.push_back(Feature);
  471. if (Options.Entropic)
  472. Corpus.UpdateFeatureFrequency(II, Feature);
  473. if (Options.ReduceInputs && II && !II->NeverReduce)
  474. if (std::binary_search(II->UniqFeatureSet.begin(),
  475. II->UniqFeatureSet.end(), Feature))
  476. FoundUniqFeaturesOfII++;
  477. });
  478. if (FoundUniqFeatures)
  479. *FoundUniqFeatures = FoundUniqFeaturesOfII;
  480. PrintPulseAndReportSlowInput(Data, Size);
  481. size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore;
  482. if (NumNewFeatures || ForceAddToCorpus) {
  483. TPC.UpdateObservedPCs();
  484. auto NewII =
  485. Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile,
  486. TPC.ObservedFocusFunction(), ForceAddToCorpus,
  487. TimeOfUnit, UniqFeatureSetTmp, DFT, II);
  488. WriteFeatureSetToFile(Options.FeaturesDir, Sha1ToString(NewII->Sha1),
  489. NewII->UniqFeatureSet);
  490. WriteEdgeToMutationGraphFile(Options.MutationGraphFile, NewII, II,
  491. MD.MutationSequence());
  492. return true;
  493. }
  494. if (II && FoundUniqFeaturesOfII &&
  495. II->DataFlowTraceForFocusFunction.empty() &&
  496. FoundUniqFeaturesOfII == II->UniqFeatureSet.size() &&
  497. II->U.size() > Size) {
  498. auto OldFeaturesFile = Sha1ToString(II->Sha1);
  499. Corpus.Replace(II, {Data, Data + Size}, TimeOfUnit);
  500. RenameFeatureSetFile(Options.FeaturesDir, OldFeaturesFile,
  501. Sha1ToString(II->Sha1));
  502. return true;
  503. }
  504. return false;
  505. }
  506. void Fuzzer::TPCUpdateObservedPCs() { TPC.UpdateObservedPCs(); }
  507. size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const {
  508. assert(InFuzzingThread());
  509. *Data = CurrentUnitData;
  510. return CurrentUnitSize;
  511. }
  512. void Fuzzer::CrashOnOverwrittenData() {
  513. Printf("==%d== ERROR: libFuzzer: fuzz target overwrites its const input\n",
  514. GetPid());
  515. PrintStackTrace();
  516. Printf("SUMMARY: libFuzzer: overwrites-const-input\n");
  517. DumpCurrentUnit("crash-");
  518. PrintFinalStats();
  519. _Exit(Options.ErrorExitCode); // Stop right now.
  520. }
  521. // Compare two arrays, but not all bytes if the arrays are large.
  522. static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) {
  523. const size_t Limit = 64;
  524. if (Size <= 64)
  525. return !memcmp(A, B, Size);
  526. // Compare first and last Limit/2 bytes.
  527. return !memcmp(A, B, Limit / 2) &&
  528. !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2);
  529. }
  530. // This method is not inlined because it would cause a test to fail where it
  531. // is part of the stack unwinding. See D97975 for details.
  532. ATTRIBUTE_NOINLINE bool Fuzzer::ExecuteCallback(const uint8_t *Data,
  533. size_t Size) {
  534. TPC.RecordInitialStack();
  535. TotalNumberOfRuns++;
  536. assert(InFuzzingThread());
  537. // We copy the contents of Unit into a separate heap buffer
  538. // so that we reliably find buffer overflows in it.
  539. uint8_t *DataCopy = new uint8_t[Size];
  540. memcpy(DataCopy, Data, Size);
  541. if (EF->__msan_unpoison)
  542. EF->__msan_unpoison(DataCopy, Size);
  543. if (EF->__msan_unpoison_param)
  544. EF->__msan_unpoison_param(2);
  545. if (CurrentUnitData && CurrentUnitData != Data)
  546. memcpy(CurrentUnitData, Data, Size);
  547. CurrentUnitSize = Size;
  548. int CBRes = 0;
  549. {
  550. ScopedEnableMsanInterceptorChecks S;
  551. AllocTracer.Start(Options.TraceMalloc);
  552. UnitStartTime = system_clock::now();
  553. TPC.ResetMaps();
  554. RunningUserCallback = true;
  555. CBRes = CB(DataCopy, Size);
  556. RunningUserCallback = false;
  557. UnitStopTime = system_clock::now();
  558. assert(CBRes == 0 || CBRes == -1);
  559. HasMoreMallocsThanFrees = AllocTracer.Stop();
  560. }
  561. if (!LooseMemeq(DataCopy, Data, Size))
  562. CrashOnOverwrittenData();
  563. CurrentUnitSize = 0;
  564. delete[] DataCopy;
  565. return CBRes == 0;
  566. }
  567. std::string Fuzzer::WriteToOutputCorpus(const Unit &U) {
  568. if (Options.OnlyASCII)
  569. assert(IsASCII(U));
  570. if (Options.OutputCorpus.empty())
  571. return "";
  572. std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U));
  573. WriteToFile(U, Path);
  574. if (Options.Verbosity >= 2)
  575. Printf("Written %zd bytes to %s\n", U.size(), Path.c_str());
  576. return Path;
  577. }
  578. void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) {
  579. if (!Options.SaveArtifacts)
  580. return;
  581. std::string Path = Options.ArtifactPrefix + Prefix + Hash(U);
  582. if (!Options.ExactArtifactPath.empty())
  583. Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix.
  584. WriteToFile(U, Path);
  585. Printf("artifact_prefix='%s'; Test unit written to %s\n",
  586. Options.ArtifactPrefix.c_str(), Path.c_str());
  587. if (U.size() <= kMaxUnitSizeToPrint)
  588. Printf("Base64: %s\n", Base64(U).c_str());
  589. }
  590. void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) {
  591. if (!Options.PrintNEW)
  592. return;
  593. PrintStats(Text, "");
  594. if (Options.Verbosity) {
  595. Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize());
  596. MD.PrintMutationSequence(Options.Verbosity >= 2);
  597. Printf("\n");
  598. }
  599. }
  600. void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) {
  601. II->NumSuccessfullMutations++;
  602. MD.RecordSuccessfulMutationSequence();
  603. PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW ");
  604. WriteToOutputCorpus(U);
  605. NumberOfNewUnitsAdded++;
  606. CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus.
  607. LastCorpusUpdateRun = TotalNumberOfRuns;
  608. }
  609. // Tries detecting a memory leak on the particular input that we have just
  610. // executed before calling this function.
  611. void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size,
  612. bool DuringInitialCorpusExecution) {
  613. if (!HasMoreMallocsThanFrees)
  614. return; // mallocs==frees, a leak is unlikely.
  615. if (!Options.DetectLeaks)
  616. return;
  617. if (!DuringInitialCorpusExecution &&
  618. TotalNumberOfRuns >= Options.MaxNumberOfRuns)
  619. return;
  620. if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) ||
  621. !(EF->__lsan_do_recoverable_leak_check))
  622. return; // No lsan.
  623. // Run the target once again, but with lsan disabled so that if there is
  624. // a real leak we do not report it twice.
  625. EF->__lsan_disable();
  626. ExecuteCallback(Data, Size);
  627. EF->__lsan_enable();
  628. if (!HasMoreMallocsThanFrees)
  629. return; // a leak is unlikely.
  630. if (NumberOfLeakDetectionAttempts++ > 1000) {
  631. Options.DetectLeaks = false;
  632. Printf("INFO: libFuzzer disabled leak detection after every mutation.\n"
  633. " Most likely the target function accumulates allocated\n"
  634. " memory in a global state w/o actually leaking it.\n"
  635. " You may try running this binary with -trace_malloc=[12]"
  636. " to get a trace of mallocs and frees.\n"
  637. " If LeakSanitizer is enabled in this process it will still\n"
  638. " run on the process shutdown.\n");
  639. return;
  640. }
  641. // Now perform the actual lsan pass. This is expensive and we must ensure
  642. // we don't call it too often.
  643. if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it.
  644. if (DuringInitialCorpusExecution)
  645. Printf("\nINFO: a leak has been found in the initial corpus.\n\n");
  646. Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n");
  647. CurrentUnitSize = Size;
  648. DumpCurrentUnit("leak-");
  649. PrintFinalStats();
  650. _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on.
  651. }
  652. }
  653. void Fuzzer::MutateAndTestOne() {
  654. MD.StartMutationSequence();
  655. auto &II = Corpus.ChooseUnitToMutate(MD.GetRand());
  656. if (Options.DoCrossOver) {
  657. auto &CrossOverII = Corpus.ChooseUnitToCrossOverWith(
  658. MD.GetRand(), Options.CrossOverUniformDist);
  659. MD.SetCrossOverWith(&CrossOverII.U);
  660. }
  661. const auto &U = II.U;
  662. memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1));
  663. assert(CurrentUnitData);
  664. size_t Size = U.size();
  665. assert(Size <= MaxInputLen && "Oversized Unit");
  666. memcpy(CurrentUnitData, U.data(), Size);
  667. assert(MaxMutationLen > 0);
  668. size_t CurrentMaxMutationLen =
  669. Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen));
  670. assert(CurrentMaxMutationLen > 0);
  671. for (int i = 0; i < Options.MutateDepth; i++) {
  672. if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
  673. break;
  674. MaybeExitGracefully();
  675. size_t NewSize = 0;
  676. if (II.HasFocusFunction && !II.DataFlowTraceForFocusFunction.empty() &&
  677. Size <= CurrentMaxMutationLen)
  678. NewSize = MD.MutateWithMask(CurrentUnitData, Size, Size,
  679. II.DataFlowTraceForFocusFunction);
  680. // If MutateWithMask either failed or wasn't called, call default Mutate.
  681. if (!NewSize)
  682. NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen);
  683. assert(NewSize > 0 && "Mutator returned empty unit");
  684. assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit");
  685. Size = NewSize;
  686. II.NumExecutedMutations++;
  687. Corpus.IncrementNumExecutedMutations();
  688. bool FoundUniqFeatures = false;
  689. bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II,
  690. /*ForceAddToCorpus*/ false, &FoundUniqFeatures);
  691. TryDetectingAMemoryLeak(CurrentUnitData, Size,
  692. /*DuringInitialCorpusExecution*/ false);
  693. if (NewCov) {
  694. ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size});
  695. break; // We will mutate this input more in the next rounds.
  696. }
  697. if (Options.ReduceDepth && !FoundUniqFeatures)
  698. break;
  699. }
  700. II.NeedsEnergyUpdate = true;
  701. }
  702. void Fuzzer::PurgeAllocator() {
  703. if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator)
  704. return;
  705. if (duration_cast<seconds>(system_clock::now() -
  706. LastAllocatorPurgeAttemptTime)
  707. .count() < Options.PurgeAllocatorIntervalSec)
  708. return;
  709. if (Options.RssLimitMb <= 0 ||
  710. GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2)
  711. EF->__sanitizer_purge_allocator();
  712. LastAllocatorPurgeAttemptTime = system_clock::now();
  713. }
  714. void Fuzzer::ReadAndExecuteSeedCorpora(std::vector<SizedFile> &CorporaFiles) {
  715. const size_t kMaxSaneLen = 1 << 20;
  716. const size_t kMinDefaultLen = 4096;
  717. size_t MaxSize = 0;
  718. size_t MinSize = -1;
  719. size_t TotalSize = 0;
  720. for (auto &File : CorporaFiles) {
  721. MaxSize = Max(File.Size, MaxSize);
  722. MinSize = Min(File.Size, MinSize);
  723. TotalSize += File.Size;
  724. }
  725. if (Options.MaxLen == 0)
  726. SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen));
  727. assert(MaxInputLen > 0);
  728. // Test the callback with empty input and never try it again.
  729. uint8_t dummy = 0;
  730. ExecuteCallback(&dummy, 0);
  731. if (CorporaFiles.empty()) {
  732. Printf("INFO: A corpus is not provided, starting from an empty corpus\n");
  733. Unit U({'\n'}); // Valid ASCII input.
  734. RunOne(U.data(), U.size());
  735. } else {
  736. Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb"
  737. " rss: %zdMb\n",
  738. CorporaFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb());
  739. if (Options.ShuffleAtStartUp)
  740. std::shuffle(CorporaFiles.begin(), CorporaFiles.end(), MD.GetRand());
  741. if (Options.PreferSmall) {
  742. std::stable_sort(CorporaFiles.begin(), CorporaFiles.end());
  743. assert(CorporaFiles.front().Size <= CorporaFiles.back().Size);
  744. }
  745. // Load and execute inputs one by one.
  746. for (auto &SF : CorporaFiles) {
  747. auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false);
  748. assert(U.size() <= MaxInputLen);
  749. RunOne(U.data(), U.size(), /*MayDeleteFile*/ false, /*II*/ nullptr,
  750. /*ForceAddToCorpus*/ Options.KeepSeed,
  751. /*FoundUniqFeatures*/ nullptr);
  752. CheckExitOnSrcPosOrItem();
  753. TryDetectingAMemoryLeak(U.data(), U.size(),
  754. /*DuringInitialCorpusExecution*/ true);
  755. }
  756. }
  757. PrintStats("INITED");
  758. if (!Options.FocusFunction.empty()) {
  759. Printf("INFO: %zd/%zd inputs touch the focus function\n",
  760. Corpus.NumInputsThatTouchFocusFunction(), Corpus.size());
  761. if (!Options.DataFlowTrace.empty())
  762. Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n",
  763. Corpus.NumInputsWithDataFlowTrace(),
  764. Corpus.NumInputsThatTouchFocusFunction());
  765. }
  766. if (Corpus.empty() && Options.MaxNumberOfRuns) {
  767. Printf("WARNING: no interesting inputs were found so far. "
  768. "Is the code instrumented for coverage?\n"
  769. "This may also happen if the target rejected all inputs we tried so "
  770. "far\n");
  771. // The remaining logic requires that the corpus is not empty,
  772. // so we add one fake input to the in-memory corpus.
  773. Corpus.AddToCorpus({'\n'}, /*NumFeatures=*/1, /*MayDeleteFile=*/true,
  774. /*HasFocusFunction=*/false, /*NeverReduce=*/false,
  775. /*TimeOfUnit=*/duration_cast<microseconds>(0s), {0}, DFT,
  776. /*BaseII*/ nullptr);
  777. }
  778. }
  779. void Fuzzer::Loop(std::vector<SizedFile> &CorporaFiles) {
  780. auto FocusFunctionOrAuto = Options.FocusFunction;
  781. DFT.Init(Options.DataFlowTrace, &FocusFunctionOrAuto, CorporaFiles,
  782. MD.GetRand());
  783. TPC.SetFocusFunction(FocusFunctionOrAuto);
  784. ReadAndExecuteSeedCorpora(CorporaFiles);
  785. DFT.Clear(); // No need for DFT any more.
  786. TPC.SetPrintNewPCs(Options.PrintNewCovPcs);
  787. TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs);
  788. system_clock::time_point LastCorpusReload = system_clock::now();
  789. TmpMaxMutationLen =
  790. Min(MaxMutationLen, Max(size_t(4), Corpus.MaxInputSize()));
  791. while (true) {
  792. auto Now = system_clock::now();
  793. if (!Options.StopFile.empty() &&
  794. !FileToVector(Options.StopFile, 1, false).empty())
  795. break;
  796. if (duration_cast<seconds>(Now - LastCorpusReload).count() >=
  797. Options.ReloadIntervalSec) {
  798. RereadOutputCorpus(MaxInputLen);
  799. LastCorpusReload = system_clock::now();
  800. }
  801. if (TotalNumberOfRuns >= Options.MaxNumberOfRuns)
  802. break;
  803. if (TimedOut())
  804. break;
  805. // Update TmpMaxMutationLen
  806. if (Options.LenControl) {
  807. if (TmpMaxMutationLen < MaxMutationLen &&
  808. TotalNumberOfRuns - LastCorpusUpdateRun >
  809. Options.LenControl * Log(TmpMaxMutationLen)) {
  810. TmpMaxMutationLen =
  811. Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen));
  812. LastCorpusUpdateRun = TotalNumberOfRuns;
  813. }
  814. } else {
  815. TmpMaxMutationLen = MaxMutationLen;
  816. }
  817. // Perform several mutations and runs.
  818. MutateAndTestOne();
  819. PurgeAllocator();
  820. }
  821. PrintStats("DONE ", "\n");
  822. MD.PrintRecommendedDictionary();
  823. }
  824. void Fuzzer::MinimizeCrashLoop(const Unit &U) {
  825. if (U.size() <= 1)
  826. return;
  827. while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) {
  828. MD.StartMutationSequence();
  829. memcpy(CurrentUnitData, U.data(), U.size());
  830. for (int i = 0; i < Options.MutateDepth; i++) {
  831. size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen);
  832. assert(NewSize > 0 && NewSize <= MaxMutationLen);
  833. ExecuteCallback(CurrentUnitData, NewSize);
  834. PrintPulseAndReportSlowInput(CurrentUnitData, NewSize);
  835. TryDetectingAMemoryLeak(CurrentUnitData, NewSize,
  836. /*DuringInitialCorpusExecution*/ false);
  837. }
  838. }
  839. }
  840. } // namespace fuzzer
  841. extern "C" {
  842. ATTRIBUTE_INTERFACE size_t
  843. LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) {
  844. assert(fuzzer::F);
  845. return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize);
  846. }
  847. } // extern "C"