blob: 321f2654c736c5b33dbd4f0fe8c3c0f35e536172 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +00001//===- FuzzerMerge.cpp - merging corpora ----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// Merging corpora.
10//===----------------------------------------------------------------------===//
11
morehousea80f6452017-12-04 19:25:59 +000012#include "FuzzerCommand.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000013#include "FuzzerMerge.h"
14#include "FuzzerIO.h"
15#include "FuzzerInternal.h"
16#include "FuzzerTracePC.h"
17#include "FuzzerUtil.h"
18
19#include <fstream>
20#include <iterator>
21#include <set>
22#include <sstream>
23
24namespace fuzzer {
25
26bool Merger::Parse(const std::string &Str, bool ParseCoverage) {
27 std::istringstream SS(Str);
28 return Parse(SS, ParseCoverage);
29}
30
31void Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) {
32 if (!Parse(IS, ParseCoverage)) {
33 Printf("MERGE: failed to parse the control file (unexpected error)\n");
34 exit(1);
35 }
36}
37
38// The control file example:
39//
40// 3 # The number of inputs
41// 1 # The number of inputs in the first corpus, <= the previous number
42// file0
43// file1
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.
48// STARTED 2 567
49// DONE 2 8 9
50bool Merger::Parse(std::istream &IS, bool ParseCoverage) {
51 LastFailure.clear();
52 std::string Line;
53
54 // Parse NumFiles.
55 if (!std::getline(IS, Line, '\n')) return false;
56 std::istringstream L1(Line);
57 size_t NumFiles = 0;
58 L1 >> NumFiles;
59 if (NumFiles == 0 || NumFiles > 10000000) return false;
60
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;
67
68 // Parse file names.
69 Files.resize(NumFiles);
70 for (size_t i = 0; i < NumFiles; i++)
71 if (!std::getline(IS, Files[i].Name, '\n'))
72 return false;
73
74 // Parse STARTED and DONE lines.
75 size_t ExpectedStartMarker = 0;
76 const size_t kInvalidStartMarker = -1;
77 size_t LastSeenStartMarker = kInvalidStartMarker;
george.karpenkovfbfa45c2017-08-27 23:20:09 +000078 Vector<uint32_t> TmpFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +000079 while (std::getline(IS, Line, '\n')) {
80 std::istringstream ISS1(Line);
81 std::string Marker;
82 size_t N;
83 ISS1 >> Marker;
84 ISS1 >> N;
85 if (Marker == "STARTED") {
86 // STARTED FILE_ID FILE_SIZE
87 if (ExpectedStartMarker != N)
88 return false;
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)
97 return false;
98 LastSeenStartMarker = kInvalidStartMarker;
99 if (ParseCoverage) {
100 TmpFeatures.clear(); // use a vector from outer scope to avoid resizes.
101 while (ISS1 >> std::hex >> N)
102 TmpFeatures.push_back(N);
mgrang166fcb92018-03-20 00:44:59 +0000103 llvm::sort(TmpFeatures.begin(), TmpFeatures.end());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000104 Files[CurrentFileIdx].Features = TmpFeatures;
105 }
106 } else {
107 return false;
108 }
109 }
110 if (LastSeenStartMarker != kInvalidStartMarker)
111 LastFailure = Files[LastSeenStartMarker].Name;
112
113 FirstNotProcessedFile = ExpectedStartMarker;
114 return true;
115}
116
117size_t Merger::ApproximateMemoryConsumption() const {
118 size_t Res = 0;
119 for (const auto &F: Files)
120 Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
121 return Res;
122}
123
124// Decides which files need to be merged (add thost to NewFiles).
125// Returns the number of new features added.
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000126size_t Merger::Merge(const Set<uint32_t> &InitialFeatures,
127 Vector<std::string> *NewFiles) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000128 NewFiles->clear();
129 assert(NumFilesInFirstCorpus <= Files.size());
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000130 Set<uint32_t> AllFeatures(InitialFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000131
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());
136 }
137 size_t InitialNumFeatures = AllFeatures.size();
138
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;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000142 Vector<uint32_t> Tmp;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000143 std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
144 AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
145 Cur.swap(Tmp);
146 }
147
148 // Sort. Give preference to
149 // * smaller files
150 // * files with more features.
mgrang166fcb92018-03-20 00:44:59 +0000151 llvm::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();
156 });
george.karpenkov29efa6d2017-08-21 23:25:50 +0000157
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);
168 }
169 return AllFeatures.size() - InitialNumFeatures;
170}
171
172void Merger::PrintSummary(std::ostream &OS) {
173 for (auto &File : Files) {
174 OS << std::hex;
175 OS << File.Name << " size: " << File.Size << " features: ";
176 for (auto Feature : File.Features)
177 OS << " " << Feature;
178 OS << "\n";
179 }
180}
181
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000182Set<uint32_t> Merger::AllFeatures() const {
183 Set<uint32_t> S;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000184 for (auto &File : Files)
185 S.insert(File.Features.begin(), File.Features.end());
186 return S;
187}
188
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000189Set<uint32_t> Merger::ParseSummary(std::istream &IS) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000190 std::string Line, Tmp;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000191 Set<uint32_t> Res;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000192 while (std::getline(IS, Line, '\n')) {
193 size_t N;
194 std::istringstream ISS1(Line);
195 ISS1 >> Tmp; // Name
196 ISS1 >> Tmp; // size:
197 assert(Tmp == "size:" && "Corrupt summary file");
198 ISS1 >> std::hex;
199 ISS1 >> N; // File Size
200 ISS1 >> Tmp; // features:
201 assert(Tmp == "features:" && "Corrupt summary file");
202 while (ISS1 >> std::hex >> N)
203 Res.insert(N);
204 }
205 return Res;
206}
207
208// Inner process. May crash if the target crashes.
209void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
210 Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
211 Merger M;
212 std::ifstream IF(CFPath);
213 M.ParseOrExit(IF, false);
214 IF.close();
215 if (!M.LastFailure.empty())
216 Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
217 M.LastFailure.c_str());
218
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);
223
224 std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
kccb966c9e2017-09-15 22:02:26 +0000225 Set<size_t> AllFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000226 for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
kcc1239a992017-11-09 20:30:19 +0000227 MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000228 auto U = FileToVector(M.Files[i].Name);
229 if (U.size() > MaxInputLen) {
230 U.resize(MaxInputLen);
231 U.shrink_to_fit();
232 }
233 std::ostringstream StartedLine;
234 // Write the pre-run marker.
235 OF << "STARTED " << std::dec << i << " " << U.size() << "\n";
morehousea80f6452017-12-04 19:25:59 +0000236 OF.flush(); // Flush is important since Command::Execute may crash.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000237 // Run.
238 TPC.ResetMaps();
239 ExecuteCallback(U.data(), U.size());
kccb966c9e2017-09-15 22:02:26 +0000240 // 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;
kccc924e382017-09-15 22:10:36 +0000246 TPC.CollectFeatures([&](size_t Feature) {
kccb966c9e2017-09-15 22:02:26 +0000247 if (AllFeatures.insert(Feature).second)
248 UniqFeatures.insert(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000249 });
250 // Show stats.
251 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
252 PrintStats("pulse ");
253 // Write the post-run marker and the coverage.
254 OF << "DONE " << i;
kccb966c9e2017-09-15 22:02:26 +0000255 for (size_t F : UniqFeatures)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000256 OF << " " << std::hex << F;
257 OF << "\n";
kcca00e8072017-11-09 21:30:33 +0000258 OF.flush();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000259 }
260}
261
kcc99a71a12017-11-09 05:49:28 +0000262static void WriteNewControlFile(const std::string &CFPath,
263 const Vector<SizedFile> &AllFiles,
264 size_t NumFilesInFirstCorpus) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000265 RemoveFile(CFPath);
266 std::ofstream ControlFile(CFPath);
267 ControlFile << AllFiles.size() << "\n";
268 ControlFile << NumFilesInFirstCorpus << "\n";
kccb966c9e2017-09-15 22:02:26 +0000269 for (auto &SF: AllFiles)
270 ControlFile << SF.File << "\n";
george.karpenkov29efa6d2017-08-21 23:25:50 +0000271 if (!ControlFile) {
272 Printf("MERGE-OUTER: failed to write to the control file: %s\n",
273 CFPath.c_str());
274 exit(1);
275 }
kcc99a71a12017-11-09 05:49:28 +0000276}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000277
kcc99a71a12017-11-09 05:49:28 +0000278// Outer process. Does not call the target code and thus sohuld not fail.
279void 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");
286 return;
287 }
288 auto CFPath =
289 MergeControlFilePathOrNull
290 ? MergeControlFilePathOrNull
291 : DirPlusFile(TmpDir(),
292 "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
293
294 size_t NumAttempts = 0;
295 if (MergeControlFilePathOrNull && FileSize(MergeControlFilePathOrNull)) {
296 Printf("MERGE-OUTER: non-empty control file provided: '%s'\n",
297 MergeControlFilePathOrNull);
298 Merger M;
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");
310 exit(0);
311 }
312
313 NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
314 } else {
315 Printf("MERGE-OUTER: bad control file, will overwrite it\n");
316 }
317 }
318
319 if (!NumAttempts) {
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();
mgrang166fcb92018-03-20 00:44:59 +0000324 llvm::sort(AllFiles.begin(), AllFiles.end());
kcc99a71a12017-11-09 05:49:28 +0000325 for (size_t i = 1; i < Corpora.size(); i++)
326 GetSizedFilesFromDir(Corpora[i], &AllFiles);
mgrang166fcb92018-03-20 00:44:59 +0000327 llvm::sort(AllFiles.begin() + NumFilesInFirstCorpus, AllFiles.end());
kcc99a71a12017-11-09 05:49:28 +0000328 Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n",
329 AllFiles.size(), NumFilesInFirstCorpus);
330 WriteNewControlFile(CFPath, AllFiles, NumFilesInFirstCorpus);
331 NumAttempts = AllFiles.size();
332 }
333
334 // Execute the inner process until it passes.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000335 // Every inner process should execute at least one input.
morehousea80f6452017-12-04 19:25:59 +0000336 Command BaseCmd(Args);
337 BaseCmd.removeFlag("merge");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000338 bool Success = false;
kcc99a71a12017-11-09 05:49:28 +0000339 for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
kcc1239a992017-11-09 20:30:19 +0000340 MaybeExitGracefully();
kcc99a71a12017-11-09 05:49:28 +0000341 Printf("MERGE-OUTER: attempt %zd\n", Attempt);
morehousea80f6452017-12-04 19:25:59 +0000342 Command Cmd(BaseCmd);
343 Cmd.addFlag("merge_control_file", CFPath);
344 Cmd.addFlag("merge_inner", "1");
345 auto ExitCode = ExecuteCommand(Cmd);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000346 if (!ExitCode) {
kcc99a71a12017-11-09 05:49:28 +0000347 Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000348 Success = true;
349 break;
350 }
351 }
352 if (!Success) {
353 Printf("MERGE-OUTER: zero succesfull attempts, exiting\n");
354 exit(1);
355 }
356 // Read the control file and do the merge.
357 Merger M;
358 std::ifstream IF(CFPath);
359 IF.seekg(0, IF.end);
360 Printf("MERGE-OUTER: the control file has %zd bytes\n", (size_t)IF.tellg());
361 IF.seekg(0, IF.beg);
362 M.ParseOrExit(IF, true);
363 IF.close();
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);
371 }
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000372 Vector<std::string> NewFiles;
373 Set<uint32_t> InitialFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000374 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());
379 }
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)
kccc6402fe2017-11-15 16:42:52 +0000384 WriteToOutputCorpus(FileToVector(F, MaxInputLen));
kccc51afd72017-11-09 01:05:29 +0000385 // We are done, delete the control file if it was a temporary one.
386 if (!MergeControlFilePathOrNull)
387 RemoveFile(CFPath);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000388}
389
390} // namespace fuzzer