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