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. |
| 278 | #if !LIBFUZZER_WINDOWS |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 279 | if (!InFuzzingThread()) |
| 280 | return; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 281 | #endif |
morehouse | c6ee875 | 2018-07-17 16:12:00 +0000 | [diff] [blame] | 282 | if (!RunningUserCallback) |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 283 | return; // We have not started running units yet. |
| 284 | size_t Seconds = |
| 285 | duration_cast<seconds>(system_clock::now() - UnitStartTime).count(); |
| 286 | if (Seconds == 0) |
| 287 | return; |
| 288 | if (Options.Verbosity >= 2) |
| 289 | Printf("AlarmCallback %zd\n", Seconds); |
| 290 | if (Seconds >= (size_t)Options.UnitTimeoutSec) { |
morehouse | 5a4566a | 2018-05-01 21:01:53 +0000 | [diff] [blame] | 291 | if (EF->__sanitizer_acquire_crash_state && |
| 292 | !EF->__sanitizer_acquire_crash_state()) |
| 293 | return; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 294 | Printf("ALARM: working on the last Unit for %zd seconds\n", Seconds); |
| 295 | Printf(" and the timeout value is %d (use -timeout=N to change)\n", |
| 296 | Options.UnitTimeoutSec); |
| 297 | DumpCurrentUnit("timeout-"); |
| 298 | Printf("==%lu== ERROR: libFuzzer: timeout after %d seconds\n", GetPid(), |
| 299 | Seconds); |
morehouse | bd67cc2 | 2018-05-08 23:45:05 +0000 | [diff] [blame] | 300 | PrintStackTrace(); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 301 | Printf("SUMMARY: libFuzzer: timeout\n"); |
| 302 | PrintFinalStats(); |
| 303 | _Exit(Options.TimeoutExitCode); // Stop right now. |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | void Fuzzer::RssLimitCallback() { |
morehouse | 5a4566a | 2018-05-01 21:01:53 +0000 | [diff] [blame] | 308 | if (EF->__sanitizer_acquire_crash_state && |
| 309 | !EF->__sanitizer_acquire_crash_state()) |
| 310 | return; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 311 | Printf( |
| 312 | "==%lu== ERROR: libFuzzer: out-of-memory (used: %zdMb; limit: %zdMb)\n", |
| 313 | GetPid(), GetPeakRSSMb(), Options.RssLimitMb); |
| 314 | Printf(" To change the out-of-memory limit use -rss_limit_mb=<N>\n\n"); |
morehouse | bd67cc2 | 2018-05-08 23:45:05 +0000 | [diff] [blame] | 315 | PrintMemoryProfile(); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 316 | DumpCurrentUnit("oom-"); |
| 317 | Printf("SUMMARY: libFuzzer: out-of-memory\n"); |
| 318 | PrintFinalStats(); |
| 319 | _Exit(Options.ErrorExitCode); // Stop right now. |
| 320 | } |
| 321 | |
| 322 | void Fuzzer::PrintStats(const char *Where, const char *End, size_t Units) { |
| 323 | size_t ExecPerSec = execPerSec(); |
| 324 | if (!Options.Verbosity) |
| 325 | return; |
| 326 | Printf("#%zd\t%s", TotalNumberOfRuns, Where); |
| 327 | if (size_t N = TPC.GetTotalPCCoverage()) |
| 328 | Printf(" cov: %zd", N); |
| 329 | if (size_t N = Corpus.NumFeatures()) |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 330 | Printf(" ft: %zd", N); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 331 | if (!Corpus.empty()) { |
| 332 | Printf(" corp: %zd", Corpus.NumActiveUnits()); |
| 333 | if (size_t N = Corpus.SizeInBytes()) { |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 334 | if (N < (1 << 14)) |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 335 | Printf("/%zdb", N); |
| 336 | else if (N < (1 << 24)) |
| 337 | Printf("/%zdKb", N >> 10); |
| 338 | else |
| 339 | Printf("/%zdMb", N >> 20); |
| 340 | } |
kcc | 3acbe07 | 2018-05-16 23:26:37 +0000 | [diff] [blame] | 341 | if (size_t FF = Corpus.NumInputsThatTouchFocusFunction()) |
| 342 | Printf(" focus: %zd", FF); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 343 | } |
morehouse | a6c692c | 2018-02-22 19:00:17 +0000 | [diff] [blame] | 344 | if (TmpMaxMutationLen) |
| 345 | Printf(" lim: %zd", TmpMaxMutationLen); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 346 | if (Units) |
| 347 | Printf(" units: %zd", Units); |
| 348 | |
| 349 | Printf(" exec/s: %zd", ExecPerSec); |
| 350 | Printf(" rss: %zdMb", GetPeakRSSMb()); |
| 351 | Printf("%s", End); |
| 352 | } |
| 353 | |
| 354 | void Fuzzer::PrintFinalStats() { |
| 355 | if (Options.PrintCoverage) |
| 356 | TPC.PrintCoverage(); |
dor1s | bb93329 | 2018-07-16 16:01:31 +0000 | [diff] [blame] | 357 | if (Options.PrintUnstableStats) |
| 358 | TPC.PrintUnstableStats(); |
kcc | a7dd2a9 | 2018-05-21 19:47:00 +0000 | [diff] [blame] | 359 | if (Options.DumpCoverage) |
| 360 | TPC.DumpCoverage(); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 361 | if (Options.PrintCorpusStats) |
| 362 | Corpus.PrintStats(); |
dor1s | 2f72894 | 2018-07-17 20:37:40 +0000 | [diff] [blame^] | 363 | if (Options.PrintMutationStats) MD.PrintMutationStats(); |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 364 | if (!Options.PrintFinalStats) |
| 365 | return; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 366 | size_t ExecPerSec = execPerSec(); |
| 367 | Printf("stat::number_of_executed_units: %zd\n", TotalNumberOfRuns); |
| 368 | Printf("stat::average_exec_per_sec: %zd\n", ExecPerSec); |
| 369 | Printf("stat::new_units_added: %zd\n", NumberOfNewUnitsAdded); |
| 370 | Printf("stat::slowest_unit_time_sec: %zd\n", TimeOfLongestUnitInSeconds); |
| 371 | Printf("stat::peak_rss_mb: %zd\n", GetPeakRSSMb()); |
| 372 | } |
| 373 | |
| 374 | void Fuzzer::SetMaxInputLen(size_t MaxInputLen) { |
| 375 | assert(this->MaxInputLen == 0); // Can only reset MaxInputLen from 0 to non-0. |
| 376 | assert(MaxInputLen); |
| 377 | this->MaxInputLen = MaxInputLen; |
| 378 | this->MaxMutationLen = MaxInputLen; |
| 379 | AllocateCurrentUnitData(); |
| 380 | Printf("INFO: -max_len is not provided; " |
| 381 | "libFuzzer will not generate inputs larger than %zd bytes\n", |
| 382 | MaxInputLen); |
| 383 | } |
| 384 | |
| 385 | void Fuzzer::SetMaxMutationLen(size_t MaxMutationLen) { |
| 386 | assert(MaxMutationLen && MaxMutationLen <= MaxInputLen); |
| 387 | this->MaxMutationLen = MaxMutationLen; |
| 388 | } |
| 389 | |
| 390 | void Fuzzer::CheckExitOnSrcPosOrItem() { |
| 391 | if (!Options.ExitOnSrcPos.empty()) { |
george.karpenkov | fbfa45c | 2017-08-27 23:20:09 +0000 | [diff] [blame] | 392 | static auto *PCsSet = new Set<uintptr_t>; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 393 | auto HandlePC = [&](uintptr_t PC) { |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 394 | if (!PCsSet->insert(PC).second) |
| 395 | return; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 396 | std::string Descr = DescribePC("%F %L", PC + 1); |
| 397 | if (Descr.find(Options.ExitOnSrcPos) != std::string::npos) { |
| 398 | Printf("INFO: found line matching '%s', exiting.\n", |
| 399 | Options.ExitOnSrcPos.c_str()); |
| 400 | _Exit(0); |
| 401 | } |
| 402 | }; |
| 403 | TPC.ForEachObservedPC(HandlePC); |
| 404 | } |
| 405 | if (!Options.ExitOnItem.empty()) { |
| 406 | if (Corpus.HasUnit(Options.ExitOnItem)) { |
| 407 | Printf("INFO: found item with checksum '%s', exiting.\n", |
| 408 | Options.ExitOnItem.c_str()); |
| 409 | _Exit(0); |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | void Fuzzer::RereadOutputCorpus(size_t MaxSize) { |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 415 | if (Options.OutputCorpus.empty() || !Options.ReloadIntervalSec) |
| 416 | return; |
george.karpenkov | fbfa45c | 2017-08-27 23:20:09 +0000 | [diff] [blame] | 417 | Vector<Unit> AdditionalCorpus; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 418 | ReadDirToVectorOfUnits(Options.OutputCorpus.c_str(), &AdditionalCorpus, |
| 419 | &EpochOfLastReadOfOutputCorpus, MaxSize, |
| 420 | /*ExitOnError*/ false); |
| 421 | if (Options.Verbosity >= 2) |
| 422 | Printf("Reload: read %zd new units.\n", AdditionalCorpus.size()); |
| 423 | bool Reloaded = false; |
| 424 | for (auto &U : AdditionalCorpus) { |
| 425 | if (U.size() > MaxSize) |
| 426 | U.resize(MaxSize); |
| 427 | if (!Corpus.HasUnit(U)) { |
| 428 | if (RunOne(U.data(), U.size())) { |
| 429 | CheckExitOnSrcPosOrItem(); |
| 430 | Reloaded = true; |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | if (Reloaded) |
| 435 | PrintStats("RELOAD"); |
| 436 | } |
| 437 | |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 438 | void Fuzzer::PrintPulseAndReportSlowInput(const uint8_t *Data, size_t Size) { |
| 439 | auto TimeOfUnit = |
| 440 | duration_cast<seconds>(UnitStopTime - UnitStartTime).count(); |
| 441 | if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)) && |
| 442 | secondsSinceProcessStartUp() >= 2) |
| 443 | PrintStats("pulse "); |
| 444 | if (TimeOfUnit > TimeOfLongestUnitInSeconds * 1.1 && |
| 445 | TimeOfUnit >= Options.ReportSlowUnits) { |
| 446 | TimeOfLongestUnitInSeconds = TimeOfUnit; |
| 447 | Printf("Slowest unit: %zd s:\n", TimeOfLongestUnitInSeconds); |
| 448 | WriteUnitToFileWithPrefix({Data, Data + Size}, "slow-unit-"); |
| 449 | } |
| 450 | } |
| 451 | |
dor1s | bb93329 | 2018-07-16 16:01:31 +0000 | [diff] [blame] | 452 | void Fuzzer::CheckForUnstableCounters(const uint8_t *Data, size_t Size) { |
| 453 | auto CBSetupAndRun = [&]() { |
| 454 | ScopedEnableMsanInterceptorChecks S; |
| 455 | UnitStartTime = system_clock::now(); |
| 456 | TPC.ResetMaps(); |
morehouse | c6ee875 | 2018-07-17 16:12:00 +0000 | [diff] [blame] | 457 | RunningUserCallback = true; |
dor1s | bb93329 | 2018-07-16 16:01:31 +0000 | [diff] [blame] | 458 | CB(Data, Size); |
morehouse | c6ee875 | 2018-07-17 16:12:00 +0000 | [diff] [blame] | 459 | RunningUserCallback = false; |
dor1s | bb93329 | 2018-07-16 16:01:31 +0000 | [diff] [blame] | 460 | UnitStopTime = system_clock::now(); |
| 461 | }; |
| 462 | |
| 463 | // Copy original run counters into our unstable counters |
| 464 | TPC.InitializeUnstableCounters(); |
| 465 | |
| 466 | // First Rerun |
| 467 | CBSetupAndRun(); |
| 468 | TPC.UpdateUnstableCounters(); |
| 469 | |
| 470 | // Second Rerun |
| 471 | CBSetupAndRun(); |
| 472 | TPC.UpdateUnstableCounters(); |
| 473 | } |
| 474 | |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 475 | bool Fuzzer::RunOne(const uint8_t *Data, size_t Size, bool MayDeleteFile, |
kcc | b6836be | 2017-12-01 19:18:38 +0000 | [diff] [blame] | 476 | InputInfo *II, bool *FoundUniqFeatures) { |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 477 | if (!Size) |
| 478 | return false; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 479 | |
| 480 | ExecuteCallback(Data, Size); |
| 481 | |
| 482 | UniqFeatureSetTmp.clear(); |
| 483 | size_t FoundUniqFeaturesOfII = 0; |
| 484 | size_t NumUpdatesBefore = Corpus.NumFeatureUpdates(); |
| 485 | TPC.CollectFeatures([&](size_t Feature) { |
| 486 | if (Corpus.AddFeature(Feature, Size, Options.Shrink)) |
| 487 | UniqFeatureSetTmp.push_back(Feature); |
| 488 | if (Options.ReduceInputs && II) |
| 489 | if (std::binary_search(II->UniqFeatureSet.begin(), |
| 490 | II->UniqFeatureSet.end(), Feature)) |
| 491 | FoundUniqFeaturesOfII++; |
| 492 | }); |
kcc | b6836be | 2017-12-01 19:18:38 +0000 | [diff] [blame] | 493 | if (FoundUniqFeatures) |
| 494 | *FoundUniqFeatures = FoundUniqFeaturesOfII; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 495 | PrintPulseAndReportSlowInput(Data, Size); |
| 496 | size_t NumNewFeatures = Corpus.NumFeatureUpdates() - NumUpdatesBefore; |
dor1s | bb93329 | 2018-07-16 16:01:31 +0000 | [diff] [blame] | 497 | |
| 498 | // If print_unstable_stats, execute the same input two more times to detect |
| 499 | // unstable edges. |
| 500 | if (NumNewFeatures && Options.PrintUnstableStats) |
| 501 | CheckForUnstableCounters(Data, Size); |
| 502 | |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 503 | if (NumNewFeatures) { |
| 504 | TPC.UpdateObservedPCs(); |
| 505 | Corpus.AddToCorpus({Data, Data + Size}, NumNewFeatures, MayDeleteFile, |
kcc | 3acbe07 | 2018-05-16 23:26:37 +0000 | [diff] [blame] | 506 | TPC.ObservedFocusFunction(), |
kcc | adf188b | 2018-06-07 01:40:20 +0000 | [diff] [blame] | 507 | UniqFeatureSetTmp, DFT); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 508 | return true; |
| 509 | } |
| 510 | if (II && FoundUniqFeaturesOfII && |
kcc | adf188b | 2018-06-07 01:40:20 +0000 | [diff] [blame] | 511 | II->DataFlowTraceForFocusFunction.empty() && |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 512 | FoundUniqFeaturesOfII == II->UniqFeatureSet.size() && |
| 513 | II->U.size() > Size) { |
| 514 | Corpus.Replace(II, {Data, Data + Size}); |
| 515 | return true; |
| 516 | } |
| 517 | return false; |
| 518 | } |
| 519 | |
| 520 | size_t Fuzzer::GetCurrentUnitInFuzzingThead(const uint8_t **Data) const { |
| 521 | assert(InFuzzingThread()); |
| 522 | *Data = CurrentUnitData; |
| 523 | return CurrentUnitSize; |
| 524 | } |
| 525 | |
| 526 | void Fuzzer::CrashOnOverwrittenData() { |
| 527 | Printf("==%d== ERROR: libFuzzer: fuzz target overwrites it's const input\n", |
| 528 | GetPid()); |
| 529 | DumpCurrentUnit("crash-"); |
| 530 | Printf("SUMMARY: libFuzzer: out-of-memory\n"); |
| 531 | _Exit(Options.ErrorExitCode); // Stop right now. |
| 532 | } |
| 533 | |
| 534 | // Compare two arrays, but not all bytes if the arrays are large. |
| 535 | static bool LooseMemeq(const uint8_t *A, const uint8_t *B, size_t Size) { |
| 536 | const size_t Limit = 64; |
| 537 | if (Size <= 64) |
| 538 | return !memcmp(A, B, Size); |
| 539 | // Compare first and last Limit/2 bytes. |
| 540 | return !memcmp(A, B, Limit / 2) && |
| 541 | !memcmp(A + Size - Limit / 2, B + Size - Limit / 2, Limit / 2); |
| 542 | } |
| 543 | |
| 544 | void Fuzzer::ExecuteCallback(const uint8_t *Data, size_t Size) { |
| 545 | TPC.RecordInitialStack(); |
| 546 | TotalNumberOfRuns++; |
| 547 | assert(InFuzzingThread()); |
| 548 | if (SMR.IsClient()) |
| 549 | SMR.WriteByteArray(Data, Size); |
| 550 | // We copy the contents of Unit into a separate heap buffer |
| 551 | // so that we reliably find buffer overflows in it. |
| 552 | uint8_t *DataCopy = new uint8_t[Size]; |
| 553 | memcpy(DataCopy, Data, Size); |
morehouse | 1467b79 | 2018-07-09 23:51:08 +0000 | [diff] [blame] | 554 | if (EF->__msan_unpoison) |
| 555 | EF->__msan_unpoison(DataCopy, Size); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 556 | if (CurrentUnitData && CurrentUnitData != Data) |
| 557 | memcpy(CurrentUnitData, Data, Size); |
| 558 | CurrentUnitSize = Size; |
morehouse | 1467b79 | 2018-07-09 23:51:08 +0000 | [diff] [blame] | 559 | { |
| 560 | ScopedEnableMsanInterceptorChecks S; |
| 561 | AllocTracer.Start(Options.TraceMalloc); |
| 562 | UnitStartTime = system_clock::now(); |
| 563 | TPC.ResetMaps(); |
morehouse | c6ee875 | 2018-07-17 16:12:00 +0000 | [diff] [blame] | 564 | RunningUserCallback = true; |
morehouse | 1467b79 | 2018-07-09 23:51:08 +0000 | [diff] [blame] | 565 | int Res = CB(DataCopy, Size); |
morehouse | c6ee875 | 2018-07-17 16:12:00 +0000 | [diff] [blame] | 566 | RunningUserCallback = false; |
morehouse | 1467b79 | 2018-07-09 23:51:08 +0000 | [diff] [blame] | 567 | UnitStopTime = system_clock::now(); |
| 568 | (void)Res; |
| 569 | assert(Res == 0); |
| 570 | HasMoreMallocsThanFrees = AllocTracer.Stop(); |
| 571 | } |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 572 | if (!LooseMemeq(DataCopy, Data, Size)) |
| 573 | CrashOnOverwrittenData(); |
| 574 | CurrentUnitSize = 0; |
| 575 | delete[] DataCopy; |
| 576 | } |
| 577 | |
| 578 | void Fuzzer::WriteToOutputCorpus(const Unit &U) { |
| 579 | if (Options.OnlyASCII) |
| 580 | assert(IsASCII(U)); |
| 581 | if (Options.OutputCorpus.empty()) |
| 582 | return; |
| 583 | std::string Path = DirPlusFile(Options.OutputCorpus, Hash(U)); |
| 584 | WriteToFile(U, Path); |
| 585 | if (Options.Verbosity >= 2) |
| 586 | Printf("Written %zd bytes to %s\n", U.size(), Path.c_str()); |
| 587 | } |
| 588 | |
| 589 | void Fuzzer::WriteUnitToFileWithPrefix(const Unit &U, const char *Prefix) { |
| 590 | if (!Options.SaveArtifacts) |
| 591 | return; |
| 592 | std::string Path = Options.ArtifactPrefix + Prefix + Hash(U); |
| 593 | if (!Options.ExactArtifactPath.empty()) |
| 594 | Path = Options.ExactArtifactPath; // Overrides ArtifactPrefix. |
| 595 | WriteToFile(U, Path); |
| 596 | Printf("artifact_prefix='%s'; Test unit written to %s\n", |
| 597 | Options.ArtifactPrefix.c_str(), Path.c_str()); |
| 598 | if (U.size() <= kMaxUnitSizeToPrint) |
| 599 | Printf("Base64: %s\n", Base64(U).c_str()); |
| 600 | } |
| 601 | |
| 602 | void Fuzzer::PrintStatusForNewUnit(const Unit &U, const char *Text) { |
| 603 | if (!Options.PrintNEW) |
| 604 | return; |
| 605 | PrintStats(Text, ""); |
| 606 | if (Options.Verbosity) { |
| 607 | Printf(" L: %zd/%zd ", U.size(), Corpus.MaxInputSize()); |
| 608 | MD.PrintMutationSequence(); |
| 609 | Printf("\n"); |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | void Fuzzer::ReportNewCoverage(InputInfo *II, const Unit &U) { |
| 614 | II->NumSuccessfullMutations++; |
| 615 | MD.RecordSuccessfulMutationSequence(); |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 616 | PrintStatusForNewUnit(U, II->Reduced ? "REDUCE" : "NEW "); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 617 | WriteToOutputCorpus(U); |
| 618 | NumberOfNewUnitsAdded++; |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 619 | CheckExitOnSrcPosOrItem(); // Check only after the unit is saved to corpus. |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 620 | LastCorpusUpdateRun = TotalNumberOfRuns; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 621 | } |
| 622 | |
| 623 | // Tries detecting a memory leak on the particular input that we have just |
| 624 | // executed before calling this function. |
| 625 | void Fuzzer::TryDetectingAMemoryLeak(const uint8_t *Data, size_t Size, |
| 626 | bool DuringInitialCorpusExecution) { |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 627 | if (!HasMoreMallocsThanFrees) |
| 628 | return; // mallocs==frees, a leak is unlikely. |
| 629 | if (!Options.DetectLeaks) |
| 630 | return; |
dor1s | 38279cb | 2017-09-12 02:01:54 +0000 | [diff] [blame] | 631 | if (!DuringInitialCorpusExecution && |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 632 | TotalNumberOfRuns >= Options.MaxNumberOfRuns) |
| 633 | return; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 634 | if (!&(EF->__lsan_enable) || !&(EF->__lsan_disable) || |
| 635 | !(EF->__lsan_do_recoverable_leak_check)) |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 636 | return; // No lsan. |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 637 | // Run the target once again, but with lsan disabled so that if there is |
| 638 | // a real leak we do not report it twice. |
| 639 | EF->__lsan_disable(); |
| 640 | ExecuteCallback(Data, Size); |
| 641 | EF->__lsan_enable(); |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 642 | if (!HasMoreMallocsThanFrees) |
| 643 | return; // a leak is unlikely. |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 644 | if (NumberOfLeakDetectionAttempts++ > 1000) { |
| 645 | Options.DetectLeaks = false; |
| 646 | Printf("INFO: libFuzzer disabled leak detection after every mutation.\n" |
| 647 | " Most likely the target function accumulates allocated\n" |
| 648 | " memory in a global state w/o actually leaking it.\n" |
| 649 | " You may try running this binary with -trace_malloc=[12]" |
| 650 | " to get a trace of mallocs and frees.\n" |
| 651 | " If LeakSanitizer is enabled in this process it will still\n" |
| 652 | " run on the process shutdown.\n"); |
| 653 | return; |
| 654 | } |
| 655 | // Now perform the actual lsan pass. This is expensive and we must ensure |
| 656 | // we don't call it too often. |
| 657 | if (EF->__lsan_do_recoverable_leak_check()) { // Leak is found, report it. |
| 658 | if (DuringInitialCorpusExecution) |
| 659 | Printf("\nINFO: a leak has been found in the initial corpus.\n\n"); |
| 660 | Printf("INFO: to ignore leaks on libFuzzer side use -detect_leaks=0.\n\n"); |
| 661 | CurrentUnitSize = Size; |
| 662 | DumpCurrentUnit("leak-"); |
| 663 | PrintFinalStats(); |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 664 | _Exit(Options.ErrorExitCode); // not exit() to disable lsan further on. |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 665 | } |
| 666 | } |
| 667 | |
| 668 | void Fuzzer::MutateAndTestOne() { |
| 669 | MD.StartMutationSequence(); |
| 670 | |
| 671 | auto &II = Corpus.ChooseUnitToMutate(MD.GetRand()); |
| 672 | const auto &U = II.U; |
| 673 | memcpy(BaseSha1, II.Sha1, sizeof(BaseSha1)); |
| 674 | assert(CurrentUnitData); |
| 675 | size_t Size = U.size(); |
| 676 | assert(Size <= MaxInputLen && "Oversized Unit"); |
| 677 | memcpy(CurrentUnitData, U.data(), Size); |
| 678 | |
| 679 | assert(MaxMutationLen > 0); |
| 680 | |
| 681 | size_t CurrentMaxMutationLen = |
| 682 | Min(MaxMutationLen, Max(U.size(), TmpMaxMutationLen)); |
| 683 | assert(CurrentMaxMutationLen > 0); |
| 684 | |
| 685 | for (int i = 0; i < Options.MutateDepth; i++) { |
| 686 | if (TotalNumberOfRuns >= Options.MaxNumberOfRuns) |
| 687 | break; |
kcc | 1239a99 | 2017-11-09 20:30:19 +0000 | [diff] [blame] | 688 | MaybeExitGracefully(); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 689 | size_t NewSize = 0; |
| 690 | NewSize = MD.Mutate(CurrentUnitData, Size, CurrentMaxMutationLen); |
| 691 | assert(NewSize > 0 && "Mutator returned empty unit"); |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 692 | assert(NewSize <= CurrentMaxMutationLen && "Mutator return oversized unit"); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 693 | Size = NewSize; |
| 694 | II.NumExecutedMutations++; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 695 | |
kcc | b6836be | 2017-12-01 19:18:38 +0000 | [diff] [blame] | 696 | bool FoundUniqFeatures = false; |
| 697 | bool NewCov = RunOne(CurrentUnitData, Size, /*MayDeleteFile=*/true, &II, |
| 698 | &FoundUniqFeatures); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 699 | TryDetectingAMemoryLeak(CurrentUnitData, Size, |
| 700 | /*DuringInitialCorpusExecution*/ false); |
kcc | b6836be | 2017-12-01 19:18:38 +0000 | [diff] [blame] | 701 | if (NewCov) { |
morehouse | 553f00b | 2017-11-09 20:44:08 +0000 | [diff] [blame] | 702 | ReportNewCoverage(&II, {CurrentUnitData, CurrentUnitData + Size}); |
kcc | b6836be | 2017-12-01 19:18:38 +0000 | [diff] [blame] | 703 | break; // We will mutate this input more in the next rounds. |
| 704 | } |
| 705 | if (Options.ReduceDepth && !FoundUniqFeatures) |
dor1s | e6729cb | 2018-07-16 15:15:34 +0000 | [diff] [blame] | 706 | break; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 707 | } |
| 708 | } |
| 709 | |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 710 | void Fuzzer::PurgeAllocator() { |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 711 | if (Options.PurgeAllocatorIntervalSec < 0 || !EF->__sanitizer_purge_allocator) |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 712 | return; |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 713 | if (duration_cast<seconds>(system_clock::now() - |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 714 | LastAllocatorPurgeAttemptTime) |
| 715 | .count() < Options.PurgeAllocatorIntervalSec) |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 716 | return; |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 717 | |
| 718 | if (Options.RssLimitMb <= 0 || |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 719 | GetPeakRSSMb() > static_cast<size_t>(Options.RssLimitMb) / 2) |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 720 | EF->__sanitizer_purge_allocator(); |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 721 | |
| 722 | LastAllocatorPurgeAttemptTime = system_clock::now(); |
| 723 | } |
| 724 | |
kcc | 2e93b3f | 2017-08-29 02:05:01 +0000 | [diff] [blame] | 725 | void Fuzzer::ReadAndExecuteSeedCorpora(const Vector<std::string> &CorpusDirs) { |
| 726 | const size_t kMaxSaneLen = 1 << 20; |
| 727 | const size_t kMinDefaultLen = 4096; |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 728 | Vector<SizedFile> SizedFiles; |
| 729 | size_t MaxSize = 0; |
| 730 | size_t MinSize = -1; |
| 731 | size_t TotalSize = 0; |
kcc | 7f5f222 | 2017-09-12 21:58:07 +0000 | [diff] [blame] | 732 | size_t LastNumFiles = 0; |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 733 | for (auto &Dir : CorpusDirs) { |
kcc | 7f5f222 | 2017-09-12 21:58:07 +0000 | [diff] [blame] | 734 | GetSizedFilesFromDir(Dir, &SizedFiles); |
| 735 | Printf("INFO: % 8zd files found in %s\n", SizedFiles.size() - LastNumFiles, |
| 736 | Dir.c_str()); |
| 737 | LastNumFiles = SizedFiles.size(); |
| 738 | } |
| 739 | for (auto &File : SizedFiles) { |
| 740 | MaxSize = Max(File.Size, MaxSize); |
| 741 | MinSize = Min(File.Size, MinSize); |
| 742 | TotalSize += File.Size; |
kcc | 2e93b3f | 2017-08-29 02:05:01 +0000 | [diff] [blame] | 743 | } |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 744 | if (Options.MaxLen == 0) |
| 745 | SetMaxInputLen(std::min(std::max(kMinDefaultLen, MaxSize), kMaxSaneLen)); |
| 746 | assert(MaxInputLen > 0); |
| 747 | |
kcc | 2cd9f09 | 2017-10-13 01:12:23 +0000 | [diff] [blame] | 748 | // Test the callback with empty input and never try it again. |
| 749 | uint8_t dummy = 0; |
| 750 | ExecuteCallback(&dummy, 0); |
| 751 | |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 752 | if (SizedFiles.empty()) { |
| 753 | Printf("INFO: A corpus is not provided, starting from an empty corpus\n"); |
| 754 | Unit U({'\n'}); // Valid ASCII input. |
| 755 | RunOne(U.data(), U.size()); |
| 756 | } else { |
| 757 | Printf("INFO: seed corpus: files: %zd min: %zdb max: %zdb total: %zdb" |
| 758 | " rss: %zdMb\n", |
| 759 | SizedFiles.size(), MinSize, MaxSize, TotalSize, GetPeakRSSMb()); |
| 760 | if (Options.ShuffleAtStartUp) |
| 761 | std::shuffle(SizedFiles.begin(), SizedFiles.end(), MD.GetRand()); |
| 762 | |
kcc | 7f5f222 | 2017-09-12 21:58:07 +0000 | [diff] [blame] | 763 | if (Options.PreferSmall) { |
| 764 | std::stable_sort(SizedFiles.begin(), SizedFiles.end()); |
| 765 | assert(SizedFiles.front().Size <= SizedFiles.back().Size); |
| 766 | } |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 767 | |
| 768 | // Load and execute inputs one by one. |
| 769 | for (auto &SF : SizedFiles) { |
kcc | ae85e29 | 2017-08-31 19:17:15 +0000 | [diff] [blame] | 770 | auto U = FileToVector(SF.File, MaxInputLen, /*ExitOnError=*/false); |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 771 | assert(U.size() <= MaxInputLen); |
| 772 | RunOne(U.data(), U.size()); |
| 773 | CheckExitOnSrcPosOrItem(); |
| 774 | TryDetectingAMemoryLeak(U.data(), U.size(), |
| 775 | /*DuringInitialCorpusExecution*/ true); |
| 776 | } |
kcc | 2e93b3f | 2017-08-29 02:05:01 +0000 | [diff] [blame] | 777 | } |
| 778 | |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 779 | PrintStats("INITED"); |
kcc | 3acbe07 | 2018-05-16 23:26:37 +0000 | [diff] [blame] | 780 | if (!Options.FocusFunction.empty()) |
| 781 | Printf("INFO: %zd/%zd inputs touch the focus function\n", |
| 782 | Corpus.NumInputsThatTouchFocusFunction(), Corpus.size()); |
kcc | adf188b | 2018-06-07 01:40:20 +0000 | [diff] [blame] | 783 | if (!Options.DataFlowTrace.empty()) |
| 784 | Printf("INFO: %zd/%zd inputs have the Data Flow Trace\n", |
| 785 | Corpus.NumInputsWithDataFlowTrace(), Corpus.size()); |
kcc | 3acbe07 | 2018-05-16 23:26:37 +0000 | [diff] [blame] | 786 | |
dor1s | 770a9bc | 2018-05-23 19:42:30 +0000 | [diff] [blame] | 787 | if (Corpus.empty() && Options.MaxNumberOfRuns) { |
kcc | dc00cd3 | 2017-08-29 20:51:24 +0000 | [diff] [blame] | 788 | Printf("ERROR: no interesting inputs were found. " |
| 789 | "Is the code instrumented for coverage? Exiting.\n"); |
| 790 | exit(1); |
kcc | 2e93b3f | 2017-08-29 02:05:01 +0000 | [diff] [blame] | 791 | } |
kcc | 2e93b3f | 2017-08-29 02:05:01 +0000 | [diff] [blame] | 792 | } |
| 793 | |
| 794 | void Fuzzer::Loop(const Vector<std::string> &CorpusDirs) { |
| 795 | ReadAndExecuteSeedCorpora(CorpusDirs); |
kcc | adf188b | 2018-06-07 01:40:20 +0000 | [diff] [blame] | 796 | DFT.Clear(); // No need for DFT any more. |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 797 | TPC.SetPrintNewPCs(Options.PrintNewCovPcs); |
kcc | 00da648 | 2017-08-25 20:09:25 +0000 | [diff] [blame] | 798 | TPC.SetPrintNewFuncs(Options.PrintNewCovFuncs); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 799 | system_clock::time_point LastCorpusReload = system_clock::now(); |
| 800 | if (Options.DoCrossOver) |
| 801 | MD.SetCorpus(&Corpus); |
| 802 | while (true) { |
| 803 | auto Now = system_clock::now(); |
| 804 | if (duration_cast<seconds>(Now - LastCorpusReload).count() >= |
| 805 | Options.ReloadIntervalSec) { |
| 806 | RereadOutputCorpus(MaxInputLen); |
| 807 | LastCorpusReload = system_clock::now(); |
| 808 | } |
| 809 | if (TotalNumberOfRuns >= Options.MaxNumberOfRuns) |
| 810 | break; |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 811 | if (TimedOut()) |
| 812 | break; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 813 | |
| 814 | // Update TmpMaxMutationLen |
morehouse | 8c42ada | 2018-02-13 20:52:15 +0000 | [diff] [blame] | 815 | if (Options.LenControl) { |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 816 | if (TmpMaxMutationLen < MaxMutationLen && |
kcc | e29d7e3 | 2017-12-12 23:11:28 +0000 | [diff] [blame] | 817 | TotalNumberOfRuns - LastCorpusUpdateRun > |
morehouse | 8c42ada | 2018-02-13 20:52:15 +0000 | [diff] [blame] | 818 | Options.LenControl * Log(TmpMaxMutationLen)) { |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 819 | TmpMaxMutationLen = |
kcc | e29d7e3 | 2017-12-12 23:11:28 +0000 | [diff] [blame] | 820 | Min(MaxMutationLen, TmpMaxMutationLen + Log(TmpMaxMutationLen)); |
kcc | e29d7e3 | 2017-12-12 23:11:28 +0000 | [diff] [blame] | 821 | LastCorpusUpdateRun = TotalNumberOfRuns; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 822 | } |
| 823 | } else { |
| 824 | TmpMaxMutationLen = MaxMutationLen; |
| 825 | } |
| 826 | |
| 827 | // Perform several mutations and runs. |
| 828 | MutateAndTestOne(); |
alekseyshl | d995b55 | 2017-10-23 22:04:30 +0000 | [diff] [blame] | 829 | |
| 830 | PurgeAllocator(); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 831 | } |
| 832 | |
| 833 | PrintStats("DONE ", "\n"); |
| 834 | MD.PrintRecommendedDictionary(); |
| 835 | } |
| 836 | |
| 837 | void Fuzzer::MinimizeCrashLoop(const Unit &U) { |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 838 | if (U.size() <= 1) |
| 839 | return; |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 840 | while (!TimedOut() && TotalNumberOfRuns < Options.MaxNumberOfRuns) { |
| 841 | MD.StartMutationSequence(); |
| 842 | memcpy(CurrentUnitData, U.data(), U.size()); |
| 843 | for (int i = 0; i < Options.MutateDepth; i++) { |
| 844 | size_t NewSize = MD.Mutate(CurrentUnitData, U.size(), MaxMutationLen); |
| 845 | assert(NewSize > 0 && NewSize <= MaxMutationLen); |
| 846 | ExecuteCallback(CurrentUnitData, NewSize); |
| 847 | PrintPulseAndReportSlowInput(CurrentUnitData, NewSize); |
| 848 | TryDetectingAMemoryLeak(CurrentUnitData, NewSize, |
| 849 | /*DuringInitialCorpusExecution*/ false); |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | void Fuzzer::AnnounceOutput(const uint8_t *Data, size_t Size) { |
| 855 | if (SMR.IsServer()) { |
| 856 | SMR.WriteByteArray(Data, Size); |
| 857 | } else if (SMR.IsClient()) { |
| 858 | SMR.PostClient(); |
| 859 | SMR.WaitServer(); |
| 860 | size_t OtherSize = SMR.ReadByteArraySize(); |
| 861 | uint8_t *OtherData = SMR.GetByteArray(); |
| 862 | if (Size != OtherSize || memcmp(Data, OtherData, Size) != 0) { |
| 863 | size_t i = 0; |
| 864 | for (i = 0; i < Min(Size, OtherSize); i++) |
| 865 | if (Data[i] != OtherData[i]) |
| 866 | break; |
| 867 | Printf("==%lu== ERROR: libFuzzer: equivalence-mismatch. Sizes: %zd %zd; " |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 868 | "offset %zd\n", |
| 869 | GetPid(), Size, OtherSize, i); |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 870 | DumpCurrentUnit("mismatch-"); |
| 871 | Printf("SUMMARY: libFuzzer: equivalence-mismatch\n"); |
| 872 | PrintFinalStats(); |
| 873 | _Exit(Options.ErrorExitCode); |
| 874 | } |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | } // namespace fuzzer |
| 879 | |
| 880 | extern "C" { |
| 881 | |
phosek | 966475e | 2018-01-17 20:39:14 +0000 | [diff] [blame] | 882 | __attribute__((visibility("default"))) size_t |
| 883 | LLVMFuzzerMutate(uint8_t *Data, size_t Size, size_t MaxSize) { |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 884 | assert(fuzzer::F); |
| 885 | return fuzzer::F->GetMD().DefaultMutate(Data, Size, MaxSize); |
| 886 | } |
| 887 | |
| 888 | // Experimental |
phosek | 966475e | 2018-01-17 20:39:14 +0000 | [diff] [blame] | 889 | __attribute__((visibility("default"))) void |
| 890 | LLVMFuzzerAnnounceOutput(const uint8_t *Data, size_t Size) { |
george.karpenkov | 29efa6d | 2017-08-21 23:25:50 +0000 | [diff] [blame] | 891 | assert(fuzzer::F); |
| 892 | fuzzer::F->AnnounceOutput(Data, Size); |
| 893 | } |
alekseyshl | 9f6a9f2 | 2017-10-23 23:24:33 +0000 | [diff] [blame] | 894 | } // extern "C" |