Path: blob/main/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerDataFlowTrace.cpp
35262 views
//===- FuzzerDataFlowTrace.cpp - DataFlowTrace ---*- C++ -* ===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7// fuzzer::DataFlowTrace8//===----------------------------------------------------------------------===//910#include "FuzzerDataFlowTrace.h"1112#include "FuzzerCommand.h"13#include "FuzzerIO.h"14#include "FuzzerRandom.h"15#include "FuzzerSHA1.h"16#include "FuzzerUtil.h"1718#include <cstdlib>19#include <fstream>20#include <numeric>21#include <queue>22#include <sstream>23#include <string>24#include <unordered_map>25#include <unordered_set>26#include <vector>2728namespace fuzzer {29static const char *kFunctionsTxt = "functions.txt";3031bool BlockCoverage::AppendCoverage(const std::string &S) {32std::stringstream SS(S);33return AppendCoverage(SS);34}3536// Coverage lines have this form:37// CN X Y Z T38// where N is the number of the function, T is the total number of instrumented39// BBs, and X,Y,Z, if present, are the indices of covered BB.40// BB #0, which is the entry block, is not explicitly listed.41bool BlockCoverage::AppendCoverage(std::istream &IN) {42std::string L;43while (std::getline(IN, L, '\n')) {44if (L.empty())45continue;46std::stringstream SS(L.c_str() + 1);47size_t FunctionId = 0;48SS >> FunctionId;49if (L[0] == 'F') {50FunctionsWithDFT.insert(FunctionId);51continue;52}53if (L[0] != 'C') continue;54std::vector<uint32_t> CoveredBlocks;55while (true) {56uint32_t BB = 0;57SS >> BB;58if (!SS) break;59CoveredBlocks.push_back(BB);60}61if (CoveredBlocks.empty()) return false;62// Ensures no CoverageVector is longer than UINT32_MAX.63uint32_t NumBlocks = CoveredBlocks.back();64CoveredBlocks.pop_back();65for (auto BB : CoveredBlocks)66if (BB >= NumBlocks) return false;67auto It = Functions.find(FunctionId);68auto &Counters =69It == Functions.end()70? Functions.insert({FunctionId, std::vector<uint32_t>(NumBlocks)})71.first->second72: It->second;7374if (Counters.size() != NumBlocks) return false; // wrong number of blocks.7576Counters[0]++;77for (auto BB : CoveredBlocks)78Counters[BB]++;79}80return true;81}8283// Assign weights to each function.84// General principles:85// * any uncovered function gets weight 0.86// * a function with lots of uncovered blocks gets bigger weight.87// * a function with a less frequently executed code gets bigger weight.88std::vector<double> BlockCoverage::FunctionWeights(size_t NumFunctions) const {89std::vector<double> Res(NumFunctions);90for (const auto &It : Functions) {91auto FunctionID = It.first;92auto Counters = It.second;93assert(FunctionID < NumFunctions);94auto &Weight = Res[FunctionID];95// Give higher weight if the function has a DFT.96Weight = FunctionsWithDFT.count(FunctionID) ? 1000. : 1;97// Give higher weight to functions with less frequently seen basic blocks.98Weight /= SmallestNonZeroCounter(Counters);99// Give higher weight to functions with the most uncovered basic blocks.100Weight *= NumberOfUncoveredBlocks(Counters) + 1;101}102return Res;103}104105void DataFlowTrace::ReadCoverage(const std::string &DirPath) {106std::vector<SizedFile> Files;107GetSizedFilesFromDir(DirPath, &Files);108for (auto &SF : Files) {109auto Name = Basename(SF.File);110if (Name == kFunctionsTxt) continue;111if (!CorporaHashes.count(Name)) continue;112std::ifstream IF(SF.File);113Coverage.AppendCoverage(IF);114}115}116117static void DFTStringAppendToVector(std::vector<uint8_t> *DFT,118const std::string &DFTString) {119assert(DFT->size() == DFTString.size());120for (size_t I = 0, Len = DFT->size(); I < Len; I++)121(*DFT)[I] = DFTString[I] == '1';122}123124// converts a string of '0' and '1' into a std::vector<uint8_t>125static std::vector<uint8_t> DFTStringToVector(const std::string &DFTString) {126std::vector<uint8_t> DFT(DFTString.size());127DFTStringAppendToVector(&DFT, DFTString);128return DFT;129}130131static bool ParseError(const char *Err, const std::string &Line) {132Printf("DataFlowTrace: parse error: %s: Line: %s\n", Err, Line.c_str());133return false;134}135136// TODO(metzman): replace std::string with std::string_view for137// better performance. Need to figure our how to use string_view on Windows.138static bool ParseDFTLine(const std::string &Line, size_t *FunctionNum,139std::string *DFTString) {140if (!Line.empty() && Line[0] != 'F')141return false; // Ignore coverage.142size_t SpacePos = Line.find(' ');143if (SpacePos == std::string::npos)144return ParseError("no space in the trace line", Line);145if (Line.empty() || Line[0] != 'F')146return ParseError("the trace line doesn't start with 'F'", Line);147*FunctionNum = std::atol(Line.c_str() + 1);148const char *Beg = Line.c_str() + SpacePos + 1;149const char *End = Line.c_str() + Line.size();150assert(Beg < End);151size_t Len = End - Beg;152for (size_t I = 0; I < Len; I++) {153if (Beg[I] != '0' && Beg[I] != '1')154return ParseError("the trace should contain only 0 or 1", Line);155}156*DFTString = Beg;157return true;158}159160bool DataFlowTrace::Init(const std::string &DirPath, std::string *FocusFunction,161std::vector<SizedFile> &CorporaFiles, Random &Rand) {162if (DirPath.empty()) return false;163Printf("INFO: DataFlowTrace: reading from '%s'\n", DirPath.c_str());164std::vector<SizedFile> Files;165GetSizedFilesFromDir(DirPath, &Files);166std::string L;167size_t FocusFuncIdx = SIZE_MAX;168std::vector<std::string> FunctionNames;169170// Collect the hashes of the corpus files.171for (auto &SF : CorporaFiles)172CorporaHashes.insert(Hash(FileToVector(SF.File)));173174// Read functions.txt175std::ifstream IF(DirPlusFile(DirPath, kFunctionsTxt));176size_t NumFunctions = 0;177while (std::getline(IF, L, '\n')) {178FunctionNames.push_back(L);179NumFunctions++;180if (*FocusFunction == L)181FocusFuncIdx = NumFunctions - 1;182}183if (!NumFunctions)184return false;185186if (*FocusFunction == "auto") {187// AUTOFOCUS works like this:188// * reads the coverage data from the DFT files.189// * assigns weights to functions based on coverage.190// * chooses a random function according to the weights.191ReadCoverage(DirPath);192auto Weights = Coverage.FunctionWeights(NumFunctions);193std::vector<double> Intervals(NumFunctions + 1);194std::iota(Intervals.begin(), Intervals.end(), 0);195auto Distribution = std::piecewise_constant_distribution<double>(196Intervals.begin(), Intervals.end(), Weights.begin());197FocusFuncIdx = static_cast<size_t>(Distribution(Rand));198*FocusFunction = FunctionNames[FocusFuncIdx];199assert(FocusFuncIdx < NumFunctions);200Printf("INFO: AUTOFOCUS: %zd %s\n", FocusFuncIdx,201FunctionNames[FocusFuncIdx].c_str());202for (size_t i = 0; i < NumFunctions; i++) {203if (Weights[i] == 0.0)204continue;205Printf(" [%zd] W %g\tBB-tot %u\tBB-cov %u\tEntryFreq %u:\t%s\n", i,206Weights[i], Coverage.GetNumberOfBlocks(i),207Coverage.GetNumberOfCoveredBlocks(i), Coverage.GetCounter(i, 0),208FunctionNames[i].c_str());209}210}211212if (!NumFunctions || FocusFuncIdx == SIZE_MAX || Files.size() <= 1)213return false;214215// Read traces.216size_t NumTraceFiles = 0;217size_t NumTracesWithFocusFunction = 0;218for (auto &SF : Files) {219auto Name = Basename(SF.File);220if (Name == kFunctionsTxt) continue;221if (!CorporaHashes.count(Name)) continue; // not in the corpus.222NumTraceFiles++;223// Printf("=== %s\n", Name.c_str());224std::ifstream IF(SF.File);225while (std::getline(IF, L, '\n')) {226size_t FunctionNum = 0;227std::string DFTString;228if (ParseDFTLine(L, &FunctionNum, &DFTString) &&229FunctionNum == FocusFuncIdx) {230NumTracesWithFocusFunction++;231232if (FunctionNum >= NumFunctions)233return ParseError("N is greater than the number of functions", L);234Traces[Name] = DFTStringToVector(DFTString);235// Print just a few small traces.236if (NumTracesWithFocusFunction <= 3 && DFTString.size() <= 16)237Printf("%s => |%s|\n", Name.c_str(), std::string(DFTString).c_str());238break; // No need to parse the following lines.239}240}241}242Printf("INFO: DataFlowTrace: %zd trace files, %zd functions, "243"%zd traces with focus function\n",244NumTraceFiles, NumFunctions, NumTracesWithFocusFunction);245return NumTraceFiles > 0;246}247248int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,249const std::vector<SizedFile> &CorporaFiles) {250Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",251DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());252if (CorporaFiles.empty()) {253Printf("ERROR: can't collect data flow without corpus provided.");254return 1;255}256257static char DFSanEnv[] = "DFSAN_OPTIONS=warn_unimplemented=0";258putenv(DFSanEnv);259MkDir(DirPath);260for (auto &F : CorporaFiles) {261// For every input F we need to collect the data flow and the coverage.262// Data flow collection may fail if we request too many DFSan tags at once.263// So, we start from requesting all tags in range [0,Size) and if that fails264// we then request tags in [0,Size/2) and [Size/2, Size), and so on.265// Function number => DFT.266auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));267std::unordered_map<size_t, std::vector<uint8_t>> DFTMap;268std::unordered_set<std::string> Cov;269Command Cmd;270Cmd.addArgument(DFTBinary);271Cmd.addArgument(F.File);272Cmd.addArgument(OutPath);273Printf("CMD: %s\n", Cmd.toString().c_str());274ExecuteCommand(Cmd);275}276// Write functions.txt if it's currently empty or doesn't exist.277auto FunctionsTxtPath = DirPlusFile(DirPath, kFunctionsTxt);278if (FileToString(FunctionsTxtPath).empty()) {279Command Cmd;280Cmd.addArgument(DFTBinary);281Cmd.setOutputFile(FunctionsTxtPath);282ExecuteCommand(Cmd);283}284return 0;285}286287} // namespace fuzzer288289290