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