[libFuzzer] avoid build warnings in non-assert build (useful warning in this case)
[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 //   * Fuzzer::ApplyTraceBasedMutation() tries to use the data recorded
50 //     by __dfsw_* hooks to guide the fuzzing towards new application states.
51 //
52 // Parts of this code will not function when DFSan is not linked in.
53 // Instead of using ifdefs and thus requiring a separate build of lib/Fuzzer
54 // we redeclare the dfsan_* interface functions as weak and check if they
55 // are nullptr before calling.
56 // If this approach proves to be useful we may add attribute(weak) to the
57 // dfsan declarations in dfsan_interface.h
58 //
59 // This module is in the "proof of concept" stage.
60 // It is capable of solving only the simplest puzzles
61 // like test/dfsan/DFSanSimpleCmpTest.cpp.
62 //===----------------------------------------------------------------------===//
63
64 /* Example of manual usage (-fsanitize=dataflow is optional):
65 (
66   cd $LLVM/lib/Fuzzer/
67   clang  -fPIC -c -g -O2 -std=c++11 Fuzzer*.cpp
68   clang++ -O0 -std=c++11 -fsanitize-coverage=edge,trace-cmp \
69     -fsanitize=dataflow \
70     test/dfsan/DFSanSimpleCmpTest.cpp Fuzzer*.o
71   ./a.out
72 )
73 */
74
75 #include "FuzzerInternal.h"
76 #include <sanitizer/dfsan_interface.h>
77
78 #include <algorithm>
79 #include <cstring>
80 #include <unordered_map>
81
82 extern "C" {
83 __attribute__((weak))
84 dfsan_label dfsan_create_label(const char *desc, void *userdata);
85 __attribute__((weak))
86 void dfsan_set_label(dfsan_label label, void *addr, size_t size);
87 __attribute__((weak))
88 void dfsan_add_label(dfsan_label label, void *addr, size_t size);
89 __attribute__((weak))
90 const struct dfsan_label_info *dfsan_get_label_info(dfsan_label label);
91 __attribute__((weak))
92 dfsan_label dfsan_read_label(const void *addr, size_t size);
93 }  // extern "C"
94
95 namespace fuzzer {
96
97 static bool ReallyHaveDFSan() {
98   return &dfsan_create_label != nullptr;
99 }
100
101 // These values are copied from include/llvm/IR/InstrTypes.h.
102 // We do not include the LLVM headers here to remain independent.
103 // If these values ever change, an assertion in ComputeCmp will fail.
104 enum Predicate {
105   ICMP_EQ = 32,  ///< equal
106   ICMP_NE = 33,  ///< not equal
107   ICMP_UGT = 34, ///< unsigned greater than
108   ICMP_UGE = 35, ///< unsigned greater or equal
109   ICMP_ULT = 36, ///< unsigned less than
110   ICMP_ULE = 37, ///< unsigned less or equal
111   ICMP_SGT = 38, ///< signed greater than
112   ICMP_SGE = 39, ///< signed greater or equal
113   ICMP_SLT = 40, ///< signed less than
114   ICMP_SLE = 41, ///< signed less or equal
115 };
116
117 template <class U, class S>
118 bool ComputeCmp(size_t CmpType, U Arg1, U Arg2) {
119   switch(CmpType) {
120     case ICMP_EQ : return Arg1 == Arg2;
121     case ICMP_NE : return Arg1 != Arg2;
122     case ICMP_UGT: return Arg1 > Arg2;
123     case ICMP_UGE: return Arg1 >= Arg2;
124     case ICMP_ULT: return Arg1 < Arg2;
125     case ICMP_ULE: return Arg1 <= Arg2;
126     case ICMP_SGT: return (S)Arg1 > (S)Arg2;
127     case ICMP_SGE: return (S)Arg1 >= (S)Arg2;
128     case ICMP_SLT: return (S)Arg1 < (S)Arg2;
129     case ICMP_SLE: return (S)Arg1 <= (S)Arg2;
130     default: assert(0 && "unsupported CmpType");
131   }
132   return false;
133 }
134
135 static bool ComputeCmp(size_t CmpSize, size_t CmpType, uint64_t Arg1,
136                        uint64_t Arg2) {
137   if (CmpSize == 8) return ComputeCmp<uint64_t, int64_t>(CmpType, Arg1, Arg2);
138   if (CmpSize == 4) return ComputeCmp<uint32_t, int32_t>(CmpType, Arg1, Arg2);
139   if (CmpSize == 2) return ComputeCmp<uint16_t, int16_t>(CmpType, Arg1, Arg2);
140   if (CmpSize == 1) return ComputeCmp<uint8_t, int8_t>(CmpType, Arg1, Arg2);
141   // Other size, ==
142   if (CmpType == ICMP_EQ) return Arg1 == Arg2;
143   // assert(0 && "unsupported cmp and type size combination");
144   return true;
145 }
146
147 // As a simplification we use the range of input bytes instead of a set of input
148 // bytes.
149 struct LabelRange {
150   uint16_t Beg, End;  // Range is [Beg, End), thus Beg==End is an empty range.
151
152   LabelRange(uint16_t Beg = 0, uint16_t End = 0) : Beg(Beg), End(End) {}
153
154   static LabelRange Join(LabelRange LR1, LabelRange LR2) {
155     if (LR1.Beg == LR1.End) return LR2;
156     if (LR2.Beg == LR2.End) return LR1;
157     return {std::min(LR1.Beg, LR2.Beg), std::max(LR1.End, LR2.End)};
158   }
159   LabelRange &Join(LabelRange LR) {
160     return *this = Join(*this, LR);
161   }
162   static LabelRange Singleton(const dfsan_label_info *LI) {
163     uint16_t Idx = (uint16_t)(uintptr_t)LI->userdata;
164     assert(Idx > 0);
165     return {(uint16_t)(Idx - 1), Idx};
166   }
167 };
168
169 // A passport for a CMP site. We want to keep track of where the given CMP is
170 // and how many times it is evaluated to true or false.
171 struct CmpSitePassport {
172   uintptr_t PC;
173   size_t Counter[2];
174
175   bool IsInterestingCmpTarget() {
176     static const size_t kRareEnough = 50;
177     size_t C0 = Counter[0];
178     size_t C1 = Counter[1];
179     return C0 > kRareEnough * (C1 + 1) || C1 > kRareEnough * (C0 + 1);
180   }
181 };
182
183 // For now, just keep a simple imprecise hash table PC => CmpSitePassport.
184 // Potentially, will need to have a compiler support to have a precise mapping
185 // and also thread-safety.
186 struct CmpSitePassportTable {
187   static const size_t kSize = 99991;  // Prime.
188   CmpSitePassport Passports[kSize];
189
190   CmpSitePassport *GetPassport(uintptr_t PC) {
191     uintptr_t Idx = PC & kSize;
192     CmpSitePassport *Res = &Passports[Idx];
193     if (Res->PC == 0)  // Not thread safe.
194       Res->PC = PC;
195     return Res->PC == PC ? Res : nullptr;
196   }
197 };
198
199 static CmpSitePassportTable CSPTable;  // Zero initialized.
200
201 // For now, very simple: put Size bytes of Data at position Pos.
202 struct TraceBasedMutation {
203   size_t Pos;
204   size_t Size;
205   uint64_t Data;
206 };
207
208 class TraceState {
209  public:
210    TraceState(const Fuzzer::FuzzingOptions &Options, const Unit &CurrentUnit)
211        : Options(Options), CurrentUnit(CurrentUnit) {}
212
213   LabelRange GetLabelRange(dfsan_label L);
214   void DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
215                         uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
216                         dfsan_label L2);
217   void DFSanSwitchCallback(uint64_t PC, size_t ValSizeInBits, uint64_t Val,
218                            size_t NumCases, uint64_t *Cases, dfsan_label L);
219   void TraceCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType, uint64_t Arg1,
220                         uint64_t Arg2);
221
222   void TraceSwitchCallback(uintptr_t PC, size_t ValSizeInBits, uint64_t Val,
223                            size_t NumCases, uint64_t *Cases);
224   int TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
225                            size_t DataSize);
226
227   void StartTraceRecording() {
228     if (!Options.UseTraces) return;
229     RecordingTraces = true;
230     Mutations.clear();
231   }
232
233   size_t StopTraceRecording(FuzzerRandomBase &Rand) {
234     RecordingTraces = false;
235     std::random_shuffle(Mutations.begin(), Mutations.end(), Rand);
236     return std::min(Mutations.size(), 128UL);
237   }
238
239   void ApplyTraceBasedMutation(size_t Idx, fuzzer::Unit *U);
240
241  private:
242   bool IsTwoByteData(uint64_t Data) {
243     int64_t Signed = static_cast<int64_t>(Data);
244     Signed >>= 16;
245     return Signed == 0 || Signed == -1L;
246   }
247   bool RecordingTraces = false;
248   std::vector<TraceBasedMutation> Mutations;
249   LabelRange LabelRanges[1 << (sizeof(dfsan_label) * 8)] = {};
250   const Fuzzer::FuzzingOptions &Options;
251   const Unit &CurrentUnit;
252 };
253
254 LabelRange TraceState::GetLabelRange(dfsan_label L) {
255   LabelRange &LR = LabelRanges[L];
256   if (LR.Beg < LR.End || L == 0)
257     return LR;
258   const dfsan_label_info *LI = dfsan_get_label_info(L);
259   if (LI->l1 || LI->l2)
260     return LR = LabelRange::Join(GetLabelRange(LI->l1), GetLabelRange(LI->l2));
261   return LR = LabelRange::Singleton(LI);
262 }
263
264 void TraceState::ApplyTraceBasedMutation(size_t Idx, fuzzer::Unit *U) {
265   assert(Idx < Mutations.size());
266   auto &M = Mutations[Idx];
267   if (Options.Verbosity >= 3)
268     Printf("TBM %zd %zd %zd\n", M.Pos, M.Size, M.Data);
269   if (M.Pos + M.Size > U->size()) return;
270   memcpy(U->data() + M.Pos, &M.Data, M.Size);
271 }
272
273 void TraceState::DFSanCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType,
274                                   uint64_t Arg1, uint64_t Arg2, dfsan_label L1,
275                                   dfsan_label L2) {
276   assert(ReallyHaveDFSan());
277   if (!RecordingTraces) return;
278   if (L1 == 0 && L2 == 0)
279     return;  // Not actionable.
280   if (L1 != 0 && L2 != 0)
281     return;  // Probably still actionable.
282   bool Res = ComputeCmp(CmpSize, CmpType, Arg1, Arg2);
283   uint64_t Data = L1 ? Arg2 : Arg1;
284   LabelRange LR = L1 ? GetLabelRange(L1) : GetLabelRange(L2);
285
286   for (size_t Pos = LR.Beg; Pos + CmpSize <= LR.End; Pos++) {
287     Mutations.push_back({Pos, CmpSize, Data});
288     Mutations.push_back({Pos, CmpSize, Data + 1});
289     Mutations.push_back({Pos, CmpSize, Data - 1});
290   }
291
292   if (CmpSize > LR.End - LR.Beg)
293     Mutations.push_back({LR.Beg, (unsigned)(LR.End - LR.Beg), Data});
294
295
296   if (Options.Verbosity >= 3)
297     Printf("DFSanCmpCallback: PC %lx S %zd T %zd A1 %llx A2 %llx R %d L1 %d L2 "
298            "%d MU %zd\n",
299            PC, CmpSize, CmpType, Arg1, Arg2, Res, L1, L2, Mutations.size());
300 }
301
302 void TraceState::DFSanSwitchCallback(uint64_t PC, size_t ValSizeInBits,
303                                      uint64_t Val, size_t NumCases,
304                                      uint64_t *Cases, dfsan_label L) {
305   assert(ReallyHaveDFSan());
306   if (!RecordingTraces) return;
307   if (!L) return;  // Not actionable.
308   LabelRange LR = GetLabelRange(L);
309   size_t ValSize = ValSizeInBits / 8;
310   bool TryShort = IsTwoByteData(Val);
311   for (size_t i = 0; i < NumCases; i++)
312     TryShort &= IsTwoByteData(Cases[i]);
313
314   for (size_t Pos = LR.Beg; Pos + ValSize <= LR.End; Pos++)
315     for (size_t i = 0; i < NumCases; i++)
316       Mutations.push_back({Pos, ValSize, Cases[i]});
317
318   if (TryShort)
319     for (size_t Pos = LR.Beg; Pos + 2 <= LR.End; Pos++)
320       for (size_t i = 0; i < NumCases; i++)
321         Mutations.push_back({Pos, 2, Cases[i]});
322
323   if (Options.Verbosity >= 3)
324     Printf("DFSanSwitchCallback: PC %lx Val %zd SZ %zd # %zd L %d: {%d, %d} "
325            "TryShort %d\n",
326            PC, Val, ValSize, NumCases, L, LR.Beg, LR.End, TryShort);
327 }
328
329 int TraceState::TryToAddDesiredData(uint64_t PresentData, uint64_t DesiredData,
330                                     size_t DataSize) {
331   int Res = 0;
332   const uint8_t *Beg = CurrentUnit.data();
333   const uint8_t *End = Beg + CurrentUnit.size();
334   for (const uint8_t *Cur = Beg; Cur < End; Cur += DataSize) {
335     Cur = (uint8_t *)memmem(Cur, End - Cur, &PresentData, DataSize);
336     if (!Cur)
337       break;
338     size_t Pos = Cur - Beg;
339     assert(Pos < CurrentUnit.size());
340     if (Mutations.size() > 100000U) return Res;  // Just in case.
341     Mutations.push_back({Pos, DataSize, DesiredData});
342     Mutations.push_back({Pos, DataSize, DesiredData + 1});
343     Mutations.push_back({Pos, DataSize, DesiredData - 1});
344     Cur += DataSize;
345     Res++;
346   }
347   return Res;
348 }
349
350 void TraceState::TraceCmpCallback(uintptr_t PC, size_t CmpSize, size_t CmpType, uint64_t Arg1,
351                         uint64_t Arg2) {
352   if (!RecordingTraces) return;
353   int Added = 0;
354   CmpSitePassport *CSP = CSPTable.GetPassport(PC);
355   if (!CSP) return;
356   CSP->Counter[ComputeCmp(CmpSize, CmpType, Arg1, Arg2)]++;
357   size_t C0 = CSP->Counter[0];
358   size_t C1 = CSP->Counter[1];
359   // FIXME: is this a good idea or a bad?
360   // if (!CSP->IsInterestingCmpTarget())
361   //  return;
362   if (Options.Verbosity >= 3)
363     Printf("TraceCmp: %p %zd/%zd; %zd %zd\n", CSP->PC, C0, C1, Arg1, Arg2);
364   Added += TryToAddDesiredData(Arg1, Arg2, CmpSize);
365   Added += TryToAddDesiredData(Arg2, Arg1, CmpSize);
366   if (!Added && CmpSize == 4 && IsTwoByteData(Arg1) && IsTwoByteData(Arg2)) {
367     Added += TryToAddDesiredData(Arg1, Arg2, 2);
368     Added += TryToAddDesiredData(Arg2, Arg1, 2);
369   }
370 }
371
372 void TraceState::TraceSwitchCallback(uintptr_t PC, size_t ValSizeInBits,
373                                      uint64_t Val, size_t NumCases,
374                                      uint64_t *Cases) {
375   if (!RecordingTraces) return;
376   size_t ValSize = ValSizeInBits / 8;
377   bool TryShort = IsTwoByteData(Val);
378   for (size_t i = 0; i < NumCases; i++)
379     TryShort &= IsTwoByteData(Cases[i]);
380
381   if (Options.Verbosity >= 3)
382     Printf("TraceSwitch: %p %zd # %zd; TryShort %d\n", PC, Val, NumCases,
383            TryShort);
384
385   for (size_t i = 0; i < NumCases; i++) {
386     TryToAddDesiredData(Val, Cases[i], ValSize);
387     if (TryShort)
388       TryToAddDesiredData(Val, Cases[i], 2);
389   }
390
391 }
392
393 static TraceState *TS;
394
395 void Fuzzer::StartTraceRecording() {
396   if (!TS) return;
397   if (ReallyHaveDFSan())
398     for (size_t i = 0; i < static_cast<size_t>(Options.MaxLen); i++)
399       dfsan_set_label(i + 1, &CurrentUnit[i], 1);
400   TS->StartTraceRecording();
401 }
402
403 size_t Fuzzer::StopTraceRecording() {
404   if (!TS) return 0;
405   return TS->StopTraceRecording(USF.GetRand());
406 }
407
408 void Fuzzer::ApplyTraceBasedMutation(size_t Idx, Unit *U) {
409   assert(TS);
410   TS->ApplyTraceBasedMutation(Idx, U);
411 }
412
413 void Fuzzer::InitializeTraceState() {
414   if (!Options.UseTraces) return;
415   TS = new TraceState(Options, CurrentUnit);
416   CurrentUnit.resize(Options.MaxLen);
417   // The rest really requires DFSan.
418   if (!ReallyHaveDFSan()) return;
419   for (size_t i = 0; i < static_cast<size_t>(Options.MaxLen); i++) {
420     dfsan_label L = dfsan_create_label("input", (void*)(i + 1));
421     // We assume that no one else has called dfsan_create_label before.
422     if (L != i + 1) {
423       Printf("DFSan labels are not starting from 1, exiting\n");
424       exit(1);
425     }
426   }
427 }
428
429 static size_t InternalStrnlen(const char *S, size_t MaxLen) {
430   size_t Len = 0;
431   for (; Len < MaxLen && S[Len]; Len++) {}
432   return Len;
433 }
434
435 }  // namespace fuzzer
436
437 using fuzzer::TS;
438
439 extern "C" {
440 void __dfsw___sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
441                                       uint64_t Arg2, dfsan_label L0,
442                                       dfsan_label L1, dfsan_label L2) {
443   if (!TS) return;
444   assert(L0 == 0);
445   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
446   uint64_t CmpSize = (SizeAndType >> 32) / 8;
447   uint64_t Type = (SizeAndType << 32) >> 32;
448   TS->DFSanCmpCallback(PC, CmpSize, Type, Arg1, Arg2, L1, L2);
449 }
450
451 void __dfsw___sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases,
452                                          dfsan_label L1, dfsan_label L2) {
453   if (!TS) return;
454   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
455   TS->DFSanSwitchCallback(PC, Cases[1], Val, Cases[0], Cases+2, L1);
456 }
457
458 void dfsan_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2,
459                             size_t n, dfsan_label s1_label,
460                             dfsan_label s2_label, dfsan_label n_label) {
461   if (!TS) return;
462   uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
463   uint64_t S1 = 0, S2 = 0;
464   // Simplification: handle only first 8 bytes.
465   memcpy(&S1, s1, std::min(n, sizeof(S1)));
466   memcpy(&S2, s2, std::min(n, sizeof(S2)));
467   dfsan_label L1 = dfsan_read_label(s1, n);
468   dfsan_label L2 = dfsan_read_label(s2, n);
469   TS->DFSanCmpCallback(PC, n, fuzzer::ICMP_EQ, S1, S2, L1, L2);
470 }
471
472 void dfsan_weak_hook_strncmp(void *caller_pc, const char *s1, const char *s2,
473                              size_t n, dfsan_label s1_label,
474                              dfsan_label s2_label, dfsan_label n_label) {
475   if (!TS) return;
476   uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
477   uint64_t S1 = 0, S2 = 0;
478   n = std::min(n, fuzzer::InternalStrnlen(s1, n));
479   n = std::min(n, fuzzer::InternalStrnlen(s2, n));
480   // Simplification: handle only first 8 bytes.
481   memcpy(&S1, s1, std::min(n, sizeof(S1)));
482   memcpy(&S2, s2, std::min(n, sizeof(S2)));
483   dfsan_label L1 = dfsan_read_label(s1, n);
484   dfsan_label L2 = dfsan_read_label(s2, n);
485   TS->DFSanCmpCallback(PC, n, fuzzer::ICMP_EQ, S1, S2, L1, L2);
486 }
487
488 void dfsan_weak_hook_strcmp(void *caller_pc, const char *s1, const char *s2,
489                             dfsan_label s1_label, dfsan_label s2_label) {
490   if (!TS) return;
491   uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
492   uint64_t S1 = 0, S2 = 0;
493   size_t Len1 = strlen(s1);
494   size_t Len2 = strlen(s2);
495   size_t N = std::min(Len1, Len2);
496   if (N <= 1) return;  // Not interesting.
497   // Simplification: handle only first 8 bytes.
498   memcpy(&S1, s1, std::min(N, sizeof(S1)));
499   memcpy(&S2, s2, std::min(N, sizeof(S2)));
500   dfsan_label L1 = dfsan_read_label(s1, Len1);
501   dfsan_label L2 = dfsan_read_label(s2, Len2);
502   TS->DFSanCmpCallback(PC, N, fuzzer::ICMP_EQ, S1, S2, L1, L2);
503 }
504
505 void __sanitizer_weak_hook_memcmp(void *caller_pc, const void *s1,
506                                   const void *s2, size_t n) {
507   if (!TS) return;
508   uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
509   uint64_t S1 = 0, S2 = 0;
510   // Simplification: handle only first 8 bytes.
511   memcpy(&S1, s1, std::min(n, sizeof(S1)));
512   memcpy(&S2, s2, std::min(n, sizeof(S2)));
513   TS->TraceCmpCallback(PC, n, fuzzer::ICMP_EQ, S1, S2);
514 }
515
516 void __sanitizer_weak_hook_strncmp(void *caller_pc, const char *s1,
517                                    const char *s2, size_t n) {
518   if (!TS) return;
519   uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
520   uint64_t S1 = 0, S2 = 0;
521   size_t Len1 = fuzzer::InternalStrnlen(s1, n);
522   size_t Len2 = fuzzer::InternalStrnlen(s2, n);
523   n = std::min(n, Len1);
524   n = std::min(n, Len2);
525   if (n <= 1) return;  // Not interesting.
526   // Simplification: handle only first 8 bytes.
527   memcpy(&S1, s1, std::min(n, sizeof(S1)));
528   memcpy(&S2, s2, std::min(n, sizeof(S2)));
529   TS->TraceCmpCallback(PC, n, fuzzer::ICMP_EQ, S1, S2);
530 }
531
532 void __sanitizer_weak_hook_strcmp(void *caller_pc, const char *s1,
533                                    const char *s2) {
534   if (!TS) return;
535   uintptr_t PC = reinterpret_cast<uintptr_t>(caller_pc);
536   uint64_t S1 = 0, S2 = 0;
537   size_t Len1 = strlen(s1);
538   size_t Len2 = strlen(s2);
539   size_t N = std::min(Len1, Len2);
540   if (N <= 1) return;  // Not interesting.
541   // Simplification: handle only first 8 bytes.
542   memcpy(&S1, s1, std::min(N, sizeof(S1)));
543   memcpy(&S2, s2, std::min(N, sizeof(S2)));
544   TS->TraceCmpCallback(PC, N, fuzzer::ICMP_EQ, S1, S2);
545 }
546
547
548 void __sanitizer_cov_trace_cmp(uint64_t SizeAndType, uint64_t Arg1,
549                                uint64_t Arg2) {
550   if (!TS) return;
551   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
552   uint64_t CmpSize = (SizeAndType >> 32) / 8;
553   uint64_t Type = (SizeAndType << 32) >> 32;
554   TS->TraceCmpCallback(PC, CmpSize, Type, Arg1, Arg2);
555 }
556
557 void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases) {
558   if (!TS) return;
559   uintptr_t PC = reinterpret_cast<uintptr_t>(__builtin_return_address(0));
560   TS->TraceSwitchCallback(PC, Cases[1], Val, Cases[0], Cases + 2);
561 }
562
563 }  // extern "C"