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