blob: bfcdf006192e50b76d77828607038f083d522a29 [file] [log] [blame]
kcc86e43882018-06-06 01:23:29 +00001//===- FuzzerDataFlowTrace.cpp - DataFlowTrace ---*- C++ -* ===//
2//
chandlerc40284492019-01-19 08:50:56 +00003// 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
kcc86e43882018-06-06 01:23:29 +00006//
7//===----------------------------------------------------------------------===//
8// fuzzer::DataFlowTrace
9//===----------------------------------------------------------------------===//
10
11#include "FuzzerDataFlowTrace.h"
kcc81236df2019-05-14 21:47:35 +000012
13#include "FuzzerCommand.h"
kcc86e43882018-06-06 01:23:29 +000014#include "FuzzerIO.h"
kccf7d6ba32019-05-09 21:29:45 +000015#include "FuzzerRandom.h"
kcc81236df2019-05-14 21:47:35 +000016#include "FuzzerSHA1.h"
17#include "FuzzerUtil.h"
kcc86e43882018-06-06 01:23:29 +000018
19#include <cstdlib>
20#include <fstream>
kcc908220a2019-05-10 00:59:32 +000021#include <numeric>
kcc81236df2019-05-14 21:47:35 +000022#include <queue>
kccf7d6ba32019-05-09 21:29:45 +000023#include <sstream>
kcc86e43882018-06-06 01:23:29 +000024#include <string>
kcc81236df2019-05-14 21:47:35 +000025#include <unordered_map>
26#include <unordered_set>
kcc86e43882018-06-06 01:23:29 +000027#include <vector>
28
29namespace fuzzer {
kccf7d6ba32019-05-09 21:29:45 +000030static const char *kFunctionsTxt = "functions.txt";
31
32bool 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.
42bool 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.
83Vector<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;
kcc81236df2019-05-14 21:47:35 +000088 assert(FunctionID < NumFunctions);
kccf7d6ba32019-05-09 21:29:45 +000089 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
97void 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 std::ifstream IF(SF.File);
104 Coverage.AppendCoverage(IF);
105 }
106}
kcc86e43882018-06-06 01:23:29 +0000107
kcc81236df2019-05-14 21:47:35 +0000108static void DFTStringAppendToVector(Vector<uint8_t> *DFT,
109 const std::string_view DFTString) {
110 assert(DFT->size() == DFTString.size());
111 for (size_t I = 0, Len = DFT->size(); I < Len; I++)
112 (*DFT)[I] = DFTString[I] == '1';
113}
114
115// converts a string of '0' and '1' into a Vector<uint8_t>
116static Vector<uint8_t> DFTStringToVector(const std::string_view DFTString) {
117 Vector<uint8_t> DFT(DFTString.size());
118 DFTStringAppendToVector(&DFT, DFTString);
119 return DFT;
120}
121
122static std::ostream &operator<<(std::ostream &OS, const Vector<uint8_t> &DFT) {
123 for (auto B : DFT)
124 OS << (B ? "1" : "0");
125 return OS;
126}
127
128static bool ParseError(const char *Err, const std::string &Line) {
129 Printf("DataFlowTrace: parse error: %s: Line: %s\n", Err, Line.c_str());
130 return false;
131};
132
133static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
134 std::string_view *DFTString) {
135 if (!Line.empty() && Line[0] != 'F')
136 return false; // Ignore coverage.
137 size_t SpacePos = Line.find(' ');
138 if (SpacePos == std::string::npos)
139 return ParseError("no space in the trace line", Line);
140 if (Line.empty() || Line[0] != 'F')
141 return ParseError("the trace line doesn't start with 'F'", Line);
142 *FunctionNum = std::atol(Line.c_str() + 1);
143 const char *Beg = Line.c_str() + SpacePos + 1;
144 const char *End = Line.c_str() + Line.size();
145 assert(Beg < End);
146 size_t Len = End - Beg;
147 for (size_t I = 0; I < Len; I++) {
148 if (Beg[I] != '0' && Beg[I] != '1')
149 return ParseError("the trace should contain only 0 or 1", Line);
150 }
151 *DFTString = Beg;
152 return true;
153}
154
155bool DataFlowTrace::Init(const std::string &DirPath,
kccf7d6ba32019-05-09 21:29:45 +0000156 std::string *FocusFunction,
157 Random &Rand) {
kcc81236df2019-05-14 21:47:35 +0000158 if (DirPath.empty()) return false;
kcc86e43882018-06-06 01:23:29 +0000159 Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
160 Vector<SizedFile> Files;
161 GetSizedFilesFromDir(DirPath, &Files);
162 std::string L;
kccf7d6ba32019-05-09 21:29:45 +0000163 size_t FocusFuncIdx = SIZE_MAX;
164 Vector<std::string> FunctionNames;
kcc86e43882018-06-06 01:23:29 +0000165
166 // Read functions.txt
167 std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
kcc86e43882018-06-06 01:23:29 +0000168 size_t NumFunctions = 0;
169 while (std::getline(IF, L, '\n')) {
kccf7d6ba32019-05-09 21:29:45 +0000170 FunctionNames.push_back(L);
kcc86e43882018-06-06 01:23:29 +0000171 NumFunctions++;
kccf7d6ba32019-05-09 21:29:45 +0000172 if (*FocusFunction == L)
kcc86e43882018-06-06 01:23:29 +0000173 FocusFuncIdx = NumFunctions - 1;
174 }
kccf7d6ba32019-05-09 21:29:45 +0000175
176 if (*FocusFunction == "auto") {
177 // AUTOFOCUS works like this:
178 // * reads the coverage data from the DFT files.
179 // * assigns weights to functions based on coverage.
180 // * chooses a random function according to the weights.
181 ReadCoverage(DirPath);
182 auto Weights = Coverage.FunctionWeights(NumFunctions);
183 Vector<double> Intervals(NumFunctions + 1);
184 std::iota(Intervals.begin(), Intervals.end(), 0);
185 auto Distribution = std::piecewise_constant_distribution<double>(
186 Intervals.begin(), Intervals.end(), Weights.begin());
187 FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
188 *FocusFunction = FunctionNames[FocusFuncIdx];
189 assert(FocusFuncIdx < NumFunctions);
190 Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
191 FunctionNames[FocusFuncIdx].c_str());
192 for (size_t i = 0; i < NumFunctions; i++) {
193 if (!Weights[i]) continue;
194 Printf(" [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
195 Weights[i], Coverage.GetNumberOfBlocks(i),
196 Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
197 FunctionNames[i].c_str());
198 }
199 }
200
kcc86e43882018-06-06 01:23:29 +0000201 if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
kcc81236df2019-05-14 21:47:35 +0000202 return false;
kccf7d6ba32019-05-09 21:29:45 +0000203
kcc86e43882018-06-06 01:23:29 +0000204 // Read traces.
205 size_t NumTraceFiles = 0;
206 size_t NumTracesWithFocusFunction = 0;
207 for (auto &SF : Files) {
208 auto Name = Basename(SF.File);
209 if (Name == kFunctionsTxt) continue;
kcc86e43882018-06-06 01:23:29 +0000210 NumTraceFiles++;
211 // Printf("=== %s\n", Name.c_str());
212 std::ifstream IF(SF.File);
213 while (std::getline(IF, L, '\n')) {
kcc81236df2019-05-14 21:47:35 +0000214 size_t FunctionNum = 0;
215 std::string_view DFTString;
216 if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
217 FunctionNum == FocusFuncIdx) {
kcc86e43882018-06-06 01:23:29 +0000218 NumTracesWithFocusFunction++;
kcc81236df2019-05-14 21:47:35 +0000219
220 if (FunctionNum >= NumFunctions)
221 return ParseError("N is greater than the number of functions", L);
222 Traces[Name] = DFTStringToVector(DFTString);
kcc86e43882018-06-06 01:23:29 +0000223 // Print just a few small traces.
kcc81236df2019-05-14 21:47:35 +0000224 if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)
225 Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());
226 break; // No need to parse the following lines.
kcc86e43882018-06-06 01:23:29 +0000227 }
228 }
229 }
230 assert(NumTraceFiles == Files.size() - 1);
231 Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
232 "%zd traces with focus function\n",
233 NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
kcc81236df2019-05-14 21:47:35 +0000234 return true;
kcc86e43882018-06-06 01:23:29 +0000235}
236
kcc908220a2019-05-10 00:59:32 +0000237int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
kcc11883b22019-05-10 01:34:26 +0000238 const Vector<SizedFile> &CorporaFiles) {
kcc81236df2019-05-14 21:47:35 +0000239 Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
240 DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
241 MkDir(DirPath);
242 auto Temp = TempPath(".dft");
243 for (auto &F : CorporaFiles) {
244 // For every input F we need to collect the data flow and the coverage.
245 // Data flow collection may fail if we request too many DFSan tags at once.
246 // So, we start from requesting all tags in range [0,Size) and if that fails
247 // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
248 // Function number => DFT.
249 std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
250 std::unordered_set<std::string> Cov;
251 std::queue<std::pair<size_t, size_t>> Q;
252 Q.push({0, F.Size});
253 while (!Q.empty()) {
254 auto R = Q.front();
255 Printf("\n\n\n********* Trying: [%zd, %zd)\n", R.first, R.second);
256 Q.pop();
257 Command Cmd;
258 Cmd.addArgument(DFTBinary);
259 Cmd.addArgument(std::to_string(R.first));
260 Cmd.addArgument(std::to_string(R.second));
261 Cmd.addArgument(F.File);
262 Cmd.addArgument(Temp);
263 Printf("CMD: %s\n", Cmd.toString().c_str());
264 if (ExecuteCommand(Cmd)) {
265 // DFSan has failed, collect tags for two subsets.
266 if (R.second - R.first >= 2) {
267 size_t Mid = (R.second + R.first) / 2;
268 Q.push({R.first, Mid});
269 Q.push({Mid, R.second});
270 }
271 } else {
272 Printf("********* Success: [%zd, %zd)\n", R.first, R.second);
273 std::ifstream IF(Temp);
274 std::string L;
275 while (std::getline(IF, L, '\n')) {
276 // Data flow collection has succeeded.
277 // Merge the results with the other runs.
278 if (L.empty()) continue;
279 if (L[0] == 'C') {
280 // Take coverage lines as is, they will be the same in all attempts.
281 Cov.insert(L);
282 } else if (L[0] == 'F') {
283 size_t FunctionNum = 0;
284 std::string_view DFTString;
285 if (ParseDFTLine(L, &FunctionNum, &DFTString)) {
286 auto &DFT = DFTMap[FunctionNum];
287 if (DFT.empty()) {
288 // Haven't seen this function before, take DFT as is.
289 DFT = DFTStringToVector(DFTString);
290 } else if (DFT.size() == DFTString.size()) {
291 // Have seen this function already, merge DFTs.
292 DFTStringAppendToVector(&DFT, DFTString);
293 }
294 }
295 }
296 }
297 }
298 }
299 auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
300 // Dump combined DFT to disk.
301 Printf("Producing DFT for %s\n", OutPath.c_str());
302 std::ofstream OF(OutPath);
303 for (auto &DFT: DFTMap)
304 OF << "F" << DFT.first << " " << DFT.second << std::endl;
305 for (auto &C : Cov)
306 OF << C << std::endl;
307 }
308 RemoveFile(Temp);
309 // Write functions.txt.
310 Command Cmd;
311 Cmd.addArgument(DFTBinary);
312 Cmd.setOutputFile(DirPlusFile(DirPath, "functions.txt"));
313 ExecuteCommand(Cmd);
kcc908220a2019-05-10 00:59:32 +0000314 return 0;
315}
316
kcc86e43882018-06-06 01:23:29 +0000317} // namespace fuzzer