1 //===- FuzzerDataFlowTrace.cpp - DataFlowTrace                ---*- C++ -* ===//
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 // fuzzer::DataFlowTrace
9 //===----------------------------------------------------------------------===//
10 
11 #include "FuzzerDataFlowTrace.h"
12 
13 #include "FuzzerCommand.h"
14 #include "FuzzerIO.h"
15 #include "FuzzerRandom.h"
16 #include "FuzzerSHA1.h"
17 #include "FuzzerUtil.h"
18 
19 #include <cstdlib>
20 #include <fstream>
21 #include <numeric>
22 #include <queue>
23 #include <sstream>
24 #include <string>
25 #include <unordered_map>
26 #include <unordered_set>
27 #include <vector>
28 
29 namespace fuzzer {
30 static const char *kFunctionsTxt = "functions.txt";
31 
32 bool BlockCoverage::AppendCoverage(const std::string &S) {
33   std::stringstream SS(S);
34   return AppendCoverage(SS);
35 }
36 
37 // Coverage lines have this form:
38 // CN X Y Z T
39 // where N is the number of the function, T is the total number of instrumented
40 // BBs, and X,Y,Z, if present, are the indecies of covered BB.
41 // BB #0, which is the entry block, is not explicitly listed.
42 bool BlockCoverage::AppendCoverage(std::istream &IN) {
43   std::string L;
44   while (std::getline(IN, L, '\n')) {
45     if (L.empty() || L[0] != 'C')
46       continue; // Ignore non-coverage lines.
47     std::stringstream SS(L.c_str() + 1);
48     size_t FunctionId  = 0;
49     SS >> FunctionId;
50     Vector<uint32_t> CoveredBlocks;
51     while (true) {
52       uint32_t BB = 0;
53       SS >> BB;
54       if (!SS) break;
55       CoveredBlocks.push_back(BB);
56     }
57     if (CoveredBlocks.empty()) return false;
58     uint32_t NumBlocks = CoveredBlocks.back();
59     CoveredBlocks.pop_back();
60     for (auto BB : CoveredBlocks)
61       if (BB >= NumBlocks) return false;
62     auto It = Functions.find(FunctionId);
63     auto &Counters =
64         It == Functions.end()
65             ? Functions.insert({FunctionId, Vector<uint32_t>(NumBlocks)})
66                   .first->second
67             : It->second;
68 
69     if (Counters.size() != NumBlocks) return false;  // wrong number of blocks.
70 
71     Counters[0]++;
72     for (auto BB : CoveredBlocks)
73       Counters[BB]++;
74   }
75   return true;
76 }
77 
78 // Assign weights to each function.
79 // General principles:
80 //   * any uncovered function gets weight 0.
81 //   * a function with lots of uncovered blocks gets bigger weight.
82 //   * a function with a less frequently executed code gets bigger weight.
83 Vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {
84   Vector<double> Res(NumFunctions);
85   for (auto It : Functions) {
86     auto FunctionID = It.first;
87     auto Counters = It.second;
88     assert(FunctionID < NumFunctions);
89     auto &Weight = Res[FunctionID];
90     Weight = 1000.;  // this function is covered.
91     Weight /= SmallestNonZeroCounter(Counters);
92     Weight *= NumberOfUncoveredBlocks(Counters) + 1;  // make sure it's not 0.
93   }
94   return Res;
95 }
96 
97 void DataFlowTrace::ReadCoverage(const std::string &DirPath) {
98   Vector<SizedFile> Files;
99   GetSizedFilesFromDir(DirPath, &Files);
100   for (auto &SF : Files) {
101     auto Name = Basename(SF.File);
102     if (Name == kFunctionsTxt) continue;
103     if (!CorporaHashes.count(Name)) continue;
104     std::ifstream IF(SF.File);
105     Coverage.AppendCoverage(IF);
106   }
107 }
108 
109 static void DFTStringAppendToVector(Vector<uint8_t> *DFT,
110                                     const std::string &DFTString) {
111   assert(DFT->size() == DFTString.size());
112   for (size_t I = 0, Len = DFT->size(); I < Len; I++)
113     (*DFT)[I] = DFTString[I] == '1';
114 }
115 
116 // converts a string of '0' and '1' into a Vector<uint8_t>
117 static Vector<uint8_t> DFTStringToVector(const std::string &DFTString) {
118   Vector<uint8_t> DFT(DFTString.size());
119   DFTStringAppendToVector(&DFT, DFTString);
120   return DFT;
121 }
122 
123 static std::ostream &operator<<(std::ostream &OS, const Vector<uint8_t> &DFT) {
124   for (auto B : DFT)
125     OS << (B ? "1" : "0");
126   return OS;
127 }
128 
129 static bool ParseError(const char *Err, const std::string &Line) {
130   Printf("DataFlowTrace: parse error: %s: Line: %s\n", Err, Line.c_str());
131   return false;
132 };
133 
134 // TODO(metzman): replace std::string with std::string_view for
135 // better performance. Need to figure our how to use string_view on Windows.
136 static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
137                          std::string *DFTString) {
138   if (!Line.empty() && Line[0] != 'F')
139     return false; // Ignore coverage.
140   size_t SpacePos = Line.find(' ');
141   if (SpacePos == std::string::npos)
142     return ParseError("no space in the trace line", Line);
143   if (Line.empty() || Line[0] != 'F')
144     return ParseError("the trace line doesn't start with 'F'", Line);
145   *FunctionNum = std::atol(Line.c_str() + 1);
146   const char *Beg = Line.c_str() + SpacePos + 1;
147   const char *End = Line.c_str() + Line.size();
148   assert(Beg < End);
149   size_t Len = End - Beg;
150   for (size_t I = 0; I < Len; I++) {
151     if (Beg[I] != '0' && Beg[I] != '1')
152       return ParseError("the trace should contain only 0 or 1", Line);
153   }
154   *DFTString = Beg;
155   return true;
156 }
157 
158 bool DataFlowTrace::Init(const std::string &DirPath, std::string *FocusFunction,
159                          Vector<SizedFile> &CorporaFiles, Random &Rand) {
160   if (DirPath.empty()) return false;
161   Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
162   Vector<SizedFile> Files;
163   GetSizedFilesFromDir(DirPath, &Files);
164   std::string L;
165   size_t FocusFuncIdx = SIZE_MAX;
166   Vector<std::string> FunctionNames;
167 
168   // Collect the hashes of the corpus files.
169   for (auto &SF : CorporaFiles)
170     CorporaHashes.insert(Hash(FileToVector(SF.File)));
171 
172   // Read functions.txt
173   std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
174   size_t NumFunctions = 0;
175   while (std::getline(IF, L, '\n')) {
176     FunctionNames.push_back(L);
177     NumFunctions++;
178     if (*FocusFunction == L)
179       FocusFuncIdx = NumFunctions - 1;
180   }
181   if (!NumFunctions)
182     return false;
183 
184   if (*FocusFunction == "auto") {
185     // AUTOFOCUS works like this:
186     // * reads the coverage data from the DFT files.
187     // * assigns weights to functions based on coverage.
188     // * chooses a random function according to the weights.
189     ReadCoverage(DirPath);
190     auto Weights = Coverage.FunctionWeights(NumFunctions);
191     Vector<double> Intervals(NumFunctions + 1);
192     std::iota(Intervals.begin(), Intervals.end(), 0);
193     auto Distribution = std::piecewise_constant_distribution<double>(
194         Intervals.begin(), Intervals.end(), Weights.begin());
195     FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
196     *FocusFunction = FunctionNames[FocusFuncIdx];
197     assert(FocusFuncIdx < NumFunctions);
198     Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
199            FunctionNames[FocusFuncIdx].c_str());
200     for (size_t i = 0; i < NumFunctions; i++) {
201       if (!Weights[i]) continue;
202       Printf("  [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
203              Weights[i], Coverage.GetNumberOfBlocks(i),
204              Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
205              FunctionNames[i].c_str());
206     }
207   }
208 
209   if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
210     return false;
211 
212   // Read traces.
213   size_t NumTraceFiles = 0;
214   size_t NumTracesWithFocusFunction = 0;
215   for (auto &SF : Files) {
216     auto Name = Basename(SF.File);
217     if (Name == kFunctionsTxt) continue;
218     if (!CorporaHashes.count(Name)) continue;  // not in the corpus.
219     NumTraceFiles++;
220     // Printf("=== %s\n", Name.c_str());
221     std::ifstream IF(SF.File);
222     while (std::getline(IF, L, '\n')) {
223       size_t FunctionNum = 0;
224       std::string DFTString;
225       if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
226           FunctionNum == FocusFuncIdx) {
227         NumTracesWithFocusFunction++;
228 
229         if (FunctionNum >= NumFunctions)
230           return ParseError("N is greater than the number of functions", L);
231         Traces[Name] = DFTStringToVector(DFTString);
232         // Print just a few small traces.
233         if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)
234           Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());
235         break; // No need to parse the following lines.
236       }
237     }
238   }
239   Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
240          "%zd traces with focus function\n",
241          NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
242   return NumTraceFiles > 0;
243 }
244 
245 int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
246                     const Vector<SizedFile> &CorporaFiles) {
247   Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
248          DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
249   MkDir(DirPath);
250   auto Temp = TempPath(".dft");
251   for (auto &F : CorporaFiles) {
252     // For every input F we need to collect the data flow and the coverage.
253     // Data flow collection may fail if we request too many DFSan tags at once.
254     // So, we start from requesting all tags in range [0,Size) and if that fails
255     // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
256     // Function number => DFT.
257     std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
258     std::unordered_set<std::string> Cov;
259     std::queue<std::pair<size_t, size_t>> Q;
260     Q.push({0, F.Size});
261     while (!Q.empty()) {
262       auto R = Q.front();
263       Printf("\n\n\n********* Trying: [%zd, %zd)\n", R.first, R.second);
264       Q.pop();
265       Command Cmd;
266       Cmd.addArgument(DFTBinary);
267       Cmd.addArgument(std::to_string(R.first));
268       Cmd.addArgument(std::to_string(R.second));
269       Cmd.addArgument(F.File);
270       Cmd.addArgument(Temp);
271       Printf("CMD: %s\n", Cmd.toString().c_str());
272       if (ExecuteCommand(Cmd)) {
273         // DFSan has failed, collect tags for two subsets.
274         if (R.second - R.first >= 2) {
275           size_t Mid = (R.second + R.first) / 2;
276           Q.push({R.first, Mid});
277           Q.push({Mid, R.second});
278         }
279       } else {
280         Printf("********* Success: [%zd, %zd)\n", R.first, R.second);
281         std::ifstream IF(Temp);
282         std::string L;
283         while (std::getline(IF, L, '\n')) {
284           // Data flow collection has succeeded.
285           // Merge the results with the other runs.
286           if (L.empty()) continue;
287           if (L[0] == 'C') {
288             // Take coverage lines as is, they will be the same in all attempts.
289             Cov.insert(L);
290           } else if (L[0] == 'F') {
291             size_t FunctionNum = 0;
292             std::string DFTString;
293             if (ParseDFTLine(L, &FunctionNum, &DFTString)) {
294               auto &DFT = DFTMap[FunctionNum];
295               if (DFT.empty()) {
296                 // Haven't seen this function before, take DFT as is.
297                 DFT = DFTStringToVector(DFTString);
298               } else if (DFT.size() == DFTString.size()) {
299                 // Have seen this function already, merge DFTs.
300                 DFTStringAppendToVector(&DFT, DFTString);
301               }
302             }
303           }
304         }
305       }
306     }
307     auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
308     // Dump combined DFT to disk.
309     Printf("Producing DFT for %s\n", OutPath.c_str());
310     std::ofstream OF(OutPath);
311     for (auto &DFT: DFTMap)
312       OF << "F" << DFT.first << " " << DFT.second << std::endl;
313     for (auto &C : Cov)
314       OF << C << std::endl;
315   }
316   RemoveFile(Temp);
317   // Write functions.txt if it's currently empty or doesn't exist.
318   auto FunctionsTxtPath = DirPlusFile(DirPath, kFunctionsTxt);
319   if (FileToString(FunctionsTxtPath).empty()) {
320     Command Cmd;
321     Cmd.addArgument(DFTBinary);
322     Cmd.setOutputFile(FunctionsTxtPath);
323     ExecuteCommand(Cmd);
324   }
325   return 0;
326 }
327 
328 }  // namespace fuzzer
329