blob: ea6794c75aaced56f65ecd975199af8f87c53e13 [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 {
71 public:
72 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);
78 void HandlePCsInit(const uint8_t *Start, const uint8_t *Stop);
79 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; }
83 void SetUseValueProfile(bool VP) { UseValueProfile = VP; }
84 void SetPrintNewPCs(bool P) { DoPrintNewPCs = P; }
85 void UpdateObservedPCs();
86 template <class Callback> void CollectFeatures(Callback CB) const;
87
88 void ResetMaps() {
89 ValueProfileMap.Reset();
90 if (NumModules)
91 memset(Counters(), 0, GetNumPCs());
92 ClearExtraCounters();
93 ClearInlineCounters();
94 }
95
96 void ClearInlineCounters();
97
98 void UpdateFeatureSet(size_t CurrentElementIdx, size_t CurrentElementSize);
99 void PrintFeatureSet();
100
101 void PrintModuleInfo();
102
103 void PrintCoverage();
104 void DumpCoverage();
105
106 void AddValueForMemcmp(void *caller_pc, const void *s1, const void *s2,
107 size_t n, bool StopAtZero);
108
109 TableOfRecentCompares<uint32_t, 32> TORC4;
110 TableOfRecentCompares<uint64_t, 32> TORC8;
111 TableOfRecentCompares<Word, 32> TORCW;
112 MemMemTable<1024> MMT;
113
114 size_t GetNumPCs() const {
115 return NumGuards == 0 ? (1 << kTracePcBits) : Min(kNumPCs, NumGuards + 1);
116 }
117 uintptr_t GetPC(size_t Idx) {
118 assert(Idx < GetNumPCs());
119 return PCs()[Idx];
120 }
121
122 void RecordCurrentStack() {
123 uintptr_t Stack = GetCurrentStack();
124 if (Stack < LowestStack)
125 LowestStack = Stack;
126 }
127 void RecordInitialStack() {
128 InitialStack = GetCurrentStack();
129 LowestStack = InitialStack;
130 }
131 uintptr_t GetCurrentStack() const {
132 return reinterpret_cast<uintptr_t>(__builtin_frame_address(0));
133 }
134 uintptr_t GetMaxStackOffset() const { return InitialStack - LowestStack; }
135
136 template<class CallBack>
137 void ForEachObservedPC(CallBack CB) {
138 for (auto PC : ObservedPCs)
139 CB(PC);
140 }
141
142private:
143 bool UseCounters = false;
144 bool UseValueProfile = false;
145 bool DoPrintNewPCs = false;
146
147 struct Module {
148 uint32_t *Start, *Stop;
149 };
150
151 Module Modules[4096];
152 size_t NumModules; // linker-initialized.
153 size_t NumGuards; // linker-initialized.
154
155 struct { uint8_t *Start, *Stop; } ModuleCounters[4096];
156 size_t NumModulesWithInline8bitCounters; // linker-initialized.
157 size_t NumInline8bitCounters;
158
159 struct { const uintptr_t *Start, *Stop; } ModulePCTable[4096];
160 size_t NumPCTables;
161 size_t NumPCsInPCTables;
162
163 uint8_t *Counters() const;
164 uintptr_t *PCs() const;
165
166 std::set<uintptr_t> ObservedPCs;
167
168 ValueBitMap ValueProfileMap;
169 uintptr_t InitialStack, LowestStack; // Assume stack grows down.
170};
171
172template <class Callback>
173// void Callback(size_t FirstFeature, size_t Idx, uint8_t Value);
174ATTRIBUTE_NO_SANITIZE_ALL
175void ForEachNonZeroByte(const uint8_t *Begin, const uint8_t *End,
176 size_t FirstFeature, Callback Handle8bitCounter) {
177 typedef uintptr_t LargeType;
178 const size_t Step = sizeof(LargeType) / sizeof(uint8_t);
179 const size_t StepMask = Step - 1;
180 auto P = Begin;
181 // Iterate by 1 byte until either the alignment boundary or the end.
182 for (; reinterpret_cast<uintptr_t>(P) & StepMask && P < End; P++)
183 if (uint8_t V = *P)
184 Handle8bitCounter(FirstFeature, P - Begin, V);
185
186 // Iterate by Step bytes at a time.
187 for (; P < End; P += Step)
188 if (LargeType Bundle = *reinterpret_cast<const LargeType *>(P))
189 for (size_t I = 0; I < Step; I++, Bundle >>= 8)
190 if (uint8_t V = Bundle & 0xff)
191 Handle8bitCounter(FirstFeature, P - Begin + I, V);
192
193 // Iterate by 1 byte until the end.
194 for (; P < End; P++)
195 if (uint8_t V = *P)
196 Handle8bitCounter(FirstFeature, P - Begin, V);
197}
198
199template <class Callback> // bool Callback(size_t Feature)
200ATTRIBUTE_NO_SANITIZE_ADDRESS
201__attribute__((noinline))
202void TracePC::CollectFeatures(Callback HandleFeature) const {
203 uint8_t *Counters = this->Counters();
204 size_t N = GetNumPCs();
205 auto Handle8bitCounter = [&](size_t FirstFeature,
206 size_t Idx, uint8_t Counter) {
207 assert(Counter);
208 unsigned Bit = 0;
209 /**/ if (Counter >= 128) Bit = 7;
210 else if (Counter >= 32) Bit = 6;
211 else if (Counter >= 16) Bit = 5;
212 else if (Counter >= 8) Bit = 4;
213 else if (Counter >= 4) Bit = 3;
214 else if (Counter >= 3) Bit = 2;
215 else if (Counter >= 2) Bit = 1;
216 HandleFeature(FirstFeature + Idx * 8 + Bit);
217 };
218
219 size_t FirstFeature = 0;
220
221 if (!NumInline8bitCounters) {
222 ForEachNonZeroByte(Counters, Counters + N, FirstFeature, Handle8bitCounter);
223 FirstFeature += N * 8;
224 }
225
226 if (NumInline8bitCounters) {
227 for (size_t i = 0; i < NumModulesWithInline8bitCounters; i++) {
228 ForEachNonZeroByte(ModuleCounters[i].Start, ModuleCounters[i].Stop,
229 FirstFeature, Handle8bitCounter);
230 FirstFeature += 8 * (ModuleCounters[i].Stop - ModuleCounters[i].Start);
231 }
232 }
233
234 ForEachNonZeroByte(ExtraCountersBegin(), ExtraCountersEnd(), FirstFeature,
235 Handle8bitCounter);
236 FirstFeature += (ExtraCountersEnd() - ExtraCountersBegin()) * 8;
237
238 if (UseValueProfile) {
239 ValueProfileMap.ForEach([&](size_t Idx) {
240 HandleFeature(FirstFeature + Idx);
241 });
242 FirstFeature += ValueProfileMap.SizeInBits();
243 }
244
245 if (auto MaxStackOffset = GetMaxStackOffset())
246 HandleFeature(FirstFeature + MaxStackOffset);
247}
248
249extern TracePC TPC;
250
251} // namespace fuzzer
252
253#endif // LLVM_FUZZER_TRACE_PC