FuzzerLoop.cpp 31 KB

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