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