blob: d9a427cbec8aa5f4e23bf25d370e83df27b0ad19 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +00001//===- FuzzerTracePC.h - Internal header for the Fuzzer ---------*- C++ -* ===//
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// fuzzer::TracePC
10//===----------------------------------------------------------------------===//
11
12#ifndef LLVM_FUZZER_TRACE_PC
13#define LLVM_FUZZER_TRACE_PC
14
15#include "FuzzerDefs.h"
16#include "FuzzerDictionary.h"
17#include "FuzzerValueBitMap.h"
18
19#include <set>
20
21namespace fuzzer {
22
23// TableOfRecentCompares (TORC) remembers the most recently performed
24// comparisons of type T.
25// We record the arguments of CMP instructions in this table unconditionally
26// because it seems cheaper this way than to compute some expensive
27// conditions inside __sanitizer_cov_trace_cmp*.
28// After the unit has been executed we may decide to use the contents of
29// this table to populate a Dictionary.
30template<class T, size_t kSizeT>
31struct TableOfRecentCompares {
32 static const size_t kSize = kSizeT;
33 struct Pair {
34 T A, B;
35 };
36 ATTRIBUTE_NO_SANITIZE_ALL
37 void Insert(size_t Idx, const T &Arg1, const T &Arg2) {
38 Idx = Idx % kSize;
39 Table[Idx].A = Arg1;
40 Table[Idx].B = Arg2;
41 }
42
43 Pair Get(size_t I) { return Table[I % kSize]; }
44
45 Pair Table[kSize];
46};
47
48template <size_t kSizeT>
49struct MemMemTable {
50 static const size_t kSize = kSizeT;
51 Word MemMemWords[kSize];
52 Word EmptyWord;
53
54 void Add(const uint8_t *Data, size_t Size) {
55 if (Size <= 2) return;
56 Size = std::min(Size, Word::GetMaxSize());
57 size_t Idx = SimpleFastHash(Data, Size) % kSize;
58 MemMemWords[Idx].Set(Data, Size);
59 }
60 const Word &Get(size_t Idx) {
61 for (size_t i = 0; i < kSize; i++) {
62 const Word &W = MemMemWords[(Idx + i) % kSize];
63 if (W.size()) return W;
64 }
65 EmptyWord.Set(nullptr, 0);
66 return EmptyWord;
67 }
68};
69
70class TracePC {
dor1se6729cb2018-07-16 15:15:34 +000071 public:
george.karpenkov29efa6d2017-08-21 23:25:50 +000072 static const size_t kNumPCs = 1 << 21;
73 // How many bits of PC are used from __sanitizer_cov_trace_pc.
74 static const size_t kTracePcBits = 18;
75
76 void HandleInit(uint32_t *Start, uint32_t *Stop);
77 void HandleInline8bitCountersInit(uint8_t *Start, uint8_t *Stop);
kcc98957a12017-08-25 19:29:47 +000078 void HandlePCsInit(const uintptr_t *Start, const uintptr_t *Stop);
george.karpenkov29efa6d2017-08-21 23:25:50 +000079 void HandleCallerCallee(uintptr_t Caller, uintptr_t Callee);
80 template <class T> void HandleCmp(uintptr_t PC, T Arg1, T Arg2);
81 size_t GetTotalPCCoverage();
82 void SetUseCounters(bool UC) { UseCounters = UC; }
kcc3850d062018-07-03 22:33:09 +000083 void SetUseValueProfileMask(uint32_t VPMask) { UseValueProfileMask = VPMask; }
george.karpenkov29efa6d2017-08-21 23:25:50 +000084 void SetPrintNewPCs(bool P) { DoPrintNewPCs = P; }
kccec9da662017-08-28 22:52:22 +000085 void SetPrintNewFuncs(size_t P) { NumPrintNewFuncs = P; }
george.karpenkov29efa6d2017-08-21 23:25:50 +000086 void UpdateObservedPCs();
87 template <class Callback> void CollectFeatures(Callback CB) const;
88
89 void ResetMaps() {
90 ValueProfileMap.Reset();
91 if (NumModules)
92 memset(Counters(), 0, GetNumPCs());
93 ClearExtraCounters();
94 ClearInlineCounters();
95 }
96
97 void ClearInlineCounters();
98
99 void UpdateFeatureSet(size_t CurrentElementIdx, size_t CurrentElementSize);
100 void PrintFeatureSet();
101
102 void PrintModuleInfo();
103
104 void PrintCoverage();
kcca7dd2a92018-05-21 19:47:00 +0000105 void DumpCoverage();
dor1sbb933292018-07-16 16:01:31 +0000106 void PrintUnstableStats();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000107
kcc85cad3d2018-05-11 01:17:52 +0000108 template<class CallBack>
109 void IterateCoveredFunctions(CallBack CB);
110
george.karpenkov29efa6d2017-08-21 23:25:50 +0000111 void AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
112 size_t n, bool StopAtZero);
113
114 TableOfRecentCompares<uint32_t, 32> TORC4;
115 TableOfRecentCompares<uint64_t, 32> TORC8;
116 TableOfRecentCompares<Word, 32> TORCW;
117 MemMemTable<1024> MMT;
118
119 size_t GetNumPCs() const {
120 return NumGuards == 0 ? (1 << kTracePcBits) : Min(kNumPCs, NumGuards + 1);
121 }
122 uintptr_t GetPC(size_t Idx) {
123 assert(Idx < GetNumPCs());
124 return PCs()[Idx];
125 }
126
kcc1c0379f2017-08-22 01:28:32 +0000127 void RecordInitialStack();
128 uintptr_t GetMaxStackOffset() const;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000129
130 template<class CallBack>
131 void ForEachObservedPC(CallBack CB) {
132 for (auto PC : ObservedPCs)
133 CB(PC);
134 }
135
kcc3acbe072018-05-16 23:26:37 +0000136 void SetFocusFunction(const std::string &FuncName);
137 bool ObservedFocusFunction();
138
dor1sbb933292018-07-16 16:01:31 +0000139 void InitializeUnstableCounters();
140 void UpdateUnstableCounters();
141
george.karpenkov29efa6d2017-08-21 23:25:50 +0000142private:
dor1sbb933292018-07-16 16:01:31 +0000143 // Value used to represent unstable edge.
144 static constexpr int16_t kUnstableCounter = -1;
145
146 // Uses 16-bit signed type to be able to accommodate any possible value from
147 // uint8_t counter and -1 constant as well.
148 int16_t UnstableCounters[kNumPCs];
149
george.karpenkov29efa6d2017-08-21 23:25:50 +0000150 bool UseCounters = false;
kcc3850d062018-07-03 22:33:09 +0000151 uint32_t UseValueProfileMask = false;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000152 bool DoPrintNewPCs = false;
kccec9da662017-08-28 22:52:22 +0000153 size_t NumPrintNewFuncs = 0;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000154
155 struct Module {
156 uint32_t *Start, *Stop;
157 };
158
159 Module Modules[4096];
160 size_t NumModules; // linker-initialized.
161 size_t NumGuards; // linker-initialized.
162
163 struct { uint8_t *Start, *Stop; } ModuleCounters[4096];
164 size_t NumModulesWithInline8bitCounters; // linker-initialized.
165 size_t NumInline8bitCounters;
166
kcc98957a12017-08-25 19:29:47 +0000167 struct PCTableEntry {
168 uintptr_t PC, PCFlags;
169 };
170
171 struct { const PCTableEntry *Start, *Stop; } ModulePCTable[4096];
george.karpenkov29efa6d2017-08-21 23:25:50 +0000172 size_t NumPCTables;
173 size_t NumPCsInPCTables;
174
175 uint8_t *Counters() const;
176 uintptr_t *PCs() const;
177
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000178 Set<uintptr_t> ObservedPCs;
179 Set<uintptr_t> ObservedFuncs;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000180
dor1sd7197f42018-07-18 17:03:27 +0000181 template <class Callback>
182 void IterateInline8bitCounters(Callback CB) const;
183
kcc3acbe072018-05-16 23:26:37 +0000184 std::pair<size_t, size_t> FocusFunction = {-1, -1}; // Module and PC IDs.
185
george.karpenkov29efa6d2017-08-21 23:25:50 +0000186 ValueBitMap ValueProfileMap;
kcc1c0379f2017-08-22 01:28:32 +0000187 uintptr_t InitialStack;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000188};
189
190template <class Callback>
191// void Callback(size_t FirstFeature, size_t Idx, uint8_t Value);
192ATTRIBUTE_NO_SANITIZE_ALL
193void ForEachNonZeroByte(const uint8_t *Begin, const uint8_t *End,
194 size_t FirstFeature, Callback Handle8bitCounter) {
195 typedef uintptr_t LargeType;
196 const size_t Step = sizeof(LargeType) / sizeof(uint8_t);
197 const size_t StepMask = Step - 1;
198 auto P = Begin;
199 // Iterate by 1 byte until either the alignment boundary or the end.
200 for (; reinterpret_cast<uintptr_t>(P) & StepMask && P < End; P++)
201 if (uint8_t V = *P)
202 Handle8bitCounter(FirstFeature, P - Begin, V);
203
204 // Iterate by Step bytes at a time.
205 for (; P < End; P += Step)
206 if (LargeType Bundle = *reinterpret_cast<const LargeType *>(P))
207 for (size_t I = 0; I < Step; I++, Bundle >>= 8)
208 if (uint8_t V = Bundle & 0xff)
209 Handle8bitCounter(FirstFeature, P - Begin + I, V);
210
211 // Iterate by 1 byte until the end.
212 for (; P < End; P++)
213 if (uint8_t V = *P)
214 Handle8bitCounter(FirstFeature, P - Begin, V);
215}
216
delcypher64c03342017-11-28 17:41:58 +0000217// Given a non-zero Counter returns a number in the range [0,7].
kcc1c0379f2017-08-22 01:28:32 +0000218template<class T>
219unsigned CounterToFeature(T Counter) {
dor1se6729cb2018-07-16 15:15:34 +0000220 // Returns a feature number by placing Counters into buckets as illustrated
221 // below.
222 //
223 // Counter bucket: [1] [2] [3] [4-7] [8-15] [16-31] [32-127] [128+]
224 // Feature number: 0 1 2 3 4 5 6 7
225 //
226 // This is a heuristic taken from AFL (see
227 // http://lcamtuf.coredump.cx/afl/technical_details.txt).
228 //
229 // This implementation may change in the future so clients should
230 // not rely on it.
231 assert(Counter);
232 unsigned Bit = 0;
233 /**/ if (Counter >= 128) Bit = 7;
234 else if (Counter >= 32) Bit = 6;
235 else if (Counter >= 16) Bit = 5;
236 else if (Counter >= 8) Bit = 4;
237 else if (Counter >= 4) Bit = 3;
238 else if (Counter >= 3) Bit = 2;
239 else if (Counter >= 2) Bit = 1;
240 return Bit;
kcc1c0379f2017-08-22 01:28:32 +0000241}
242
kccc924e382017-09-15 22:10:36 +0000243template <class Callback> // void Callback(size_t Feature)
kcc1c0379f2017-08-22 01:28:32 +0000244ATTRIBUTE_NO_SANITIZE_ADDRESS
245__attribute__((noinline))
246void TracePC::CollectFeatures(Callback HandleFeature) const {
247 uint8_t *Counters = this->Counters();
248 size_t N = GetNumPCs();
249 auto Handle8bitCounter = [&](size_t FirstFeature,
250 size_t Idx, uint8_t Counter) {
kcc1f5638d2017-12-08 22:21:42 +0000251 if (UseCounters)
252 HandleFeature(FirstFeature + Idx * 8 + CounterToFeature(Counter));
253 else
254 HandleFeature(FirstFeature + Idx);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000255 };
256
257 size_t FirstFeature = 0;
258
259 if (!NumInline8bitCounters) {
260 ForEachNonZeroByte(Counters, Counters + N, FirstFeature, Handle8bitCounter);
261 FirstFeature += N * 8;
262 }
263
264 if (NumInline8bitCounters) {
265 for (size_t i = 0; i < NumModulesWithInline8bitCounters; i++) {
266 ForEachNonZeroByte(ModuleCounters[i].Start, ModuleCounters[i].Stop,
267 FirstFeature, Handle8bitCounter);
268 FirstFeature += 8 * (ModuleCounters[i].Stop - ModuleCounters[i].Start);
269 }
270 }
271
george.karpenkov29efa6d2017-08-21 23:25:50 +0000272 ForEachNonZeroByte(ExtraCountersBegin(), ExtraCountersEnd(), FirstFeature,
273 Handle8bitCounter);
274 FirstFeature += (ExtraCountersEnd() - ExtraCountersBegin()) * 8;
275
kcc3850d062018-07-03 22:33:09 +0000276 if (UseValueProfileMask) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000277 ValueProfileMap.ForEach([&](size_t Idx) {
278 HandleFeature(FirstFeature + Idx);
279 });
280 FirstFeature += ValueProfileMap.SizeInBits();
281 }
282
kccd804ddb2017-12-09 19:18:10 +0000283 // Step function, grows similar to 8 * Log_2(A).
284 auto StackDepthStepFunction = [](uint32_t A) -> uint32_t {
dor1sa66e7762017-12-20 19:31:51 +0000285 if (!A) return A;
kcce29d7e32017-12-12 23:11:28 +0000286 uint32_t Log2 = Log(A);
kccd804ddb2017-12-09 19:18:10 +0000287 if (Log2 < 3) return A;
288 Log2 -= 3;
289 return (Log2 + 1) * 8 + ((A >> Log2) & 7);
290 };
291 assert(StackDepthStepFunction(1024) == 64);
292 assert(StackDepthStepFunction(1024 * 4) == 80);
293 assert(StackDepthStepFunction(1024 * 1024) == 144);
294
george.karpenkov29efa6d2017-08-21 23:25:50 +0000295 if (auto MaxStackOffset = GetMaxStackOffset())
kccd804ddb2017-12-09 19:18:10 +0000296 HandleFeature(FirstFeature + StackDepthStepFunction(MaxStackOffset / 8));
george.karpenkov29efa6d2017-08-21 23:25:50 +0000297}
298
299extern TracePC TPC;
300
301} // namespace fuzzer
302
303#endif // LLVM_FUZZER_TRACE_PC