Bug Summary

File:compiler-rt/lib/fuzzer/FuzzerTracePC.cpp
Warning:line 419, column 1
Address of stack memory associated with local variable 'stack' is still referred to by the global variable '__sancov_lowest_stack' upon returning to the caller. This will be a dangling reference

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name FuzzerTracePC.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=all -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/projects/compiler-rt/lib/fuzzer -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/projects/compiler-rt/lib/fuzzer -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/fuzzer -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/fuzzer/../../include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O3 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-unused-parameter -Wno-variadic-macros -Wno-format-pedantic -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/projects/compiler-rt/lib/fuzzer -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -fno-builtin -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/compiler-rt/lib/fuzzer/FuzzerTracePC.cpp
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
28ATTRIBUTES_INTERFACE_TLS_INITIAL_EXEC__attribute__((visibility("default"))) __attribute__((tls_model
("initial-exec"))) thread_local
uintptr_t __sancov_lowest_stack;
29
30namespace fuzzer {
31
32TracePC TPC;
33
34size_t TracePC::GetTotalPCCoverage() {
35 return ObservedPCs.size();
36}
37
38
39void 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 <(static_cast<void> (0))
45 sizeof(Modules) / sizeof(Modules[0]))(static_cast<void> (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)(static_cast<void> (0));
55 M.Regions = new Module::Region[M.NumRegions];
56 assert(M.Regions)(static_cast<void> (0));
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)(static_cast<void> (0));
65 assert(M.Size() == (size_t)(Stop - Start))(static_cast<void> (0));
66 assert(M.Stop() == Stop)(static_cast<void> (0));
67 assert(M.Start() == Start)(static_cast<void> (0));
68 NumInline8bitCounters += M.Size();
69}
70
71void 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]))(static_cast<void> (0));
76 ModulePCTable[NumPCTables++] = {B, E};
77 NumPCsInPCTables += E - B;
78}
79
80void 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 size_t MaxFeatures = CollectFeatures([](uint32_t) {});
111 if (MaxFeatures > std::numeric_limits<uint32_t>::max())
112 Printf("WARNING: The coverage PC tables may produce up to %zu features.\n"
113 "This exceeds the maximum 32-bit value. Some features may be\n"
114 "ignored, and fuzzing may become less precise. If possible,\n"
115 "consider refactoring the fuzzer into several smaller fuzzers\n"
116 "linked against only a portion of the current target.\n",
117 MaxFeatures);
118}
119
120ATTRIBUTE_NO_SANITIZE_ALL
121void TracePC::HandleCallerCallee(uintptr_t Caller, uintptr_t Callee) {
122 const uintptr_t kBits = 12;
123 const uintptr_t kMask = (1 << kBits) - 1;
124 uintptr_t Idx = (Caller & kMask) | ((Callee & kMask) << kBits);
125 ValueProfileMap.AddValueModPrime(Idx);
126}
127
128/// \return the address of the previous instruction.
129/// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.h`
130inline ALWAYS_INLINE__attribute__((always_inline)) uintptr_t GetPreviousInstructionPc(uintptr_t PC) {
131#if defined(__arm__)
132 // T32 (Thumb) branch instructions might be 16 or 32 bit long,
133 // so we return (pc-2) in that case in order to be safe.
134 // For A32 mode we return (pc-4) because all instructions are 32 bit long.
135 return (PC - 3) & (~1);
136#elif defined(__powerpc__) || defined(__powerpc64__) || defined(__aarch64__)
137 // PCs are always 4 byte aligned.
138 return PC - 4;
139#elif defined(__sparc__) || defined(__mips__)
140 return PC - 8;
141#else
142 return PC - 1;
143#endif
144}
145
146/// \return the address of the next instruction.
147/// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.cpp`
148ALWAYS_INLINE__attribute__((always_inline)) uintptr_t TracePC::GetNextInstructionPc(uintptr_t PC) {
149#if defined(__mips__)
150 return PC + 8;
151#elif defined(__powerpc__) || defined(__sparc__) || defined(__arm__) || \
152 defined(__aarch64__)
153 return PC + 4;
154#else
155 return PC + 1;
156#endif
157}
158
159void TracePC::UpdateObservedPCs() {
160 std::vector<uintptr_t> CoveredFuncs;
161 auto ObservePC = [&](const PCTableEntry *TE) {
162 if (ObservedPCs.insert(TE).second && DoPrintNewPCs) {
163 PrintPC("\tNEW_PC: %p %F %L", "\tNEW_PC: %p",
164 GetNextInstructionPc(TE->PC));
165 Printf("\n");
166 }
167 };
168
169 auto Observe = [&](const PCTableEntry *TE) {
170 if (PcIsFuncEntry(TE))
171 if (++ObservedFuncs[TE->PC] == 1 && NumPrintNewFuncs)
172 CoveredFuncs.push_back(TE->PC);
173 ObservePC(TE);
174 };
175
176 if (NumPCsInPCTables) {
177 if (NumInline8bitCounters == NumPCsInPCTables) {
178 for (size_t i = 0; i < NumModules; i++) {
179 auto &M = Modules[i];
180 assert(M.Size() ==(static_cast<void> (0))
181 (size_t)(ModulePCTable[i].Stop - ModulePCTable[i].Start))(static_cast<void> (0));
182 for (size_t r = 0; r < M.NumRegions; r++) {
183 auto &R = M.Regions[r];
184 if (!R.Enabled) continue;
185 for (uint8_t *P = R.Start; P < R.Stop; P++)
186 if (*P)
187 Observe(&ModulePCTable[i].Start[M.Idx(P)]);
188 }
189 }
190 }
191 }
192
193 for (size_t i = 0, N = Min(CoveredFuncs.size(), NumPrintNewFuncs); i < N;
194 i++) {
195 Printf("\tNEW_FUNC[%zd/%zd]: ", i + 1, CoveredFuncs.size());
196 PrintPC("%p %F %L", "%p", GetNextInstructionPc(CoveredFuncs[i]));
197 Printf("\n");
198 }
199}
200
201uintptr_t TracePC::PCTableEntryIdx(const PCTableEntry *TE) {
202 size_t TotalTEs = 0;
203 for (size_t i = 0; i < NumPCTables; i++) {
204 auto &M = ModulePCTable[i];
205 if (TE >= M.Start && TE < M.Stop)
206 return TotalTEs + TE - M.Start;
207 TotalTEs += M.Stop - M.Start;
208 }
209 assert(0)(static_cast<void> (0));
210 return 0;
211}
212
213const TracePC::PCTableEntry *TracePC::PCTableEntryByIdx(uintptr_t Idx) {
214 for (size_t i = 0; i < NumPCTables; i++) {
215 auto &M = ModulePCTable[i];
216 size_t Size = M.Stop - M.Start;
217 if (Idx < Size) return &M.Start[Idx];
218 Idx -= Size;
219 }
220 return nullptr;
221}
222
223static std::string GetModuleName(uintptr_t PC) {
224 char ModulePathRaw[4096] = ""; // What's PATH_MAX in portable C++?
225 void *OffsetRaw = nullptr;
226 if (!EF->__sanitizer_get_module_and_offset_for_pc(
227 reinterpret_cast<void *>(PC), ModulePathRaw,
228 sizeof(ModulePathRaw), &OffsetRaw))
229 return "";
230 return ModulePathRaw;
231}
232
233template<class CallBack>
234void TracePC::IterateCoveredFunctions(CallBack CB) {
235 for (size_t i = 0; i < NumPCTables; i++) {
236 auto &M = ModulePCTable[i];
237 assert(M.Start < M.Stop)(static_cast<void> (0));
238 auto ModuleName = GetModuleName(M.Start->PC);
239 for (auto NextFE = M.Start; NextFE < M.Stop; ) {
240 auto FE = NextFE;
241 assert(PcIsFuncEntry(FE) && "Not a function entry point")(static_cast<void> (0));
242 do {
243 NextFE++;
244 } while (NextFE < M.Stop && !(PcIsFuncEntry(NextFE)));
245 CB(FE, NextFE, ObservedFuncs[FE->PC]);
246 }
247 }
248}
249
250void TracePC::SetFocusFunction(const std::string &FuncName) {
251 // This function should be called once.
252 assert(!FocusFunctionCounterPtr)(static_cast<void> (0));
253 // "auto" is not a valid function name. If this function is called with "auto"
254 // that means the auto focus functionality failed.
255 if (FuncName.empty() || FuncName == "auto")
256 return;
257 for (size_t M = 0; M < NumModules; M++) {
258 auto &PCTE = ModulePCTable[M];
259 size_t N = PCTE.Stop - PCTE.Start;
260 for (size_t I = 0; I < N; I++) {
261 if (!(PcIsFuncEntry(&PCTE.Start[I]))) continue; // not a function entry.
262 auto Name = DescribePC("%F", GetNextInstructionPc(PCTE.Start[I].PC));
263 if (Name[0] == 'i' && Name[1] == 'n' && Name[2] == ' ')
264 Name = Name.substr(3, std::string::npos);
265 if (FuncName != Name) continue;
266 Printf("INFO: Focus function is set to '%s'\n", Name.c_str());
267 FocusFunctionCounterPtr = Modules[M].Start() + I;
268 return;
269 }
270 }
271
272 Printf("ERROR: Failed to set focus function. Make sure the function name is "
273 "valid (%s) and symbolization is enabled.\n", FuncName.c_str());
274 exit(1);
275}
276
277bool TracePC::ObservedFocusFunction() {
278 return FocusFunctionCounterPtr && *FocusFunctionCounterPtr;
279}
280
281void TracePC::PrintCoverage(bool PrintAllCounters) {
282 if (!EF->__sanitizer_symbolize_pc ||
283 !EF->__sanitizer_get_module_and_offset_for_pc) {
284 Printf("INFO: __sanitizer_symbolize_pc or "
285 "__sanitizer_get_module_and_offset_for_pc is not available,"
286 " not printing coverage\n");
287 return;
288 }
289 Printf(PrintAllCounters ? "FULL COVERAGE:\n" : "COVERAGE:\n");
290 auto CoveredFunctionCallback = [&](const PCTableEntry *First,
291 const PCTableEntry *Last,
292 uintptr_t Counter) {
293 assert(First < Last)(static_cast<void> (0));
294 auto VisualizePC = GetNextInstructionPc(First->PC);
295 std::string FileStr = DescribePC("%s", VisualizePC);
296 if (!IsInterestingCoverageFile(FileStr))
297 return;
298 std::string FunctionStr = DescribePC("%F", VisualizePC);
299 if (FunctionStr.find("in ") == 0)
300 FunctionStr = FunctionStr.substr(3);
301 std::string LineStr = DescribePC("%l", VisualizePC);
302 size_t NumEdges = Last - First;
303 std::vector<uintptr_t> UncoveredPCs;
304 std::vector<uintptr_t> CoveredPCs;
305 for (auto TE = First; TE < Last; TE++)
306 if (!ObservedPCs.count(TE))
307 UncoveredPCs.push_back(TE->PC);
308 else
309 CoveredPCs.push_back(TE->PC);
310
311 if (PrintAllCounters) {
312 Printf("U");
313 for (auto PC : UncoveredPCs)
314 Printf(DescribePC(" %l", GetNextInstructionPc(PC)).c_str());
315 Printf("\n");
316
317 Printf("C");
318 for (auto PC : CoveredPCs)
319 Printf(DescribePC(" %l", GetNextInstructionPc(PC)).c_str());
320 Printf("\n");
321 } else {
322 Printf("%sCOVERED_FUNC: hits: %zd", Counter ? "" : "UN", Counter);
323 Printf(" edges: %zd/%zd", NumEdges - UncoveredPCs.size(), NumEdges);
324 Printf(" %s %s:%s\n", FunctionStr.c_str(), FileStr.c_str(),
325 LineStr.c_str());
326 if (Counter)
327 for (auto PC : UncoveredPCs)
328 Printf(" UNCOVERED_PC: %s\n",
329 DescribePC("%s:%l", GetNextInstructionPc(PC)).c_str());
330 }
331 };
332
333 IterateCoveredFunctions(CoveredFunctionCallback);
334}
335
336// Value profile.
337// We keep track of various values that affect control flow.
338// These values are inserted into a bit-set-based hash map.
339// Every new bit in the map is treated as a new coverage.
340//
341// For memcmp/strcmp/etc the interesting value is the length of the common
342// prefix of the parameters.
343// For cmp instructions the interesting value is a XOR of the parameters.
344// The interesting value is mixed up with the PC and is then added to the map.
345
346ATTRIBUTE_NO_SANITIZE_ALL
347void TracePC::AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
348 size_t n, bool StopAtZero) {
349 if (!n) return;
350 size_t Len = std::min(n, Word::GetMaxSize());
351 const uint8_t *A1 = reinterpret_cast<const uint8_t *>(s1);
352 const uint8_t *A2 = reinterpret_cast<const uint8_t *>(s2);
353 uint8_t B1[Word::kMaxSize];
354 uint8_t B2[Word::kMaxSize];
355 // Copy the data into locals in this non-msan-instrumented function
356 // to avoid msan complaining further.
357 size_t Hash = 0; // Compute some simple hash of both strings.
358 for (size_t i = 0; i < Len; i++) {
359 B1[i] = A1[i];
360 B2[i] = A2[i];
361 size_t T = B1[i];
362 Hash ^= (T << 8) | B2[i];
363 }
364 size_t I = 0;
365 uint8_t HammingDistance = 0;
366 for (; I < Len; I++) {
367 if (B1[I] != B2[I] || (StopAtZero && B1[I] == 0)) {
368 HammingDistance = static_cast<uint8_t>(Popcountll(B1[I] ^ B2[I]));
369 break;
370 }
371 }
372 size_t PC = reinterpret_cast<size_t>(caller_pc);
373 size_t Idx = (PC & 4095) | (I << 12);
374 Idx += HammingDistance;
375 ValueProfileMap.AddValue(Idx);
376 TORCW.Insert(Idx ^ Hash, Word(B1, Len), Word(B2, Len));
377}
378
379template <class T>
380ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt"))) ALWAYS_INLINE__attribute__((always_inline))
381ATTRIBUTE_NO_SANITIZE_ALL
382void TracePC::HandleCmp(uintptr_t PC, T Arg1, T Arg2) {
383 uint64_t ArgXor = Arg1 ^ Arg2;
384 if (sizeof(T) == 4)
385 TORC4.Insert(ArgXor, Arg1, Arg2);
386 else if (sizeof(T) == 8)
387 TORC8.Insert(ArgXor, Arg1, Arg2);
388 uint64_t HammingDistance = Popcountll(ArgXor); // [0,64]
389 uint64_t AbsoluteDistance = (Arg1 == Arg2 ? 0 : Clzll(Arg1 - Arg2) + 1);
390 ValueProfileMap.AddValue(PC * 128 + HammingDistance);
391 ValueProfileMap.AddValue(PC * 128 + 64 + AbsoluteDistance);
392}
393
394static size_t InternalStrnlen(const char *S, size_t MaxLen) {
395 size_t Len = 0;
396 for (; Len < MaxLen && S[Len]; Len++) {}
397 return Len;
398}
399
400// Finds min of (strlen(S1), strlen(S2)).
401// Needed bacause one of these strings may actually be non-zero terminated.
402static size_t InternalStrnlen2(const char *S1, const char *S2) {
403 size_t Len = 0;
404 for (; S1[Len] && S2[Len]; Len++) {}
405 return Len;
406}
407
408void TracePC::ClearInlineCounters() {
409 IterateCounterRegions([](const Module::Region &R){
410 if (R.Enabled)
411 memset(R.Start, 0, R.Stop - R.Start);
412 });
413}
414
415ATTRIBUTE_NO_SANITIZE_ALL
416void TracePC::RecordInitialStack() {
417 int stack;
418 __sancov_lowest_stack = InitialStack = reinterpret_cast<uintptr_t>(&stack);
419}
Address of stack memory associated with local variable 'stack' is still referred to by the global variable '__sancov_lowest_stack' upon returning to the caller. This will be a dangling reference
420
421uintptr_t TracePC::GetMaxStackOffset() const {
422 return InitialStack - __sancov_lowest_stack; // Stack grows down
423}
424
425void WarnAboutDeprecatedInstrumentation(const char *flag) {
426 // Use RawPrint because Printf cannot be used on Windows before OutputFile is
427 // initialized.
428 RawPrint(flag);
429 RawPrint(
430 " is no longer supported by libFuzzer.\n"
431 "Please either migrate to a compiler that supports -fsanitize=fuzzer\n"
432 "or use an older version of libFuzzer\n");
433 exit(1);
434}
435
436} // namespace fuzzer
437
438extern "C" {
439ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
440ATTRIBUTE_NO_SANITIZE_ALL
441void __sanitizer_cov_trace_pc_guard(uint32_t *Guard) {
442 fuzzer::WarnAboutDeprecatedInstrumentation(
443 "-fsanitize-coverage=trace-pc-guard");
444}
445
446// Best-effort support for -fsanitize-coverage=trace-pc, which is available
447// in both Clang and GCC.
448ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
449ATTRIBUTE_NO_SANITIZE_ALL
450void __sanitizer_cov_trace_pc() {
451 fuzzer::WarnAboutDeprecatedInstrumentation("-fsanitize-coverage=trace-pc");
452}
453
454ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
455void __sanitizer_cov_trace_pc_guard_init(uint32_t *Start, uint32_t *Stop) {
456 fuzzer::WarnAboutDeprecatedInstrumentation(
457 "-fsanitize-coverage=trace-pc-guard");
458}
459
460ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
461void __sanitizer_cov_8bit_counters_init(uint8_t *Start, uint8_t *Stop) {
462 fuzzer::TPC.HandleInline8bitCountersInit(Start, Stop);
463}
464
465ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
466void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg,
467 const uintptr_t *pcs_end) {
468 fuzzer::TPC.HandlePCsInit(pcs_beg, pcs_end);
469}
470
471ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
472ATTRIBUTE_NO_SANITIZE_ALL
473void __sanitizer_cov_trace_pc_indir(uintptr_t Callee) {
474 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
475 fuzzer::TPC.HandleCallerCallee(PC, Callee);
476}
477
478ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
479ATTRIBUTE_NO_SANITIZE_ALL
480ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
481void __sanitizer_cov_trace_cmp8(uint64_t Arg1, uint64_t Arg2) {
482 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
483 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
484}
485
486ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
487ATTRIBUTE_NO_SANITIZE_ALL
488ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
489// Now the __sanitizer_cov_trace_const_cmp[1248] callbacks just mimic
490// the behaviour of __sanitizer_cov_trace_cmp[1248] ones. This, however,
491// should be changed later to make full use of instrumentation.
492void __sanitizer_cov_trace_const_cmp8(uint64_t Arg1, uint64_t Arg2) {
493 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
494 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
495}
496
497ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
498ATTRIBUTE_NO_SANITIZE_ALL
499ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
500void __sanitizer_cov_trace_cmp4(uint32_t Arg1, uint32_t Arg2) {
501 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
502 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
503}
504
505ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
506ATTRIBUTE_NO_SANITIZE_ALL
507ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
508void __sanitizer_cov_trace_const_cmp4(uint32_t Arg1, uint32_t Arg2) {
509 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
510 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
511}
512
513ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
514ATTRIBUTE_NO_SANITIZE_ALL
515ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
516void __sanitizer_cov_trace_cmp2(uint16_t Arg1, uint16_t Arg2) {
517 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
518 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
519}
520
521ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
522ATTRIBUTE_NO_SANITIZE_ALL
523ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
524void __sanitizer_cov_trace_const_cmp2(uint16_t Arg1, uint16_t Arg2) {
525 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
526 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
527}
528
529ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
530ATTRIBUTE_NO_SANITIZE_ALL
531ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
532void __sanitizer_cov_trace_cmp1(uint8_t Arg1, uint8_t Arg2) {
533 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
534 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
535}
536
537ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
538ATTRIBUTE_NO_SANITIZE_ALL
539ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
540void __sanitizer_cov_trace_const_cmp1(uint8_t Arg1, uint8_t Arg2) {
541 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
542 fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
543}
544
545ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
546ATTRIBUTE_NO_SANITIZE_ALL
547ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
548void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) {
549 uint64_t N = Cases[0];
550 uint64_t ValSizeInBits = Cases[1];
551 uint64_t *Vals = Cases + 2;
552 // Skip the most common and the most boring case: all switch values are small.
553 // We may want to skip this at compile-time, but it will make the
554 // instrumentation less general.
555 if (Vals[N - 1] < 256)
556 return;
557 // Also skip small inputs values, they won't give good signal.
558 if (Val < 256)
559 return;
560 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
561 size_t i;
562 uint64_t Smaller = 0;
563 uint64_t Larger = ~(uint64_t)0;
564 // Find two switch values such that Smaller < Val < Larger.
565 // Use 0 and 0xfff..f as the defaults.
566 for (i = 0; i < N; i++) {
567 if (Val < Vals[i]) {
568 Larger = Vals[i];
569 break;
570 }
571 if (Val > Vals[i]) Smaller = Vals[i];
572 }
573
574 // Apply HandleCmp to {Val,Smaller} and {Val, Larger},
575 // use i as the PC modifier for HandleCmp.
576 if (ValSizeInBits == 16) {
577 fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint16_t>(Val),
578 (uint16_t)(Smaller));
579 fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint16_t>(Val),
580 (uint16_t)(Larger));
581 } else if (ValSizeInBits == 32) {
582 fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint32_t>(Val),
583 (uint32_t)(Smaller));
584 fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint32_t>(Val),
585 (uint32_t)(Larger));
586 } else {
587 fuzzer::TPC.HandleCmp(PC + 2*i, Val, Smaller);
588 fuzzer::TPC.HandleCmp(PC + 2*i + 1, Val, Larger);
589 }
590}
591
592ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
593ATTRIBUTE_NO_SANITIZE_ALL
594ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
595void __sanitizer_cov_trace_div4(uint32_t Val) {
596 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
597 fuzzer::TPC.HandleCmp(PC, Val, (uint32_t)0);
598}
599
600ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
601ATTRIBUTE_NO_SANITIZE_ALL
602ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
603void __sanitizer_cov_trace_div8(uint64_t Val) {
604 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
605 fuzzer::TPC.HandleCmp(PC, Val, (uint64_t)0);
606}
607
608ATTRIBUTE_INTERFACE__attribute__((visibility("default")))
609ATTRIBUTE_NO_SANITIZE_ALL
610ATTRIBUTE_TARGET_POPCNT__attribute__((target("popcnt")))
611void __sanitizer_cov_trace_gep(uintptr_t Idx) {
612 uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC()__builtin_return_address(0));
613 fuzzer::TPC.HandleCmp(PC, Idx, (uintptr_t)0);
614}
615
616ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
617void __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
625ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
626void __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
638ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
639void __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
648ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
649void __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
655ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
656void __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
662ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
663void __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
669ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
670void __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
676ATTRIBUTE_INTERFACE__attribute__((visibility("default"))) ATTRIBUTE_NO_SANITIZE_MEMORY__attribute__((no_sanitize("memory")))
677void __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"