blob: 9f15cb83a2a20815875fa6876a9aa26a3282bb29 [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>
kcccdef88a2019-05-14 22:05:41 +000025#include <string_view>
kcc81236df2019-05-14 21:47:35 +000026#include <unordered_map>
27#include <unordered_set>
kcc86e43882018-06-06 01:23:29 +000028#include <vector>
29
30namespace fuzzer {
kccf7d6ba32019-05-09 21:29:45 +000031static const char *kFunctionsTxt = "functions.txt";
32
33bool BlockCoverage::AppendCoverage(const std::string &S) {
34 std::stringstream SS(S);
35 return AppendCoverage(SS);
36}
37
38// Coverage lines have this form:
39// CN X Y Z T
40// where N is the number of the function, T is the total number of instrumented
41// BBs, and X,Y,Z, if present, are the indecies of covered BB.
42// BB #0, which is the entry block, is not explicitly listed.
43bool BlockCoverage::AppendCoverage(std::istream &IN) {
44 std::string L;
45 while (std::getline(IN, L, '\n')) {
46 if (L.empty() || L[0] != 'C')
47 continue; // Ignore non-coverage lines.
48 std::stringstream SS(L.c_str() + 1);
49 size_t FunctionId = 0;
50 SS >> FunctionId;
51 Vector<uint32_t> CoveredBlocks;
52 while (true) {
53 uint32_t BB = 0;
54 SS >> BB;
55 if (!SS) break;
56 CoveredBlocks.push_back(BB);
57 }
58 if (CoveredBlocks.empty()) return false;
59 uint32_t NumBlocks = CoveredBlocks.back();
60 CoveredBlocks.pop_back();
61 for (auto BB : CoveredBlocks)
62 if (BB >= NumBlocks) return false;
63 auto It = Functions.find(FunctionId);
64 auto &Counters =
65 It == Functions.end()
66 ? Functions.insert({FunctionId, Vector<uint32_t>(NumBlocks)})
67 .first->second
68 : It->second;
69
70 if (Counters.size() != NumBlocks) return false; // wrong number of blocks.
71
72 Counters[0]++;
73 for (auto BB : CoveredBlocks)
74 Counters[BB]++;
75 }
76 return true;
77}
78
79// Assign weights to each function.
80// General principles:
81// * any uncovered function gets weight 0.
82// * a function with lots of uncovered blocks gets bigger weight.
83// * a function with a less frequently executed code gets bigger weight.
84Vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {
85 Vector<double> Res(NumFunctions);
86 for (auto It : Functions) {
87 auto FunctionID = It.first;
88 auto Counters = It.second;
kcc81236df2019-05-14 21:47:35 +000089 assert(FunctionID < NumFunctions);
kccf7d6ba32019-05-09 21:29:45 +000090 auto &Weight = Res[FunctionID];
91 Weight = 1000.; // this function is covered.
92 Weight /= SmallestNonZeroCounter(Counters);
93 Weight *= NumberOfUncoveredBlocks(Counters) + 1; // make sure it's not 0.
94 }
95 return Res;
96}
97
98void DataFlowTrace::ReadCoverage(const std::string &DirPath) {
99 Vector<SizedFile> Files;
100 GetSizedFilesFromDir(DirPath, &Files);
101 for (auto &SF : Files) {
102 auto Name = Basename(SF.File);
103 if (Name == kFunctionsTxt) continue;
104 std::ifstream IF(SF.File);
105 Coverage.AppendCoverage(IF);
106 }
107}
kcc86e43882018-06-06 01:23:29 +0000108
kcc81236df2019-05-14 21:47:35 +0000109static void DFTStringAppendToVector(Vector<uint8_t> *DFT,
110 const std::string_view 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>
117static Vector<uint8_t> DFTStringToVector(const std::string_view DFTString) {
118 Vector<uint8_t> DFT(DFTString.size());
119 DFTStringAppendToVector(&DFT, DFTString);
120 return DFT;
121}
122
123static 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
129static 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
134static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
135 std::string_view *DFTString) {
136 if (!Line.empty() && Line[0] != 'F')
137 return false; // Ignore coverage.
138 size_t SpacePos = Line.find(' ');
139 if (SpacePos == std::string::npos)
140 return ParseError("no space in the trace line", Line);
141 if (Line.empty() || Line[0] != 'F')
142 return ParseError("the trace line doesn't start with 'F'", Line);
143 *FunctionNum = std::atol(Line.c_str() + 1);
144 const char *Beg = Line.c_str() + SpacePos + 1;
145 const char *End = Line.c_str() + Line.size();
146 assert(Beg < End);
147 size_t Len = End - Beg;
148 for (size_t I = 0; I < Len; I++) {
149 if (Beg[I] != '0' && Beg[I] != '1')
150 return ParseError("the trace should contain only 0 or 1", Line);
151 }
152 *DFTString = Beg;
153 return true;
154}
155
156bool DataFlowTrace::Init(const std::string &DirPath,
kccf7d6ba32019-05-09 21:29:45 +0000157 std::string *FocusFunction,
158 Random &Rand) {
kcc81236df2019-05-14 21:47:35 +0000159 if (DirPath.empty()) return false;
kcc86e43882018-06-06 01:23:29 +0000160 Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
161 Vector<SizedFile> Files;
162 GetSizedFilesFromDir(DirPath, &Files);
163 std::string L;
kccf7d6ba32019-05-09 21:29:45 +0000164 size_t FocusFuncIdx = SIZE_MAX;
165 Vector<std::string> FunctionNames;
kcc86e43882018-06-06 01:23:29 +0000166
167 // Read functions.txt
168 std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
kcc86e43882018-06-06 01:23:29 +0000169 size_t NumFunctions = 0;
170 while (std::getline(IF, L, '\n')) {
kccf7d6ba32019-05-09 21:29:45 +0000171 FunctionNames.push_back(L);
kcc86e43882018-06-06 01:23:29 +0000172 NumFunctions++;
kccf7d6ba32019-05-09 21:29:45 +0000173 if (*FocusFunction == L)
kcc86e43882018-06-06 01:23:29 +0000174 FocusFuncIdx = NumFunctions - 1;
175 }
kccf7d6ba32019-05-09 21:29:45 +0000176
177 if (*FocusFunction == "auto") {
178 // AUTOFOCUS works like this:
179 // * reads the coverage data from the DFT files.
180 // * assigns weights to functions based on coverage.
181 // * chooses a random function according to the weights.
182 ReadCoverage(DirPath);
183 auto Weights = Coverage.FunctionWeights(NumFunctions);
184 Vector<double> Intervals(NumFunctions + 1);
185 std::iota(Intervals.begin(), Intervals.end(), 0);
186 auto Distribution = std::piecewise_constant_distribution<double>(
187 Intervals.begin(), Intervals.end(), Weights.begin());
188 FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
189 *FocusFunction = FunctionNames[FocusFuncIdx];
190 assert(FocusFuncIdx < NumFunctions);
191 Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
192 FunctionNames[FocusFuncIdx].c_str());
193 for (size_t i = 0; i < NumFunctions; i++) {
194 if (!Weights[i]) continue;
195 Printf(" [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
196 Weights[i], Coverage.GetNumberOfBlocks(i),
197 Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
198 FunctionNames[i].c_str());
199 }
200 }
201
kcc86e43882018-06-06 01:23:29 +0000202 if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
kcc81236df2019-05-14 21:47:35 +0000203 return false;
kccf7d6ba32019-05-09 21:29:45 +0000204
kcc86e43882018-06-06 01:23:29 +0000205 // Read traces.
206 size_t NumTraceFiles = 0;
207 size_t NumTracesWithFocusFunction = 0;
208 for (auto &SF : Files) {
209 auto Name = Basename(SF.File);
210 if (Name == kFunctionsTxt) continue;
kcc86e43882018-06-06 01:23:29 +0000211 NumTraceFiles++;
212 // Printf("=== %s\n", Name.c_str());
213 std::ifstream IF(SF.File);
214 while (std::getline(IF, L, '\n')) {
kcc81236df2019-05-14 21:47:35 +0000215 size_t FunctionNum = 0;
216 std::string_view DFTString;
217 if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
218 FunctionNum == FocusFuncIdx) {
kcc86e43882018-06-06 01:23:29 +0000219 NumTracesWithFocusFunction++;
kcc81236df2019-05-14 21:47:35 +0000220
221 if (FunctionNum >= NumFunctions)
222 return ParseError("N is greater than the number of functions", L);
223 Traces[Name] = DFTStringToVector(DFTString);
kcc86e43882018-06-06 01:23:29 +0000224 // Print just a few small traces.
kcc81236df2019-05-14 21:47:35 +0000225 if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)
226 Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());
227 break; // No need to parse the following lines.
kcc86e43882018-06-06 01:23:29 +0000228 }
229 }
230 }
231 assert(NumTraceFiles == Files.size() - 1);
232 Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
233 "%zd traces with focus function\n",
234 NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
kcc81236df2019-05-14 21:47:35 +0000235 return true;
kcc86e43882018-06-06 01:23:29 +0000236}
237
kcc908220a2019-05-10 00:59:32 +0000238int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
kcc11883b22019-05-10 01:34:26 +0000239 const Vector<SizedFile> &CorporaFiles) {
kcc81236df2019-05-14 21:47:35 +0000240 Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
241 DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
242 MkDir(DirPath);
243 auto Temp = TempPath(".dft");
244 for (auto &F : CorporaFiles) {
245 // For every input F we need to collect the data flow and the coverage.
246 // Data flow collection may fail if we request too many DFSan tags at once.
247 // So, we start from requesting all tags in range [0,Size) and if that fails
248 // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
249 // Function number => DFT.
250 std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
251 std::unordered_set<std::string> Cov;
252 std::queue<std::pair<size_t, size_t>> Q;
253 Q.push({0, F.Size});
254 while (!Q.empty()) {
255 auto R = Q.front();
256 Printf("\n\n\n********* Trying: [%zd, %zd)\n", R.first, R.second);
257 Q.pop();
258 Command Cmd;
259 Cmd.addArgument(DFTBinary);
260 Cmd.addArgument(std::to_string(R.first));
261 Cmd.addArgument(std::to_string(R.second));
262 Cmd.addArgument(F.File);
263 Cmd.addArgument(Temp);
264 Printf("CMD: %s\n", Cmd.toString().c_str());
265 if (ExecuteCommand(Cmd)) {
266 // DFSan has failed, collect tags for two subsets.
267 if (R.second - R.first >= 2) {
268 size_t Mid = (R.second + R.first) / 2;
269 Q.push({R.first, Mid});
270 Q.push({Mid, R.second});
271 }
272 } else {
273 Printf("********* Success: [%zd, %zd)\n", R.first, R.second);
274 std::ifstream IF(Temp);
275 std::string L;
276 while (std::getline(IF, L, '\n')) {
277 // Data flow collection has succeeded.
278 // Merge the results with the other runs.
279 if (L.empty()) continue;
280 if (L[0] == 'C') {
281 // Take coverage lines as is, they will be the same in all attempts.
282 Cov.insert(L);
283 } else if (L[0] == 'F') {
284 size_t FunctionNum = 0;
285 std::string_view DFTString;
286 if (ParseDFTLine(L, &FunctionNum, &DFTString)) {
287 auto &DFT = DFTMap[FunctionNum];
288 if (DFT.empty()) {
289 // Haven't seen this function before, take DFT as is.
290 DFT = DFTStringToVector(DFTString);
291 } else if (DFT.size() == DFTString.size()) {
292 // Have seen this function already, merge DFTs.
293 DFTStringAppendToVector(&DFT, DFTString);
294 }
295 }
296 }
297 }
298 }
299 }
300 auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
301 // Dump combined DFT to disk.
302 Printf("Producing DFT for %s\n", OutPath.c_str());
303 std::ofstream OF(OutPath);
304 for (auto &DFT: DFTMap)
305 OF << "F" << DFT.first << " " << DFT.second << std::endl;
306 for (auto &C : Cov)
307 OF << C << std::endl;
308 }
309 RemoveFile(Temp);
310 // Write functions.txt.
311 Command Cmd;
312 Cmd.addArgument(DFTBinary);
313 Cmd.setOutputFile(DirPlusFile(DirPath, "functions.txt"));
314 ExecuteCommand(Cmd);
kcc908220a2019-05-10 00:59:32 +0000315 return 0;
316}
317
kcc86e43882018-06-06 01:23:29 +0000318} // namespace fuzzer