975cfbdf1d1b3a12fa9210300980b41dedcc14e1
[oota-llvm.git] / lib / Fuzzer / FuzzerTraceState.cpp
1 //===- FuzzerTraceState.cpp - Trace-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 // This file implements a mutation algorithm based on instruction traces and
10 // on taint analysis feedback from DFSan.
11 //
12 // Instruction traces are special hooks inserted by the compiler around
13 // interesting instructions. Currently supported traces:
14 //   * __sanitizer_cov_trace_cmp -- inserted before every ICMP instruction,
15 //    receives the type, size and arguments of ICMP.
16 //
17 // Every time a traced event is intercepted we analyse the data involved
18 // in the event and suggest a mutation for future executions.
19 // For example if 4 bytes of data that derive from input bytes {4,5,6,7}
20 // are compared with a constant 12345,
21 // we try to insert 12345, 12344, 12346 into bytes
22 // {4,5,6,7} of the next fuzzed inputs.
23 //
24 // The fuzzer can work only with the traces, or with both traces and DFSan.
25 //
26 // DataFlowSanitizer (DFSan) is a tool for
27 // generalised dynamic data flow (taint) analysis:
28 // http://clang.llvm.org/docs/DataFlowSanitizer.html .
29 //
30 // The approach with DFSan-based fuzzing has some similarity to
31 // "Taint-based Directed Whitebox Fuzzing"
32 // by Vijay Ganesh & Tim Leek & Martin Rinard:
33 // http://dspace.mit.edu/openaccess-disseminate/1721.1/59320,
34 // but it uses a full blown LLVM IR taint analysis and separate instrumentation
35 // to analyze all of the "attack points" at once.
36 //
37 // Workflow with DFSan:
38 //   * lib/Fuzzer/Fuzzer*.cpp is compiled w/o any instrumentation.
39 //   * The code under test is compiled with DFSan *and* with instruction traces.
40 //   * Every call to HOOK(a,b) is replaced by DFSan with
41 //     __dfsw_HOOK(a, b, label(a), label(b)) so that __dfsw_HOOK
42 //     gets all the taint labels for the arguments.
43 //   * At the Fuzzer startup we assign a unique DFSan label
44 //     to every byte of the input string (Fuzzer::CurrentUnit) so that for any
45 //     chunk of data we know which input bytes it has derived from.
46 //   * The __dfsw_* functions (implemented in this file) record the
47 //     parameters (i.e. the application data and the corresponding taint labels)
48 //     in a global state.
49 //
50 // Parts of this code will not function when DFSan is not linked in.
51 // Instead of using ifdefs and thus requiring a separate build of lib/Fuzzer
52 // we redeclare the dfsan_* interface functions as weak and check if they
53 // are nullptr before calling.
54 // If this approach proves to be useful we may add attribute(weak) to the
55 // dfsan declarations in dfsan_interface.h
56 //
57 // This module is in the "proof of concept" stage.
58 // It is capable of solving only the simplest puzzles
59 // like test/dfsan/DFSanSimpleCmpTest.cpp.
60 //===----------------------------------------------------------------------===//
61
62 /* Example of manual usage (-fsanitize=dataflow is optional):
63 (
64   cd $LLVM/lib/Fuzzer/
65   clang  -fPIC -c -g -O2 -std=c++11 Fuzzer*.cpp
66   clang++ -O0 -std=c++11 -fsanitize-coverage=edge,trace-cmp \
67     -fsanitize=dataflow \
68     test/SimpleCmpTest.cpp Fuzzer*.o
69   ./a.out -use_traces=1
70 )
71 */
72
73 #include "FuzzerDFSan.h"
74 #include "FuzzerInternal.h"
75
76 #include <algorithm>
77 #include <cstring>
78 #include <thread>
79 #include <map>
80
81 #if !LLVM_FUZZER_SUPPORTS_DFSAN
82 // Stubs for dfsan for platforms where dfsan does not exist and weak
83 // functions don't work.
84 extern "C" {
85 dfsan_label dfsan_create_label(const char *desc, void *userdata) { return 0; }
86 void dfsan_set_label(dfsan_label label, void *addr, size_t size) {}
87 void dfsan_add_label(dfsan_label label, void *addr, size_t size) {}
88 const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label) {
89   return nullptr;
90 }
91 dfsan_label dfsan_read_label(const void *addr, size_t size) { return 0; }
92 }  // extern "C"
93 #endif  // !LLVM_FUZZER_SUPPORTS_DFSAN
94
95 namespace fuzzer {
96
97 // These values are copied from include/llvm/IR/InstrTypes.h.
98 // We do not include the LLVM headers here to remain independent.
99 // If these values ever change, an assertion in ComputeCmp will fail.
100 enum Predicate {
101   ICMP_EQ = 32,  ///< equal
102   ICMP_NE = 33,  ///< not equal
103   ICMP_UGT = 34, ///< unsigned greater than
104   ICMP_UGE = 35, ///< unsigned greater or equal
105   ICMP_ULT = 36, ///< unsigned less than
106   ICMP_ULE = 37, ///< unsigned less or equal
107   ICMP_SGT = 38, ///< signed greater than
108   ICMP_SGE = 39, ///< signed greater or equal
109   ICMP_SLT = 40, ///< signed less than
110   ICMP_SLE = 41, ///< signed less or equal
111 };
112
113 template <class U, class S>
114 bool ComputeCmp(size_t CmpType, U Arg1, U Arg2) {
115   switch(CmpType) {
116     case ICMP_EQ : return Arg1 == Arg2;
117     case ICMP_NE : return Arg1 != Arg2;
118     case ICMP_UGT: return Arg1 > Arg2;
119     case ICMP_UGE: return Arg1 >= Arg2;
120     case ICMP_ULT: return Arg1 < Arg2;
121     case ICMP_ULE: return Arg1 <= Arg2;
122     case ICMP_SGT: return (S)Arg1 > (S)Arg2;
123     case ICMP_SGE: return (S)Arg1 >= (S)Arg2;
124     case ICMP_SLT: return (S)Arg1 < (S)Arg2;
125     case ICMP_SLE: return (S)Arg1 <= (S)Arg2;
126     default: assert(0 && "unsupported CmpType");
127   }
128   return false;
129 }
130
131 static bool ComputeCmp(size_t CmpSize, size_t CmpType, uint64_t Arg1,
132                        uint64_t Arg2) {
133   if (CmpSize == 8) return ComputeCmp<uint64_t, int64_t>(CmpType, Arg1, Arg2);
134   if (CmpSize == 4) return ComputeCmp<uint32_t, int32_t>(CmpType, Arg1, Arg2);
135   if (CmpSize == 2) return ComputeCmp<uint16_t, int16_t>(CmpType, Arg1, Arg2);
136   if (CmpSize == 1) return ComputeCmp<uint8_t, int8_t>(CmpType, Arg1, Arg2);
137   // Other size, ==
138   if (CmpType == ICMP_EQ) return Arg1 == Arg2;
139   // assert(0 && "unsupported cmp and type size combination");
140   return true;
141 }
142
143 // As a simplification we use the range of input bytes instead of a set of input
144 // bytes.
145 struct LabelRange {
146   uint16_t Beg, End;  // Range is [Beg, End), thus Beg==End is an empty range.
147
148   LabelRange(uint16_t Beg = 0, uint16_t End = 0) : Beg(Beg), End(End) {}
149
150   static LabelRange Join(LabelRange LR1, LabelRange LR2) {
151     if (LR1.Beg == LR1.End) return LR2;
152     if (LR2.Beg == LR2.End) return LR1;
153     return {std::min(LR1.Beg, LR2.Beg), std::max(LR1.End, LR2.End)};
154   }
155   LabelRange &Join(LabelRange LR) {
156     return *this = Join(*this, LR);
157   }
158   static LabelRange Singleton(const dfsan_label_info *LI) {
159     uint16_t Idx = (uint16_t)(uintptr_t)LI->userdata;
160     assert(Idx > 0);
161     return {(uint16_t)(Idx - 1), Idx};
162   }
163 };
164
165 // For now, very simple: put Size bytes of Data at position Pos.
166 struct TraceBasedMutation {
167   static const size_t kMaxSize = 28;
168   uint32_t Pos : 24;
169   uint32_t Size : 8;
170   uint8_t  Data[kMaxSize];
171 };
172
173 static void PrintDataByte(uint8_t Byte) {
174   if (Byte == '\\')
175     Printf("\\\\");
176   else if (Byte == '"')
177     Printf("\\\"");
178   else if (Byte >= 32 && Byte < 127)
179     Printf("%c", Byte);
180   else
181     Printf("\\x%02x", Byte);
182 }
183
184 static void PrintData(const uint8_t *Data, size_t Size) {
185   Printf("\"");
186   for (size_t i = 0; i < Size; i++) {
187     PrintDataByte(Data[i]);
188   }
189   Printf("\"");
190 }
191
192 const size_t TraceBasedMutation::kMaxSize;
193
194 class TraceState {
195  public:
196   TraceState(UserSuppliedFuzzer &USF,
197              const Fuzzer::FuzzingOptions &Options, const Unit &CurrentUnit)
198        : USF(USF), Options(Options), CurrentUnit(CurrentUnit) {
199     // Current trace collection is not thread-friendly and it probably
200     // does not have to be such, but at least we should not crash in presence
201     // of threads. So, just ignore all traces coming from all threads but one.
202     IsMyThread = true;
203   }
204
205   LabelRange GetLabelRange(dfsan_label L);
206   void DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
207                         uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
208                         dfsan_label L2);
209   void DFSanMemcmpCallback(size_t CmpSize, const uint8_t *Data1,
210                            const uint8_t *Data2, dfsan_label L1,
211                            dfsan_label L2);
212   void DFSanSwitchCallback(uint64_t PC, size_t ValSizeInBits, uint64_t Val,
213                            size_t NumCases, uint64_t *Cases, dfsan_label L);
214   void TraceCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
215                         uint64_t Arg1, uint64_t Arg2);
216   void TraceMemcmpCallback(size_t CmpSize, const uint8_t *Data1,
217                            const uint8_t *Data2);
218
219   void TraceSwitchCallback(uintptr_t PC, size_t ValSizeInBits, uint64_t Val,
220                            size_t NumCases, uint64_t *Cases);
221   int TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
222                            size_t DataSize);
223   int TryToAddDesiredData(const uint8_t *PresentData,
224                           const uint8_t *DesiredData, size_t DataSize);
225
226   void StartTraceRecording() {
227     if (!Options.UseTraces) return;
228     RecordingTraces = true;
229     NumMutations = 0;
230     USF.GetMD().ClearAutoDictionary();
231   }
232
233   void StopTraceRecording() {
234     if (!RecordingTraces) return;
235     RecordingTraces = false;
236     for (size_t i = 0; i < NumMutations; i++) {
237       auto &M = Mutations[i];
238       Unit U(M.Data, M.Data + M.Size);
239       if (Options.Verbosity >= 2) {
240         AutoDictUnitCounts[U]++;
241         AutoDictAdds++;
242         if ((AutoDictAdds & (AutoDictAdds - 1)) == 0) {
243           typedef std::pair<size_t, Unit> CU;
244           std::vector<CU> CountedUnits;
245           for (auto &I : AutoDictUnitCounts)
246             CountedUnits.push_back(std::make_pair(I.second, I.first));
247           std::sort(CountedUnits.begin(), CountedUnits.end(),
248                     [](const CU &a, const CU &b) { return a.first > b.first; });
249           Printf("AutoDict:\n");
250           for (auto &I : CountedUnits) {
251             Printf("   %zd ", I.first);
252             PrintData(I.second.data(), I.second.size());
253             Printf("\n");
254           }
255         }
256       }
257       USF.GetMD().AddWordToAutoDictionary(U, M.Pos);
258     }
259   }
260
261   void AddMutation(uint32_t Pos, uint32_t Size, const uint8_t *Data) {
262     if (NumMutations >= kMaxMutations) return;
263     assert(Size <= TraceBasedMutation::kMaxSize);
264     auto &M = Mutations[NumMutations++];
265     M.Pos = Pos;
266     M.Size = Size;
267     memcpy(M.Data, Data, Size);
268   }
269
270   void AddMutation(uint32_t Pos, uint32_t Size, uint64_t Data) {
271     assert(Size <= sizeof(Data));
272     AddMutation(Pos, Size, reinterpret_cast<uint8_t*>(&Data));
273   }
274
275  private:
276   bool IsTwoByteData(uint64_t Data) {
277     int64_t Signed = static_cast<int64_t>(Data);
278     Signed >>= 16;
279     return Signed == 0 || Signed == -1L;
280   }
281   bool RecordingTraces = false;
282   static const size_t kMaxMutations = 1 << 16;
283   size_t NumMutations;
284   TraceBasedMutation Mutations[kMaxMutations];
285   LabelRange LabelRanges[1 << (sizeof(dfsan_label) * 8)];
286   UserSuppliedFuzzer &USF;
287   const Fuzzer::FuzzingOptions &Options;
288   const Unit &CurrentUnit;
289   std::map<Unit, size_t> AutoDictUnitCounts;
290   size_t AutoDictAdds = 0;
291   static thread_local bool IsMyThread;
292 };
293
294 thread_local bool TraceState::IsMyThread;
295
296 LabelRange TraceState::GetLabelRange(dfsan_label L) {
297   LabelRange &LR = LabelRanges[L];
298   if (LR.Beg < LR.End || L == 0)
299     return LR;
300   const dfsan_label_info *LI = dfsan_get_label_info(L);
301   if (LI->l1 || LI->l2)
302     return LR = LabelRange::Join(GetLabelRange(LI->l1), GetLabelRange(LI->l2));
303   return LR = LabelRange::Singleton(LI);
304 }
305
306 void TraceState::DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
307                                   uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
308                                   dfsan_label L2) {
309   assert(ReallyHaveDFSan());
310   if (!RecordingTraces || !IsMyThread) return;
311   if (L1 == 0 && L2 == 0)
312     return;  // Not actionable.
313   if (L1 != 0 && L2 != 0)
314     return;  // Probably still actionable.
315   bool Res = ComputeCmp(CmpSize, CmpType, Arg1, Arg2);
316   uint64_t Data = L1 ? Arg2 : Arg1;
317   LabelRange LR = L1 ? GetLabelRange(L1) : GetLabelRange(L2);
318
319   for (size_t Pos = LR.Beg; Pos + CmpSize <= LR.End; Pos++) {
320     AddMutation(Pos, CmpSize, Data);
321     AddMutation(Pos, CmpSize, Data + 1);
322     AddMutation(Pos, CmpSize, Data - 1);
323   }
324
325   if (CmpSize > LR.End - LR.Beg)
326     AddMutation(LR.Beg, (unsigned)(LR.End - LR.Beg), Data);
327
328
329   if (Options.Verbosity >= 3)
330     Printf("DFSanCmpCallback: PC %lx S %zd T %zd A1 %llx A2 %llx R %d L1 %d L2 "
331            "%d MU %zd\n",
332            PC, CmpSize, CmpType, Arg1, Arg2, Res, L1, L2, NumMutations);
333 }
334
335 void TraceState::DFSanMemcmpCallback(size_t CmpSize, const uint8_t *Data1,
336                                      const uint8_t *Data2, dfsan_label L1,
337                                      dfsan_label L2) {
338
339   assert(ReallyHaveDFSan());
340   if (!RecordingTraces || !IsMyThread) return;
341   if (L1 == 0 && L2 == 0)
342     return;  // Not actionable.
343   if (L1 != 0 && L2 != 0)
344     return;  // Probably still actionable.
345
346   const uint8_t *Data = L1 ? Data2 : Data1;
347   LabelRange LR = L1 ? GetLabelRange(L1) : GetLabelRange(L2);
348   for (size_t Pos = LR.Beg; Pos + CmpSize <= LR.End; Pos++) {
349     AddMutation(Pos, CmpSize, Data);
350     if (Options.Verbosity >= 3)
351       Printf("DFSanMemcmpCallback: Pos %d Size %d\n", Pos, CmpSize);
352   }
353 }
354
355 void TraceState::DFSanSwitchCallback(uint64_t PC, size_t ValSizeInBits,
356                                      uint64_t Val, size_t NumCases,
357                                      uint64_t *Cases, dfsan_label L) {
358   assert(ReallyHaveDFSan());
359   if (!RecordingTraces || !IsMyThread) return;
360   if (!L) return;  // Not actionable.
361   LabelRange LR = GetLabelRange(L);
362   size_t ValSize = ValSizeInBits / 8;
363   bool TryShort = IsTwoByteData(Val);
364   for (size_t i = 0; i < NumCases; i++)
365     TryShort &= IsTwoByteData(Cases[i]);
366
367   for (size_t Pos = LR.Beg; Pos + ValSize <= LR.End; Pos++)
368     for (size_t i = 0; i < NumCases; i++)
369       AddMutation(Pos, ValSize, Cases[i]);
370
371   if (TryShort)
372     for (size_t Pos = LR.Beg; Pos + 2 <= LR.End; Pos++)
373       for (size_t i = 0; i < NumCases; i++)
374         AddMutation(Pos, 2, Cases[i]);
375
376   if (Options.Verbosity >= 3)
377     Printf("DFSanSwitchCallback: PC %lx Val %zd SZ %zd # %zd L %d: {%d, %d} "
378            "TryShort %d\n",
379            PC, Val, ValSize, NumCases, L, LR.Beg, LR.End, TryShort);
380 }
381
382 int TraceState::TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
383                                     size_t DataSize) {
384   int Res = 0;
385   const uint8_t *Beg = CurrentUnit.data();
386   const uint8_t *End = Beg + CurrentUnit.size();
387   for (const uint8_t *Cur = Beg; Cur < End; Cur++) {
388     Cur = (uint8_t *)memmem(Cur, End - Cur, &PresentData, DataSize);
389     if (!Cur)
390       break;
391     size_t Pos = Cur - Beg;
392     assert(Pos < CurrentUnit.size());
393     AddMutation(Pos, DataSize, DesiredData);
394     AddMutation(Pos, DataSize, DesiredData + 1);
395     AddMutation(Pos, DataSize, DesiredData - 1);
396     Res++;
397   }
398   return Res;
399 }
400
401 int TraceState::TryToAddDesiredData(const uint8_t *PresentData,
402                                     const uint8_t *DesiredData,
403                                     size_t DataSize) {
404   int Res = 0;
405   const uint8_t *Beg = CurrentUnit.data();
406   const uint8_t *End = Beg + CurrentUnit.size();
407   for (const uint8_t *Cur = Beg; Cur < End; Cur++) {
408     Cur = (uint8_t *)memmem(Cur, End - Cur, PresentData, DataSize);
409     if (!Cur)
410       break;
411     size_t Pos = Cur - Beg;
412     assert(Pos < CurrentUnit.size());
413     AddMutation(Pos, DataSize, DesiredData);
414     Res++;
415   }
416   return Res;
417 }
418
419 void TraceState::TraceCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
420                                   uint64_t Arg1, uint64_t Arg2) {
421   if (!RecordingTraces || !IsMyThread) return;
422   if ((CmpType == ICMP_EQ || CmpType == ICMP_NE) && Arg1 == Arg2)
423     return;  // No reason to mutate.
424   int Added = 0;
425   Added += TryToAddDesiredData(Arg1, Arg2, CmpSize);
426   Added += TryToAddDesiredData(Arg2, Arg1, CmpSize);
427   if (!Added && CmpSize == 4 && IsTwoByteData(Arg1) && IsTwoByteData(Arg2)) {
428     Added += TryToAddDesiredData(Arg1, Arg2, 2);
429     Added += TryToAddDesiredData(Arg2, Arg1, 2);
430   }
431   if (Options.Verbosity >= 3 && Added)
432     Printf("TraceCmp %zd/%zd: %p %zd %zd\n", CmpSize, CmpType, PC, Arg1, Arg2);
433 }
434
435 void TraceState::TraceMemcmpCallback(size_t CmpSize, const uint8_t *Data1,
436                                      const uint8_t *Data2) {
437   if (!RecordingTraces || !IsMyThread) return;
438   CmpSize = std::min(CmpSize, TraceBasedMutation::kMaxSize);
439   int Added2 = TryToAddDesiredData(Data1, Data2, CmpSize);
440   int Added1 = TryToAddDesiredData(Data2, Data1, CmpSize);
441   if ((Added1 || Added2) && Options.Verbosity >= 3) {
442     Printf("MemCmp Added %d%d: ", Added1, Added2);
443     if (Added1) PrintData(Data1, CmpSize);
444     if (Added2) PrintData(Data2, CmpSize);
445     Printf("\n");
446   }
447 }
448
449 void TraceState::TraceSwitchCallback(uintptr_t PC, size_t ValSizeInBits,
450                                      uint64_t Val, size_t NumCases,
451                                      uint64_t *Cases) {
452   if (!RecordingTraces || !IsMyThread) return;
453   size_t ValSize = ValSizeInBits / 8;
454   bool TryShort = IsTwoByteData(Val);
455   for (size_t i = 0; i < NumCases; i++)
456     TryShort &= IsTwoByteData(Cases[i]);
457
458   if (Options.Verbosity >= 3)
459     Printf("TraceSwitch: %p %zd # %zd; TryShort %d\n", PC, Val, NumCases,
460            TryShort);
461
462   for (size_t i = 0; i < NumCases; i++) {
463     TryToAddDesiredData(Val, Cases[i], ValSize);
464     if (TryShort)
465       TryToAddDesiredData(Val, Cases[i], 2);
466   }
467 }
468
469 static TraceState *TS;
470
471 void Fuzzer::StartTraceRecording() {
472   if (!TS) return;
473   if (ReallyHaveDFSan())
474     for (size_t i = 0; i < static_cast<size_t>(Options.MaxLen); i++)
475       dfsan_set_label(i + 1, &CurrentUnit[i], 1);
476   TS->StartTraceRecording();
477 }
478
479 void Fuzzer::StopTraceRecording() {
480   if (!TS) return;
481   TS->StopTraceRecording();
482 }
483
484 void Fuzzer::InitializeTraceState() {
485   if (!Options.UseTraces) return;
486   TS = new TraceState(USF, Options, CurrentUnit);
487   CurrentUnit.resize(Options.MaxLen);
488   // The rest really requires DFSan.
489   if (!ReallyHaveDFSan()) return;
490   for (size_t i = 0; i < static_cast<size_t>(Options.MaxLen); i++) {
491     dfsan_label L = dfsan_create_label("input", (void*)(i + 1));
492     // We assume that no one else has called dfsan_create_label before.
493     if (L != i + 1) {
494       Printf("DFSan labels are not starting from 1, exiting\n");
495       exit(1);
496     }
497   }
498 }
499
500 static size_t InternalStrnlen(const char *S, size_t MaxLen) {
501   size_t Len = 0;
502   for (; Len < MaxLen && S[Len]; Len++) {}
503   return Len;
504 }
505
506 }  // namespace fuzzer
507
508 using fuzzer::TS;
509
510 extern "C" {
511 void __dfsw___sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
512                                       uint64_t Arg2, dfsan_label L0,
513                                       dfsan_label L1, dfsan_label L2) {
514   if (!TS) return;
515   assert(L0 == 0);
516   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
517   uint64_t CmpSize = (SizeAndType >> 32) / 8;
518   uint64_t Type = (SizeAndType << 32) >> 32;
519   TS->DFSanCmpCallback(PC, CmpSize, Type, Arg1, Arg2, L1, L2);
520 }
521
522 void __dfsw___sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases,
523                                          dfsan_label L1, dfsan_label L2) {
524   if (!TS) return;
525   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
526   TS->DFSanSwitchCallback(PC, Cases[1], Val, Cases[0], Cases+2, L1);
527 }
528
529 void dfsan_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2,
530                             size_t n, dfsan_label s1_label,
531                             dfsan_label s2_label, dfsan_label n_label) {
532   if (!TS) return;
533   dfsan_label L1 = dfsan_read_label(s1, n);
534   dfsan_label L2 = dfsan_read_label(s2, n);
535   TS->DFSanMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1),
536                           reinterpret_cast<const uint8_t *>(s2), L1, L2);
537 }
538
539 void dfsan_weak_hook_strncmp(void *caller_pc, const char *s1, const char *s2,
540                              size_t n, dfsan_label s1_label,
541                              dfsan_label s2_label, dfsan_label n_label) {
542   if (!TS) return;
543   n = std::min(n, fuzzer::InternalStrnlen(s1, n));
544   n = std::min(n, fuzzer::InternalStrnlen(s2, n));
545   dfsan_label L1 = dfsan_read_label(s1, n);
546   dfsan_label L2 = dfsan_read_label(s2, n);
547   TS->DFSanMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1),
548                           reinterpret_cast<const uint8_t *>(s2), L1, L2);
549 }
550
551 void dfsan_weak_hook_strcmp(void *caller_pc, const char *s1, const char *s2,
552                             dfsan_label s1_label, dfsan_label s2_label) {
553   if (!TS) return;
554   size_t Len1 = strlen(s1);
555   size_t Len2 = strlen(s2);
556   size_t N = std::min(Len1, Len2);
557   if (N <= 1) return;  // Not interesting.
558   dfsan_label L1 = dfsan_read_label(s1, Len1);
559   dfsan_label L2 = dfsan_read_label(s2, Len2);
560   TS->DFSanMemcmpCallback(N, reinterpret_cast<const uint8_t *>(s1),
561                           reinterpret_cast<const uint8_t *>(s2), L1, L2);
562 }
563
564 void __sanitizer_weak_hook_memcmp(void *caller_pc, const void *s1,
565                                   const void *s2, size_t n, int result) {
566   if (!TS) return;
567   if (result == 0) return;  // No reason to mutate.
568   if (n <= 1) return;  // Not interesting.
569   TS->TraceMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1),
570                           reinterpret_cast<const uint8_t *>(s2));
571 }
572
573 void __sanitizer_weak_hook_strncmp(void *caller_pc, const char *s1,
574                                    const char *s2, size_t n, int result) {
575   if (!TS) return;
576   if (result == 0) return;  // No reason to mutate.
577   size_t Len1 = fuzzer::InternalStrnlen(s1, n);
578   size_t Len2 = fuzzer::InternalStrnlen(s2, n);
579   n = std::min(n, Len1);
580   n = std::min(n, Len2);
581   if (n <= 1) return;  // Not interesting.
582   TS->TraceMemcmpCallback(n, reinterpret_cast<const uint8_t *>(s1),
583                           reinterpret_cast<const uint8_t *>(s2));
584 }
585
586 void __sanitizer_weak_hook_strcmp(void *caller_pc, const char *s1,
587                                    const char *s2, int result) {
588   if (!TS) return;
589   if (result == 0) return;  // No reason to mutate.
590   size_t Len1 = strlen(s1);
591   size_t Len2 = strlen(s2);
592   size_t N = std::min(Len1, Len2);
593   if (N <= 1) return;  // Not interesting.
594   TS->TraceMemcmpCallback(N, reinterpret_cast<const uint8_t *>(s1),
595                           reinterpret_cast<const uint8_t *>(s2));
596 }
597
598 __attribute__((visibility("default")))
599 void __sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
600                                uint64_t Arg2) {
601   if (!TS) return;
602   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
603   uint64_t CmpSize = (SizeAndType >> 32) / 8;
604   uint64_t Type = (SizeAndType << 32) >> 32;
605   TS->TraceCmpCallback(PC, CmpSize, Type, Arg1, Arg2);
606 }
607
608 __attribute__((visibility("default")))
609 void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) {
610   if (!TS) return;
611   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
612   TS->TraceSwitchCallback(PC, Cases[1], Val, Cases[0], Cases + 2);
613 }
614
615 }  // extern "C"