Bug Summary

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