kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 1 | //===- FuzzerDataFlowTrace.cpp - DataFlowTrace ---*- C++ -* ===// |
| 2 | // |
chandlerc | 4028449 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // fuzzer::DataFlowTrace |
| 9 | //===----------------------------------------------------------------------===// |
| 10 | |
| 11 | #include "FuzzerDataFlowTrace.h" |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 12 | |
| 13 | #include "FuzzerCommand.h" |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 14 | #include "FuzzerIO.h" |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 15 | #include "FuzzerRandom.h" |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 16 | #include "FuzzerSHA1.h" |
| 17 | #include "FuzzerUtil.h" |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 18 | |
| 19 | #include <cstdlib> |
| 20 | #include <fstream> |
kcc | 908220a | 2019-05-10 00:59:32 +0000 | [diff] [blame] | 21 | #include <numeric> |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 22 | #include <queue> |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 23 | #include <sstream> |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 24 | #include <string> |
kcc | cdef88a | 2019-05-14 22:05:41 +0000 | [diff] [blame^] | 25 | #include <string_view> |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 26 | #include <unordered_map> |
| 27 | #include <unordered_set> |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 28 | #include <vector> |
| 29 | |
| 30 | namespace fuzzer { |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 31 | static const char *kFunctionsTxt = "functions.txt"; |
| 32 | |
| 33 | bool 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. |
| 43 | bool 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. |
| 84 | Vector<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; |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 89 | assert(FunctionID < NumFunctions); |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 90 | 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 | |
| 98 | void 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 | } |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 108 | |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 109 | static 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> |
| 117 | static 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 | |
| 123 | static 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 | |
| 129 | static 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 | |
| 134 | static 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 | |
| 156 | bool DataFlowTrace::Init(const std::string &DirPath, |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 157 | std::string *FocusFunction, |
| 158 | Random &Rand) { |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 159 | if (DirPath.empty()) return false; |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 160 | Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str()); |
| 161 | Vector<SizedFile> Files; |
| 162 | GetSizedFilesFromDir(DirPath, &Files); |
| 163 | std::string L; |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 164 | size_t FocusFuncIdx = SIZE_MAX; |
| 165 | Vector<std::string> FunctionNames; |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 166 | |
| 167 | // Read functions.txt |
| 168 | std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt)); |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 169 | size_t NumFunctions = 0; |
| 170 | while (std::getline(IF, L, '\n')) { |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 171 | FunctionNames.push_back(L); |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 172 | NumFunctions++; |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 173 | if (*FocusFunction == L) |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 174 | FocusFuncIdx = NumFunctions - 1; |
| 175 | } |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 176 | |
| 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 | |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 202 | if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1) |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 203 | return false; |
kcc | f7d6ba3 | 2019-05-09 21:29:45 +0000 | [diff] [blame] | 204 | |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 205 | // 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; |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 211 | NumTraceFiles++; |
| 212 | // Printf("=== %s\n", Name.c_str()); |
| 213 | std::ifstream IF(SF.File); |
| 214 | while (std::getline(IF, L, '\n')) { |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 215 | size_t FunctionNum = 0; |
| 216 | std::string_view DFTString; |
| 217 | if (ParseDFTLine(L, &FunctionNum, &DFTString) && |
| 218 | FunctionNum == FocusFuncIdx) { |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 219 | NumTracesWithFocusFunction++; |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 220 | |
| 221 | if (FunctionNum >= NumFunctions) |
| 222 | return ParseError("N is greater than the number of functions", L); |
| 223 | Traces[Name] = DFTStringToVector(DFTString); |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 224 | // Print just a few small traces. |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 225 | 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. |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 228 | } |
| 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); |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 235 | return true; |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 236 | } |
| 237 | |
kcc | 908220a | 2019-05-10 00:59:32 +0000 | [diff] [blame] | 238 | int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath, |
kcc | 11883b2 | 2019-05-10 01:34:26 +0000 | [diff] [blame] | 239 | const Vector<SizedFile> &CorporaFiles) { |
kcc | 81236df | 2019-05-14 21:47:35 +0000 | [diff] [blame] | 240 | 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); |
kcc | 908220a | 2019-05-10 00:59:32 +0000 | [diff] [blame] | 315 | return 0; |
| 316 | } |
| 317 | |
kcc | 86e4388 | 2018-06-06 01:23:29 +0000 | [diff] [blame] | 318 | } // namespace fuzzer |