11fd005f5SKostya Serebryany //===- FuzzerDataFlowTrace.cpp - DataFlowTrace                ---*- C++ -* ===//
21fd005f5SKostya Serebryany //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61fd005f5SKostya Serebryany //
71fd005f5SKostya Serebryany //===----------------------------------------------------------------------===//
81fd005f5SKostya Serebryany // fuzzer::DataFlowTrace
91fd005f5SKostya Serebryany //===----------------------------------------------------------------------===//
101fd005f5SKostya Serebryany 
111fd005f5SKostya Serebryany #include "FuzzerDataFlowTrace.h"
1227d22b6bSKostya Serebryany 
1327d22b6bSKostya Serebryany #include "FuzzerCommand.h"
141fd005f5SKostya Serebryany #include "FuzzerIO.h"
15e9aaa558SKostya Serebryany #include "FuzzerRandom.h"
1627d22b6bSKostya Serebryany #include "FuzzerSHA1.h"
1727d22b6bSKostya Serebryany #include "FuzzerUtil.h"
181fd005f5SKostya Serebryany 
191fd005f5SKostya Serebryany #include <cstdlib>
201fd005f5SKostya Serebryany #include <fstream>
21da96d921SKostya Serebryany #include <numeric>
2227d22b6bSKostya Serebryany #include <queue>
23e9aaa558SKostya Serebryany #include <sstream>
241fd005f5SKostya Serebryany #include <string>
2527d22b6bSKostya Serebryany #include <unordered_map>
2627d22b6bSKostya Serebryany #include <unordered_set>
271fd005f5SKostya Serebryany #include <vector>
281fd005f5SKostya Serebryany 
291fd005f5SKostya Serebryany namespace fuzzer {
30e9aaa558SKostya Serebryany static const char *kFunctionsTxt = "functions.txt";
31e9aaa558SKostya Serebryany 
AppendCoverage(const std::string & S)32e9aaa558SKostya Serebryany bool BlockCoverage::AppendCoverage(const std::string &S) {
33e9aaa558SKostya Serebryany   std::stringstream SS(S);
34e9aaa558SKostya Serebryany   return AppendCoverage(SS);
35e9aaa558SKostya Serebryany }
36e9aaa558SKostya Serebryany 
37e9aaa558SKostya Serebryany // Coverage lines have this form:
38e9aaa558SKostya Serebryany // CN X Y Z T
39e9aaa558SKostya Serebryany // where N is the number of the function, T is the total number of instrumented
40*a1e7e401SKazuaki Ishizaki // BBs, and X,Y,Z, if present, are the indices of covered BB.
41e9aaa558SKostya Serebryany // BB #0, which is the entry block, is not explicitly listed.
AppendCoverage(std::istream & IN)42e9aaa558SKostya Serebryany bool BlockCoverage::AppendCoverage(std::istream &IN) {
43e9aaa558SKostya Serebryany   std::string L;
44e9aaa558SKostya Serebryany   while (std::getline(IN, L, '\n')) {
450feed5d5SKostya Serebryany     if (L.empty())
460feed5d5SKostya Serebryany       continue;
47e9aaa558SKostya Serebryany     std::stringstream SS(L.c_str() + 1);
48e9aaa558SKostya Serebryany     size_t FunctionId  = 0;
49e9aaa558SKostya Serebryany     SS >> FunctionId;
500feed5d5SKostya Serebryany     if (L[0] == 'F') {
510feed5d5SKostya Serebryany       FunctionsWithDFT.insert(FunctionId);
520feed5d5SKostya Serebryany       continue;
530feed5d5SKostya Serebryany     }
540feed5d5SKostya Serebryany     if (L[0] != 'C') continue;
557c921753SKostya Serebryany     std::vector<uint32_t> CoveredBlocks;
56e9aaa558SKostya Serebryany     while (true) {
57e9aaa558SKostya Serebryany       uint32_t BB = 0;
58e9aaa558SKostya Serebryany       SS >> BB;
59e9aaa558SKostya Serebryany       if (!SS) break;
60e9aaa558SKostya Serebryany       CoveredBlocks.push_back(BB);
61e9aaa558SKostya Serebryany     }
62e9aaa558SKostya Serebryany     if (CoveredBlocks.empty()) return false;
636708186cSAaron Green     // Ensures no CoverageVector is longer than UINT32_MAX.
64e9aaa558SKostya Serebryany     uint32_t NumBlocks = CoveredBlocks.back();
65e9aaa558SKostya Serebryany     CoveredBlocks.pop_back();
66e9aaa558SKostya Serebryany     for (auto BB : CoveredBlocks)
67e9aaa558SKostya Serebryany       if (BB >= NumBlocks) return false;
68e9aaa558SKostya Serebryany     auto It = Functions.find(FunctionId);
69e9aaa558SKostya Serebryany     auto &Counters =
70e9aaa558SKostya Serebryany         It == Functions.end()
717c921753SKostya Serebryany             ? Functions.insert({FunctionId, std::vector<uint32_t>(NumBlocks)})
72e9aaa558SKostya Serebryany                   .first->second
73e9aaa558SKostya Serebryany             : It->second;
74e9aaa558SKostya Serebryany 
75e9aaa558SKostya Serebryany     if (Counters.size() != NumBlocks) return false;  // wrong number of blocks.
76e9aaa558SKostya Serebryany 
77e9aaa558SKostya Serebryany     Counters[0]++;
78e9aaa558SKostya Serebryany     for (auto BB : CoveredBlocks)
79e9aaa558SKostya Serebryany       Counters[BB]++;
80e9aaa558SKostya Serebryany   }
81e9aaa558SKostya Serebryany   return true;
82e9aaa558SKostya Serebryany }
83e9aaa558SKostya Serebryany 
84e9aaa558SKostya Serebryany // Assign weights to each function.
85e9aaa558SKostya Serebryany // General principles:
86e9aaa558SKostya Serebryany //   * any uncovered function gets weight 0.
87e9aaa558SKostya Serebryany //   * a function with lots of uncovered blocks gets bigger weight.
88e9aaa558SKostya Serebryany //   * a function with a less frequently executed code gets bigger weight.
FunctionWeights(size_t NumFunctions) const897c921753SKostya Serebryany std::vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {
907c921753SKostya Serebryany   std::vector<double> Res(NumFunctions);
91e9aaa558SKostya Serebryany   for (auto It : Functions) {
92e9aaa558SKostya Serebryany     auto FunctionID = It.first;
93e9aaa558SKostya Serebryany     auto Counters = It.second;
9427d22b6bSKostya Serebryany     assert(FunctionID < NumFunctions);
95e9aaa558SKostya Serebryany     auto &Weight = Res[FunctionID];
960feed5d5SKostya Serebryany     // Give higher weight if the function has a DFT.
970feed5d5SKostya Serebryany     Weight = FunctionsWithDFT.count(FunctionID) ? 1000. : 1;
980feed5d5SKostya Serebryany     // Give higher weight to functions with less frequently seen basic blocks.
99e9aaa558SKostya Serebryany     Weight /= SmallestNonZeroCounter(Counters);
1000feed5d5SKostya Serebryany     // Give higher weight to functions with the most uncovered basic blocks.
1010feed5d5SKostya Serebryany     Weight *= NumberOfUncoveredBlocks(Counters) + 1;
102e9aaa558SKostya Serebryany   }
103e9aaa558SKostya Serebryany   return Res;
104e9aaa558SKostya Serebryany }
105e9aaa558SKostya Serebryany 
ReadCoverage(const std::string & DirPath)106e9aaa558SKostya Serebryany void DataFlowTrace::ReadCoverage(const std::string &DirPath) {
1077c921753SKostya Serebryany   std::vector<SizedFile> Files;
108e9aaa558SKostya Serebryany   GetSizedFilesFromDir(DirPath, &Files);
109e9aaa558SKostya Serebryany   for (auto &SF : Files) {
110e9aaa558SKostya Serebryany     auto Name = Basename(SF.File);
111e9aaa558SKostya Serebryany     if (Name == kFunctionsTxt) continue;
112060f4b48SKostya Serebryany     if (!CorporaHashes.count(Name)) continue;
113e9aaa558SKostya Serebryany     std::ifstream IF(SF.File);
114e9aaa558SKostya Serebryany     Coverage.AppendCoverage(IF);
115e9aaa558SKostya Serebryany   }
116e9aaa558SKostya Serebryany }
1171fd005f5SKostya Serebryany 
DFTStringAppendToVector(std::vector<uint8_t> * DFT,const std::string & DFTString)1187c921753SKostya Serebryany static void DFTStringAppendToVector(std::vector<uint8_t> *DFT,
1192e2dfe21SKostya Serebryany                                     const std::string &DFTString) {
12027d22b6bSKostya Serebryany   assert(DFT->size() == DFTString.size());
12127d22b6bSKostya Serebryany   for (size_t I = 0, Len = DFT->size(); I < Len; I++)
12227d22b6bSKostya Serebryany     (*DFT)[I] = DFTString[I] == '1';
12327d22b6bSKostya Serebryany }
12427d22b6bSKostya Serebryany 
1257c921753SKostya Serebryany // converts a string of '0' and '1' into a std::vector<uint8_t>
DFTStringToVector(const std::string & DFTString)1267c921753SKostya Serebryany static std::vector<uint8_t> DFTStringToVector(const std::string &DFTString) {
1277c921753SKostya Serebryany   std::vector<uint8_t> DFT(DFTString.size());
12827d22b6bSKostya Serebryany   DFTStringAppendToVector(&DFT, DFTString);
12927d22b6bSKostya Serebryany   return DFT;
13027d22b6bSKostya Serebryany }
13127d22b6bSKostya Serebryany 
ParseError(const char * Err,const std::string & Line)13227d22b6bSKostya Serebryany static bool ParseError(const char *Err, const std::string &Line) {
13327d22b6bSKostya Serebryany   Printf("DataFlowTrace: parse error: %s: Line: %s\n", Err, Line.c_str());
13427d22b6bSKostya Serebryany   return false;
1352fa6838eSKostya Serebryany }
13627d22b6bSKostya Serebryany 
1372e2dfe21SKostya Serebryany // TODO(metzman): replace std::string with std::string_view for
1382e2dfe21SKostya Serebryany // better performance. Need to figure our how to use string_view on Windows.
ParseDFTLine(const std::string & Line,size_t * FunctionNum,std::string * DFTString)13927d22b6bSKostya Serebryany static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
1402e2dfe21SKostya Serebryany                          std::string *DFTString) {
14127d22b6bSKostya Serebryany   if (!Line.empty() && Line[0] != 'F')
14227d22b6bSKostya Serebryany     return false; // Ignore coverage.
14327d22b6bSKostya Serebryany   size_t SpacePos = Line.find(' ');
14427d22b6bSKostya Serebryany   if (SpacePos == std::string::npos)
14527d22b6bSKostya Serebryany     return ParseError("no space in the trace line", Line);
14627d22b6bSKostya Serebryany   if (Line.empty() || Line[0] != 'F')
14727d22b6bSKostya Serebryany     return ParseError("the trace line doesn't start with 'F'", Line);
14827d22b6bSKostya Serebryany   *FunctionNum = std::atol(Line.c_str() + 1);
14927d22b6bSKostya Serebryany   const char *Beg = Line.c_str() + SpacePos + 1;
15027d22b6bSKostya Serebryany   const char *End = Line.c_str() + Line.size();
15127d22b6bSKostya Serebryany   assert(Beg < End);
15227d22b6bSKostya Serebryany   size_t Len = End - Beg;
15327d22b6bSKostya Serebryany   for (size_t I = 0; I < Len; I++) {
15427d22b6bSKostya Serebryany     if (Beg[I] != '0' && Beg[I] != '1')
15527d22b6bSKostya Serebryany       return ParseError("the trace should contain only 0 or 1", Line);
15627d22b6bSKostya Serebryany   }
15727d22b6bSKostya Serebryany   *DFTString = Beg;
15827d22b6bSKostya Serebryany   return true;
15927d22b6bSKostya Serebryany }
16027d22b6bSKostya Serebryany 
Init(const std::string & DirPath,std::string * FocusFunction,std::vector<SizedFile> & CorporaFiles,Random & Rand)161060f4b48SKostya Serebryany bool DataFlowTrace::Init(const std::string &DirPath, std::string *FocusFunction,
1627c921753SKostya Serebryany                          std::vector<SizedFile> &CorporaFiles, Random &Rand) {
16327d22b6bSKostya Serebryany   if (DirPath.empty()) return false;
1641fd005f5SKostya Serebryany   Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
1657c921753SKostya Serebryany   std::vector<SizedFile> Files;
1661fd005f5SKostya Serebryany   GetSizedFilesFromDir(DirPath, &Files);
1671fd005f5SKostya Serebryany   std::string L;
168e9aaa558SKostya Serebryany   size_t FocusFuncIdx = SIZE_MAX;
1697c921753SKostya Serebryany   std::vector<std::string> FunctionNames;
1701fd005f5SKostya Serebryany 
171060f4b48SKostya Serebryany   // Collect the hashes of the corpus files.
172060f4b48SKostya Serebryany   for (auto &SF : CorporaFiles)
173060f4b48SKostya Serebryany     CorporaHashes.insert(Hash(FileToVector(SF.File)));
174060f4b48SKostya Serebryany 
1751fd005f5SKostya Serebryany   // Read functions.txt
1761fd005f5SKostya Serebryany   std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
1771fd005f5SKostya Serebryany   size_t NumFunctions = 0;
1781fd005f5SKostya Serebryany   while (std::getline(IF, L, '\n')) {
179e9aaa558SKostya Serebryany     FunctionNames.push_back(L);
1801fd005f5SKostya Serebryany     NumFunctions++;
181e9aaa558SKostya Serebryany     if (*FocusFunction == L)
1821fd005f5SKostya Serebryany       FocusFuncIdx = NumFunctions - 1;
1831fd005f5SKostya Serebryany   }
184b7cc3d99SKostya Serebryany   if (!NumFunctions)
185b7cc3d99SKostya Serebryany     return false;
186e9aaa558SKostya Serebryany 
187e9aaa558SKostya Serebryany   if (*FocusFunction == "auto") {
188e9aaa558SKostya Serebryany     // AUTOFOCUS works like this:
189e9aaa558SKostya Serebryany     // * reads the coverage data from the DFT files.
190e9aaa558SKostya Serebryany     // * assigns weights to functions based on coverage.
191e9aaa558SKostya Serebryany     // * chooses a random function according to the weights.
192e9aaa558SKostya Serebryany     ReadCoverage(DirPath);
193e9aaa558SKostya Serebryany     auto Weights = Coverage.FunctionWeights(NumFunctions);
1947c921753SKostya Serebryany     std::vector<double> Intervals(NumFunctions + 1);
195e9aaa558SKostya Serebryany     std::iota(Intervals.begin(), Intervals.end(), 0);
196e9aaa558SKostya Serebryany     auto Distribution = std::piecewise_constant_distribution<double>(
197e9aaa558SKostya Serebryany         Intervals.begin(), Intervals.end(), Weights.begin());
198e9aaa558SKostya Serebryany     FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
199e9aaa558SKostya Serebryany     *FocusFunction = FunctionNames[FocusFuncIdx];
200e9aaa558SKostya Serebryany     assert(FocusFuncIdx < NumFunctions);
201e9aaa558SKostya Serebryany     Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
202e9aaa558SKostya Serebryany            FunctionNames[FocusFuncIdx].c_str());
203e9aaa558SKostya Serebryany     for (size_t i = 0; i < NumFunctions; i++) {
2046708186cSAaron Green       if (Weights[i] == 0.0)
2056708186cSAaron Green         continue;
206e9aaa558SKostya Serebryany       Printf("  [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
207e9aaa558SKostya Serebryany              Weights[i], Coverage.GetNumberOfBlocks(i),
208e9aaa558SKostya Serebryany              Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
209e9aaa558SKostya Serebryany              FunctionNames[i].c_str());
210e9aaa558SKostya Serebryany     }
211e9aaa558SKostya Serebryany   }
212e9aaa558SKostya Serebryany 
2131fd005f5SKostya Serebryany   if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
21427d22b6bSKostya Serebryany     return false;
215e9aaa558SKostya Serebryany 
2161fd005f5SKostya Serebryany   // Read traces.
2171fd005f5SKostya Serebryany   size_t NumTraceFiles = 0;
2181fd005f5SKostya Serebryany   size_t NumTracesWithFocusFunction = 0;
2191fd005f5SKostya Serebryany   for (auto &SF : Files) {
2201fd005f5SKostya Serebryany     auto Name = Basename(SF.File);
2211fd005f5SKostya Serebryany     if (Name == kFunctionsTxt) continue;
222060f4b48SKostya Serebryany     if (!CorporaHashes.count(Name)) continue;  // not in the corpus.
2231fd005f5SKostya Serebryany     NumTraceFiles++;
2241fd005f5SKostya Serebryany     // Printf("=== %s\n", Name.c_str());
2251fd005f5SKostya Serebryany     std::ifstream IF(SF.File);
2261fd005f5SKostya Serebryany     while (std::getline(IF, L, '\n')) {
22727d22b6bSKostya Serebryany       size_t FunctionNum = 0;
2282e2dfe21SKostya Serebryany       std::string DFTString;
22927d22b6bSKostya Serebryany       if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
23027d22b6bSKostya Serebryany           FunctionNum == FocusFuncIdx) {
2311fd005f5SKostya Serebryany         NumTracesWithFocusFunction++;
23227d22b6bSKostya Serebryany 
23327d22b6bSKostya Serebryany         if (FunctionNum >= NumFunctions)
23427d22b6bSKostya Serebryany           return ParseError("N is greater than the number of functions", L);
23527d22b6bSKostya Serebryany         Traces[Name] = DFTStringToVector(DFTString);
2361fd005f5SKostya Serebryany         // Print just a few small traces.
23727d22b6bSKostya Serebryany         if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)
23827d22b6bSKostya Serebryany           Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());
2391fd005f5SKostya Serebryany         break; // No need to parse the following lines.
2401fd005f5SKostya Serebryany       }
2411fd005f5SKostya Serebryany     }
2421fd005f5SKostya Serebryany   }
2431fd005f5SKostya Serebryany   Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
2441fd005f5SKostya Serebryany          "%zd traces with focus function\n",
2451fd005f5SKostya Serebryany          NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
246060f4b48SKostya Serebryany   return NumTraceFiles > 0;
2471fd005f5SKostya Serebryany }
2481fd005f5SKostya Serebryany 
CollectDataFlow(const std::string & DFTBinary,const std::string & DirPath,const std::vector<SizedFile> & CorporaFiles)249da96d921SKostya Serebryany int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
2507c921753SKostya Serebryany                     const std::vector<SizedFile> &CorporaFiles) {
25127d22b6bSKostya Serebryany   Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
25227d22b6bSKostya Serebryany          DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
253ad7b908bSMax Moroz   if (CorporaFiles.empty()) {
254ad7b908bSMax Moroz     Printf("ERROR: can't collect data flow without corpus provided.");
255ad7b908bSMax Moroz     return 1;
256ad7b908bSMax Moroz   }
257ad7b908bSMax Moroz 
258e2d0b44aSMatt Morehouse   static char DFSanEnv[] = "DFSAN_OPTIONS=warn_unimplemented=0";
2593f39123dSKostya Serebryany   putenv(DFSanEnv);
26027d22b6bSKostya Serebryany   MkDir(DirPath);
26127d22b6bSKostya Serebryany   for (auto &F : CorporaFiles) {
26227d22b6bSKostya Serebryany     // For every input F we need to collect the data flow and the coverage.
26327d22b6bSKostya Serebryany     // Data flow collection may fail if we request too many DFSan tags at once.
26427d22b6bSKostya Serebryany     // So, we start from requesting all tags in range [0,Size) and if that fails
26527d22b6bSKostya Serebryany     // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
26627d22b6bSKostya Serebryany     // Function number => DFT.
2673f39123dSKostya Serebryany     auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
2687c921753SKostya Serebryany     std::unordered_map<size_t, std::vector<uint8_t>> DFTMap;
26927d22b6bSKostya Serebryany     std::unordered_set<std::string> Cov;
27027d22b6bSKostya Serebryany     Command Cmd;
27127d22b6bSKostya Serebryany     Cmd.addArgument(DFTBinary);
27227d22b6bSKostya Serebryany     Cmd.addArgument(F.File);
2733f39123dSKostya Serebryany     Cmd.addArgument(OutPath);
27427d22b6bSKostya Serebryany     Printf("CMD: %s\n", Cmd.toString().c_str());
2753f39123dSKostya Serebryany     ExecuteCommand(Cmd);
27627d22b6bSKostya Serebryany   }
277eac9a783SKostya Serebryany   // Write functions.txt if it's currently empty or doesn't exist.
278060f4b48SKostya Serebryany   auto FunctionsTxtPath = DirPlusFile(DirPath, kFunctionsTxt);
279eac9a783SKostya Serebryany   if (FileToString(FunctionsTxtPath).empty()) {
28027d22b6bSKostya Serebryany     Command Cmd;
28127d22b6bSKostya Serebryany     Cmd.addArgument(DFTBinary);
282eac9a783SKostya Serebryany     Cmd.setOutputFile(FunctionsTxtPath);
28327d22b6bSKostya Serebryany     ExecuteCommand(Cmd);
284eac9a783SKostya Serebryany   }
285da96d921SKostya Serebryany   return 0;
286da96d921SKostya Serebryany }
287da96d921SKostya Serebryany 
2881fd005f5SKostya Serebryany }  // namespace fuzzer
289