1 /*===- DataFlow.cpp - a standalone DataFlow tracer                  -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // An experimental data-flow tracer for fuzz targets.
9 // It is based on DFSan and SanitizerCoverage.
10 // https://clang.llvm.org/docs/DataFlowSanitizer.html
11 // https://clang.llvm.org/docs/SanitizerCoverage.html#tracing-data-flow
12 //
13 // It executes the fuzz target on the given input while monitoring the
14 // data flow for every instrumented comparison instruction.
15 //
16 // The output shows which functions depend on which bytes of the input.
17 //
18 // Build:
19 //   1. Compile this file with -fsanitize=dataflow
20 //   2. Build the fuzz target with -g -fsanitize=dataflow
21 //       -fsanitize-coverage=trace-pc-guard,pc-table,func,trace-cmp
22 //   3. Link those together with -fsanitize=dataflow
23 //
24 //  -fsanitize-coverage=trace-cmp inserts callbacks around every comparison
25 //  instruction, DFSan modifies the calls to pass the data flow labels.
26 //  The callbacks update the data flow label for the current function.
27 //  See e.g. __dfsw___sanitizer_cov_trace_cmp1 below.
28 //
29 //  -fsanitize-coverage=trace-pc-guard,pc-table,func instruments function
30 //  entries so that the comparison callback knows that current function.
31 //
32 //
33 // Run:
34 //   # Collect data flow for INPUT_FILE, write to OUTPUT_FILE (default: stdout)
35 //   ./a.out INPUT_FILE [OUTPUT_FILE]
36 //
37 //   # Print all instrumented functions. llvm-symbolizer must be present in PATH
38 //   ./a.out
39 //
40 // Example output:
41 // ===============
42 //  F0 11111111111111
43 //  F1 10000000000000
44 //  ===============
45 // "FN xxxxxxxxxx": tells what bytes of the input does the function N depend on.
46 //    The byte string is LEN+1 bytes. The last byte is set if the function
47 //    depends on the input length.
48 //===----------------------------------------------------------------------===*/
49 
50 #include <assert.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <stdint.h>
54 #include <string.h>
55 
56 #include <execinfo.h>  // backtrace_symbols_fd
57 
58 #include <sanitizer/dfsan_interface.h>
59 
60 extern "C" {
61 extern int LLVMFuzzerTestOneInput(const unsigned char *Data, size_t Size);
62 __attribute__((weak)) extern int LLVMFuzzerInitialize(int *argc, char ***argv);
63 } // extern "C"
64 
65 static size_t InputLen;
66 static size_t NumFuncs;
67 static const uintptr_t *FuncsBeg;
68 static __thread size_t CurrentFunc;
69 static dfsan_label *FuncLabels;  // Array of NumFuncs elements.
70 static char *PrintableStringForLabel;  // InputLen + 2 bytes.
71 static bool LabelSeen[1 << 8 * sizeof(dfsan_label)];
72 
73 // Prints all instrumented functions.
74 static int PrintFunctions() {
75   // We don't have the symbolizer integrated with dfsan yet.
76   // So use backtrace_symbols_fd and pipe it through llvm-symbolizer.
77   // TODO(kcc): this is pretty ugly and may break in lots of ways.
78   //      We'll need to make a proper in-process symbolizer work with DFSan.
79   FILE *Pipe = popen("sed 's/(+/ /g; s/).*//g' "
80                      "| llvm-symbolizer "
81                      "| grep 'dfs\\$' "
82                      "| sed 's/dfs\\$//g'", "w");
83   for (size_t I = 0; I < NumFuncs; I++) {
84     uintptr_t PC = FuncsBeg[I * 2];
85     void *const Buf[1] = {(void*)PC};
86     backtrace_symbols_fd(Buf, 1, fileno(Pipe));
87   }
88   pclose(Pipe);
89   return 0;
90 }
91 
92 extern "C"
93 void SetBytesForLabel(dfsan_label L, char *Bytes) {
94   if (LabelSeen[L])
95     return;
96   LabelSeen[L] = true;
97   assert(L);
98   if (L <= InputLen + 1) {
99     Bytes[L - 1] = '1';
100   } else {
101     auto *DLI = dfsan_get_label_info(L);
102     SetBytesForLabel(DLI->l1, Bytes);
103     SetBytesForLabel(DLI->l2, Bytes);
104   }
105 }
106 
107 static char *GetPrintableStringForLabel(dfsan_label L) {
108   memset(PrintableStringForLabel, '0', InputLen + 1);
109   PrintableStringForLabel[InputLen + 1] = 0;
110   memset(LabelSeen, 0, sizeof(LabelSeen));
111   SetBytesForLabel(L, PrintableStringForLabel);
112   return PrintableStringForLabel;
113 }
114 
115 static void PrintDataFlow(FILE *Out) {
116   for (size_t I = 0; I < NumFuncs; I++)
117     if (FuncLabels[I])
118       fprintf(Out, "F%zd %s\n", I, GetPrintableStringForLabel(FuncLabels[I]));
119 }
120 
121 int main(int argc, char **argv) {
122   if (LLVMFuzzerInitialize)
123     LLVMFuzzerInitialize(&argc, &argv);
124   if (argc == 1)
125     return PrintFunctions();
126   assert(argc == 4 || argc == 5);
127   size_t Beg = atoi(argv[1]);
128   size_t End = atoi(argv[2]);
129   assert(Beg < End);
130 
131   const char *Input = argv[3];
132   fprintf(stderr, "INFO: reading '%s'\n", Input);
133   FILE *In = fopen(Input, "r");
134   assert(In);
135   fseek(In, 0, SEEK_END);
136   InputLen = ftell(In);
137   fseek(In, 0, SEEK_SET);
138   unsigned char *Buf = (unsigned char*)malloc(InputLen);
139   size_t NumBytesRead = fread(Buf, 1, InputLen, In);
140   assert(NumBytesRead == InputLen);
141   PrintableStringForLabel = (char*)malloc(InputLen + 2);
142   fclose(In);
143 
144   fprintf(stderr, "INFO: running '%s'\n", Input);
145   for (size_t I = 1; I <= InputLen; I++) {
146     dfsan_label L = dfsan_create_label("", nullptr);
147     assert(L == I);
148     size_t Idx = I - 1;
149     if (Idx >= Beg && Idx < End)
150       dfsan_set_label(L, Buf + Idx, 1);
151   }
152   dfsan_label SizeL = dfsan_create_label("", nullptr);
153   assert(SizeL == InputLen + 1);
154   dfsan_set_label(SizeL, &InputLen, sizeof(InputLen));
155 
156   LLVMFuzzerTestOneInput(Buf, InputLen);
157   free(Buf);
158 
159   bool OutIsStdout = argc == 4;
160   fprintf(stderr, "INFO: writing dataflow to %s\n",
161           OutIsStdout ? "<stdout>" : argv[4]);
162   FILE *Out = OutIsStdout ? stdout : fopen(argv[4], "w");
163   PrintDataFlow(Out);
164   if (!OutIsStdout) fclose(Out);
165 }
166 
167 extern "C" {
168 
169 void __sanitizer_cov_trace_pc_guard_init(uint32_t *start,
170                                          uint32_t *stop) {
171   assert(NumFuncs == 0 && "This tool does not support DSOs");
172   assert(start < stop && "The code is not instrumented for coverage");
173   if (start == stop || *start) return;  // Initialize only once.
174   for (uint32_t *x = start; x < stop; x++)
175     *x = ++NumFuncs;  // The first index is 1.
176   FuncLabels = (dfsan_label*)calloc(NumFuncs, sizeof(dfsan_label));
177   fprintf(stderr, "INFO: %zd instrumented function(s) observed\n", NumFuncs);
178 }
179 
180 void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg,
181                               const uintptr_t *pcs_end) {
182   assert(NumFuncs == (pcs_end - pcs_beg) / 2);
183   FuncsBeg = pcs_beg;
184 }
185 
186 void __sanitizer_cov_trace_pc_indir(uint64_t x){}  // unused.
187 
188 void __sanitizer_cov_trace_pc_guard(uint32_t *guard){
189   uint32_t FuncNum = *guard - 1;  // Guards start from 1.
190   assert(FuncNum < NumFuncs);
191   CurrentFunc = FuncNum;
192 }
193 
194 void __dfsw___sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases,
195                                          dfsan_label L1, dfsan_label UnusedL) {
196   assert(CurrentFunc < NumFuncs);
197   FuncLabels[CurrentFunc] = dfsan_union(FuncLabels[CurrentFunc], L1);
198 }
199 
200 #define HOOK(Name, Type)                                                       \
201   void Name(Type Arg1, Type Arg2, dfsan_label L1, dfsan_label L2) {            \
202     assert(CurrentFunc < NumFuncs);                                            \
203     FuncLabels[CurrentFunc] =                                                  \
204         dfsan_union(FuncLabels[CurrentFunc], dfsan_union(L1, L2));             \
205   }
206 
207 HOOK(__dfsw___sanitizer_cov_trace_const_cmp1, uint8_t)
208 HOOK(__dfsw___sanitizer_cov_trace_const_cmp2, uint16_t)
209 HOOK(__dfsw___sanitizer_cov_trace_const_cmp4, uint32_t)
210 HOOK(__dfsw___sanitizer_cov_trace_const_cmp8, uint64_t)
211 HOOK(__dfsw___sanitizer_cov_trace_cmp1, uint8_t)
212 HOOK(__dfsw___sanitizer_cov_trace_cmp2, uint16_t)
213 HOOK(__dfsw___sanitizer_cov_trace_cmp4, uint32_t)
214 HOOK(__dfsw___sanitizer_cov_trace_cmp8, uint64_t)
215 
216 } // extern "C"
217