blob: bd249c4b6caf5c15235e3cfaf744c7d50fa4e8c6 [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;
kcc81cba772019-05-24 00:43:52 +0000103 if (!CorporaHashes.count(Name)) continue;
kccf7d6ba32019-05-09 21:29:45 +0000104 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,
kcc0cd1e562019-05-14 22:16:04 +0000110 const std::string &DFTString) {
kcc81236df2019-05-14 21:47:35 +0000111 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>
kcc0cd1e562019-05-14 22:16:04 +0000117static Vector<uint8_t> DFTStringToVector(const std::string &DFTString) {
kcc81236df2019-05-14 21:47:35 +0000118 Vector<uint8_t> DFT(DFTString.size());
119 DFTStringAppendToVector(&DFT, DFTString);
120 return DFT;
121}
122
kcc81236df2019-05-14 21:47:35 +0000123static 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
kcc0cd1e562019-05-14 22:16:04 +0000128// TODO(metzman): replace std::string with std::string_view for
129// better performance. Need to figure our how to use string_view on Windows.
kcc81236df2019-05-14 21:47:35 +0000130static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
kcc0cd1e562019-05-14 22:16:04 +0000131 std::string *DFTString) {
kcc81236df2019-05-14 21:47:35 +0000132 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
kcc81cba772019-05-24 00:43:52 +0000152bool DataFlowTrace::Init(const std::string &DirPath, std::string *FocusFunction,
153 Vector<SizedFile> &CorporaFiles, Random &Rand) {
kcc81236df2019-05-14 21:47:35 +0000154 if (DirPath.empty()) return false;
kcc86e43882018-06-06 01:23:29 +0000155 Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
156 Vector<SizedFile> Files;
157 GetSizedFilesFromDir(DirPath, &Files);
158 std::string L;
kccf7d6ba32019-05-09 21:29:45 +0000159 size_t FocusFuncIdx = SIZE_MAX;
160 Vector<std::string> FunctionNames;
kcc86e43882018-06-06 01:23:29 +0000161
kcc81cba772019-05-24 00:43:52 +0000162 // Collect the hashes of the corpus files.
163 for (auto &SF : CorporaFiles)
164 CorporaHashes.insert(Hash(FileToVector(SF.File)));
165
kcc86e43882018-06-06 01:23:29 +0000166 // 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 }
kccd701d9e2019-05-23 00:22:46 +0000175 if (!NumFunctions)
176 return false;
kccf7d6ba32019-05-09 21:29:45 +0000177
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
kcc86e43882018-06-06 01:23:29 +0000203 if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
kcc81236df2019-05-14 21:47:35 +0000204 return false;
kccf7d6ba32019-05-09 21:29:45 +0000205
kcc86e43882018-06-06 01:23:29 +0000206 // 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;
kcc81cba772019-05-24 00:43:52 +0000212 if (!CorporaHashes.count(Name)) continue; // not in the corpus.
kcc86e43882018-06-06 01:23:29 +0000213 NumTraceFiles++;
214 // Printf("=== %s\n", Name.c_str());
215 std::ifstream IF(SF.File);
216 while (std::getline(IF, L, '\n')) {
kcc81236df2019-05-14 21:47:35 +0000217 size_t FunctionNum = 0;
kcc0cd1e562019-05-14 22:16:04 +0000218 std::string DFTString;
kcc81236df2019-05-14 21:47:35 +0000219 if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
220 FunctionNum == FocusFuncIdx) {
kcc86e43882018-06-06 01:23:29 +0000221 NumTracesWithFocusFunction++;
kcc81236df2019-05-14 21:47:35 +0000222
223 if (FunctionNum >= NumFunctions)
224 return ParseError("N is greater than the number of functions", L);
225 Traces[Name] = DFTStringToVector(DFTString);
kcc86e43882018-06-06 01:23:29 +0000226 // Print just a few small traces.
kcc81236df2019-05-14 21:47:35 +0000227 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.
kcc86e43882018-06-06 01:23:29 +0000230 }
231 }
232 }
kcc86e43882018-06-06 01:23:29 +0000233 Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
234 "%zd traces with focus function\n",
235 NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
kcc81cba772019-05-24 00:43:52 +0000236 return NumTraceFiles > 0;
kcc86e43882018-06-06 01:23:29 +0000237}
238
kcc908220a2019-05-10 00:59:32 +0000239int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
kcc11883b22019-05-10 01:34:26 +0000240 const Vector<SizedFile> &CorporaFiles) {
kcc81236df2019-05-14 21:47:35 +0000241 Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
242 DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
kcc0a66b5b2019-06-14 19:54:32 +0000243 static char DFSanEnv[] = "DFSAN_OPTIONS=fast16labels=1:warn_unimplemented=0";
244 putenv(DFSanEnv);
kcc81236df2019-05-14 21:47:35 +0000245 MkDir(DirPath);
kcc81236df2019-05-14 21:47:35 +0000246 for (auto &F : CorporaFiles) {
247 // For every input F we need to collect the data flow and the coverage.
248 // Data flow collection may fail if we request too many DFSan tags at once.
249 // So, we start from requesting all tags in range [0,Size) and if that fails
250 // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
251 // Function number => DFT.
kcc0a66b5b2019-06-14 19:54:32 +0000252 auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
kcc81236df2019-05-14 21:47:35 +0000253 std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
254 std::unordered_set<std::string> Cov;
kcc0a66b5b2019-06-14 19:54:32 +0000255 Command Cmd;
256 Cmd.addArgument(DFTBinary);
257 Cmd.addArgument(F.File);
258 Cmd.addArgument(OutPath);
259 Printf("CMD: %s\n", Cmd.toString().c_str());
260 ExecuteCommand(Cmd);
kcc81236df2019-05-14 21:47:35 +0000261 }
kccecf5e562019-05-23 01:03:42 +0000262 // Write functions.txt if it's currently empty or doesn't exist.
kcc81cba772019-05-24 00:43:52 +0000263 auto FunctionsTxtPath = DirPlusFile(DirPath, kFunctionsTxt);
kccecf5e562019-05-23 01:03:42 +0000264 if (FileToString(FunctionsTxtPath).empty()) {
265 Command Cmd;
266 Cmd.addArgument(DFTBinary);
267 Cmd.setOutputFile(FunctionsTxtPath);
268 ExecuteCommand(Cmd);
269 }
kcc908220a2019-05-10 00:59:32 +0000270 return 0;
271}
272
kcc86e43882018-06-06 01:23:29 +0000273} // namespace fuzzer