Bug Summary

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