FuzzerTracePC.h 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //===- FuzzerTracePC.h - Internal header for the Fuzzer ---------*- C++ -* ===//
  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. // fuzzer::TracePC
  9. //===----------------------------------------------------------------------===//
  10. #ifndef LLVM_FUZZER_TRACE_PC
  11. #define LLVM_FUZZER_TRACE_PC
  12. #include "FuzzerDefs.h"
  13. #include "FuzzerDictionary.h"
  14. #include "FuzzerValueBitMap.h"
  15. #include <set>
  16. #include <unordered_map>
  17. namespace fuzzer {
  18. // TableOfRecentCompares (TORC) remembers the most recently performed
  19. // comparisons of type T.
  20. // We record the arguments of CMP instructions in this table unconditionally
  21. // because it seems cheaper this way than to compute some expensive
  22. // conditions inside __sanitizer_cov_trace_cmp*.
  23. // After the unit has been executed we may decide to use the contents of
  24. // this table to populate a Dictionary.
  25. template<class T, size_t kSizeT>
  26. struct TableOfRecentCompares {
  27. static const size_t kSize = kSizeT;
  28. struct Pair {
  29. T A, B;
  30. };
  31. ATTRIBUTE_NO_SANITIZE_ALL
  32. void Insert(size_t Idx, const T &Arg1, const T &Arg2) {
  33. Idx = Idx % kSize;
  34. Table[Idx].A = Arg1;
  35. Table[Idx].B = Arg2;
  36. }
  37. Pair Get(size_t I) { return Table[I % kSize]; }
  38. Pair Table[kSize];
  39. };
  40. template <size_t kSizeT>
  41. struct MemMemTable {
  42. static const size_t kSize = kSizeT;
  43. Word MemMemWords[kSize];
  44. Word EmptyWord;
  45. void Add(const uint8_t *Data, size_t Size) {
  46. if (Size <= 2) return;
  47. Size = std::min(Size, Word::GetMaxSize());
  48. auto Idx = SimpleFastHash(Data, Size) % kSize;
  49. MemMemWords[Idx].Set(Data, Size);
  50. }
  51. const Word &Get(size_t Idx) {
  52. for (size_t i = 0; i < kSize; i++) {
  53. const Word &W = MemMemWords[(Idx + i) % kSize];
  54. if (W.size()) return W;
  55. }
  56. EmptyWord.Set(nullptr, 0);
  57. return EmptyWord;
  58. }
  59. };
  60. class TracePC {
  61. public:
  62. void HandleInline8bitCountersInit(uint8_t *Start, uint8_t *Stop);
  63. void HandlePCsInit(const uintptr_t *Start, const uintptr_t *Stop);
  64. void HandleCallerCallee(uintptr_t Caller, uintptr_t Callee);
  65. template <class T> void HandleCmp(uintptr_t PC, T Arg1, T Arg2);
  66. size_t GetTotalPCCoverage();
  67. void SetUseCounters(bool UC) { UseCounters = UC; }
  68. void SetUseValueProfileMask(uint32_t VPMask) { UseValueProfileMask = VPMask; }
  69. void SetPrintNewPCs(bool P) { DoPrintNewPCs = P; }
  70. void SetPrintNewFuncs(size_t P) { NumPrintNewFuncs = P; }
  71. void UpdateObservedPCs();
  72. template <class Callback> size_t CollectFeatures(Callback CB) const;
  73. void ResetMaps() {
  74. ValueProfileMap.Reset();
  75. ClearExtraCounters();
  76. ClearInlineCounters();
  77. }
  78. void ClearInlineCounters();
  79. void UpdateFeatureSet(size_t CurrentElementIdx, size_t CurrentElementSize);
  80. void PrintFeatureSet();
  81. void PrintModuleInfo();
  82. void PrintCoverage(bool PrintAllCounters);
  83. template<class CallBack>
  84. void IterateCoveredFunctions(CallBack CB);
  85. void AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
  86. size_t n, bool StopAtZero);
  87. TableOfRecentCompares<uint32_t, 32> TORC4;
  88. TableOfRecentCompares<uint64_t, 32> TORC8;
  89. TableOfRecentCompares<Word, 32> TORCW;
  90. MemMemTable<1024> MMT;
  91. void RecordInitialStack();
  92. uintptr_t GetMaxStackOffset() const;
  93. template<class CallBack>
  94. void ForEachObservedPC(CallBack CB) {
  95. for (auto PC : ObservedPCs)
  96. CB(PC);
  97. }
  98. void SetFocusFunction(const std::string &FuncName);
  99. bool ObservedFocusFunction();
  100. struct PCTableEntry {
  101. uintptr_t PC, PCFlags;
  102. };
  103. uintptr_t PCTableEntryIdx(const PCTableEntry *TE);
  104. const PCTableEntry *PCTableEntryByIdx(uintptr_t Idx);
  105. static uintptr_t GetNextInstructionPc(uintptr_t PC);
  106. bool PcIsFuncEntry(const PCTableEntry *TE) { return TE->PCFlags & 1; }
  107. private:
  108. bool UseCounters = false;
  109. uint32_t UseValueProfileMask = false;
  110. bool DoPrintNewPCs = false;
  111. size_t NumPrintNewFuncs = 0;
  112. // Module represents the array of 8-bit counters split into regions
  113. // such that every region, except maybe the first and the last one, is one
  114. // full page.
  115. struct Module {
  116. struct Region {
  117. uint8_t *Start, *Stop;
  118. bool Enabled;
  119. bool OneFullPage;
  120. };
  121. Region *Regions;
  122. size_t NumRegions;
  123. uint8_t *Start() { return Regions[0].Start; }
  124. uint8_t *Stop() { return Regions[NumRegions - 1].Stop; }
  125. size_t Size() { return Stop() - Start(); }
  126. size_t Idx(uint8_t *P) {
  127. assert(P >= Start() && P < Stop());
  128. return P - Start();
  129. }
  130. };
  131. Module Modules[4096];
  132. size_t NumModules; // linker-initialized.
  133. size_t NumInline8bitCounters;
  134. template <class Callback>
  135. void IterateCounterRegions(Callback CB) {
  136. for (size_t m = 0; m < NumModules; m++)
  137. for (size_t r = 0; r < Modules[m].NumRegions; r++)
  138. CB(Modules[m].Regions[r]);
  139. }
  140. struct { const PCTableEntry *Start, *Stop; } ModulePCTable[4096];
  141. size_t NumPCTables;
  142. size_t NumPCsInPCTables;
  143. std::set<const PCTableEntry *> ObservedPCs;
  144. std::unordered_map<uintptr_t, uintptr_t> ObservedFuncs; // PC => Counter.
  145. uint8_t *FocusFunctionCounterPtr = nullptr;
  146. ValueBitMap ValueProfileMap;
  147. uintptr_t InitialStack;
  148. };
  149. template <class Callback>
  150. // void Callback(size_t FirstFeature, size_t Idx, uint8_t Value);
  151. ATTRIBUTE_NO_SANITIZE_ALL
  152. size_t ForEachNonZeroByte(const uint8_t *Begin, const uint8_t *End,
  153. size_t FirstFeature, Callback Handle8bitCounter) {
  154. typedef uintptr_t LargeType;
  155. const size_t Step = sizeof(LargeType) / sizeof(uint8_t);
  156. const size_t StepMask = Step - 1;
  157. auto P = Begin;
  158. // Iterate by 1 byte until either the alignment boundary or the end.
  159. for (; reinterpret_cast<uintptr_t>(P) & StepMask && P < End; P++)
  160. if (uint8_t V = *P)
  161. Handle8bitCounter(FirstFeature, P - Begin, V);
  162. // Iterate by Step bytes at a time.
  163. for (; P + Step <= End; P += Step)
  164. if (LargeType Bundle = *reinterpret_cast<const LargeType *>(P)) {
  165. Bundle = HostToLE(Bundle);
  166. for (size_t I = 0; I < Step; I++, Bundle >>= 8)
  167. if (uint8_t V = Bundle & 0xff)
  168. Handle8bitCounter(FirstFeature, P - Begin + I, V);
  169. }
  170. // Iterate by 1 byte until the end.
  171. for (; P < End; P++)
  172. if (uint8_t V = *P)
  173. Handle8bitCounter(FirstFeature, P - Begin, V);
  174. return End - Begin;
  175. }
  176. // Given a non-zero Counter returns a number in the range [0,7].
  177. template<class T>
  178. unsigned CounterToFeature(T Counter) {
  179. // Returns a feature number by placing Counters into buckets as illustrated
  180. // below.
  181. //
  182. // Counter bucket: [1] [2] [3] [4-7] [8-15] [16-31] [32-127] [128+]
  183. // Feature number: 0 1 2 3 4 5 6 7
  184. //
  185. // This is a heuristic taken from AFL (see
  186. // http://lcamtuf.coredump.cx/afl/technical_details.txt).
  187. //
  188. // This implementation may change in the future so clients should
  189. // not rely on it.
  190. assert(Counter);
  191. unsigned Bit = 0;
  192. /**/ if (Counter >= 128) Bit = 7;
  193. else if (Counter >= 32) Bit = 6;
  194. else if (Counter >= 16) Bit = 5;
  195. else if (Counter >= 8) Bit = 4;
  196. else if (Counter >= 4) Bit = 3;
  197. else if (Counter >= 3) Bit = 2;
  198. else if (Counter >= 2) Bit = 1;
  199. return Bit;
  200. }
  201. template <class Callback> // void Callback(uint32_t Feature)
  202. ATTRIBUTE_NO_SANITIZE_ADDRESS ATTRIBUTE_NOINLINE size_t
  203. TracePC::CollectFeatures(Callback HandleFeature) const {
  204. auto Handle8bitCounter = [&](size_t FirstFeature,
  205. size_t Idx, uint8_t Counter) {
  206. if (UseCounters)
  207. HandleFeature(static_cast<uint32_t>(FirstFeature + Idx * 8 +
  208. CounterToFeature(Counter)));
  209. else
  210. HandleFeature(static_cast<uint32_t>(FirstFeature + Idx));
  211. };
  212. size_t FirstFeature = 0;
  213. for (size_t i = 0; i < NumModules; i++) {
  214. for (size_t r = 0; r < Modules[i].NumRegions; r++) {
  215. if (!Modules[i].Regions[r].Enabled) continue;
  216. FirstFeature += 8 * ForEachNonZeroByte(Modules[i].Regions[r].Start,
  217. Modules[i].Regions[r].Stop,
  218. FirstFeature, Handle8bitCounter);
  219. }
  220. }
  221. FirstFeature +=
  222. 8 * ForEachNonZeroByte(ExtraCountersBegin(), ExtraCountersEnd(),
  223. FirstFeature, Handle8bitCounter);
  224. if (UseValueProfileMask) {
  225. ValueProfileMap.ForEach([&](size_t Idx) {
  226. HandleFeature(static_cast<uint32_t>(FirstFeature + Idx));
  227. });
  228. FirstFeature += ValueProfileMap.SizeInBits();
  229. }
  230. // Step function, grows similar to 8 * Log_2(A).
  231. auto StackDepthStepFunction = [](size_t A) -> size_t {
  232. if (!A)
  233. return A;
  234. auto Log2 = Log(A);
  235. if (Log2 < 3)
  236. return A;
  237. Log2 -= 3;
  238. return (Log2 + 1) * 8 + ((A >> Log2) & 7);
  239. };
  240. assert(StackDepthStepFunction(1024) == 64);
  241. assert(StackDepthStepFunction(1024 * 4) == 80);
  242. assert(StackDepthStepFunction(1024 * 1024) == 144);
  243. if (auto MaxStackOffset = GetMaxStackOffset()) {
  244. HandleFeature(static_cast<uint32_t>(
  245. FirstFeature + StackDepthStepFunction(MaxStackOffset / 8)));
  246. FirstFeature += StackDepthStepFunction(std::numeric_limits<size_t>::max());
  247. }
  248. return FirstFeature;
  249. }
  250. extern TracePC TPC;
  251. } // namespace fuzzer
  252. #endif // LLVM_FUZZER_TRACE_PC