1 //===- FuzzerTracePC.cpp - PC tracing--------------------------------------===//
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 // Trace PCs.
10 // This module implements __sanitizer_cov_trace_pc_guard[_init],
11 // the callback required for -fsanitize-coverage=trace-pc-guard instrumentation.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "FuzzerTracePC.h"
16 #include "FuzzerCorpus.h"
17 #include "FuzzerDefs.h"
18 #include "FuzzerDictionary.h"
19 #include "FuzzerExtFunctions.h"
20 #include "FuzzerIO.h"
21 #include "FuzzerUtil.h"
22 #include "FuzzerValueBitMap.h"
23 #include <set>
24 
25 // The coverage counters and PCs.
26 // These are declared as global variables named "__sancov_*" to simplify
27 // experiments with inlined instrumentation.
28 alignas(64) ATTRIBUTE_INTERFACE
29 uint8_t __sancov_trace_pc_guard_8bit_counters[fuzzer::TracePC::kNumPCs];
30 
31 ATTRIBUTE_INTERFACE
32 uintptr_t __sancov_trace_pc_pcs[fuzzer::TracePC::kNumPCs];
33 
34 // Used by -fsanitize-coverage=stack-depth to track stack depth
35 ATTRIBUTE_INTERFACE __attribute__((tls_model("initial-exec")))
36 thread_local uintptr_t __sancov_lowest_stack;
37 
38 namespace fuzzer {
39 
40 TracePC TPC;
41 
42 uint8_t *TracePC::Counters() const {
43   return __sancov_trace_pc_guard_8bit_counters;
44 }
45 
46 uintptr_t *TracePC::PCs() const {
47   return __sancov_trace_pc_pcs;
48 }
49 
50 size_t TracePC::GetTotalPCCoverage() {
51   if (ObservedPCs.size())
52     return ObservedPCs.size();
53   size_t Res = 0;
54   for (size_t i = 1, N = GetNumPCs(); i < N; i++)
55     if (PCs()[i])
56       Res++;
57   return Res;
58 }
59 
60 template<class CallBack>
61 void TracePC::IterateInline8bitCounters(CallBack CB) const {
62   if (NumInline8bitCounters && NumInline8bitCounters == NumPCsInPCTables) {
63     size_t CounterIdx = 0;
64     for (size_t i = 0; i < NumModulesWithInline8bitCounters; i++) {
65       uint8_t *Beg = ModuleCounters[i].Start;
66       size_t Size = ModuleCounters[i].Stop - Beg;
67       assert(Size == (size_t)(ModulePCTable[i].Stop - ModulePCTable[i].Start));
68       for (size_t j = 0; j < Size; j++, CounterIdx++)
69         CB(i, j, CounterIdx);
70     }
71   }
72 }
73 
74 // Initializes unstable counters by copying Inline8bitCounters to unstable
75 // counters.
76 void TracePC::InitializeUnstableCounters() {
77   IterateInline8bitCounters([&](int i, int j, int UnstableIdx) {
78     UnstableCounters[UnstableIdx].Counter = ModuleCounters[i].Start[j];
79   });
80 }
81 
82 // Compares the current counters with counters from previous runs
83 // and records differences as unstable edges.
84 void TracePC::UpdateUnstableCounters(int UnstableMode) {
85   IterateInline8bitCounters([&](int i, int j, int UnstableIdx) {
86     if (ModuleCounters[i].Start[j] != UnstableCounters[UnstableIdx].Counter) {
87       UnstableCounters[UnstableIdx].IsUnstable = true;
88       if (UnstableMode == ZeroUnstable)
89         UnstableCounters[UnstableIdx].Counter = 0;
90       else if (UnstableMode == MinUnstable)
91         UnstableCounters[UnstableIdx].Counter = std::min(
92             ModuleCounters[i].Start[j], UnstableCounters[UnstableIdx].Counter);
93     }
94   });
95 }
96 
97 // Moves the minimum hit counts to ModuleCounters.
98 void TracePC::ApplyUnstableCounters() {
99   IterateInline8bitCounters([&](int i, int j, int UnstableIdx) {
100     ModuleCounters[i].Start[j] = UnstableCounters[UnstableIdx].Counter;
101   });
102 }
103 
104 void TracePC::HandleInline8bitCountersInit(uint8_t *Start, uint8_t *Stop) {
105   if (Start == Stop) return;
106   if (NumModulesWithInline8bitCounters &&
107       ModuleCounters[NumModulesWithInline8bitCounters-1].Start == Start) return;
108   assert(NumModulesWithInline8bitCounters <
109          sizeof(ModuleCounters) / sizeof(ModuleCounters[0]));
110   ModuleCounters[NumModulesWithInline8bitCounters++] = {Start, Stop};
111   NumInline8bitCounters += Stop - Start;
112 }
113 
114 void TracePC::HandlePCsInit(const uintptr_t *Start, const uintptr_t *Stop) {
115   const PCTableEntry *B = reinterpret_cast<const PCTableEntry *>(Start);
116   const PCTableEntry *E = reinterpret_cast<const PCTableEntry *>(Stop);
117   if (NumPCTables && ModulePCTable[NumPCTables - 1].Start == B) return;
118   assert(NumPCTables < sizeof(ModulePCTable) / sizeof(ModulePCTable[0]));
119   ModulePCTable[NumPCTables++] = {B, E};
120   NumPCsInPCTables += E - B;
121 }
122 
123 void TracePC::HandleInit(uint32_t *Start, uint32_t *Stop) {
124   if (Start == Stop || *Start) return;
125   assert(NumModules < sizeof(Modules) / sizeof(Modules[0]));
126   for (uint32_t *P = Start; P < Stop; P++) {
127     NumGuards++;
128     if (NumGuards == kNumPCs) {
129       RawPrint(
130           "WARNING: The binary has too many instrumented PCs.\n"
131           "         You may want to reduce the size of the binary\n"
132           "         for more efficient fuzzing and precise coverage data\n");
133     }
134     *P = NumGuards % kNumPCs;
135   }
136   Modules[NumModules].Start = Start;
137   Modules[NumModules].Stop = Stop;
138   NumModules++;
139 }
140 
141 void TracePC::PrintModuleInfo() {
142   if (NumGuards) {
143     Printf("INFO: Loaded %zd modules   (%zd guards): ", NumModules, NumGuards);
144     for (size_t i = 0; i < NumModules; i++)
145       Printf("%zd [%p, %p), ", Modules[i].Stop - Modules[i].Start,
146              Modules[i].Start, Modules[i].Stop);
147     Printf("\n");
148   }
149   if (NumModulesWithInline8bitCounters) {
150     Printf("INFO: Loaded %zd modules   (%zd inline 8-bit counters): ",
151            NumModulesWithInline8bitCounters, NumInline8bitCounters);
152     for (size_t i = 0; i < NumModulesWithInline8bitCounters; i++)
153       Printf("%zd [%p, %p), ", ModuleCounters[i].Stop - ModuleCounters[i].Start,
154              ModuleCounters[i].Start, ModuleCounters[i].Stop);
155     Printf("\n");
156   }
157   if (NumPCTables) {
158     Printf("INFO: Loaded %zd PC tables (%zd PCs): ", NumPCTables,
159            NumPCsInPCTables);
160     for (size_t i = 0; i < NumPCTables; i++) {
161       Printf("%zd [%p,%p), ", ModulePCTable[i].Stop - ModulePCTable[i].Start,
162              ModulePCTable[i].Start, ModulePCTable[i].Stop);
163     }
164     Printf("\n");
165 
166     if ((NumGuards && NumGuards != NumPCsInPCTables) ||
167         (NumInline8bitCounters && NumInline8bitCounters != NumPCsInPCTables)) {
168       Printf("ERROR: The size of coverage PC tables does not match the\n"
169              "number of instrumented PCs. This might be a compiler bug,\n"
170              "please contact the libFuzzer developers.\n"
171              "Also check https://bugs.llvm.org/show_bug.cgi?id=34636\n"
172              "for possible workarounds (tl;dr: don't use the old GNU ld)\n");
173       _Exit(1);
174     }
175   }
176   if (size_t NumExtraCounters = ExtraCountersEnd() - ExtraCountersBegin())
177     Printf("INFO: %zd Extra Counters\n", NumExtraCounters);
178 }
179 
180 ATTRIBUTE_NO_SANITIZE_ALL
181 void TracePC::HandleCallerCallee(uintptr_t Caller, uintptr_t Callee) {
182   const uintptr_t kBits = 12;
183   const uintptr_t kMask = (1 << kBits) - 1;
184   uintptr_t Idx = (Caller & kMask) | ((Callee & kMask) << kBits);
185   ValueProfileMap.AddValueModPrime(Idx);
186 }
187 
188 void TracePC::UpdateObservedPCs() {
189   Vector<uintptr_t> CoveredFuncs;
190   auto ObservePC = [&](uintptr_t PC) {
191     if (ObservedPCs.insert(PC).second && DoPrintNewPCs) {
192       PrintPC("\tNEW_PC: %p %F %L", "\tNEW_PC: %p", PC + 1);
193       Printf("\n");
194     }
195   };
196 
197   auto Observe = [&](const PCTableEntry &TE) {
198     if (TE.PCFlags & 1)
199       if (++ObservedFuncs[TE.PC] == 1 && NumPrintNewFuncs)
200         CoveredFuncs.push_back(TE.PC);
201     ObservePC(TE.PC);
202   };
203 
204   if (NumPCsInPCTables) {
205     if (NumInline8bitCounters == NumPCsInPCTables) {
206       IterateInline8bitCounters([&](int i, int j, int CounterIdx) {
207         if (ModuleCounters[i].Start[j])
208           Observe(ModulePCTable[i].Start[j]);
209       });
210     } else if (NumGuards == NumPCsInPCTables) {
211       size_t GuardIdx = 1;
212       for (size_t i = 0; i < NumModules; i++) {
213         uint32_t *Beg = Modules[i].Start;
214         size_t Size = Modules[i].Stop - Beg;
215         assert(Size ==
216                (size_t)(ModulePCTable[i].Stop - ModulePCTable[i].Start));
217         for (size_t j = 0; j < Size; j++, GuardIdx++)
218           if (Counters()[GuardIdx])
219             Observe(ModulePCTable[i].Start[j]);
220       }
221     }
222   }
223 
224   for (size_t i = 0, N = Min(CoveredFuncs.size(), NumPrintNewFuncs); i < N;
225        i++) {
226     Printf("\tNEW_FUNC[%zd/%zd]: ", i + 1, CoveredFuncs.size());
227     PrintPC("%p %F %L", "%p", CoveredFuncs[i] + 1);
228     Printf("\n");
229   }
230 }
231 
232 inline ALWAYS_INLINE uintptr_t GetPreviousInstructionPc(uintptr_t PC) {
233   // TODO: this implementation is x86 only.
234   // see sanitizer_common GetPreviousInstructionPc for full implementation.
235   return PC - 1;
236 }
237 
238 inline ALWAYS_INLINE uintptr_t GetNextInstructionPc(uintptr_t PC) {
239   // TODO: this implementation is x86 only.
240   // see sanitizer_common GetPreviousInstructionPc for full implementation.
241   return PC + 1;
242 }
243 
244 static std::string GetModuleName(uintptr_t PC) {
245   char ModulePathRaw[4096] = "";  // What's PATH_MAX in portable C++?
246   void *OffsetRaw = nullptr;
247   if (!EF->__sanitizer_get_module_and_offset_for_pc(
248       reinterpret_cast<void *>(PC), ModulePathRaw,
249       sizeof(ModulePathRaw), &OffsetRaw))
250     return "";
251   return ModulePathRaw;
252 }
253 
254 template<class CallBack>
255 void TracePC::IterateCoveredFunctions(CallBack CB) {
256   for (size_t i = 0; i < NumPCTables; i++) {
257     auto &M = ModulePCTable[i];
258     assert(M.Start < M.Stop);
259     auto ModuleName = GetModuleName(M.Start->PC);
260     for (auto NextFE = M.Start; NextFE < M.Stop; ) {
261       auto FE = NextFE;
262       assert((FE->PCFlags & 1) && "Not a function entry point");
263       do {
264         NextFE++;
265       } while (NextFE < M.Stop && !(NextFE->PCFlags & 1));
266       if (ObservedFuncs.count(FE->PC))
267         CB(FE, NextFE, ObservedFuncs[FE->PC]);
268     }
269   }
270 }
271 
272 void TracePC::SetFocusFunction(const std::string &FuncName) {
273   // This function should be called once.
274   assert(FocusFunction.first > NumModulesWithInline8bitCounters);
275   if (FuncName.empty())
276     return;
277   for (size_t M = 0; M < NumModulesWithInline8bitCounters; M++) {
278     auto &PCTE = ModulePCTable[M];
279     size_t N = PCTE.Stop - PCTE.Start;
280     for (size_t I = 0; I < N; I++) {
281       if (!(PCTE.Start[I].PCFlags & 1)) continue;  // not a function entry.
282       auto Name = DescribePC("%F", GetNextInstructionPc(PCTE.Start[I].PC));
283       if (Name[0] == 'i' && Name[1] == 'n' && Name[2] == ' ')
284         Name = Name.substr(3, std::string::npos);
285       if (FuncName != Name) continue;
286       Printf("INFO: Focus function is set to '%s'\n", Name.c_str());
287       FocusFunction = {M, I};
288       return;
289     }
290   }
291 }
292 
293 bool TracePC::ObservedFocusFunction() {
294   size_t I = FocusFunction.first;
295   size_t J = FocusFunction.second;
296   if (I >= NumModulesWithInline8bitCounters)
297     return false;
298   auto &MC = ModuleCounters[I];
299   size_t Size = MC.Stop - MC.Start;
300   if (J >= Size)
301     return false;
302   return MC.Start[J] != 0;
303 }
304 
305 void TracePC::PrintCoverage() {
306   if (!EF->__sanitizer_symbolize_pc ||
307       !EF->__sanitizer_get_module_and_offset_for_pc) {
308     Printf("INFO: __sanitizer_symbolize_pc or "
309            "__sanitizer_get_module_and_offset_for_pc is not available,"
310            " not printing coverage\n");
311     return;
312   }
313   Printf("COVERAGE:\n");
314   auto CoveredFunctionCallback = [&](const PCTableEntry *First,
315                                      const PCTableEntry *Last,
316                                      uintptr_t Counter) {
317     assert(First < Last);
318     auto VisualizePC = GetNextInstructionPc(First->PC);
319     std::string FileStr = DescribePC("%s", VisualizePC);
320     if (!IsInterestingCoverageFile(FileStr))
321       return;
322     std::string FunctionStr = DescribePC("%F", VisualizePC);
323     if (FunctionStr.find("in ") == 0)
324       FunctionStr = FunctionStr.substr(3);
325     std::string LineStr = DescribePC("%l", VisualizePC);
326     size_t Line = std::stoul(LineStr);
327     size_t NumEdges = Last - First;
328     Vector<uintptr_t> UncoveredPCs;
329     for (auto TE = First; TE < Last; TE++)
330       if (!ObservedPCs.count(TE->PC))
331         UncoveredPCs.push_back(TE->PC);
332     Printf("COVERED_FUNC: hits: %zd", Counter);
333     Printf(" edges: %zd/%zd", NumEdges - UncoveredPCs.size(), NumEdges);
334     Printf(" %s %s:%zd\n", FunctionStr.c_str(), FileStr.c_str(), Line);
335     for (auto PC: UncoveredPCs)
336       Printf("  UNCOVERED_PC: %s\n",
337              DescribePC("%s:%l", GetNextInstructionPc(PC)).c_str());
338   };
339 
340   IterateCoveredFunctions(CoveredFunctionCallback);
341 }
342 
343 void TracePC::DumpCoverage() {
344   if (EF->__sanitizer_dump_coverage) {
345     Vector<uintptr_t> PCsCopy(GetNumPCs());
346     for (size_t i = 0; i < GetNumPCs(); i++)
347       PCsCopy[i] = PCs()[i] ? GetPreviousInstructionPc(PCs()[i]) : 0;
348     EF->__sanitizer_dump_coverage(PCsCopy.data(), PCsCopy.size());
349   }
350 }
351 
352 void TracePC::PrintUnstableStats() {
353   size_t count = 0;
354   for (size_t i = 0; i < NumInline8bitCounters; i++)
355     if (UnstableCounters[i].IsUnstable)
356       count++;
357   Printf("stat::stability_rate: %.2f\n",
358          100 - static_cast<float>(count * 100) / NumInline8bitCounters);
359 }
360 
361 // Value profile.
362 // We keep track of various values that affect control flow.
363 // These values are inserted into a bit-set-based hash map.
364 // Every new bit in the map is treated as a new coverage.
365 //
366 // For memcmp/strcmp/etc the interesting value is the length of the common
367 // prefix of the parameters.
368 // For cmp instructions the interesting value is a XOR of the parameters.
369 // The interesting value is mixed up with the PC and is then added to the map.
370 
371 ATTRIBUTE_NO_SANITIZE_ALL
372 void TracePC::AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
373                                 size_t n, bool StopAtZero) {
374   if (!n) return;
375   size_t Len = std::min(n, Word::GetMaxSize());
376   const uint8_t *A1 = reinterpret_cast<const uint8_t *>(s1);
377   const uint8_t *A2 = reinterpret_cast<const uint8_t *>(s2);
378   uint8_t B1[Word::kMaxSize];
379   uint8_t B2[Word::kMaxSize];
380   // Copy the data into locals in this non-msan-instrumented function
381   // to avoid msan complaining further.
382   size_t Hash = 0;  // Compute some simple hash of both strings.
383   for (size_t i = 0; i < Len; i++) {
384     B1[i] = A1[i];
385     B2[i] = A2[i];
386     size_t T = B1[i];
387     Hash ^= (T << 8) | B2[i];
388   }
389   size_t I = 0;
390   for (; I < Len; I++)
391     if (B1[I] != B2[I] || (StopAtZero && B1[I] == 0))
392       break;
393   size_t PC = reinterpret_cast<size_t>(caller_pc);
394   size_t Idx = (PC & 4095) | (I << 12);
395   ValueProfileMap.AddValue(Idx);
396   TORCW.Insert(Idx ^ Hash, Word(B1, Len), Word(B2, Len));
397 }
398 
399 template <class T>
400 ATTRIBUTE_TARGET_POPCNT ALWAYS_INLINE
401 ATTRIBUTE_NO_SANITIZE_ALL
402 void TracePC::HandleCmp(uintptr_t PC, T Arg1, T Arg2) {
403   uint64_t ArgXor = Arg1 ^ Arg2;
404   uint64_t ArgDistance = __builtin_popcountll(ArgXor) + 1; // [1,65]
405   uintptr_t Idx = ((PC & 4095) + 1) * ArgDistance;
406   if (sizeof(T) == 4)
407       TORC4.Insert(ArgXor, Arg1, Arg2);
408   else if (sizeof(T) == 8)
409       TORC8.Insert(ArgXor, Arg1, Arg2);
410   // TODO: remove these flags and instead use all metrics at once.
411   if (UseValueProfileMask & 1)
412     ValueProfileMap.AddValue(Idx);
413   if (UseValueProfileMask & 2)
414     ValueProfileMap.AddValue(
415         PC * 64 + (Arg1 == Arg2 ? 0 : __builtin_clzll(Arg1 - Arg2) + 1));
416   if (UseValueProfileMask & 4)  // alternative way to use the hamming distance
417     ValueProfileMap.AddValue(PC * 64 + ArgDistance);
418 }
419 
420 static size_t InternalStrnlen(const char *S, size_t MaxLen) {
421   size_t Len = 0;
422   for (; Len < MaxLen && S[Len]; Len++) {}
423   return Len;
424 }
425 
426 // Finds min of (strlen(S1), strlen(S2)).
427 // Needed bacause one of these strings may actually be non-zero terminated.
428 static size_t InternalStrnlen2(const char *S1, const char *S2) {
429   size_t Len = 0;
430   for (; S1[Len] && S2[Len]; Len++)  {}
431   return Len;
432 }
433 
434 void TracePC::ClearInlineCounters() {
435   for (size_t i = 0; i < NumModulesWithInline8bitCounters; i++) {
436     uint8_t *Beg = ModuleCounters[i].Start;
437     size_t Size = ModuleCounters[i].Stop - Beg;
438     memset(Beg, 0, Size);
439   }
440 }
441 
442 ATTRIBUTE_NO_SANITIZE_ALL
443 void TracePC::RecordInitialStack() {
444   int stack;
445   __sancov_lowest_stack = InitialStack = reinterpret_cast<uintptr_t>(&stack);
446 }
447 
448 uintptr_t TracePC::GetMaxStackOffset() const {
449   return InitialStack - __sancov_lowest_stack;  // Stack grows down
450 }
451 
452 } // namespace fuzzer
453 
454 extern "C" {
455 ATTRIBUTE_INTERFACE
456 ATTRIBUTE_NO_SANITIZE_ALL
457 void __sanitizer_cov_trace_pc_guard(uint32_t *Guard) {
458   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
459   uint32_t Idx = *Guard;
460   __sancov_trace_pc_pcs[Idx] = PC;
461   __sancov_trace_pc_guard_8bit_counters[Idx]++;
462 }
463 
464 // Best-effort support for -fsanitize-coverage=trace-pc, which is available
465 // in both Clang and GCC.
466 ATTRIBUTE_INTERFACE
467 ATTRIBUTE_NO_SANITIZE_ALL
468 void __sanitizer_cov_trace_pc() {
469   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
470   uintptr_t Idx = PC & (((uintptr_t)1 << fuzzer::TracePC::kTracePcBits) - 1);
471   __sancov_trace_pc_pcs[Idx] = PC;
472   __sancov_trace_pc_guard_8bit_counters[Idx]++;
473 }
474 
475 ATTRIBUTE_INTERFACE
476 void __sanitizer_cov_trace_pc_guard_init(uint32_t *Start, uint32_t *Stop) {
477   fuzzer::TPC.HandleInit(Start, Stop);
478 }
479 
480 ATTRIBUTE_INTERFACE
481 void __sanitizer_cov_8bit_counters_init(uint8_t *Start, uint8_t *Stop) {
482   fuzzer::TPC.HandleInline8bitCountersInit(Start, Stop);
483 }
484 
485 ATTRIBUTE_INTERFACE
486 void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg,
487                               const uintptr_t *pcs_end) {
488   fuzzer::TPC.HandlePCsInit(pcs_beg, pcs_end);
489 }
490 
491 ATTRIBUTE_INTERFACE
492 ATTRIBUTE_NO_SANITIZE_ALL
493 void __sanitizer_cov_trace_pc_indir(uintptr_t Callee) {
494   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
495   fuzzer::TPC.HandleCallerCallee(PC, Callee);
496 }
497 
498 ATTRIBUTE_INTERFACE
499 ATTRIBUTE_NO_SANITIZE_ALL
500 ATTRIBUTE_TARGET_POPCNT
501 void __sanitizer_cov_trace_cmp8(uint64_t Arg1, uint64_t Arg2) {
502   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
503   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
504 }
505 
506 ATTRIBUTE_INTERFACE
507 ATTRIBUTE_NO_SANITIZE_ALL
508 ATTRIBUTE_TARGET_POPCNT
509 // Now the __sanitizer_cov_trace_const_cmp[1248] callbacks just mimic
510 // the behaviour of __sanitizer_cov_trace_cmp[1248] ones. This, however,
511 // should be changed later to make full use of instrumentation.
512 void __sanitizer_cov_trace_const_cmp8(uint64_t Arg1, uint64_t Arg2) {
513   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
514   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
515 }
516 
517 ATTRIBUTE_INTERFACE
518 ATTRIBUTE_NO_SANITIZE_ALL
519 ATTRIBUTE_TARGET_POPCNT
520 void __sanitizer_cov_trace_cmp4(uint32_t Arg1, uint32_t Arg2) {
521   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
522   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
523 }
524 
525 ATTRIBUTE_INTERFACE
526 ATTRIBUTE_NO_SANITIZE_ALL
527 ATTRIBUTE_TARGET_POPCNT
528 void __sanitizer_cov_trace_const_cmp4(uint32_t Arg1, uint32_t Arg2) {
529   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
530   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
531 }
532 
533 ATTRIBUTE_INTERFACE
534 ATTRIBUTE_NO_SANITIZE_ALL
535 ATTRIBUTE_TARGET_POPCNT
536 void __sanitizer_cov_trace_cmp2(uint16_t Arg1, uint16_t Arg2) {
537   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
538   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
539 }
540 
541 ATTRIBUTE_INTERFACE
542 ATTRIBUTE_NO_SANITIZE_ALL
543 ATTRIBUTE_TARGET_POPCNT
544 void __sanitizer_cov_trace_const_cmp2(uint16_t Arg1, uint16_t Arg2) {
545   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
546   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
547 }
548 
549 ATTRIBUTE_INTERFACE
550 ATTRIBUTE_NO_SANITIZE_ALL
551 ATTRIBUTE_TARGET_POPCNT
552 void __sanitizer_cov_trace_cmp1(uint8_t Arg1, uint8_t Arg2) {
553   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
554   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
555 }
556 
557 ATTRIBUTE_INTERFACE
558 ATTRIBUTE_NO_SANITIZE_ALL
559 ATTRIBUTE_TARGET_POPCNT
560 void __sanitizer_cov_trace_const_cmp1(uint8_t Arg1, uint8_t Arg2) {
561   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
562   fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
563 }
564 
565 ATTRIBUTE_INTERFACE
566 ATTRIBUTE_NO_SANITIZE_ALL
567 ATTRIBUTE_TARGET_POPCNT
568 void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) {
569   uint64_t N = Cases[0];
570   uint64_t ValSizeInBits = Cases[1];
571   uint64_t *Vals = Cases + 2;
572   // Skip the most common and the most boring case.
573   if (Vals[N - 1]  < 256 && Val < 256)
574     return;
575   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
576   size_t i;
577   uint64_t Token = 0;
578   for (i = 0; i < N; i++) {
579     Token = Val ^ Vals[i];
580     if (Val < Vals[i])
581       break;
582   }
583 
584   if (ValSizeInBits == 16)
585     fuzzer::TPC.HandleCmp(PC + i, static_cast<uint16_t>(Token), (uint16_t)(0));
586   else if (ValSizeInBits == 32)
587     fuzzer::TPC.HandleCmp(PC + i, static_cast<uint32_t>(Token), (uint32_t)(0));
588   else
589     fuzzer::TPC.HandleCmp(PC + i, Token, (uint64_t)(0));
590 }
591 
592 ATTRIBUTE_INTERFACE
593 ATTRIBUTE_NO_SANITIZE_ALL
594 ATTRIBUTE_TARGET_POPCNT
595 void __sanitizer_cov_trace_div4(uint32_t Val) {
596   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
597   fuzzer::TPC.HandleCmp(PC, Val, (uint32_t)0);
598 }
599 
600 ATTRIBUTE_INTERFACE
601 ATTRIBUTE_NO_SANITIZE_ALL
602 ATTRIBUTE_TARGET_POPCNT
603 void __sanitizer_cov_trace_div8(uint64_t Val) {
604   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
605   fuzzer::TPC.HandleCmp(PC, Val, (uint64_t)0);
606 }
607 
608 ATTRIBUTE_INTERFACE
609 ATTRIBUTE_NO_SANITIZE_ALL
610 ATTRIBUTE_TARGET_POPCNT
611 void __sanitizer_cov_trace_gep(uintptr_t Idx) {
612   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
613   fuzzer::TPC.HandleCmp(PC, Idx, (uintptr_t)0);
614 }
615 
616 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
617 void __sanitizer_weak_hook_memcmp(void *caller_pc, const void *s1,
618                                   const void *s2, size_t n, int result) {
619   if (!fuzzer::RunningUserCallback) return;
620   if (result == 0) return;  // No reason to mutate.
621   if (n <= 1) return;  // Not interesting.
622   fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/false);
623 }
624 
625 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
626 void __sanitizer_weak_hook_strncmp(void *caller_pc, const char *s1,
627                                    const char *s2, size_t n, int result) {
628   if (!fuzzer::RunningUserCallback) return;
629   if (result == 0) return;  // No reason to mutate.
630   size_t Len1 = fuzzer::InternalStrnlen(s1, n);
631   size_t Len2 = fuzzer::InternalStrnlen(s2, n);
632   n = std::min(n, Len1);
633   n = std::min(n, Len2);
634   if (n <= 1) return;  // Not interesting.
635   fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/true);
636 }
637 
638 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
639 void __sanitizer_weak_hook_strcmp(void *caller_pc, const char *s1,
640                                    const char *s2, int result) {
641   if (!fuzzer::RunningUserCallback) return;
642   if (result == 0) return;  // No reason to mutate.
643   size_t N = fuzzer::InternalStrnlen2(s1, s2);
644   if (N <= 1) return;  // Not interesting.
645   fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, N, /*StopAtZero*/true);
646 }
647 
648 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
649 void __sanitizer_weak_hook_strncasecmp(void *called_pc, const char *s1,
650                                        const char *s2, size_t n, int result) {
651   if (!fuzzer::RunningUserCallback) return;
652   return __sanitizer_weak_hook_strncmp(called_pc, s1, s2, n, result);
653 }
654 
655 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
656 void __sanitizer_weak_hook_strcasecmp(void *called_pc, const char *s1,
657                                       const char *s2, int result) {
658   if (!fuzzer::RunningUserCallback) return;
659   return __sanitizer_weak_hook_strcmp(called_pc, s1, s2, result);
660 }
661 
662 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
663 void __sanitizer_weak_hook_strstr(void *called_pc, const char *s1,
664                                   const char *s2, char *result) {
665   if (!fuzzer::RunningUserCallback) return;
666   fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), strlen(s2));
667 }
668 
669 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
670 void __sanitizer_weak_hook_strcasestr(void *called_pc, const char *s1,
671                                       const char *s2, char *result) {
672   if (!fuzzer::RunningUserCallback) return;
673   fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), strlen(s2));
674 }
675 
676 ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY
677 void __sanitizer_weak_hook_memmem(void *called_pc, const void *s1, size_t len1,
678                                   const void *s2, size_t len2, void *result) {
679   if (!fuzzer::RunningUserCallback) return;
680   fuzzer::TPC.MMT.Add(reinterpret_cast<const uint8_t *>(s2), len2);
681 }
682 }  // extern "C"
683