//===- FuzzerTracePC.cpp - PC tracing--------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // Trace PCs. // This module implements __sanitizer_cov_trace_pc_guard[_init], // the callback required for -fsanitize-coverage=trace-pc-guard instrumentation. // //===----------------------------------------------------------------------===//
void TracePC::PrintModuleInfo() { if (NumModules) {
Printf("INFO: Loaded %zd modules (%zd inline 8-bit counters): ",
NumModules, NumInline8bitCounters); for (size_t i = 0; i < NumModules; i++)
Printf("%zd [%p, %p), ", Modules[i].Size(), Modules[i].Start(),
Modules[i].Stop());
Printf("\n");
} if (NumPCTables) {
Printf("INFO: Loaded %zd PC tables (%zd PCs): ", NumPCTables,
NumPCsInPCTables); for (size_t i = 0; i < NumPCTables; i++) {
Printf("%zd [%p,%p), ", ModulePCTable[i].Stop - ModulePCTable[i].Start,
ModulePCTable[i].Start, ModulePCTable[i].Stop);
}
Printf("\n");
if (NumInline8bitCounters && NumInline8bitCounters != NumPCsInPCTables) {
Printf("ERROR: The size of coverage PC tables does not match the\n" "number of instrumented PCs. This might be a compiler bug,\n" "please contact the libFuzzer developers.\n" "Also check https://bugs.llvm.org/show_bug.cgi?id=34636\n" "for possible workarounds (tl;dr: don't use the old GNU ld)\n");
_Exit(1);
}
} if (size_t NumExtraCounters = ExtraCountersEnd() - ExtraCountersBegin())
Printf("INFO: %zd Extra Counters\n", NumExtraCounters);
}
/// \return the address of the previous instruction. /// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.h` inline ALWAYS_INLINE uintptr_t GetPreviousInstructionPc(uintptr_t PC) { #ifdefined(__arm__) // T32 (Thumb) branch instructions might be 16 or 32 bit long, // so we return (pc-2) in that case in order to be safe. // For A32 mode we return (pc-4) because all instructions are 32 bit long. return (PC - 3) & (~1); #elifdefined(__powerpc__) || defined(__powerpc64__) || defined(__aarch64__) // PCs are always 4 byte aligned. return PC - 4; #elifdefined(__sparc__) || defined(__mips__) return PC - 8; #else return PC - 1; #endif
}
/// \return the address of the next instruction. /// Note: the logic is copied from `sanitizer_common/sanitizer_stacktrace.cpp`
ALWAYS_INLINE uintptr_t TracePC::GetNextInstructionPc(uintptr_t PC) { #ifdefined(__mips__) return PC + 8; #elifdefined(__powerpc__) || defined(__sparc__) || defined(__arm__) || \ defined(__aarch64__) return PC + 4; #else return PC + 1; #endif
}
auto Observe = [&](const PCTableEntry *TE) { if (PcIsFuncEntry(TE)) if (++ObservedFuncs[TE->PC] == 1 && NumPrintNewFuncs)
CoveredFuncs.push_back(TE->PC);
ObservePC(TE);
};
if (NumPCsInPCTables) { if (NumInline8bitCounters == NumPCsInPCTables) { for (size_t i = 0; i < NumModules; i++) { auto &M = Modules[i];
assert(M.Size() ==
(size_t)(ModulePCTable[i].Stop - ModulePCTable[i].Start)); for (size_t r = 0; r < M.NumRegions; r++) { auto &R = M.Regions[r]; if (!R.Enabled) continue; for (uint8_t *P = R.Start; P < R.Stop; P++) if (*P)
Observe(&ModulePCTable[i].Start[M.Idx(P)]);
}
}
}
}
for (size_t i = 0, N = Min(CoveredFuncs.size(), NumPrintNewFuncs); i < N;
i++) {
Printf("\tNEW_FUNC[%zd/%zd]: ", i + 1, CoveredFuncs.size());
PrintPC("%p %F %L", "%p", GetNextInstructionPc(CoveredFuncs[i]));
Printf("\n");
}
}
uintptr_t TracePC::PCTableEntryIdx(const PCTableEntry *TE) {
size_t TotalTEs = 0; for (size_t i = 0; i < NumPCTables; i++) { auto &M = ModulePCTable[i]; if (TE >= M.Start && TE < M.Stop) return TotalTEs + TE - M.Start;
TotalTEs += M.Stop - M.Start;
}
assert(0); return 0;
}
const TracePC::PCTableEntry *TracePC::PCTableEntryByIdx(uintptr_t Idx) { for (size_t i = 0; i < NumPCTables; i++) { auto &M = ModulePCTable[i];
size_t Size = M.Stop - M.Start; if (Idx < Size) return &M.Start[Idx];
Idx -= Size;
} return nullptr;
}
template<class CallBack> void TracePC::IterateCoveredFunctions(CallBack CB) { for (size_t i = 0; i < NumPCTables; i++) { auto &M = ModulePCTable[i];
assert(M.Start < M.Stop); auto ModuleName = GetModuleName(M.Start->PC); for (auto NextFE = M.Start; NextFE < M.Stop; ) { auto FE = NextFE;
assert(PcIsFuncEntry(FE) && "Not a function entry point"); do {
NextFE++;
} while (NextFE < M.Stop && !(PcIsFuncEntry(NextFE)));
CB(FE, NextFE, ObservedFuncs[FE->PC]);
}
}
}
int TracePC::SetFocusFunction(const std::string &FuncName) { // This function should be called once.
assert(!FocusFunctionCounterPtr); // "auto" is not a valid function name. If this function is called with "auto" // that means the auto focus functionality failed. if (FuncName.empty() || FuncName == "auto") return 0; for (size_t M = 0; M < NumModules; M++) { auto &PCTE = ModulePCTable[M];
size_t N = PCTE.Stop - PCTE.Start; for (size_t I = 0; I < N; I++) { if (!(PcIsFuncEntry(&PCTE.Start[I]))) continue; // not a function entry. auto Name = DescribePC("%F", GetNextInstructionPc(PCTE.Start[I].PC)); if (Name[0] == 'i' && Name[1] == 'n' && Name[2] == ' ')
Name = Name.substr(3, std::string::npos); if (FuncName != Name) continue;
Printf("INFO: Focus function is set to '%s'\n", Name.c_str());
FocusFunctionCounterPtr = Modules[M].Start() + I; return 0;
}
}
Printf("ERROR: Failed to set focus function. Make sure the function name is " "valid (%s) and symbolization is enabled.\n", FuncName.c_str()); return 1;
}
// Value profile. // We keep track of various values that affect control flow. // These values are inserted into a bit-set-based hash map. // Every new bit in the map is treated as a new coverage. // // For memcmp/strcmp/etc the interesting value is the length of the common // prefix of the parameters. // For cmp instructions the interesting value is a XOR of the parameters. // The interesting value is mixed up with the PC and is then added to the map.
ATTRIBUTE_NO_SANITIZE_ALL void TracePC::AddValueForMemcmp(void *caller_pc, constvoid *s1, constvoid *s2,
size_t n, bool StopAtZero) { if (!n) return;
size_t Len = std::min(n, Word::GetMaxSize()); const uint8_t *A1 = reinterpret_cast<const uint8_t *>(s1); const uint8_t *A2 = reinterpret_cast<const uint8_t *>(s2);
uint8_t B1[Word::kMaxSize];
uint8_t B2[Word::kMaxSize]; // Copy the data into locals in this non-msan-instrumented function // to avoid msan complaining further.
size_t Hash = 0; // Compute some simple hash of both strings. for (size_t i = 0; i < Len; i++) {
B1[i] = A1[i];
B2[i] = A2[i];
size_t T = B1[i];
Hash ^= (T << 8) | B2[i];
}
size_t I = 0;
uint8_t HammingDistance = 0; for (; I < Len; I++) { if (B1[I] != B2[I] || (StopAtZero && B1[I] == 0)) {
HammingDistance = Popcountll(B1[I] ^ B2[I]); break;
}
}
size_t PC = reinterpret_cast<size_t>(caller_pc);
size_t Idx = (PC & 4095) | (I << 12);
Idx += HammingDistance;
ValueProfileMap.AddValue(Idx);
TORCW.Insert(Idx ^ Hash, Word(B1, Len), Word(B2, Len));
}
static size_t InternalStrnlen(constchar *S, size_t MaxLen) {
size_t Len = 0; for (; Len < MaxLen && S[Len]; Len++) {} return Len;
}
// Finds min of (strlen(S1), strlen(S2)). // Needed bacause one of these strings may actually be non-zero terminated. static size_t InternalStrnlen2(constchar *S1, constchar *S2) {
size_t Len = 0; for (; S1[Len] && S2[Len]; Len++) {} return Len;
}
void WarnAboutDeprecatedInstrumentation(constchar *flag) { // Use RawPrint because Printf cannot be used on Windows before OutputFile is // initialized.
RawPrint(flag);
RawPrint( " is no longer supported by libFuzzer.\n" "Please either migrate to a compiler that supports -fsanitize=fuzzer\n" "or use an older version of libFuzzer\n"); exit(1);
}
// Best-effort support for -fsanitize-coverage=trace-pc, which is available // in both Clang and GCC.
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL void __sanitizer_cov_trace_pc() {
fuzzer::WarnAboutDeprecatedInstrumentation("-fsanitize-coverage=trace-pc");
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT // Now the __sanitizer_cov_trace_const_cmp[1248] callbacks just mimic // the behaviour of __sanitizer_cov_trace_cmp[1248] ones. This, however, // should be changed later to make full use of instrumentation. void __sanitizer_cov_trace_const_cmp8(uint64_t Arg1, uint64_t Arg2) {
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
fuzzer::TPC.HandleCmp(PC, Arg1, Arg2);
}
ATTRIBUTE_INTERFACE
ATTRIBUTE_NO_SANITIZE_ALL
ATTRIBUTE_TARGET_POPCNT void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) {
uint64_t N = Cases[0];
uint64_t ValSizeInBits = Cases[1];
uint64_t *Vals = Cases + 2; // Skip the most common and the most boring case: all switch values are small. // We may want to skip this at compile-time, but it will make the // instrumentation less general. if (Vals[N - 1] < 256) return; // Also skip small inputs values, they won't give good signal. if (Val < 256) return;
uintptr_t PC = reinterpret_cast<uintptr_t>(GET_CALLER_PC());
size_t i;
uint64_t Smaller = 0;
uint64_t Larger = ~(uint64_t)0; // Find two switch values such that Smaller < Val < Larger. // Use 0 and 0xfff..f as the defaults. for (i = 0; i < N; i++) { if (Val < Vals[i]) {
Larger = Vals[i]; break;
} if (Val > Vals[i]) Smaller = Vals[i];
}
// Apply HandleCmp to {Val,Smaller} and {Val, Larger}, // use i as the PC modifier for HandleCmp. if (ValSizeInBits == 16) {
fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint16_t>(Val),
(uint16_t)(Smaller));
fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint16_t>(Val),
(uint16_t)(Larger));
} elseif (ValSizeInBits == 32) {
fuzzer::TPC.HandleCmp(PC + 2 * i, static_cast<uint32_t>(Val),
(uint32_t)(Smaller));
fuzzer::TPC.HandleCmp(PC + 2 * i + 1, static_cast<uint32_t>(Val),
(uint32_t)(Larger));
} else {
fuzzer::TPC.HandleCmp(PC + 2*i, Val, Smaller);
fuzzer::TPC.HandleCmp(PC + 2*i + 1, Val, Larger);
}
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void __sanitizer_weak_hook_memcmp(void *caller_pc, constvoid *s1, constvoid *s2, size_t n, int result) { if (!fuzzer::RunningUserCallback) return; if (result == 0) return; // No reason to mutate. if (n <= 1) return; // Not interesting.
fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/false);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void __sanitizer_weak_hook_strncmp(void *caller_pc, constchar *s1, constchar *s2, size_t n, int result) { if (!fuzzer::RunningUserCallback) return; if (result == 0) return; // No reason to mutate.
size_t Len1 = fuzzer::InternalStrnlen(s1, n);
size_t Len2 = fuzzer::InternalStrnlen(s2, n);
n = std::min(n, Len1);
n = std::min(n, Len2); if (n <= 1) return; // Not interesting.
fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, n, /*StopAtZero*/true);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void __sanitizer_weak_hook_strcmp(void *caller_pc, constchar *s1, constchar *s2, int result) { if (!fuzzer::RunningUserCallback) return; if (result == 0) return; // No reason to mutate.
size_t N = fuzzer::InternalStrnlen2(s1, s2); if (N <= 1) return; // Not interesting.
fuzzer::TPC.AddValueForMemcmp(caller_pc, s1, s2, N, /*StopAtZero*/true);
}
ATTRIBUTE_INTERFACE ATTRIBUTE_NO_SANITIZE_MEMORY void __sanitizer_weak_hook_strncasecmp(void *called_pc, constchar *s1, constchar *s2, size_t n, int result) { if (!fuzzer::RunningUserCallback) return; return __sanitizer_weak_hook_strncmp(called_pc, s1, s2, n, result);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.