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