1 //===- FuzzerMerge.cpp - merging corpora ----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 //===----------------------------------------------------------------------===//
12 #include "FuzzerCommand.h"
13 #include "FuzzerMerge.h"
15 #include "FuzzerInternal.h"
16 #include "FuzzerTracePC.h"
17 #include "FuzzerUtil.h"
26 bool Merger::Parse(const std::string &Str, bool ParseCoverage) {
27 std::istringstream SS(Str);
28 return Parse(SS, ParseCoverage);
31 void Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) {
32 if (!Parse(IS, ParseCoverage)) {
33 Printf("MERGE: failed to parse the control file (unexpected error)\n");
38 // The control file example:
40 // 3 # The number of inputs
41 // 1 # The number of inputs in the first corpus, <= the previous number
44 // file2 # One file name per line.
45 // STARTED 0 123 # FileID, file size
46 // DONE 0 1 4 6 8 # FileID COV1 COV2 ...
47 // STARTED 1 456 # If DONE is missing, the input crashed while processing.
50 bool Merger::Parse(std::istream &IS, bool ParseCoverage) {
55 if (!std::getline(IS, Line, '\n')) return false;
56 std::istringstream L1(Line);
59 if (NumFiles == 0 || NumFiles > 10000000) return false;
61 // Parse NumFilesInFirstCorpus.
62 if (!std::getline(IS, Line, '\n')) return false;
63 std::istringstream L2(Line);
64 NumFilesInFirstCorpus = NumFiles + 1;
65 L2 >> NumFilesInFirstCorpus;
66 if (NumFilesInFirstCorpus > NumFiles) return false;
69 Files.resize(NumFiles);
70 for (size_t i = 0; i < NumFiles; i++)
71 if (!std::getline(IS, Files[i].Name, '\n'))
74 // Parse STARTED and DONE lines.
75 size_t ExpectedStartMarker = 0;
76 const size_t kInvalidStartMarker = -1;
77 size_t LastSeenStartMarker = kInvalidStartMarker;
78 Vector<uint32_t> TmpFeatures;
79 while (std::getline(IS, Line, '\n')) {
80 std::istringstream ISS1(Line);
85 if (Marker == "STARTED") {
86 // STARTED FILE_ID FILE_SIZE
87 if (ExpectedStartMarker != N)
89 ISS1 >> Files[ExpectedStartMarker].Size;
90 LastSeenStartMarker = ExpectedStartMarker;
91 assert(ExpectedStartMarker < Files.size());
92 ExpectedStartMarker++;
93 } else if (Marker == "DONE") {
94 // DONE FILE_ID COV1 COV2 COV3 ...
95 size_t CurrentFileIdx = N;
96 if (CurrentFileIdx != LastSeenStartMarker)
98 LastSeenStartMarker = kInvalidStartMarker;
100 TmpFeatures.clear(); // use a vector from outer scope to avoid resizes.
101 while (ISS1 >> std::hex >> N)
102 TmpFeatures.push_back(N);
103 std::sort(TmpFeatures.begin(), TmpFeatures.end());
104 Files[CurrentFileIdx].Features = TmpFeatures;
110 if (LastSeenStartMarker != kInvalidStartMarker)
111 LastFailure = Files[LastSeenStartMarker].Name;
113 FirstNotProcessedFile = ExpectedStartMarker;
117 size_t Merger::ApproximateMemoryConsumption() const {
119 for (const auto &F: Files)
120 Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
124 // Decides which files need to be merged (add thost to NewFiles).
125 // Returns the number of new features added.
126 size_t Merger::Merge(const Set<uint32_t> &InitialFeatures,
127 Vector<std::string> *NewFiles) {
129 assert(NumFilesInFirstCorpus <= Files.size());
130 Set<uint32_t> AllFeatures(InitialFeatures);
132 // What features are in the initial corpus?
133 for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
134 auto &Cur = Files[i].Features;
135 AllFeatures.insert(Cur.begin(), Cur.end());
137 size_t InitialNumFeatures = AllFeatures.size();
139 // Remove all features that we already know from all other inputs.
140 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
141 auto &Cur = Files[i].Features;
142 Vector<uint32_t> Tmp;
143 std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
144 AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
148 // Sort. Give preference to
150 // * files with more features.
151 std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
152 [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
153 if (a.Size != b.Size)
154 return a.Size < b.Size;
155 return a.Features.size() > b.Features.size();
158 // One greedy pass: add the file's features to AllFeatures.
159 // If new features were added, add this file to NewFiles.
160 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
161 auto &Cur = Files[i].Features;
162 // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
163 // Files[i].Size, Cur.size());
164 size_t OldSize = AllFeatures.size();
165 AllFeatures.insert(Cur.begin(), Cur.end());
166 if (AllFeatures.size() > OldSize)
167 NewFiles->push_back(Files[i].Name);
169 return AllFeatures.size() - InitialNumFeatures;
172 void Merger::PrintSummary(std::ostream &OS) {
173 for (auto &File : Files) {
175 OS << File.Name << " size: " << File.Size << " features: ";
176 for (auto Feature : File.Features)
177 OS << " " << Feature;
182 Set<uint32_t> Merger::AllFeatures() const {
184 for (auto &File : Files)
185 S.insert(File.Features.begin(), File.Features.end());
189 Set<uint32_t> Merger::ParseSummary(std::istream &IS) {
190 std::string Line, Tmp;
192 while (std::getline(IS, Line, '\n')) {
194 std::istringstream ISS1(Line);
196 ISS1 >> Tmp; // size:
197 assert(Tmp == "size:" && "Corrupt summary file");
199 ISS1 >> N; // File Size
200 ISS1 >> Tmp; // features:
201 assert(Tmp == "features:" && "Corrupt summary file");
202 while (ISS1 >> std::hex >> N)
208 // Inner process. May crash if the target crashes.
209 void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
210 Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
212 std::ifstream IF(CFPath);
213 M.ParseOrExit(IF, false);
215 if (!M.LastFailure.empty())
216 Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
217 M.LastFailure.c_str());
219 Printf("MERGE-INNER: %zd total files;"
220 " %zd processed earlier; will process %zd files now\n",
221 M.Files.size(), M.FirstNotProcessedFile,
222 M.Files.size() - M.FirstNotProcessedFile);
224 std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
225 Set<size_t> AllFeatures;
226 for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
227 MaybeExitGracefully();
228 auto U = FileToVector(M.Files[i].Name);
229 if (U.size() > MaxInputLen) {
230 U.resize(MaxInputLen);
233 std::ostringstream StartedLine;
234 // Write the pre-run marker.
235 OF << "STARTED " << std::dec << i << " " << U.size() << "\n";
236 OF.flush(); // Flush is important since Command::Execute may crash.
239 ExecuteCallback(U.data(), U.size());
240 // Collect coverage. We are iterating over the files in this order:
241 // * First, files in the initial corpus ordered by size, smallest first.
242 // * Then, all other files, smallest first.
243 // So it makes no sense to record all features for all files, instead we
244 // only record features that were not seen before.
245 Set<size_t> UniqFeatures;
246 TPC.CollectFeatures([&](size_t Feature) {
247 if (AllFeatures.insert(Feature).second)
248 UniqFeatures.insert(Feature);
251 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
252 PrintStats("pulse ");
253 // Write the post-run marker and the coverage.
255 for (size_t F : UniqFeatures)
256 OF << " " << std::hex << F;
262 static void WriteNewControlFile(const std::string &CFPath,
263 const Vector<SizedFile> &AllFiles,
264 size_t NumFilesInFirstCorpus) {
266 std::ofstream ControlFile(CFPath);
267 ControlFile << AllFiles.size() << "\n";
268 ControlFile << NumFilesInFirstCorpus << "\n";
269 for (auto &SF: AllFiles)
270 ControlFile << SF.File << "\n";
272 Printf("MERGE-OUTER: failed to write to the control file: %s\n",
278 // Outer process. Does not call the target code and thus sohuld not fail.
279 void Fuzzer::CrashResistantMerge(const Vector<std::string> &Args,
280 const Vector<std::string> &Corpora,
281 const char *CoverageSummaryInputPathOrNull,
282 const char *CoverageSummaryOutputPathOrNull,
283 const char *MergeControlFilePathOrNull) {
284 if (Corpora.size() <= 1) {
285 Printf("Merge requires two or more corpus dirs\n");
289 MergeControlFilePathOrNull
290 ? MergeControlFilePathOrNull
291 : DirPlusFile(TmpDir(),
292 "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
294 size_t NumAttempts = 0;
295 if (MergeControlFilePathOrNull && FileSize(MergeControlFilePathOrNull)) {
296 Printf("MERGE-OUTER: non-empty control file provided: '%s'\n",
297 MergeControlFilePathOrNull);
299 std::ifstream IF(MergeControlFilePathOrNull);
300 if (M.Parse(IF, /*ParseCoverage=*/false)) {
301 Printf("MERGE-OUTER: control file ok, %zd files total,"
302 " first not processed file %zd\n",
303 M.Files.size(), M.FirstNotProcessedFile);
304 if (!M.LastFailure.empty())
305 Printf("MERGE-OUTER: '%s' will be skipped as unlucky "
306 "(merge has stumbled on it the last time)\n",
307 M.LastFailure.c_str());
308 if (M.FirstNotProcessedFile >= M.Files.size()) {
309 Printf("MERGE-OUTER: nothing to do, merge has been completed before\n");
313 NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
315 Printf("MERGE-OUTER: bad control file, will overwrite it\n");
320 // The supplied control file is empty or bad, create a fresh one.
321 Vector<SizedFile> AllFiles;
322 GetSizedFilesFromDir(Corpora[0], &AllFiles);
323 size_t NumFilesInFirstCorpus = AllFiles.size();
324 std::sort(AllFiles.begin(), AllFiles.end());
325 for (size_t i = 1; i < Corpora.size(); i++)
326 GetSizedFilesFromDir(Corpora[i], &AllFiles);
327 std::sort(AllFiles.begin() + NumFilesInFirstCorpus, AllFiles.end());
328 Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n",
329 AllFiles.size(), NumFilesInFirstCorpus);
330 WriteNewControlFile(CFPath, AllFiles, NumFilesInFirstCorpus);
331 NumAttempts = AllFiles.size();
334 // Execute the inner process until it passes.
335 // Every inner process should execute at least one input.
336 Command BaseCmd(Args);
337 BaseCmd.removeFlag("merge");
338 bool Success = false;
339 for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
340 MaybeExitGracefully();
341 Printf("MERGE-OUTER: attempt %zd\n", Attempt);
342 Command Cmd(BaseCmd);
343 Cmd.addFlag("merge_control_file", CFPath);
344 Cmd.addFlag("merge_inner", "1");
345 auto ExitCode = ExecuteCommand(Cmd);
347 Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt);
353 Printf("MERGE-OUTER: zero succesfull attempts, exiting\n");
356 // Read the control file and do the merge.
358 std::ifstream IF(CFPath);
360 Printf("MERGE-OUTER: the control file has %zd bytes\n", (size_t)IF.tellg());
362 M.ParseOrExit(IF, true);
364 Printf("MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
365 M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
366 if (CoverageSummaryOutputPathOrNull) {
367 Printf("MERGE-OUTER: writing coverage summary for %zd files to %s\n",
368 M.Files.size(), CoverageSummaryOutputPathOrNull);
369 std::ofstream SummaryOut(CoverageSummaryOutputPathOrNull);
370 M.PrintSummary(SummaryOut);
372 Vector<std::string> NewFiles;
373 Set<uint32_t> InitialFeatures;
374 if (CoverageSummaryInputPathOrNull) {
375 std::ifstream SummaryIn(CoverageSummaryInputPathOrNull);
376 InitialFeatures = M.ParseSummary(SummaryIn);
377 Printf("MERGE-OUTER: coverage summary loaded from %s, %zd features found\n",
378 CoverageSummaryInputPathOrNull, InitialFeatures.size());
380 size_t NumNewFeatures = M.Merge(InitialFeatures, &NewFiles);
381 Printf("MERGE-OUTER: %zd new files with %zd new features added\n",
382 NewFiles.size(), NumNewFeatures);
383 for (auto &F: NewFiles)
384 WriteToOutputCorpus(FileToVector(F, MaxInputLen));
385 // We are done, delete the control file if it was a temporary one.
386 if (!MergeControlFilePathOrNull)
390 } // namespace fuzzer