Path: blob/main/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerTracePC.h
35262 views
//===- FuzzerTracePC.h - Internal header for the Fuzzer ---------*- C++ -* ===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7// fuzzer::TracePC8//===----------------------------------------------------------------------===//910#ifndef LLVM_FUZZER_TRACE_PC11#define LLVM_FUZZER_TRACE_PC1213#include "FuzzerDefs.h"14#include "FuzzerDictionary.h"15#include "FuzzerValueBitMap.h"1617#include <set>18#include <unordered_map>1920namespace fuzzer {2122// TableOfRecentCompares (TORC) remembers the most recently performed23// comparisons of type T.24// We record the arguments of CMP instructions in this table unconditionally25// because it seems cheaper this way than to compute some expensive26// conditions inside __sanitizer_cov_trace_cmp*.27// After the unit has been executed we may decide to use the contents of28// this table to populate a Dictionary.29template<class T, size_t kSizeT>30struct TableOfRecentCompares {31static const size_t kSize = kSizeT;32struct Pair {33T A, B;34};35ATTRIBUTE_NO_SANITIZE_ALL36void Insert(size_t Idx, const T &Arg1, const T &Arg2) {37Idx = Idx % kSize;38Table[Idx].A = Arg1;39Table[Idx].B = Arg2;40}4142Pair Get(size_t I) { return Table[I % kSize]; }4344Pair Table[kSize];45};4647template <size_t kSizeT>48struct MemMemTable {49static const size_t kSize = kSizeT;50Word MemMemWords[kSize];51Word EmptyWord;5253void Add(const uint8_t *Data, size_t Size) {54if (Size <= 2) return;55Size = std::min(Size, Word::GetMaxSize());56auto Idx = SimpleFastHash(Data, Size) % kSize;57MemMemWords[Idx].Set(Data, Size);58}59const Word &Get(size_t Idx) {60for (size_t i = 0; i < kSize; i++) {61const Word &W = MemMemWords[(Idx + i) % kSize];62if (W.size()) return W;63}64EmptyWord.Set(nullptr, 0);65return EmptyWord;66}67};6869class TracePC {70public:71void HandleInline8bitCountersInit(uint8_t *Start, uint8_t *Stop);72void HandlePCsInit(const uintptr_t *Start, const uintptr_t *Stop);73void HandleCallerCallee(uintptr_t Caller, uintptr_t Callee);74template <class T> void HandleCmp(uintptr_t PC, T Arg1, T Arg2);75size_t GetTotalPCCoverage();76void SetUseCounters(bool UC) { UseCounters = UC; }77void SetUseValueProfileMask(uint32_t VPMask) { UseValueProfileMask = VPMask; }78void SetPrintNewPCs(bool P) { DoPrintNewPCs = P; }79void SetPrintNewFuncs(size_t P) { NumPrintNewFuncs = P; }80void UpdateObservedPCs();81template <class Callback> size_t CollectFeatures(Callback CB) const;8283void ResetMaps() {84ValueProfileMap.Reset();85ClearExtraCounters();86ClearInlineCounters();87}8889void ClearInlineCounters();9091void UpdateFeatureSet(size_t CurrentElementIdx, size_t CurrentElementSize);92void PrintFeatureSet();9394void PrintModuleInfo();9596void PrintCoverage(bool PrintAllCounters);9798template<class CallBack>99void IterateCoveredFunctions(CallBack CB);100101void AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,102size_t n, bool StopAtZero);103104TableOfRecentCompares<uint32_t, 32> TORC4;105TableOfRecentCompares<uint64_t, 32> TORC8;106TableOfRecentCompares<Word, 32> TORCW;107MemMemTable<1024> MMT;108109void RecordInitialStack();110uintptr_t GetMaxStackOffset() const;111112template<class CallBack>113void ForEachObservedPC(CallBack CB) {114for (auto PC : ObservedPCs)115CB(PC);116}117118void SetFocusFunction(const std::string &FuncName);119bool ObservedFocusFunction();120121struct PCTableEntry {122uintptr_t PC, PCFlags;123};124125uintptr_t PCTableEntryIdx(const PCTableEntry *TE);126const PCTableEntry *PCTableEntryByIdx(uintptr_t Idx);127static uintptr_t GetNextInstructionPc(uintptr_t PC);128bool PcIsFuncEntry(const PCTableEntry *TE) { return TE->PCFlags & 1; }129130private:131bool UseCounters = false;132uint32_t UseValueProfileMask = false;133bool DoPrintNewPCs = false;134size_t NumPrintNewFuncs = 0;135136// Module represents the array of 8-bit counters split into regions137// such that every region, except maybe the first and the last one, is one138// full page.139struct Module {140struct Region {141uint8_t *Start, *Stop;142bool Enabled;143bool OneFullPage;144};145Region *Regions;146size_t NumRegions;147uint8_t *Start() { return Regions[0].Start; }148uint8_t *Stop() { return Regions[NumRegions - 1].Stop; }149size_t Size() { return Stop() - Start(); }150size_t Idx(uint8_t *P) {151assert(P >= Start() && P < Stop());152return P - Start();153}154};155156Module Modules[4096];157size_t NumModules; // linker-initialized.158size_t NumInline8bitCounters;159160template <class Callback>161void IterateCounterRegions(Callback CB) {162for (size_t m = 0; m < NumModules; m++)163for (size_t r = 0; r < Modules[m].NumRegions; r++)164CB(Modules[m].Regions[r]);165}166167struct { const PCTableEntry *Start, *Stop; } ModulePCTable[4096];168size_t NumPCTables;169size_t NumPCsInPCTables;170171std::set<const PCTableEntry *> ObservedPCs;172std::unordered_map<uintptr_t, uintptr_t> ObservedFuncs; // PC => Counter.173174uint8_t *FocusFunctionCounterPtr = nullptr;175176ValueBitMap ValueProfileMap;177uintptr_t InitialStack;178};179180template <class Callback>181// void Callback(size_t FirstFeature, size_t Idx, uint8_t Value);182ATTRIBUTE_NO_SANITIZE_ALL183size_t ForEachNonZeroByte(const uint8_t *Begin, const uint8_t *End,184size_t FirstFeature, Callback Handle8bitCounter) {185typedef uintptr_t LargeType;186const size_t Step = sizeof(LargeType) / sizeof(uint8_t);187const size_t StepMask = Step - 1;188auto P = Begin;189// Iterate by 1 byte until either the alignment boundary or the end.190for (; reinterpret_cast<uintptr_t>(P) & StepMask && P < End; P++)191if (uint8_t V = *P)192Handle8bitCounter(FirstFeature, P - Begin, V);193194// Iterate by Step bytes at a time.195for (; P + Step <= End; P += Step)196if (LargeType Bundle = *reinterpret_cast<const LargeType *>(P)) {197Bundle = HostToLE(Bundle);198for (size_t I = 0; I < Step; I++, Bundle >>= 8)199if (uint8_t V = Bundle & 0xff)200Handle8bitCounter(FirstFeature, P - Begin + I, V);201}202203// Iterate by 1 byte until the end.204for (; P < End; P++)205if (uint8_t V = *P)206Handle8bitCounter(FirstFeature, P - Begin, V);207return End - Begin;208}209210// Given a non-zero Counter returns a number in the range [0,7].211template<class T>212unsigned CounterToFeature(T Counter) {213// Returns a feature number by placing Counters into buckets as illustrated214// below.215//216// Counter bucket: [1] [2] [3] [4-7] [8-15] [16-31] [32-127] [128+]217// Feature number: 0 1 2 3 4 5 6 7218//219// This is a heuristic taken from AFL (see220// http://lcamtuf.coredump.cx/afl/technical_details.txt).221//222// This implementation may change in the future so clients should223// not rely on it.224assert(Counter);225unsigned Bit = 0;226/**/ if (Counter >= 128) Bit = 7;227else if (Counter >= 32) Bit = 6;228else if (Counter >= 16) Bit = 5;229else if (Counter >= 8) Bit = 4;230else if (Counter >= 4) Bit = 3;231else if (Counter >= 3) Bit = 2;232else if (Counter >= 2) Bit = 1;233return Bit;234}235236template <class Callback> // void Callback(uint32_t Feature)237ATTRIBUTE_NO_SANITIZE_ADDRESS ATTRIBUTE_NOINLINE size_t238TracePC::CollectFeatures(Callback HandleFeature) const {239auto Handle8bitCounter = [&](size_t FirstFeature,240size_t Idx, uint8_t Counter) {241if (UseCounters)242HandleFeature(static_cast<uint32_t>(FirstFeature + Idx * 8 +243CounterToFeature(Counter)));244else245HandleFeature(static_cast<uint32_t>(FirstFeature + Idx));246};247248size_t FirstFeature = 0;249250for (size_t i = 0; i < NumModules; i++) {251for (size_t r = 0; r < Modules[i].NumRegions; r++) {252if (!Modules[i].Regions[r].Enabled) continue;253FirstFeature += 8 * ForEachNonZeroByte(Modules[i].Regions[r].Start,254Modules[i].Regions[r].Stop,255FirstFeature, Handle8bitCounter);256}257}258259FirstFeature +=2608 * ForEachNonZeroByte(ExtraCountersBegin(), ExtraCountersEnd(),261FirstFeature, Handle8bitCounter);262263if (UseValueProfileMask) {264ValueProfileMap.ForEach([&](size_t Idx) {265HandleFeature(static_cast<uint32_t>(FirstFeature + Idx));266});267FirstFeature += ValueProfileMap.SizeInBits();268}269270// Step function, grows similar to 8 * Log_2(A).271auto StackDepthStepFunction = [](size_t A) -> size_t {272if (!A)273return A;274auto Log2 = Log(A);275if (Log2 < 3)276return A;277Log2 -= 3;278return (Log2 + 1) * 8 + ((A >> Log2) & 7);279};280assert(StackDepthStepFunction(1024) == 64);281assert(StackDepthStepFunction(1024 * 4) == 80);282assert(StackDepthStepFunction(1024 * 1024) == 144);283284if (auto MaxStackOffset = GetMaxStackOffset()) {285HandleFeature(static_cast<uint32_t>(286FirstFeature + StackDepthStepFunction(MaxStackOffset / 8)));287FirstFeature += StackDepthStepFunction(std::numeric_limits<size_t>::max());288}289290return FirstFeature;291}292293extern TracePC TPC;294295} // namespace fuzzer296297#endif // LLVM_FUZZER_TRACE_PC298299300