Bug Summary

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