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 bool ParseError(const char *Err, const std::string &Line) {
124   Printf("DataFlowTrace: parse error: %s: Line: %s\n", Err, Line.c_str());
125   return false;
126 };
127 
128 // TODO(metzman): replace std::string with std::string_view for
129 // better performance. Need to figure our how to use string_view on Windows.
130 static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
131                          std::string *DFTString) {
132   if (!Line.empty() && Line[0] != 'F')
133     return false; // Ignore coverage.
134   size_t SpacePos = Line.find(' ');
135   if (SpacePos == std::string::npos)
136     return ParseError("no space in the trace line", Line);
137   if (Line.empty() || Line[0] != 'F')
138     return ParseError("the trace line doesn't start with 'F'", Line);
139   *FunctionNum = std::atol(Line.c_str() + 1);
140   const char *Beg = Line.c_str() + SpacePos + 1;
141   const char *End = Line.c_str() + Line.size();
142   assert(Beg < End);
143   size_t Len = End - Beg;
144   for (size_t I = 0; I < Len; I++) {
145     if (Beg[I] != '0' && Beg[I] != '1')
146       return ParseError("the trace should contain only 0 or 1", Line);
147   }
148   *DFTString = Beg;
149   return true;
150 }
151 
152 bool DataFlowTrace::Init(const std::string &DirPath, std::string *FocusFunction,
153                          Vector<SizedFile> &CorporaFiles, Random &Rand) {
154   if (DirPath.empty()) return false;
155   Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
156   Vector<SizedFile> Files;
157   GetSizedFilesFromDir(DirPath, &Files);
158   std::string L;
159   size_t FocusFuncIdx = SIZE_MAX;
160   Vector<std::string> FunctionNames;
161 
162   // Collect the hashes of the corpus files.
163   for (auto &SF : CorporaFiles)
164     CorporaHashes.insert(Hash(FileToVector(SF.File)));
165 
166   // Read functions.txt
167   std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
168   size_t NumFunctions = 0;
169   while (std::getline(IF, L, '\n')) {
170     FunctionNames.push_back(L);
171     NumFunctions++;
172     if (*FocusFunction == L)
173       FocusFuncIdx = NumFunctions - 1;
174   }
175   if (!NumFunctions)
176     return false;
177 
178   if (*FocusFunction == "auto") {
179     // AUTOFOCUS works like this:
180     // * reads the coverage data from the DFT files.
181     // * assigns weights to functions based on coverage.
182     // * chooses a random function according to the weights.
183     ReadCoverage(DirPath);
184     auto Weights = Coverage.FunctionWeights(NumFunctions);
185     Vector<double> Intervals(NumFunctions + 1);
186     std::iota(Intervals.begin(), Intervals.end(), 0);
187     auto Distribution = std::piecewise_constant_distribution<double>(
188         Intervals.begin(), Intervals.end(), Weights.begin());
189     FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
190     *FocusFunction = FunctionNames[FocusFuncIdx];
191     assert(FocusFuncIdx < NumFunctions);
192     Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
193            FunctionNames[FocusFuncIdx].c_str());
194     for (size_t i = 0; i < NumFunctions; i++) {
195       if (!Weights[i]) continue;
196       Printf("  [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
197              Weights[i], Coverage.GetNumberOfBlocks(i),
198              Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
199              FunctionNames[i].c_str());
200     }
201   }
202 
203   if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
204     return false;
205 
206   // Read traces.
207   size_t NumTraceFiles = 0;
208   size_t NumTracesWithFocusFunction = 0;
209   for (auto &SF : Files) {
210     auto Name = Basename(SF.File);
211     if (Name == kFunctionsTxt) continue;
212     if (!CorporaHashes.count(Name)) continue;  // not in the corpus.
213     NumTraceFiles++;
214     // Printf("=== %s\n", Name.c_str());
215     std::ifstream IF(SF.File);
216     while (std::getline(IF, L, '\n')) {
217       size_t FunctionNum = 0;
218       std::string DFTString;
219       if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
220           FunctionNum == FocusFuncIdx) {
221         NumTracesWithFocusFunction++;
222 
223         if (FunctionNum >= NumFunctions)
224           return ParseError("N is greater than the number of functions", L);
225         Traces[Name] = DFTStringToVector(DFTString);
226         // Print just a few small traces.
227         if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)
228           Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());
229         break; // No need to parse the following lines.
230       }
231     }
232   }
233   Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
234          "%zd traces with focus function\n",
235          NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
236   return NumTraceFiles > 0;
237 }
238 
239 int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
240                     const Vector<SizedFile> &CorporaFiles) {
241   Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
242          DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
243   setenv("DFSAN_OPTIONS", "fast16labels=1:warn_unimplemented=0", 1);
244   MkDir(DirPath);
245   for (auto &F : CorporaFiles) {
246     // For every input F we need to collect the data flow and the coverage.
247     // Data flow collection may fail if we request too many DFSan tags at once.
248     // So, we start from requesting all tags in range [0,Size) and if that fails
249     // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
250     // Function number => DFT.
251     auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
252     std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
253     std::unordered_set<std::string> Cov;
254     Command Cmd;
255     Cmd.addArgument(DFTBinary);
256     Cmd.addArgument(F.File);
257     Cmd.addArgument(OutPath);
258     Printf("CMD: %s\n", Cmd.toString().c_str());
259     ExecuteCommand(Cmd);
260   }
261   // Write functions.txt if it's currently empty or doesn't exist.
262   auto FunctionsTxtPath = DirPlusFile(DirPath, kFunctionsTxt);
263   if (FileToString(FunctionsTxtPath).empty()) {
264     Command Cmd;
265     Cmd.addArgument(DFTBinary);
266     Cmd.setOutputFile(FunctionsTxtPath);
267     ExecuteCommand(Cmd);
268   }
269   return 0;
270 }
271 
272 }  // namespace fuzzer
273