217124d211037a2532d08ba9d98b8eff2872ecfa
[oota-llvm.git] / lib / Fuzzer / FuzzerDFSan.cpp
1 //===- FuzzerDFSan.cpp - DFSan-based fuzzer mutator -----------------------===//
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 // DataFlowSanitizer (DFSan) is a tool for
10 // generalised dynamic data flow (taint) analysis:
11 // http://clang.llvm.org/docs/DataFlowSanitizer.html .
12 //
13 // This file implements a mutation algorithm based on taint
14 // analysis feedback from DFSan.
15 //
16 // The approach has some similarity to "Taint-based Directed Whitebox Fuzzing"
17 // by Vijay Ganesh & Tim Leek & Martin Rinard:
18 // http://dspace.mit.edu/openaccess-disseminate/1721.1/59320,
19 // but it uses a full blown LLVM IR taint analysis and separate instrumentation
20 // to analyze all of the "attack points" at once.
21 //
22 // Workflow:
23 //   * lib/Fuzzer/Fuzzer*.cpp is compiled w/o any instrumentation.
24 //   * The code under test is compiled with DFSan *and* with special extra hooks
25 //     that are inserted before dfsan. Currently supported hooks:
26 //     - __sanitizer_cov_trace_cmp: inserted before every ICMP instruction,
27 //       receives the type, size and arguments of ICMP.
28 //   * Every call to HOOK(a,b) is replaced by DFSan with
29 //     __dfsw_HOOK(a, b, label(a), label(b)) so that __dfsw_HOOK
30 //     gets all the taint labels for the arguments.
31 //   * At the Fuzzer startup we assign a unique DFSan label
32 //     to every byte of the input string (Fuzzer::CurrentUnit) so that for any
33 //     chunk of data we know which input bytes it has derived from.
34 //   * The __dfsw_* functions (implemented in this file) record the
35 //     parameters (i.e. the application data and the corresponding taint labels)
36 //     in a global state.
37 //   * Fuzzer::MutateWithDFSan() tries to use the data recorded by __dfsw_*
38 //     hooks to guide the fuzzing towards new application states.
39 //     For example if 4 bytes of data that derive from input bytes {4,5,6,7}
40 //     are compared with a constant 12345 and the comparison always yields
41 //     the same result, we try to insert 12345, 12344, 12346 into bytes
42 //     {4,5,6,7} of the next fuzzed inputs.
43 //
44 // This code does not function when DFSan is not linked in.
45 // Instead of using ifdefs and thus requiring a separate build of lib/Fuzzer
46 // we redeclare the dfsan_* interface functions as weak and check if they
47 // are nullptr before calling.
48 // If this approach proves to be useful we may add attribute(weak) to the
49 // dfsan declarations in dfsan_interface.h
50 //
51 // This module is in the "proof of concept" stage.
52 // It is capable of solving only the simplest puzzles
53 // like test/dfsan/DFSanSimpleCmpTest.cpp.
54 //===----------------------------------------------------------------------===//
55
56 /* Example of manual usage:
57 (
58   cd $LLVM/lib/Fuzzer/
59   clang  -fPIC -c -g -O2 -std=c++11 Fuzzer*.cpp
60   clang++ -O0 -std=c++11 -fsanitize-coverage=edge,trace-cmp \
61     -fsanitize=dataflow \
62     test/dfsan/DFSanSimpleCmpTest.cpp Fuzzer*.o
63   ./a.out
64 )
65 */
66
67 #include "FuzzerInternal.h"
68 #include <sanitizer/dfsan_interface.h>
69
70 #include <algorithm>
71 #include <cstring>
72 #include <iostream>
73 #include <unordered_map>
74
75 extern "C" {
76 __attribute__((weak))
77 dfsan_label dfsan_create_label(const char *desc, void *userdata);
78 __attribute__((weak))
79 void dfsan_set_label(dfsan_label label, void *addr, size_t size);
80 __attribute__((weak))
81 void dfsan_add_label(dfsan_label label, void *addr, size_t size);
82 __attribute__((weak))
83 const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label);
84 __attribute__((weak))
85 dfsan_label dfsan_read_label(const void *addr, size_t size);
86 }  // extern "C"
87
88 namespace fuzzer {
89
90 static bool ReallyHaveDFSan() {
91   return &dfsan_create_label != nullptr;
92 }
93
94 // These values are copied from include/llvm/IR/InstrTypes.h.
95 // We do not include the LLVM headers here to remain independent.
96 // If these values ever change, an assertion in ComputeCmp will fail.
97 enum Predicate {
98   ICMP_EQ = 32,  ///< equal
99   ICMP_NE = 33,  ///< not equal
100   ICMP_UGT = 34, ///< unsigned greater than
101   ICMP_UGE = 35, ///< unsigned greater or equal
102   ICMP_ULT = 36, ///< unsigned less than
103   ICMP_ULE = 37, ///< unsigned less or equal
104   ICMP_SGT = 38, ///< signed greater than
105   ICMP_SGE = 39, ///< signed greater or equal
106   ICMP_SLT = 40, ///< signed less than
107   ICMP_SLE = 41, ///< signed less or equal
108 };
109
110 template <class U, class S>
111 bool ComputeCmp(size_t CmpType, U Arg1, U Arg2) {
112   switch(CmpType) {
113     case ICMP_EQ : return Arg1 == Arg2;
114     case ICMP_NE : return Arg1 != Arg2;
115     case ICMP_UGT: return Arg1 > Arg2;
116     case ICMP_UGE: return Arg1 >= Arg2;
117     case ICMP_ULT: return Arg1 < Arg2;
118     case ICMP_ULE: return Arg1 <= Arg2;
119     case ICMP_SGT: return (S)Arg1 > (S)Arg2;
120     case ICMP_SGE: return (S)Arg1 >= (S)Arg2;
121     case ICMP_SLT: return (S)Arg1 < (S)Arg2;
122     case ICMP_SLE: return (S)Arg1 <= (S)Arg2;
123     default: assert(0 && "unsupported CmpType");
124   }
125   return false;
126 }
127
128 static bool ComputeCmp(size_t CmpSize, size_t CmpType, uint64_t Arg1,
129                        uint64_t Arg2) {
130   if (CmpSize == 8) return ComputeCmp<uint64_t, int64_t>(CmpType, Arg1, Arg2);
131   if (CmpSize == 4) return ComputeCmp<uint32_t, int32_t>(CmpType, Arg1, Arg2);
132   if (CmpSize == 2) return ComputeCmp<uint16_t, int16_t>(CmpType, Arg1, Arg2);
133   if (CmpSize == 1) return ComputeCmp<uint8_t, int8_t>(CmpType, Arg1, Arg2);
134   assert(0 && "unsupported type size");
135   return true;
136 }
137
138 // As a simplification we use the range of input bytes instead of a set of input
139 // bytes.
140 struct LabelRange {
141   uint16_t Beg, End;  // Range is [Beg, End), thus Beg==End is an empty range.
142
143   LabelRange(uint16_t Beg = 0, uint16_t End = 0) : Beg(Beg), End(End) {}
144
145   static LabelRange Join(LabelRange LR1, LabelRange LR2) {
146     if (LR1.Beg == LR1.End) return LR2;
147     if (LR2.Beg == LR2.End) return LR1;
148     return {std::min(LR1.Beg, LR2.Beg), std::max(LR1.End, LR2.End)};
149   }
150   LabelRange &Join(LabelRange LR) {
151     return *this = Join(*this, LR);
152   }
153   static LabelRange Singleton(const dfsan_label_info *LI) {
154     uint16_t Idx = (uint16_t)(uintptr_t)LI->userdata;
155     assert(Idx > 0);
156     return {(uint16_t)(Idx - 1), Idx};
157   }
158 };
159
160 std::ostream &operator<<(std::ostream &os, const LabelRange &LR) {
161   return os << "[" << LR.Beg << "," << LR.End << ")";
162 }
163
164 // For now, very simple: put Size bytes of Data at position Pos.
165 struct TraceBasedMutation {
166   size_t Pos;
167   size_t Size;
168   uint64_t Data;
169 };
170
171 class DFSanState {
172  public:
173    DFSanState(const Fuzzer::FuzzingOptions &Options, const Unit &CurrentUnit)
174        : Options(Options), CurrentUnit(CurrentUnit) {}
175
176   LabelRange GetLabelRange(dfsan_label L);
177   void DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
178                         uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
179                         dfsan_label L2);
180   void TraceCmpCallback(size_t CmpSize, size_t CmpType, uint64_t Arg1,
181                         uint64_t Arg2);
182   int TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
183                            size_t DataSize);
184
185   void StartTraceRecording() {
186     RecordingTraces = true;
187     Mutations.clear();
188   }
189
190   size_t StopTraceRecording() {
191     RecordingTraces = false;
192     std::random_shuffle(Mutations.begin(), Mutations.end());
193     return Mutations.size();
194   }
195
196   void ApplyTraceBasedMutation(size_t Idx, fuzzer::Unit *U);
197
198  private:
199   bool IsTwoByteData(uint64_t Data) {
200     int64_t Signed = static_cast<int64_t>(Data);
201     Signed >>= 16;
202     return Signed == 0 || Signed == -1L;
203   }
204   bool RecordingTraces = false;
205   std::vector<TraceBasedMutation> Mutations;
206   LabelRange LabelRanges[1 << (sizeof(dfsan_label) * 8)] = {};
207   const Fuzzer::FuzzingOptions &Options;
208   const Unit &CurrentUnit;
209 };
210
211 LabelRange DFSanState::GetLabelRange(dfsan_label L) {
212   LabelRange &LR = LabelRanges[L];
213   if (LR.Beg < LR.End || L == 0)
214     return LR;
215   const dfsan_label_info *LI = dfsan_get_label_info(L);
216   if (LI->l1 || LI->l2)
217     return LR = LabelRange::Join(GetLabelRange(LI->l1), GetLabelRange(LI->l2));
218   return LR = LabelRange::Singleton(LI);
219 }
220
221 void DFSanState::ApplyTraceBasedMutation(size_t Idx, fuzzer::Unit *U) {
222   assert(Idx < Mutations.size());
223   auto &M = Mutations[Idx];
224   if (Options.Verbosity >= 3)
225     std::cerr << "TBM " << M.Pos << " " << M.Size << " " << M.Data << "\n";
226   if (M.Pos + M.Size > U->size()) return;
227   memcpy(U->data() + M.Pos, &M.Data, M.Size);
228 }
229
230 void DFSanState::DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
231                                   uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
232                                   dfsan_label L2) {
233   assert(ReallyHaveDFSan());
234   if (!RecordingTraces) return;
235   if (L1 == 0 && L2 == 0)
236     return;  // Not actionable.
237   if (L1 != 0 && L2 != 0)
238     return;  // Probably still actionable.
239   bool Res = ComputeCmp(CmpSize, CmpType, Arg1, Arg2);
240   uint64_t Data = L1 ? Arg2 : Arg1;
241   LabelRange LR = L1 ? GetLabelRange(L1) : GetLabelRange(L2);
242
243   for (size_t Pos = LR.Beg; Pos + CmpSize <= LR.End; Pos++) {
244     Mutations.push_back({Pos, CmpSize, Data});
245     Mutations.push_back({Pos, CmpSize, Data + 1});
246     Mutations.push_back({Pos, CmpSize, Data - 1});
247   }
248
249   if (CmpSize > LR.End - LR.Beg)
250     Mutations.push_back({LR.Beg, (unsigned)(LR.End - LR.Beg), Data});
251
252
253   if (Options.Verbosity >= 3)
254     std::cerr << "DFSAN:"
255               << " PC " << std::hex << PC << std::dec
256               << " S " << CmpSize
257               << " T " << CmpType
258               << " A1 " << Arg1 << " A2 " << Arg2 << " R " << Res
259               << " L" << L1
260               << " L" << L2
261               << " R"  << LR
262               << " MU " << Mutations.size()
263               << "\n";
264 }
265
266 int DFSanState::TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
267                                     size_t DataSize) {
268   int Res = 0;
269   const uint8_t *Beg = CurrentUnit.data();
270   const uint8_t *End = Beg + CurrentUnit.size();
271   for (const uint8_t *Cur = Beg; Cur < End; Cur += DataSize) {
272     Cur = (uint8_t *)memmem(Cur, End - Cur, &PresentData, DataSize);
273     if (!Cur)
274       break;
275     // std::cerr << "Cur " << (void*)Cur << "\n";
276     size_t Pos = Cur - Beg;
277     assert(Pos < CurrentUnit.size());
278     Mutations.push_back({Pos, DataSize, DesiredData});
279     Mutations.push_back({Pos, DataSize, DesiredData + 1});
280     Mutations.push_back({Pos, DataSize, DesiredData - 1});
281     Cur += DataSize;
282     Res++;
283   }
284   return Res;
285 }
286
287 void DFSanState::TraceCmpCallback(size_t CmpSize, size_t CmpType, uint64_t Arg1,
288                         uint64_t Arg2) {
289   if (!Options.UseTraces) return;
290   int Added = 0;
291   if (Options.Verbosity >= 3)
292     std::cerr << "TraceCmp: " << Arg1 << " " << Arg2 << "\n";
293   Added += TryToAddDesiredData(Arg1, Arg2, CmpSize);
294   Added += TryToAddDesiredData(Arg2, Arg1, CmpSize);
295   if (!Added && CmpSize == 4 && IsTwoByteData(Arg1) && IsTwoByteData(Arg2)) {
296     Added += TryToAddDesiredData(Arg1, Arg2, 2);
297     Added += TryToAddDesiredData(Arg2, Arg1, 2);
298   }
299 }
300
301 static DFSanState *DFSan;
302
303 void Fuzzer::StartTraceRecording() {
304   if (!DFSan) return;
305   DFSan->StartTraceRecording();
306 }
307
308 size_t Fuzzer::StopTraceRecording() {
309   if (!DFSan) return 0;
310   return DFSan->StopTraceRecording();
311 }
312
313 void Fuzzer::ApplyTraceBasedMutation(size_t Idx, Unit *U) {
314   assert(DFSan);
315   DFSan->ApplyTraceBasedMutation(Idx, U);
316 }
317
318 void Fuzzer::InitializeDFSan() {
319   if (!Options.UseDFSan) return;
320   DFSan = new DFSanState(Options, CurrentUnit);
321   CurrentUnit.resize(Options.MaxLen);
322   // The rest really requires DFSan.
323   if (!ReallyHaveDFSan()) return;
324   for (size_t i = 0; i < static_cast<size_t>(Options.MaxLen); i++) {
325     dfsan_label L = dfsan_create_label("input", (void*)(i + 1));
326     // We assume that no one else has called dfsan_create_label before.
327     assert(L == i + 1);
328     dfsan_set_label(L, &CurrentUnit[i], 1);
329   }
330 }
331
332 }  // namespace fuzzer
333
334 using fuzzer::DFSan;
335
336 extern "C" {
337 void __dfsw___sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
338                                       uint64_t Arg2, dfsan_label L0,
339                                       dfsan_label L1, dfsan_label L2) {
340   assert(L0 == 0);
341   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
342   uint64_t CmpSize = (SizeAndType >> 32) / 8;
343   uint64_t Type = (SizeAndType << 32) >> 32;
344   DFSan->DFSanCmpCallback(PC, CmpSize, Type, Arg1, Arg2, L1, L2);
345 }
346
347 void dfsan_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2,
348                             size_t n, dfsan_label s1_label,
349                             dfsan_label s2_label, dfsan_label n_label) {
350   uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
351   uint64_t S1 = 0, S2 = 0;
352   // Simplification: handle only first 8 bytes.
353   memcpy(&S1, s1, std::min(n, sizeof(S1)));
354   memcpy(&S2, s2, std::min(n, sizeof(S2)));
355   dfsan_label L1 = dfsan_read_label(s1, n);
356   dfsan_label L2 = dfsan_read_label(s2, n);
357   DFSan->DFSanCmpCallback(PC, n, fuzzer::ICMP_EQ, S1, S2, L1, L2);
358 }
359
360 void __sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
361                                uint64_t Arg2) {
362   if (!DFSan) return;
363   uint64_t CmpSize = (SizeAndType >> 32) / 8;
364   uint64_t Type = (SizeAndType << 32) >> 32;
365   DFSan->TraceCmpCallback(CmpSize, Type, Arg1, Arg2);
366 }
367
368 }  // extern "C"