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 #include "FuzzerIO.h"
13 #include "FuzzerRandom.h"
14 
15 #include <cstdlib>
16 #include <fstream>
17 #include <sstream>
18 #include <string>
19 #include <vector>
20 
21 namespace fuzzer {
22 static const char *kFunctionsTxt = "functions.txt";
23 
24 bool BlockCoverage::AppendCoverage(const std::string &S) {
25   std::stringstream SS(S);
26   return AppendCoverage(SS);
27 }
28 
29 // Coverage lines have this form:
30 // CN X Y Z T
31 // where N is the number of the function, T is the total number of instrumented
32 // BBs, and X,Y,Z, if present, are the indecies of covered BB.
33 // BB #0, which is the entry block, is not explicitly listed.
34 bool BlockCoverage::AppendCoverage(std::istream &IN) {
35   std::string L;
36   while (std::getline(IN, L, '\n')) {
37     if (L.empty() || L[0] != 'C')
38       continue; // Ignore non-coverage lines.
39     std::stringstream SS(L.c_str() + 1);
40     size_t FunctionId  = 0;
41     SS >> FunctionId;
42     Vector<uint32_t> CoveredBlocks;
43     while (true) {
44       uint32_t BB = 0;
45       SS >> BB;
46       if (!SS) break;
47       CoveredBlocks.push_back(BB);
48     }
49     if (CoveredBlocks.empty()) return false;
50     uint32_t NumBlocks = CoveredBlocks.back();
51     CoveredBlocks.pop_back();
52     for (auto BB : CoveredBlocks)
53       if (BB >= NumBlocks) return false;
54     auto It = Functions.find(FunctionId);
55     auto &Counters =
56         It == Functions.end()
57             ? Functions.insert({FunctionId, Vector<uint32_t>(NumBlocks)})
58                   .first->second
59             : It->second;
60 
61     if (Counters.size() != NumBlocks) return false;  // wrong number of blocks.
62 
63     Counters[0]++;
64     for (auto BB : CoveredBlocks)
65       Counters[BB]++;
66   }
67   return true;
68 }
69 
70 // Assign weights to each function.
71 // General principles:
72 //   * any uncovered function gets weight 0.
73 //   * a function with lots of uncovered blocks gets bigger weight.
74 //   * a function with a less frequently executed code gets bigger weight.
75 Vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {
76   Vector<double> Res(NumFunctions);
77   for (auto It : Functions) {
78     auto FunctionID = It.first;
79     auto Counters = It.second;
80     auto &Weight = Res[FunctionID];
81     Weight = 1000.;  // this function is covered.
82     Weight /= SmallestNonZeroCounter(Counters);
83     Weight *= NumberOfUncoveredBlocks(Counters) + 1;  // make sure it's not 0.
84   }
85   return Res;
86 }
87 
88 void DataFlowTrace::ReadCoverage(const std::string &DirPath) {
89   Vector<SizedFile> Files;
90   GetSizedFilesFromDir(DirPath, &Files);
91   for (auto &SF : Files) {
92     auto Name = Basename(SF.File);
93     if (Name == kFunctionsTxt) continue;
94     std::ifstream IF(SF.File);
95     Coverage.AppendCoverage(IF);
96   }
97 }
98 
99 void DataFlowTrace::Init(const std::string &DirPath,
100                          std::string *FocusFunction,
101                          Random &Rand) {
102   if (DirPath.empty()) return;
103   Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
104   Vector<SizedFile> Files;
105   GetSizedFilesFromDir(DirPath, &Files);
106   std::string L;
107   size_t FocusFuncIdx = SIZE_MAX;
108   Vector<std::string> FunctionNames;
109 
110   // Read functions.txt
111   std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
112   size_t NumFunctions = 0;
113   while (std::getline(IF, L, '\n')) {
114     FunctionNames.push_back(L);
115     NumFunctions++;
116     if (*FocusFunction == L)
117       FocusFuncIdx = NumFunctions - 1;
118   }
119 
120   if (*FocusFunction == "auto") {
121     // AUTOFOCUS works like this:
122     // * reads the coverage data from the DFT files.
123     // * assigns weights to functions based on coverage.
124     // * chooses a random function according to the weights.
125     ReadCoverage(DirPath);
126     auto Weights = Coverage.FunctionWeights(NumFunctions);
127     Vector<double> Intervals(NumFunctions + 1);
128     std::iota(Intervals.begin(), Intervals.end(), 0);
129     auto Distribution = std::piecewise_constant_distribution<double>(
130         Intervals.begin(), Intervals.end(), Weights.begin());
131     FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
132     *FocusFunction = FunctionNames[FocusFuncIdx];
133     assert(FocusFuncIdx < NumFunctions);
134     Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
135            FunctionNames[FocusFuncIdx].c_str());
136     for (size_t i = 0; i < NumFunctions; i++) {
137       if (!Weights[i]) continue;
138       Printf("  [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
139              Weights[i], Coverage.GetNumberOfBlocks(i),
140              Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
141              FunctionNames[i].c_str());
142     }
143   }
144 
145   if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
146     return;
147 
148   // Read traces.
149   size_t NumTraceFiles = 0;
150   size_t NumTracesWithFocusFunction = 0;
151   for (auto &SF : Files) {
152     auto Name = Basename(SF.File);
153     if (Name == kFunctionsTxt) continue;
154     auto ParseError = [&](const char *Err) {
155       Printf("DataFlowTrace: parse error: %s\n  File: %s\n  Line: %s\n", Err,
156              Name.c_str(), L.c_str());
157     };
158     NumTraceFiles++;
159     // Printf("=== %s\n", Name.c_str());
160     std::ifstream IF(SF.File);
161     while (std::getline(IF, L, '\n')) {
162       if (!L.empty() && L[0] == 'C')
163         continue; // Ignore coverage.
164       size_t SpacePos = L.find(' ');
165       if (SpacePos == std::string::npos)
166         return ParseError("no space in the trace line");
167       if (L.empty() || L[0] != 'F')
168         return ParseError("the trace line doesn't start with 'F'");
169       size_t N = std::atol(L.c_str() + 1);
170       if (N >= NumFunctions)
171         return ParseError("N is greater than the number of functions");
172       if (N == FocusFuncIdx) {
173         NumTracesWithFocusFunction++;
174         const char *Beg = L.c_str() + SpacePos + 1;
175         const char *End = L.c_str() + L.size();
176         assert(Beg < End);
177         size_t Len = End - Beg;
178         Vector<uint8_t> V(Len);
179         for (size_t I = 0; I < Len; I++) {
180           if (Beg[I] != '0' && Beg[I] != '1')
181             ParseError("the trace should contain only 0 or 1");
182           V[I] = Beg[I] == '1';
183         }
184         Traces[Name] = V;
185         // Print just a few small traces.
186         if (NumTracesWithFocusFunction <= 3 && Len <= 16)
187           Printf("%s => |%s|\n", Name.c_str(), L.c_str() + SpacePos + 1);
188         break;  // No need to parse the following lines.
189       }
190     }
191   }
192   assert(NumTraceFiles == Files.size() - 1);
193   Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
194          "%zd traces with focus function\n",
195          NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
196 }
197 
198 }  // namespace fuzzer
199 
200