1 //===- FuzzerDriver.cpp - FuzzerDriver function and flags -----------------===// 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 // FuzzerDriver and flag parsing. 9 //===----------------------------------------------------------------------===// 10 11 #include "FuzzerCommand.h" 12 #include "FuzzerCorpus.h" 13 #include "FuzzerFork.h" 14 #include "FuzzerIO.h" 15 #include "FuzzerInterface.h" 16 #include "FuzzerInternal.h" 17 #include "FuzzerMerge.h" 18 #include "FuzzerMutate.h" 19 #include "FuzzerPlatform.h" 20 #include "FuzzerRandom.h" 21 #include "FuzzerTracePC.h" 22 #include "mutagen/MutagenDispatcher.h" 23 #include <algorithm> 24 #include <atomic> 25 #include <chrono> 26 #include <cstdlib> 27 #include <cstring> 28 #include <fstream> 29 #include <mutex> 30 #include <string> 31 #include <thread> 32 33 // This function should be present in the libFuzzer so that the client 34 // binary can test for its existence. 35 #if LIBFUZZER_MSVC 36 extern "C" void __libfuzzer_is_present() {} 37 #if defined(_M_IX86) || defined(__i386__) 38 #pragma comment(linker, "/include:___libfuzzer_is_present") 39 #else 40 #pragma comment(linker, "/include:__libfuzzer_is_present") 41 #endif 42 #else 43 extern "C" __attribute__((used)) void __libfuzzer_is_present() {} 44 #endif // LIBFUZZER_MSVC 45 46 namespace fuzzer { 47 48 // Program arguments. 49 struct FlagDescription { 50 const char *Name; 51 const char *Description; 52 int Default; 53 int *IntFlag; 54 const char **StrFlag; 55 unsigned int *UIntFlag; 56 }; 57 58 struct { 59 #define FUZZER_DEPRECATED_FLAG(Name) 60 #define FUZZER_FLAG_INT(Name, Default, Description) int Name; 61 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) unsigned int Name; 62 #define FUZZER_FLAG_STRING(Name, Description) const char *Name; 63 #include "FuzzerFlags.def" 64 #undef FUZZER_DEPRECATED_FLAG 65 #undef FUZZER_FLAG_INT 66 #undef FUZZER_FLAG_UNSIGNED 67 #undef FUZZER_FLAG_STRING 68 } Flags; 69 70 static const FlagDescription FlagDescriptions [] { 71 #define FUZZER_DEPRECATED_FLAG(Name) \ 72 {#Name, "Deprecated; don't use", 0, nullptr, nullptr, nullptr}, 73 #define FUZZER_FLAG_INT(Name, Default, Description) \ 74 {#Name, Description, Default, &Flags.Name, nullptr, nullptr}, 75 #define FUZZER_FLAG_UNSIGNED(Name, Default, Description) \ 76 {#Name, Description, static_cast<int>(Default), \ 77 nullptr, nullptr, &Flags.Name}, 78 #define FUZZER_FLAG_STRING(Name, Description) \ 79 {#Name, Description, 0, nullptr, &Flags.Name, nullptr}, 80 #include "FuzzerFlags.def" 81 #undef FUZZER_DEPRECATED_FLAG 82 #undef FUZZER_FLAG_INT 83 #undef FUZZER_FLAG_UNSIGNED 84 #undef FUZZER_FLAG_STRING 85 }; 86 87 static const size_t kNumFlags = 88 sizeof(FlagDescriptions) / sizeof(FlagDescriptions[0]); 89 90 static Vector<std::string> *Inputs; 91 static std::string *ProgName; 92 93 static void PrintHelp() { 94 Printf("Usage:\n"); 95 auto Prog = ProgName->c_str(); 96 Printf("\nTo run fuzzing pass 0 or more directories.\n"); 97 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] [dir1 [dir2 ...] ]\n", Prog); 98 99 Printf("\nTo run individual tests without fuzzing pass 1 or more files:\n"); 100 Printf("%s [-flag1=val1 [-flag2=val2 ...] ] file1 [file2 ...]\n", Prog); 101 102 Printf("\nFlags: (strictly in form -flag=value)\n"); 103 size_t MaxFlagLen = 0; 104 for (size_t F = 0; F < kNumFlags; F++) 105 MaxFlagLen = std::max(strlen(FlagDescriptions[F].Name), MaxFlagLen); 106 107 for (size_t F = 0; F < kNumFlags; F++) { 108 const auto &D = FlagDescriptions[F]; 109 if (strstr(D.Description, "internal flag") == D.Description) continue; 110 Printf(" %s", D.Name); 111 for (size_t i = 0, n = MaxFlagLen - strlen(D.Name); i < n; i++) 112 Printf(" "); 113 Printf("\t"); 114 Printf("%d\t%s\n", D.Default, D.Description); 115 } 116 Printf("\nFlags starting with '--' will be ignored and " 117 "will be passed verbatim to subprocesses.\n"); 118 } 119 120 static const char *FlagValue(const char *Param, const char *Name) { 121 size_t Len = strlen(Name); 122 if (Param[0] == '-' && strstr(Param + 1, Name) == Param + 1 && 123 Param[Len + 1] == '=') 124 return &Param[Len + 2]; 125 return nullptr; 126 } 127 128 // Avoid calling stol as it triggers a bug in clang/glibc build. 129 static long MyStol(const char *Str) { 130 long Res = 0; 131 long Sign = 1; 132 if (*Str == '-') { 133 Str++; 134 Sign = -1; 135 } 136 for (size_t i = 0; Str[i]; i++) { 137 char Ch = Str[i]; 138 if (Ch < '0' || Ch > '9') 139 return Res; 140 Res = Res * 10 + (Ch - '0'); 141 } 142 return Res * Sign; 143 } 144 145 static bool ParseOneFlag(const char *Param) { 146 if (Param[0] != '-') return false; 147 if (Param[1] == '-') { 148 static bool PrintedWarning = false; 149 if (!PrintedWarning) { 150 PrintedWarning = true; 151 Printf("INFO: libFuzzer ignores flags that start with '--'\n"); 152 } 153 for (size_t F = 0; F < kNumFlags; F++) 154 if (FlagValue(Param + 1, FlagDescriptions[F].Name)) 155 Printf("WARNING: did you mean '%s' (single dash)?\n", Param + 1); 156 return true; 157 } 158 for (size_t F = 0; F < kNumFlags; F++) { 159 const char *Name = FlagDescriptions[F].Name; 160 const char *Str = FlagValue(Param, Name); 161 if (Str) { 162 if (FlagDescriptions[F].IntFlag) { 163 auto Val = MyStol(Str); 164 *FlagDescriptions[F].IntFlag = static_cast<int>(Val); 165 if (Flags.verbosity >= 2) 166 Printf("Flag: %s %d\n", Name, Val); 167 return true; 168 } else if (FlagDescriptions[F].UIntFlag) { 169 auto Val = std::stoul(Str); 170 *FlagDescriptions[F].UIntFlag = static_cast<unsigned int>(Val); 171 if (Flags.verbosity >= 2) 172 Printf("Flag: %s %u\n", Name, Val); 173 return true; 174 } else if (FlagDescriptions[F].StrFlag) { 175 *FlagDescriptions[F].StrFlag = Str; 176 if (Flags.verbosity >= 2) 177 Printf("Flag: %s %s\n", Name, Str); 178 return true; 179 } else { // Deprecated flag. 180 Printf("Flag: %s: deprecated, don't use\n", Name); 181 return true; 182 } 183 } 184 } 185 Printf("\n\nWARNING: unrecognized flag '%s'; " 186 "use -help=1 to list all flags\n\n", Param); 187 return true; 188 } 189 190 // We don't use any library to minimize dependencies. 191 static void ParseFlags(const Vector<std::string> &Args, 192 const ExternalFunctions *EF) { 193 for (size_t F = 0; F < kNumFlags; F++) { 194 if (FlagDescriptions[F].IntFlag) 195 *FlagDescriptions[F].IntFlag = FlagDescriptions[F].Default; 196 if (FlagDescriptions[F].UIntFlag) 197 *FlagDescriptions[F].UIntFlag = 198 static_cast<unsigned int>(FlagDescriptions[F].Default); 199 if (FlagDescriptions[F].StrFlag) 200 *FlagDescriptions[F].StrFlag = nullptr; 201 } 202 203 // Disable len_control by default, if LLVMFuzzerCustomMutator is used. 204 if (EF->LLVMFuzzerCustomMutator) { 205 Flags.len_control = 0; 206 Printf("INFO: found LLVMFuzzerCustomMutator (%p). " 207 "Disabling -len_control by default.\n", EF->LLVMFuzzerCustomMutator); 208 } 209 210 Inputs = new Vector<std::string>; 211 for (size_t A = 1; A < Args.size(); A++) { 212 if (ParseOneFlag(Args[A].c_str())) { 213 if (Flags.ignore_remaining_args) 214 break; 215 continue; 216 } 217 Inputs->push_back(Args[A]); 218 } 219 } 220 221 static std::mutex Mu; 222 223 static void PulseThread() { 224 while (true) { 225 SleepSeconds(600); 226 std::lock_guard<std::mutex> Lock(Mu); 227 Printf("pulse...\n"); 228 } 229 } 230 231 static void WorkerThread(const Command &BaseCmd, std::atomic<unsigned> *Counter, 232 unsigned NumJobs, std::atomic<bool> *HasErrors) { 233 while (true) { 234 unsigned C = (*Counter)++; 235 if (C >= NumJobs) break; 236 std::string Log = "fuzz-" + std::to_string(C) + ".log"; 237 Command Cmd(BaseCmd); 238 Cmd.setOutputFile(Log); 239 Cmd.combineOutAndErr(); 240 if (Flags.verbosity) { 241 std::string CommandLine = Cmd.toString(); 242 Printf("%s\n", CommandLine.c_str()); 243 } 244 int ExitCode = ExecuteCommand(Cmd); 245 if (ExitCode != 0) 246 *HasErrors = true; 247 std::lock_guard<std::mutex> Lock(Mu); 248 Printf("================== Job %u exited with exit code %d ============\n", 249 C, ExitCode); 250 fuzzer::CopyFileToErr(Log); 251 } 252 } 253 254 static void ValidateDirectoryExists(const std::string &Path, 255 bool CreateDirectory) { 256 if (Path.empty()) { 257 Printf("ERROR: Provided directory path is an empty string\n"); 258 exit(1); 259 } 260 261 if (IsDirectory(Path)) 262 return; 263 264 if (CreateDirectory) { 265 if (!MkDirRecursive(Path)) { 266 Printf("ERROR: Failed to create directory \"%s\"\n", Path.c_str()); 267 exit(1); 268 } 269 return; 270 } 271 272 Printf("ERROR: The required directory \"%s\" does not exist\n", Path.c_str()); 273 exit(1); 274 } 275 276 std::string CloneArgsWithoutX(const Vector<std::string> &Args, 277 const char *X1, const char *X2) { 278 std::string Cmd; 279 for (auto &S : Args) { 280 if (FlagValue(S.c_str(), X1) || FlagValue(S.c_str(), X2)) 281 continue; 282 Cmd += S + " "; 283 } 284 return Cmd; 285 } 286 287 static int RunInMultipleProcesses(const Vector<std::string> &Args, 288 unsigned NumWorkers, unsigned NumJobs) { 289 std::atomic<unsigned> Counter(0); 290 std::atomic<bool> HasErrors(false); 291 Command Cmd(Args); 292 Cmd.removeFlag("jobs"); 293 Cmd.removeFlag("workers"); 294 Vector<std::thread> V; 295 std::thread Pulse(PulseThread); 296 Pulse.detach(); 297 for (unsigned i = 0; i < NumWorkers; i++) 298 V.push_back(std::thread(WorkerThread, std::ref(Cmd), &Counter, NumJobs, &HasErrors)); 299 for (auto &T : V) 300 T.join(); 301 return HasErrors ? 1 : 0; 302 } 303 304 static void RssThread(Fuzzer *F, size_t RssLimitMb) { 305 while (true) { 306 SleepSeconds(1); 307 size_t Peak = GetPeakRSSMb(); 308 if (Peak > RssLimitMb) 309 F->RssLimitCallback(); 310 } 311 } 312 313 static void StartRssThread(Fuzzer *F, size_t RssLimitMb) { 314 if (!RssLimitMb) 315 return; 316 std::thread T(RssThread, F, RssLimitMb); 317 T.detach(); 318 } 319 320 int RunOneTest(Fuzzer *F, const char *InputFilePath, size_t MaxLen) { 321 Unit U = FileToVector(InputFilePath); 322 if (MaxLen && MaxLen < U.size()) 323 U.resize(MaxLen); 324 F->ExecuteCallback(U.data(), U.size()); 325 if (Flags.print_full_coverage) { 326 // Leak detection is not needed when collecting full coverage data. 327 F->TPCUpdateObservedPCs(); 328 } else { 329 F->TryDetectingAMemoryLeak(U.data(), U.size(), true); 330 } 331 return 0; 332 } 333 334 static bool AllInputsAreFiles() { 335 if (Inputs->empty()) return false; 336 for (auto &Path : *Inputs) 337 if (!IsFile(Path)) 338 return false; 339 return true; 340 } 341 342 static std::string GetDedupTokenFromCmdOutput(const std::string &S) { 343 auto Beg = S.find("DEDUP_TOKEN:"); 344 if (Beg == std::string::npos) 345 return ""; 346 auto End = S.find('\n', Beg); 347 if (End == std::string::npos) 348 return ""; 349 return S.substr(Beg, End - Beg); 350 } 351 352 int CleanseCrashInput(const Vector<std::string> &Args, 353 const FuzzingOptions &Options) { 354 if (Inputs->size() != 1 || !Flags.exact_artifact_path) { 355 Printf("ERROR: -cleanse_crash should be given one input file and" 356 " -exact_artifact_path\n"); 357 exit(1); 358 } 359 std::string InputFilePath = Inputs->at(0); 360 std::string OutputFilePath = Flags.exact_artifact_path; 361 Command Cmd(Args); 362 Cmd.removeFlag("cleanse_crash"); 363 364 assert(Cmd.hasArgument(InputFilePath)); 365 Cmd.removeArgument(InputFilePath); 366 367 auto TmpFilePath = TempPath("CleanseCrashInput", ".repro"); 368 Cmd.addArgument(TmpFilePath); 369 Cmd.setOutputFile(getDevNull()); 370 Cmd.combineOutAndErr(); 371 372 std::string CurrentFilePath = InputFilePath; 373 auto U = FileToVector(CurrentFilePath); 374 size_t Size = U.size(); 375 376 const Vector<uint8_t> ReplacementBytes = {' ', 0xff}; 377 for (int NumAttempts = 0; NumAttempts < 5; NumAttempts++) { 378 bool Changed = false; 379 for (size_t Idx = 0; Idx < Size; Idx++) { 380 Printf("CLEANSE[%d]: Trying to replace byte %zd of %zd\n", NumAttempts, 381 Idx, Size); 382 uint8_t OriginalByte = U[Idx]; 383 if (ReplacementBytes.end() != std::find(ReplacementBytes.begin(), 384 ReplacementBytes.end(), 385 OriginalByte)) 386 continue; 387 for (auto NewByte : ReplacementBytes) { 388 U[Idx] = NewByte; 389 WriteToFile(U, TmpFilePath); 390 auto ExitCode = ExecuteCommand(Cmd); 391 RemoveFile(TmpFilePath); 392 if (!ExitCode) { 393 U[Idx] = OriginalByte; 394 } else { 395 Changed = true; 396 Printf("CLEANSE: Replaced byte %zd with 0x%x\n", Idx, NewByte); 397 WriteToFile(U, OutputFilePath); 398 break; 399 } 400 } 401 } 402 if (!Changed) break; 403 } 404 return 0; 405 } 406 407 int MinimizeCrashInput(const Vector<std::string> &Args, 408 const FuzzingOptions &Options) { 409 if (Inputs->size() != 1) { 410 Printf("ERROR: -minimize_crash should be given one input file\n"); 411 exit(1); 412 } 413 std::string InputFilePath = Inputs->at(0); 414 Command BaseCmd(Args); 415 BaseCmd.removeFlag("minimize_crash"); 416 BaseCmd.removeFlag("exact_artifact_path"); 417 assert(BaseCmd.hasArgument(InputFilePath)); 418 BaseCmd.removeArgument(InputFilePath); 419 if (Flags.runs <= 0 && Flags.max_total_time == 0) { 420 Printf("INFO: you need to specify -runs=N or " 421 "-max_total_time=N with -minimize_crash=1\n" 422 "INFO: defaulting to -max_total_time=600\n"); 423 BaseCmd.addFlag("max_total_time", "600"); 424 } 425 426 BaseCmd.combineOutAndErr(); 427 428 std::string CurrentFilePath = InputFilePath; 429 while (true) { 430 Unit U = FileToVector(CurrentFilePath); 431 Printf("CRASH_MIN: minimizing crash input: '%s' (%zd bytes)\n", 432 CurrentFilePath.c_str(), U.size()); 433 434 Command Cmd(BaseCmd); 435 Cmd.addArgument(CurrentFilePath); 436 437 Printf("CRASH_MIN: executing: %s\n", Cmd.toString().c_str()); 438 std::string CmdOutput; 439 bool Success = ExecuteCommand(Cmd, &CmdOutput); 440 if (Success) { 441 Printf("ERROR: the input %s did not crash\n", CurrentFilePath.c_str()); 442 exit(1); 443 } 444 Printf("CRASH_MIN: '%s' (%zd bytes) caused a crash. Will try to minimize " 445 "it further\n", 446 CurrentFilePath.c_str(), U.size()); 447 auto DedupToken1 = GetDedupTokenFromCmdOutput(CmdOutput); 448 if (!DedupToken1.empty()) 449 Printf("CRASH_MIN: DedupToken1: %s\n", DedupToken1.c_str()); 450 451 std::string ArtifactPath = 452 Flags.exact_artifact_path 453 ? Flags.exact_artifact_path 454 : Options.ArtifactPrefix + "minimized-from-" + Hash(U); 455 Cmd.addFlag("minimize_crash_internal_step", "1"); 456 Cmd.addFlag("exact_artifact_path", ArtifactPath); 457 Printf("CRASH_MIN: executing: %s\n", Cmd.toString().c_str()); 458 CmdOutput.clear(); 459 Success = ExecuteCommand(Cmd, &CmdOutput); 460 Printf("%s", CmdOutput.c_str()); 461 if (Success) { 462 if (Flags.exact_artifact_path) { 463 CurrentFilePath = Flags.exact_artifact_path; 464 WriteToFile(U, CurrentFilePath); 465 } 466 Printf("CRASH_MIN: failed to minimize beyond %s (%d bytes), exiting\n", 467 CurrentFilePath.c_str(), U.size()); 468 break; 469 } 470 auto DedupToken2 = GetDedupTokenFromCmdOutput(CmdOutput); 471 if (!DedupToken2.empty()) 472 Printf("CRASH_MIN: DedupToken2: %s\n", DedupToken2.c_str()); 473 474 if (DedupToken1 != DedupToken2) { 475 if (Flags.exact_artifact_path) { 476 CurrentFilePath = Flags.exact_artifact_path; 477 WriteToFile(U, CurrentFilePath); 478 } 479 Printf("CRASH_MIN: mismatch in dedup tokens" 480 " (looks like a different bug). Won't minimize further\n"); 481 break; 482 } 483 484 CurrentFilePath = ArtifactPath; 485 Printf("*********************************\n"); 486 } 487 return 0; 488 } 489 490 int MinimizeCrashInputInternalStep(Fuzzer *F, InputCorpus *Corpus) { 491 assert(Inputs->size() == 1); 492 std::string InputFilePath = Inputs->at(0); 493 Unit U = FileToVector(InputFilePath); 494 Printf("INFO: Starting MinimizeCrashInputInternalStep: %zd\n", U.size()); 495 if (U.size() < 2) { 496 Printf("INFO: The input is small enough, exiting\n"); 497 exit(0); 498 } 499 F->SetMaxInputLen(U.size()); 500 F->SetMaxMutationLen(U.size() - 1); 501 F->MinimizeCrashLoop(U); 502 Printf("INFO: Done MinimizeCrashInputInternalStep, no crashes found\n"); 503 exit(0); 504 return 0; 505 } 506 507 void Merge(Fuzzer *F, FuzzingOptions &Options, const Vector<std::string> &Args, 508 const Vector<std::string> &Corpora, const char *CFPathOrNull) { 509 if (Corpora.size() < 2) { 510 Printf("INFO: Merge requires two or more corpus dirs\n"); 511 exit(0); 512 } 513 514 Vector<SizedFile> OldCorpus, NewCorpus; 515 GetSizedFilesFromDir(Corpora[0], &OldCorpus); 516 for (size_t i = 1; i < Corpora.size(); i++) 517 GetSizedFilesFromDir(Corpora[i], &NewCorpus); 518 std::sort(OldCorpus.begin(), OldCorpus.end()); 519 std::sort(NewCorpus.begin(), NewCorpus.end()); 520 521 std::string CFPath = CFPathOrNull ? CFPathOrNull : TempPath("Merge", ".txt"); 522 Vector<std::string> NewFiles; 523 Set<uint32_t> NewFeatures, NewCov; 524 CrashResistantMerge(Args, OldCorpus, NewCorpus, &NewFiles, {}, &NewFeatures, 525 {}, &NewCov, CFPath, true); 526 for (auto &Path : NewFiles) 527 F->WriteToOutputCorpus(FileToVector(Path, Options.MaxLen)); 528 // We are done, delete the control file if it was a temporary one. 529 if (!Flags.merge_control_file) 530 RemoveFile(CFPath); 531 532 exit(0); 533 } 534 535 int AnalyzeDictionary(Fuzzer *F, const Vector<Unit>& Dict, 536 UnitVector& Corpus) { 537 Printf("Started dictionary minimization (up to %d tests)\n", 538 Dict.size() * Corpus.size() * 2); 539 540 // Scores and usage count for each dictionary unit. 541 Vector<int> Scores(Dict.size()); 542 Vector<int> Usages(Dict.size()); 543 544 Vector<size_t> InitialFeatures; 545 Vector<size_t> ModifiedFeatures; 546 for (auto &C : Corpus) { 547 // Get coverage for the testcase without modifications. 548 F->ExecuteCallback(C.data(), C.size()); 549 InitialFeatures.clear(); 550 TPC.CollectFeatures([&](size_t Feature) { 551 InitialFeatures.push_back(Feature); 552 }); 553 554 for (size_t i = 0; i < Dict.size(); ++i) { 555 Vector<uint8_t> Data = C; 556 auto StartPos = std::search(Data.begin(), Data.end(), 557 Dict[i].begin(), Dict[i].end()); 558 // Skip dictionary unit, if the testcase does not contain it. 559 if (StartPos == Data.end()) 560 continue; 561 562 ++Usages[i]; 563 while (StartPos != Data.end()) { 564 // Replace all occurrences of dictionary unit in the testcase. 565 auto EndPos = StartPos + Dict[i].size(); 566 for (auto It = StartPos; It != EndPos; ++It) 567 *It ^= 0xFF; 568 569 StartPos = std::search(EndPos, Data.end(), 570 Dict[i].begin(), Dict[i].end()); 571 } 572 573 // Get coverage for testcase with masked occurrences of dictionary unit. 574 F->ExecuteCallback(Data.data(), Data.size()); 575 ModifiedFeatures.clear(); 576 TPC.CollectFeatures([&](size_t Feature) { 577 ModifiedFeatures.push_back(Feature); 578 }); 579 580 if (InitialFeatures == ModifiedFeatures) 581 --Scores[i]; 582 else 583 Scores[i] += 2; 584 } 585 } 586 587 Printf("###### Useless dictionary elements. ######\n"); 588 for (size_t i = 0; i < Dict.size(); ++i) { 589 // Dictionary units with positive score are treated as useful ones. 590 if (Scores[i] > 0) 591 continue; 592 593 Printf("\""); 594 PrintASCII(Dict[i].data(), Dict[i].size(), "\""); 595 Printf(" # Score: %d, Used: %d\n", Scores[i], Usages[i]); 596 } 597 Printf("###### End of useless dictionary elements. ######\n"); 598 return 0; 599 } 600 601 Vector<std::string> ParseSeedInuts(const char *seed_inputs) { 602 // Parse -seed_inputs=file1,file2,... or -seed_inputs=@seed_inputs_file 603 Vector<std::string> Files; 604 if (!seed_inputs) return Files; 605 std::string SeedInputs; 606 if (Flags.seed_inputs[0] == '@') 607 SeedInputs = FileToString(Flags.seed_inputs + 1); // File contains list. 608 else 609 SeedInputs = Flags.seed_inputs; // seed_inputs contains the list. 610 if (SeedInputs.empty()) { 611 Printf("seed_inputs is empty or @file does not exist.\n"); 612 exit(1); 613 } 614 // Parse SeedInputs. 615 size_t comma_pos = 0; 616 while ((comma_pos = SeedInputs.find_last_of(',')) != std::string::npos) { 617 Files.push_back(SeedInputs.substr(comma_pos + 1)); 618 SeedInputs = SeedInputs.substr(0, comma_pos); 619 } 620 Files.push_back(SeedInputs); 621 return Files; 622 } 623 624 static Vector<SizedFile> ReadCorpora(const Vector<std::string> &CorpusDirs, 625 const Vector<std::string> &ExtraSeedFiles) { 626 Vector<SizedFile> SizedFiles; 627 size_t LastNumFiles = 0; 628 for (auto &Dir : CorpusDirs) { 629 GetSizedFilesFromDir(Dir, &SizedFiles); 630 Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles, 631 Dir.c_str()); 632 LastNumFiles = SizedFiles.size(); 633 } 634 for (auto &File : ExtraSeedFiles) 635 if (auto Size = FileSize(File)) 636 SizedFiles.push_back({File, Size}); 637 return SizedFiles; 638 } 639 640 int FuzzerDriver(int *argc, char ***argv, UserCallback Callback) { 641 using namespace fuzzer; 642 assert(argc && argv && "Argument pointers cannot be nullptr"); 643 std::string Argv0((*argv)[0]); 644 EF = new ExternalFunctions(); 645 if (EF->LLVMFuzzerInitialize) 646 EF->LLVMFuzzerInitialize(argc, argv); 647 if (EF->__msan_scoped_disable_interceptor_checks) 648 EF->__msan_scoped_disable_interceptor_checks(); 649 const Vector<std::string> Args(*argv, *argv + *argc); 650 assert(!Args.empty()); 651 ProgName = new std::string(Args[0]); 652 if (Argv0 != *ProgName) { 653 Printf("ERROR: argv[0] has been modified in LLVMFuzzerInitialize\n"); 654 exit(1); 655 } 656 ParseFlags(Args, EF); 657 if (Flags.help) { 658 PrintHelp(); 659 return 0; 660 } 661 662 if (Flags.close_fd_mask & 2) 663 DupAndCloseStderr(); 664 if (Flags.close_fd_mask & 1) 665 CloseStdout(); 666 667 if (Flags.jobs > 0 && Flags.workers == 0) { 668 Flags.workers = std::min(NumberOfCpuCores() / 2, Flags.jobs); 669 if (Flags.workers > 1) 670 Printf("Running %u workers\n", Flags.workers); 671 } 672 673 if (Flags.workers > 0 && Flags.jobs > 0) 674 return RunInMultipleProcesses(Args, Flags.workers, Flags.jobs); 675 676 FuzzingOptions Options; 677 Options.Verbosity = Flags.verbosity; 678 Options.MaxLen = Flags.max_len; 679 Options.LenControl = Flags.len_control; 680 Options.KeepSeed = Flags.keep_seed; 681 Options.UnitTimeoutSec = Flags.timeout; 682 Options.ErrorExitCode = Flags.error_exitcode; 683 Options.TimeoutExitCode = Flags.timeout_exitcode; 684 Options.IgnoreTimeouts = Flags.ignore_timeouts; 685 Options.IgnoreOOMs = Flags.ignore_ooms; 686 Options.IgnoreCrashes = Flags.ignore_crashes; 687 Options.MaxTotalTimeSec = Flags.max_total_time; 688 Options.DoCrossOver = Flags.cross_over; 689 Options.CrossOverUniformDist = Flags.cross_over_uniform_dist; 690 Options.MutateDepth = Flags.mutate_depth; 691 Options.ReduceDepth = Flags.reduce_depth; 692 Options.UseCounters = Flags.use_counters; 693 Options.UseMemmem = Flags.use_memmem; 694 Options.UseCmp = Flags.use_cmp; 695 Options.UseValueProfile = Flags.use_value_profile; 696 Options.Shrink = Flags.shrink; 697 Options.ReduceInputs = Flags.reduce_inputs; 698 Options.ShuffleAtStartUp = Flags.shuffle; 699 Options.PreferSmall = Flags.prefer_small; 700 Options.ReloadIntervalSec = Flags.reload; 701 Options.OnlyASCII = Flags.only_ascii; 702 Options.DetectLeaks = Flags.detect_leaks; 703 Options.PurgeAllocatorIntervalSec = Flags.purge_allocator_interval; 704 Options.TraceMalloc = Flags.trace_malloc; 705 Options.RssLimitMb = Flags.rss_limit_mb; 706 Options.MallocLimitMb = Flags.malloc_limit_mb; 707 if (!Options.MallocLimitMb) 708 Options.MallocLimitMb = Options.RssLimitMb; 709 if (Flags.runs >= 0) 710 Options.MaxNumberOfRuns = Flags.runs; 711 if (!Inputs->empty() && !Flags.minimize_crash_internal_step) { 712 // Ensure output corpus assumed to be the first arbitrary argument input 713 // is not a path to an existing file. 714 std::string OutputCorpusDir = (*Inputs)[0]; 715 if (!IsFile(OutputCorpusDir)) { 716 Options.OutputCorpus = OutputCorpusDir; 717 ValidateDirectoryExists(Options.OutputCorpus, Flags.create_missing_dirs); 718 } 719 } 720 Options.ReportSlowUnits = Flags.report_slow_units; 721 if (Flags.artifact_prefix) { 722 Options.ArtifactPrefix = Flags.artifact_prefix; 723 724 // Since the prefix could be a full path to a file name prefix, assume 725 // that if the path ends with the platform's separator that a directory 726 // is desired 727 std::string ArtifactPathDir = Options.ArtifactPrefix; 728 if (!IsSeparator(ArtifactPathDir[ArtifactPathDir.length() - 1])) { 729 ArtifactPathDir = DirName(ArtifactPathDir); 730 } 731 ValidateDirectoryExists(ArtifactPathDir, Flags.create_missing_dirs); 732 } 733 if (Flags.exact_artifact_path) { 734 Options.ExactArtifactPath = Flags.exact_artifact_path; 735 ValidateDirectoryExists(DirName(Options.ExactArtifactPath), 736 Flags.create_missing_dirs); 737 } 738 Vector<Unit> Dictionary; 739 if (Flags.dict) 740 if (!ParseDictionaryFile(FileToString(Flags.dict), &Dictionary)) 741 return 1; 742 if (Flags.verbosity > 0 && !Dictionary.empty()) 743 Printf("Dictionary: %zd entries\n", Dictionary.size()); 744 bool RunIndividualFiles = AllInputsAreFiles(); 745 Options.SaveArtifacts = 746 !RunIndividualFiles || Flags.minimize_crash_internal_step; 747 Options.PrintNewCovPcs = Flags.print_pcs; 748 Options.PrintNewCovFuncs = Flags.print_funcs; 749 Options.PrintFinalStats = Flags.print_final_stats; 750 Options.PrintCorpusStats = Flags.print_corpus_stats; 751 Options.PrintCoverage = Flags.print_coverage; 752 Options.PrintFullCoverage = Flags.print_full_coverage; 753 if (Flags.exit_on_src_pos) 754 Options.ExitOnSrcPos = Flags.exit_on_src_pos; 755 if (Flags.exit_on_item) 756 Options.ExitOnItem = Flags.exit_on_item; 757 if (Flags.focus_function) 758 Options.FocusFunction = Flags.focus_function; 759 if (Flags.data_flow_trace) 760 Options.DataFlowTrace = Flags.data_flow_trace; 761 if (Flags.features_dir) { 762 Options.FeaturesDir = Flags.features_dir; 763 ValidateDirectoryExists(Options.FeaturesDir, Flags.create_missing_dirs); 764 } 765 if (Flags.mutation_graph_file) 766 Options.MutationGraphFile = Flags.mutation_graph_file; 767 if (Flags.collect_data_flow) 768 Options.CollectDataFlow = Flags.collect_data_flow; 769 if (Flags.stop_file) 770 Options.StopFile = Flags.stop_file; 771 Options.Entropic = Flags.entropic; 772 Options.EntropicFeatureFrequencyThreshold = 773 (size_t)Flags.entropic_feature_frequency_threshold; 774 Options.EntropicNumberOfRarestFeatures = 775 (size_t)Flags.entropic_number_of_rarest_features; 776 Options.EntropicScalePerExecTime = Flags.entropic_scale_per_exec_time; 777 if (!Options.FocusFunction.empty()) 778 Options.Entropic = false; // FocusFunction overrides entropic scheduling. 779 if (Options.Entropic) 780 Printf("INFO: Running with entropic power schedule (0x%X, %d).\n", 781 Options.EntropicFeatureFrequencyThreshold, 782 Options.EntropicNumberOfRarestFeatures); 783 struct EntropicOptions Entropic; 784 Entropic.Enabled = Options.Entropic; 785 Entropic.FeatureFrequencyThreshold = 786 Options.EntropicFeatureFrequencyThreshold; 787 Entropic.NumberOfRarestFeatures = Options.EntropicNumberOfRarestFeatures; 788 Entropic.ScalePerExecTime = Options.EntropicScalePerExecTime; 789 790 unsigned Seed = Flags.seed; 791 // Initialize Seed. 792 if (Seed == 0) 793 Seed = static_cast<unsigned>( 794 std::chrono::system_clock::now().time_since_epoch().count() + GetPid()); 795 if (Flags.verbosity) 796 Printf("INFO: Seed: %u\n", Seed); 797 798 if (Flags.collect_data_flow && !Flags.fork && !Flags.merge) { 799 if (RunIndividualFiles) 800 return CollectDataFlow(Flags.collect_data_flow, Flags.data_flow_trace, 801 ReadCorpora({}, *Inputs)); 802 else 803 return CollectDataFlow(Flags.collect_data_flow, Flags.data_flow_trace, 804 ReadCorpora(*Inputs, {})); 805 } 806 807 LLVMMutagenConfiguration Config; 808 ConfigureMutagen(Seed, Options, &Config); 809 auto *MD = new MutationDispatcher(&Config); 810 auto *Corpus = new InputCorpus(Options.OutputCorpus, Entropic); 811 auto *F = new Fuzzer(Callback, *Corpus, *MD, Options); 812 813 for (auto &U: Dictionary) 814 if (U.size() <= Word::GetMaxSize()) 815 MD->AddWordToManualDictionary(Word(U.data(), U.size())); 816 817 // Threads are only supported by Chrome. Don't use them with emscripten 818 // for now. 819 #if !LIBFUZZER_EMSCRIPTEN 820 StartRssThread(F, Flags.rss_limit_mb); 821 #endif // LIBFUZZER_EMSCRIPTEN 822 823 Options.HandleAbrt = Flags.handle_abrt; 824 Options.HandleAlrm = !Flags.minimize_crash; 825 Options.HandleBus = Flags.handle_bus; 826 Options.HandleFpe = Flags.handle_fpe; 827 Options.HandleIll = Flags.handle_ill; 828 Options.HandleInt = Flags.handle_int; 829 Options.HandleSegv = Flags.handle_segv; 830 Options.HandleTerm = Flags.handle_term; 831 Options.HandleXfsz = Flags.handle_xfsz; 832 Options.HandleUsr1 = Flags.handle_usr1; 833 Options.HandleUsr2 = Flags.handle_usr2; 834 Options.HandleWinExcept = Flags.handle_winexcept; 835 836 SetSignalHandler(Options); 837 838 std::atexit(Fuzzer::StaticExitCallback); 839 840 if (Flags.minimize_crash) 841 return MinimizeCrashInput(Args, Options); 842 843 if (Flags.minimize_crash_internal_step) 844 return MinimizeCrashInputInternalStep(F, Corpus); 845 846 if (Flags.cleanse_crash) 847 return CleanseCrashInput(Args, Options); 848 849 if (RunIndividualFiles) { 850 Options.SaveArtifacts = false; 851 int Runs = std::max(1, Flags.runs); 852 Printf("%s: Running %zd inputs %d time(s) each.\n", ProgName->c_str(), 853 Inputs->size(), Runs); 854 for (auto &Path : *Inputs) { 855 auto StartTime = system_clock::now(); 856 Printf("Running: %s\n", Path.c_str()); 857 for (int Iter = 0; Iter < Runs; Iter++) 858 RunOneTest(F, Path.c_str(), Options.MaxLen); 859 auto StopTime = system_clock::now(); 860 auto MS = duration_cast<milliseconds>(StopTime - StartTime).count(); 861 Printf("Executed %s in %zd ms\n", Path.c_str(), (long)MS); 862 } 863 Printf("***\n" 864 "*** NOTE: fuzzing was not performed, you have only\n" 865 "*** executed the target code on a fixed set of inputs.\n" 866 "***\n"); 867 F->PrintFinalStats(); 868 exit(0); 869 } 870 871 if (Flags.fork) 872 FuzzWithFork(F->GetMD().GetRand(), Options, Args, *Inputs, Flags.fork); 873 874 if (Flags.merge) 875 Merge(F, Options, Args, *Inputs, Flags.merge_control_file); 876 877 if (Flags.merge_inner) { 878 const size_t kDefaultMaxMergeLen = 1 << 20; 879 if (Options.MaxLen == 0) 880 F->SetMaxInputLen(kDefaultMaxMergeLen); 881 assert(Flags.merge_control_file); 882 F->CrashResistantMergeInternalStep(Flags.merge_control_file); 883 exit(0); 884 } 885 886 if (Flags.analyze_dict) { 887 size_t MaxLen = INT_MAX; // Large max length. 888 UnitVector InitialCorpus; 889 for (auto &Inp : *Inputs) { 890 Printf("Loading corpus dir: %s\n", Inp.c_str()); 891 ReadDirToVectorOfUnits(Inp.c_str(), &InitialCorpus, nullptr, 892 MaxLen, /*ExitOnError=*/false); 893 } 894 895 if (Dictionary.empty() || Inputs->empty()) { 896 Printf("ERROR: can't analyze dict without dict and corpus provided\n"); 897 return 1; 898 } 899 if (AnalyzeDictionary(F, Dictionary, InitialCorpus)) { 900 Printf("Dictionary analysis failed\n"); 901 exit(1); 902 } 903 Printf("Dictionary analysis succeeded\n"); 904 exit(0); 905 } 906 907 auto CorporaFiles = ReadCorpora(*Inputs, ParseSeedInuts(Flags.seed_inputs)); 908 F->Loop(CorporaFiles); 909 910 if (Flags.verbosity) 911 Printf("Done %zd runs in %zd second(s)\n", F->getTotalNumberOfRuns(), 912 F->secondsSinceProcessStartUp()); 913 F->PrintFinalStats(); 914 915 exit(0); // Don't let F destroy itself. 916 } 917 918 extern "C" ATTRIBUTE_INTERFACE int 919 LLVMFuzzerRunDriver(int *argc, char ***argv, 920 int (*UserCb)(const uint8_t *Data, size_t Size)) { 921 return FuzzerDriver(argc, argv, UserCb); 922 } 923 924 // Storage for global ExternalFunctions object. 925 ExternalFunctions *EF = nullptr; 926 927 } // namespace fuzzer 928