FuzzerDataFlowTrace.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. //===- FuzzerDataFlowTrace.cpp - DataFlowTrace ---*- C++ -* ===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. // fuzzer::DataFlowTrace
  9. //===----------------------------------------------------------------------===//
  10. #include "FuzzerDataFlowTrace.h"
  11. #include "FuzzerCommand.h"
  12. #include "FuzzerIO.h"
  13. #include "FuzzerRandom.h"
  14. #include "FuzzerSHA1.h"
  15. #include "FuzzerUtil.h"
  16. #include <cstdlib>
  17. #include <fstream>
  18. #include <numeric>
  19. #include <queue>
  20. #include <sstream>
  21. #include <string>
  22. #include <unordered_map>
  23. #include <unordered_set>
  24. #include <vector>
  25. namespace fuzzer {
  26. static const char *kFunctionsTxt = "functions.txt";
  27. bool BlockCoverage::AppendCoverage(const std::string &S) {
  28. std::stringstream SS(S);
  29. return AppendCoverage(SS);
  30. }
  31. // Coverage lines have this form:
  32. // CN X Y Z T
  33. // where N is the number of the function, T is the total number of instrumented
  34. // BBs, and X,Y,Z, if present, are the indices of covered BB.
  35. // BB #0, which is the entry block, is not explicitly listed.
  36. bool BlockCoverage::AppendCoverage(std::istream &IN) {
  37. std::string L;
  38. while (std::getline(IN, L, '\n')) {
  39. if (L.empty())
  40. continue;
  41. std::stringstream SS(L.c_str() + 1);
  42. size_t FunctionId = 0;
  43. SS >> FunctionId;
  44. if (L[0] == 'F') {
  45. FunctionsWithDFT.insert(FunctionId);
  46. continue;
  47. }
  48. if (L[0] != 'C') continue;
  49. std::vector<uint32_t> CoveredBlocks;
  50. while (true) {
  51. uint32_t BB = 0;
  52. SS >> BB;
  53. if (!SS) break;
  54. CoveredBlocks.push_back(BB);
  55. }
  56. if (CoveredBlocks.empty()) return false;
  57. // Ensures no CoverageVector is longer than UINT32_MAX.
  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, std::vector<uint32_t>(NumBlocks)})
  66. .first->second
  67. : It->second;
  68. if (Counters.size() != NumBlocks) return false; // wrong number of blocks.
  69. Counters[0]++;
  70. for (auto BB : CoveredBlocks)
  71. Counters[BB]++;
  72. }
  73. return true;
  74. }
  75. // Assign weights to each function.
  76. // General principles:
  77. // * any uncovered function gets weight 0.
  78. // * a function with lots of uncovered blocks gets bigger weight.
  79. // * a function with a less frequently executed code gets bigger weight.
  80. std::vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {
  81. std::vector<double> Res(NumFunctions);
  82. for (auto It : Functions) {
  83. auto FunctionID = It.first;
  84. auto Counters = It.second;
  85. assert(FunctionID < NumFunctions);
  86. auto &Weight = Res[FunctionID];
  87. // Give higher weight if the function has a DFT.
  88. Weight = FunctionsWithDFT.count(FunctionID) ? 1000. : 1;
  89. // Give higher weight to functions with less frequently seen basic blocks.
  90. Weight /= SmallestNonZeroCounter(Counters);
  91. // Give higher weight to functions with the most uncovered basic blocks.
  92. Weight *= NumberOfUncoveredBlocks(Counters) + 1;
  93. }
  94. return Res;
  95. }
  96. void DataFlowTrace::ReadCoverage(const std::string &DirPath) {
  97. std::vector<SizedFile> Files;
  98. GetSizedFilesFromDir(DirPath, &Files);
  99. for (auto &SF : Files) {
  100. auto Name = Basename(SF.File);
  101. if (Name == kFunctionsTxt) continue;
  102. if (!CorporaHashes.count(Name)) continue;
  103. std::ifstream IF(SF.File);
  104. Coverage.AppendCoverage(IF);
  105. }
  106. }
  107. static void DFTStringAppendToVector(std::vector<uint8_t> *DFT,
  108. const std::string &DFTString) {
  109. assert(DFT->size() == DFTString.size());
  110. for (size_t I = 0, Len = DFT->size(); I < Len; I++)
  111. (*DFT)[I] = DFTString[I] == '1';
  112. }
  113. // converts a string of '0' and '1' into a std::vector<uint8_t>
  114. static std::vector<uint8_t> DFTStringToVector(const std::string &DFTString) {
  115. std::vector<uint8_t> DFT(DFTString.size());
  116. DFTStringAppendToVector(&DFT, DFTString);
  117. return DFT;
  118. }
  119. static bool ParseError(const char *Err, const std::string &Line) {
  120. Printf("DataFlowTrace: parse error: %s: Line: %s\n", Err, Line.c_str());
  121. return false;
  122. }
  123. // TODO(metzman): replace std::string with std::string_view for
  124. // better performance. Need to figure our how to use string_view on Windows.
  125. static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,
  126. std::string *DFTString) {
  127. if (!Line.empty() && Line[0] != 'F')
  128. return false; // Ignore coverage.
  129. size_t SpacePos = Line.find(' ');
  130. if (SpacePos == std::string::npos)
  131. return ParseError("no space in the trace line", Line);
  132. if (Line.empty() || Line[0] != 'F')
  133. return ParseError("the trace line doesn't start with 'F'", Line);
  134. *FunctionNum = std::atol(Line.c_str() + 1);
  135. const char *Beg = Line.c_str() + SpacePos + 1;
  136. const char *End = Line.c_str() + Line.size();
  137. assert(Beg < End);
  138. size_t Len = End - Beg;
  139. for (size_t I = 0; I < Len; I++) {
  140. if (Beg[I] != '0' && Beg[I] != '1')
  141. return ParseError("the trace should contain only 0 or 1", Line);
  142. }
  143. *DFTString = Beg;
  144. return true;
  145. }
  146. bool DataFlowTrace::Init(const std::string &DirPath, std::string *FocusFunction,
  147. std::vector<SizedFile> &CorporaFiles, Random &Rand) {
  148. if (DirPath.empty()) return false;
  149. Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());
  150. std::vector<SizedFile> Files;
  151. GetSizedFilesFromDir(DirPath, &Files);
  152. std::string L;
  153. size_t FocusFuncIdx = SIZE_MAX;
  154. std::vector<std::string> FunctionNames;
  155. // Collect the hashes of the corpus files.
  156. for (auto &SF : CorporaFiles)
  157. CorporaHashes.insert(Hash(FileToVector(SF.File)));
  158. // Read functions.txt
  159. std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));
  160. size_t NumFunctions = 0;
  161. while (std::getline(IF, L, '\n')) {
  162. FunctionNames.push_back(L);
  163. NumFunctions++;
  164. if (*FocusFunction == L)
  165. FocusFuncIdx = NumFunctions - 1;
  166. }
  167. if (!NumFunctions)
  168. return false;
  169. if (*FocusFunction == "auto") {
  170. // AUTOFOCUS works like this:
  171. // * reads the coverage data from the DFT files.
  172. // * assigns weights to functions based on coverage.
  173. // * chooses a random function according to the weights.
  174. ReadCoverage(DirPath);
  175. auto Weights = Coverage.FunctionWeights(NumFunctions);
  176. std::vector<double> Intervals(NumFunctions + 1);
  177. std::iota(Intervals.begin(), Intervals.end(), 0);
  178. auto Distribution = std::piecewise_constant_distribution<double>(
  179. Intervals.begin(), Intervals.end(), Weights.begin());
  180. FocusFuncIdx = static_cast<size_t>(Distribution(Rand));
  181. *FocusFunction = FunctionNames[FocusFuncIdx];
  182. assert(FocusFuncIdx < NumFunctions);
  183. Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,
  184. FunctionNames[FocusFuncIdx].c_str());
  185. for (size_t i = 0; i < NumFunctions; i++) {
  186. if (Weights[i] == 0.0)
  187. continue;
  188. Printf(" [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,
  189. Weights[i], Coverage.GetNumberOfBlocks(i),
  190. Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),
  191. FunctionNames[i].c_str());
  192. }
  193. }
  194. if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)
  195. return false;
  196. // Read traces.
  197. size_t NumTraceFiles = 0;
  198. size_t NumTracesWithFocusFunction = 0;
  199. for (auto &SF : Files) {
  200. auto Name = Basename(SF.File);
  201. if (Name == kFunctionsTxt) continue;
  202. if (!CorporaHashes.count(Name)) continue; // not in the corpus.
  203. NumTraceFiles++;
  204. // Printf("=== %s\n", Name.c_str());
  205. std::ifstream IF(SF.File);
  206. while (std::getline(IF, L, '\n')) {
  207. size_t FunctionNum = 0;
  208. std::string DFTString;
  209. if (ParseDFTLine(L, &FunctionNum, &DFTString) &&
  210. FunctionNum == FocusFuncIdx) {
  211. NumTracesWithFocusFunction++;
  212. if (FunctionNum >= NumFunctions)
  213. return ParseError("N is greater than the number of functions", L);
  214. Traces[Name] = DFTStringToVector(DFTString);
  215. // Print just a few small traces.
  216. if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)
  217. Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());
  218. break; // No need to parse the following lines.
  219. }
  220. }
  221. }
  222. Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "
  223. "%zd traces with focus function\n",
  224. NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);
  225. return NumTraceFiles > 0;
  226. }
  227. int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
  228. const std::vector<SizedFile> &CorporaFiles) {
  229. Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
  230. DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
  231. if (CorporaFiles.empty()) {
  232. Printf("ERROR: can't collect data flow without corpus provided.");
  233. return 1;
  234. }
  235. static char DFSanEnv[] = "DFSAN_OPTIONS=warn_unimplemented=0";
  236. putenv(DFSanEnv);
  237. MkDir(DirPath);
  238. for (auto &F : CorporaFiles) {
  239. // For every input F we need to collect the data flow and the coverage.
  240. // Data flow collection may fail if we request too many DFSan tags at once.
  241. // So, we start from requesting all tags in range [0,Size) and if that fails
  242. // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
  243. // Function number => DFT.
  244. auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
  245. std::unordered_map<size_t, std::vector<uint8_t>> DFTMap;
  246. std::unordered_set<std::string> Cov;
  247. Command Cmd;
  248. Cmd.addArgument(DFTBinary);
  249. Cmd.addArgument(F.File);
  250. Cmd.addArgument(OutPath);
  251. Printf("CMD: %s\n", Cmd.toString().c_str());
  252. ExecuteCommand(Cmd);
  253. }
  254. // Write functions.txt if it's currently empty or doesn't exist.
  255. auto FunctionsTxtPath = DirPlusFile(DirPath, kFunctionsTxt);
  256. if (FileToString(FunctionsTxtPath).empty()) {
  257. Command Cmd;
  258. Cmd.addArgument(DFTBinary);
  259. Cmd.setOutputFile(FunctionsTxtPath);
  260. ExecuteCommand(Cmd);
  261. }
  262. return 0;
  263. }
  264. } // namespace fuzzer