blob: 50ffa98b9abe3eb355decb8f445d02f61ca5113b [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"
12#include "FuzzerIO.h"
kccf7d6ba32019-05-09 21:29:45 +000013#include "FuzzerRandom.h"
kcc86e43882018-06-06 01:23:29 +000014
15#include <cstdlib>
16#include <fstream>
kccf7d6ba32019-05-09 21:29:45 +000017#include <sstream>
kcc86e43882018-06-06 01:23:29 +000018#include <string>
19#include <vector>
20
21namespace fuzzer {
kccf7d6ba32019-05-09 21:29:45 +000022static const char *kFunctionsTxt = "functions.txt";
23
24bool 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.
34bool 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.
75Vector<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
88void 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}
kcc86e43882018-06-06 01:23:29 +000098
99void DataFlowTrace::Init(const std::string &DirPath,
kccf7d6ba32019-05-09 21:29:45 +0000100 std::string *FocusFunction,
101 Random &Rand) {
kcc86e43882018-06-06 01:23:29 +0000102 if (DirPath.empty()) return;
kcc86e43882018-06-06 01:23:29 +0000103 Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
104 Vector<SizedFile> Files;
105 GetSizedFilesFromDir(DirPath, &Files);
106 std::string L;
kccf7d6ba32019-05-09 21:29:45 +0000107 size_t FocusFuncIdx = SIZE_MAX;
108 Vector<std::string> FunctionNames;
kcc86e43882018-06-06 01:23:29 +0000109
110 // Read functions.txt
111 std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
kcc86e43882018-06-06 01:23:29 +0000112 size_t NumFunctions = 0;
113 while (std::getline(IF, L, '\n')) {
kccf7d6ba32019-05-09 21:29:45 +0000114 FunctionNames.push_back(L);
kcc86e43882018-06-06 01:23:29 +0000115 NumFunctions++;
kccf7d6ba32019-05-09 21:29:45 +0000116 if (*FocusFunction == L)
kcc86e43882018-06-06 01:23:29 +0000117 FocusFuncIdx = NumFunctions - 1;
118 }
kccf7d6ba32019-05-09 21:29:45 +0000119
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
kcc86e43882018-06-06 01:23:29 +0000145 if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
146 return;
kccf7d6ba32019-05-09 21:29:45 +0000147
kcc86e43882018-06-06 01:23:29 +0000148 // 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')) {
kcc45fa3552019-05-08 17:20:09 +0000162 if (!L.empty() && L[0] == 'C')
163 continue; // Ignore coverage.
kcc86e43882018-06-06 01:23:29 +0000164 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;
kcc0cab3f02018-07-19 01:23:32 +0000178 Vector<uint8_t> V(Len);
kcc86e43882018-06-06 01:23:29 +0000179 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 }
kccadf188b2018-06-07 01:40:20 +0000184 Traces[Name] = V;
kcc86e43882018-06-06 01:23:29 +0000185 // 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