/src/mozilla-central/tools/fuzzing/libfuzzer/FuzzerMerge.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===- 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 | | |
12 | | #include "FuzzerCommand.h" |
13 | | #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 | | |
24 | | namespace fuzzer { |
25 | | |
26 | 0 | bool Merger::Parse(const std::string &Str, bool ParseCoverage) { |
27 | 0 | std::istringstream SS(Str); |
28 | 0 | return Parse(SS, ParseCoverage); |
29 | 0 | } |
30 | | |
31 | 0 | void Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) { |
32 | 0 | if (!Parse(IS, ParseCoverage)) { |
33 | 0 | Printf("MERGE: failed to parse the control file (unexpected error)\n"); |
34 | 0 | exit(1); |
35 | 0 | } |
36 | 0 | } |
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 |
50 | 0 | bool Merger::Parse(std::istream &IS, bool ParseCoverage) { |
51 | 0 | LastFailure.clear(); |
52 | 0 | std::string Line; |
53 | 0 |
|
54 | 0 | // Parse NumFiles. |
55 | 0 | if (!std::getline(IS, Line, '\n')) return false; |
56 | 0 | std::istringstream L1(Line); |
57 | 0 | size_t NumFiles = 0; |
58 | 0 | L1 >> NumFiles; |
59 | 0 | if (NumFiles == 0 || NumFiles > 10000000) return false; |
60 | 0 | |
61 | 0 | // Parse NumFilesInFirstCorpus. |
62 | 0 | if (!std::getline(IS, Line, '\n')) return false; |
63 | 0 | std::istringstream L2(Line); |
64 | 0 | NumFilesInFirstCorpus = NumFiles + 1; |
65 | 0 | L2 >> NumFilesInFirstCorpus; |
66 | 0 | if (NumFilesInFirstCorpus > NumFiles) return false; |
67 | 0 | |
68 | 0 | // Parse file names. |
69 | 0 | Files.resize(NumFiles); |
70 | 0 | for (size_t i = 0; i < NumFiles; i++) |
71 | 0 | if (!std::getline(IS, Files[i].Name, '\n')) |
72 | 0 | return false; |
73 | 0 |
|
74 | 0 | // Parse STARTED and DONE lines. |
75 | 0 | size_t ExpectedStartMarker = 0; |
76 | 0 | const size_t kInvalidStartMarker = -1; |
77 | 0 | size_t LastSeenStartMarker = kInvalidStartMarker; |
78 | 0 | Vector<uint32_t> TmpFeatures; |
79 | 0 | while (std::getline(IS, Line, '\n')) { |
80 | 0 | std::istringstream ISS1(Line); |
81 | 0 | std::string Marker; |
82 | 0 | size_t N; |
83 | 0 | ISS1 >> Marker; |
84 | 0 | ISS1 >> N; |
85 | 0 | if (Marker == "STARTED") { |
86 | 0 | // STARTED FILE_ID FILE_SIZE |
87 | 0 | if (ExpectedStartMarker != N) |
88 | 0 | return false; |
89 | 0 | ISS1 >> Files[ExpectedStartMarker].Size; |
90 | 0 | LastSeenStartMarker = ExpectedStartMarker; |
91 | 0 | assert(ExpectedStartMarker < Files.size()); |
92 | 0 | ExpectedStartMarker++; |
93 | 0 | } else if (Marker == "DONE") { |
94 | 0 | // DONE FILE_ID COV1 COV2 COV3 ... |
95 | 0 | size_t CurrentFileIdx = N; |
96 | 0 | if (CurrentFileIdx != LastSeenStartMarker) |
97 | 0 | return false; |
98 | 0 | LastSeenStartMarker = kInvalidStartMarker; |
99 | 0 | if (ParseCoverage) { |
100 | 0 | TmpFeatures.clear(); // use a vector from outer scope to avoid resizes. |
101 | 0 | while (ISS1 >> std::hex >> N) |
102 | 0 | TmpFeatures.push_back(N); |
103 | 0 | std::sort(TmpFeatures.begin(), TmpFeatures.end()); |
104 | 0 | Files[CurrentFileIdx].Features = TmpFeatures; |
105 | 0 | } |
106 | 0 | } else { |
107 | 0 | return false; |
108 | 0 | } |
109 | 0 | } |
110 | 0 | if (LastSeenStartMarker != kInvalidStartMarker) |
111 | 0 | LastFailure = Files[LastSeenStartMarker].Name; |
112 | 0 |
|
113 | 0 | FirstNotProcessedFile = ExpectedStartMarker; |
114 | 0 | return true; |
115 | 0 | } |
116 | | |
117 | 0 | size_t Merger::ApproximateMemoryConsumption() const { |
118 | 0 | size_t Res = 0; |
119 | 0 | for (const auto &F: Files) |
120 | 0 | Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]); |
121 | 0 | return Res; |
122 | 0 | } |
123 | | |
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 | 0 | Vector<std::string> *NewFiles) { |
128 | 0 | NewFiles->clear(); |
129 | 0 | assert(NumFilesInFirstCorpus <= Files.size()); |
130 | 0 | Set<uint32_t> AllFeatures(InitialFeatures); |
131 | 0 |
|
132 | 0 | // What features are in the initial corpus? |
133 | 0 | for (size_t i = 0; i < NumFilesInFirstCorpus; i++) { |
134 | 0 | auto &Cur = Files[i].Features; |
135 | 0 | AllFeatures.insert(Cur.begin(), Cur.end()); |
136 | 0 | } |
137 | 0 | size_t InitialNumFeatures = AllFeatures.size(); |
138 | 0 |
|
139 | 0 | // Remove all features that we already know from all other inputs. |
140 | 0 | for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) { |
141 | 0 | auto &Cur = Files[i].Features; |
142 | 0 | Vector<uint32_t> Tmp; |
143 | 0 | std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(), |
144 | 0 | AllFeatures.end(), std::inserter(Tmp, Tmp.begin())); |
145 | 0 | Cur.swap(Tmp); |
146 | 0 | } |
147 | 0 |
|
148 | 0 | // Sort. Give preference to |
149 | 0 | // * smaller files |
150 | 0 | // * files with more features. |
151 | 0 | std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(), |
152 | 0 | [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool { |
153 | 0 | if (a.Size != b.Size) |
154 | 0 | return a.Size < b.Size; |
155 | 0 | return a.Features.size() > b.Features.size(); |
156 | 0 | }); |
157 | 0 |
|
158 | 0 | // One greedy pass: add the file's features to AllFeatures. |
159 | 0 | // If new features were added, add this file to NewFiles. |
160 | 0 | for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) { |
161 | 0 | auto &Cur = Files[i].Features; |
162 | 0 | // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(), |
163 | 0 | // Files[i].Size, Cur.size()); |
164 | 0 | size_t OldSize = AllFeatures.size(); |
165 | 0 | AllFeatures.insert(Cur.begin(), Cur.end()); |
166 | 0 | if (AllFeatures.size() > OldSize) |
167 | 0 | NewFiles->push_back(Files[i].Name); |
168 | 0 | } |
169 | 0 | return AllFeatures.size() - InitialNumFeatures; |
170 | 0 | } |
171 | | |
172 | 0 | void Merger::PrintSummary(std::ostream &OS) { |
173 | 0 | for (auto &File : Files) { |
174 | 0 | OS << std::hex; |
175 | 0 | OS << File.Name << " size: " << File.Size << " features: "; |
176 | 0 | for (auto Feature : File.Features) |
177 | 0 | OS << " " << Feature; |
178 | 0 | OS << "\n"; |
179 | 0 | } |
180 | 0 | } |
181 | | |
182 | 0 | Set<uint32_t> Merger::AllFeatures() const { |
183 | 0 | Set<uint32_t> S; |
184 | 0 | for (auto &File : Files) |
185 | 0 | S.insert(File.Features.begin(), File.Features.end()); |
186 | 0 | return S; |
187 | 0 | } |
188 | | |
189 | 0 | Set<uint32_t> Merger::ParseSummary(std::istream &IS) { |
190 | 0 | std::string Line, Tmp; |
191 | 0 | Set<uint32_t> Res; |
192 | 0 | while (std::getline(IS, Line, '\n')) { |
193 | 0 | size_t N; |
194 | 0 | std::istringstream ISS1(Line); |
195 | 0 | ISS1 >> Tmp; // Name |
196 | 0 | ISS1 >> Tmp; // size: |
197 | 0 | assert(Tmp == "size:" && "Corrupt summary file"); |
198 | 0 | ISS1 >> std::hex; |
199 | 0 | ISS1 >> N; // File Size |
200 | 0 | ISS1 >> Tmp; // features: |
201 | 0 | assert(Tmp == "features:" && "Corrupt summary file"); |
202 | 0 | while (ISS1 >> std::hex >> N) |
203 | 0 | Res.insert(N); |
204 | 0 | } |
205 | 0 | return Res; |
206 | 0 | } |
207 | | |
208 | | // Inner process. May crash if the target crashes. |
209 | 0 | void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) { |
210 | 0 | Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str()); |
211 | 0 | Merger M; |
212 | 0 | std::ifstream IF(CFPath); |
213 | 0 | M.ParseOrExit(IF, false); |
214 | 0 | IF.close(); |
215 | 0 | if (!M.LastFailure.empty()) |
216 | 0 | Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n", |
217 | 0 | M.LastFailure.c_str()); |
218 | 0 |
|
219 | 0 | Printf("MERGE-INNER: %zd total files;" |
220 | 0 | " %zd processed earlier; will process %zd files now\n", |
221 | 0 | M.Files.size(), M.FirstNotProcessedFile, |
222 | 0 | M.Files.size() - M.FirstNotProcessedFile); |
223 | 0 |
|
224 | 0 | std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app); |
225 | 0 | Set<size_t> AllFeatures; |
226 | 0 | for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) { |
227 | 0 | MaybeExitGracefully(); |
228 | 0 | auto U = FileToVector(M.Files[i].Name); |
229 | 0 | if (U.size() > MaxInputLen) { |
230 | 0 | U.resize(MaxInputLen); |
231 | 0 | U.shrink_to_fit(); |
232 | 0 | } |
233 | 0 | std::ostringstream StartedLine; |
234 | 0 | // Write the pre-run marker. |
235 | 0 | OF << "STARTED " << std::dec << i << " " << U.size() << "\n"; |
236 | 0 | OF.flush(); // Flush is important since Command::Execute may crash. |
237 | 0 | // Run. |
238 | 0 | TPC.ResetMaps(); |
239 | 0 | ExecuteCallback(U.data(), U.size()); |
240 | 0 | // Collect coverage. We are iterating over the files in this order: |
241 | 0 | // * First, files in the initial corpus ordered by size, smallest first. |
242 | 0 | // * Then, all other files, smallest first. |
243 | 0 | // So it makes no sense to record all features for all files, instead we |
244 | 0 | // only record features that were not seen before. |
245 | 0 | Set<size_t> UniqFeatures; |
246 | 0 | TPC.CollectFeatures([&](size_t Feature) { |
247 | 0 | if (AllFeatures.insert(Feature).second) |
248 | 0 | UniqFeatures.insert(Feature); |
249 | 0 | }); |
250 | 0 | // Show stats. |
251 | 0 | if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1))) |
252 | 0 | PrintStats("pulse "); |
253 | 0 | // Write the post-run marker and the coverage. |
254 | 0 | OF << "DONE " << i; |
255 | 0 | for (size_t F : UniqFeatures) |
256 | 0 | OF << " " << std::hex << F; |
257 | 0 | OF << "\n"; |
258 | 0 | OF.flush(); |
259 | 0 | } |
260 | 0 | } |
261 | | |
262 | | static void WriteNewControlFile(const std::string &CFPath, |
263 | | const Vector<SizedFile> &AllFiles, |
264 | 0 | size_t NumFilesInFirstCorpus) { |
265 | 0 | RemoveFile(CFPath); |
266 | 0 | std::ofstream ControlFile(CFPath); |
267 | 0 | ControlFile << AllFiles.size() << "\n"; |
268 | 0 | ControlFile << NumFilesInFirstCorpus << "\n"; |
269 | 0 | for (auto &SF: AllFiles) |
270 | 0 | ControlFile << SF.File << "\n"; |
271 | 0 | if (!ControlFile) { |
272 | 0 | Printf("MERGE-OUTER: failed to write to the control file: %s\n", |
273 | 0 | CFPath.c_str()); |
274 | 0 | exit(1); |
275 | 0 | } |
276 | 0 | } |
277 | | |
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 | 0 | const char *MergeControlFilePathOrNull) { |
284 | 0 | if (Corpora.size() <= 1) { |
285 | 0 | Printf("Merge requires two or more corpus dirs\n"); |
286 | 0 | return; |
287 | 0 | } |
288 | 0 | auto CFPath = |
289 | 0 | MergeControlFilePathOrNull |
290 | 0 | ? MergeControlFilePathOrNull |
291 | 0 | : DirPlusFile(TmpDir(), |
292 | 0 | "libFuzzerTemp." + std::to_string(GetPid()) + ".txt"); |
293 | 0 |
|
294 | 0 | size_t NumAttempts = 0; |
295 | 0 | if (MergeControlFilePathOrNull && FileSize(MergeControlFilePathOrNull)) { |
296 | 0 | Printf("MERGE-OUTER: non-empty control file provided: '%s'\n", |
297 | 0 | MergeControlFilePathOrNull); |
298 | 0 | Merger M; |
299 | 0 | std::ifstream IF(MergeControlFilePathOrNull); |
300 | 0 | if (M.Parse(IF, /*ParseCoverage=*/false)) { |
301 | 0 | Printf("MERGE-OUTER: control file ok, %zd files total," |
302 | 0 | " first not processed file %zd\n", |
303 | 0 | M.Files.size(), M.FirstNotProcessedFile); |
304 | 0 | if (!M.LastFailure.empty()) |
305 | 0 | Printf("MERGE-OUTER: '%s' will be skipped as unlucky " |
306 | 0 | "(merge has stumbled on it the last time)\n", |
307 | 0 | M.LastFailure.c_str()); |
308 | 0 | if (M.FirstNotProcessedFile >= M.Files.size()) { |
309 | 0 | Printf("MERGE-OUTER: nothing to do, merge has been completed before\n"); |
310 | 0 | exit(0); |
311 | 0 | } |
312 | 0 | |
313 | 0 | NumAttempts = M.Files.size() - M.FirstNotProcessedFile; |
314 | 0 | } else { |
315 | 0 | Printf("MERGE-OUTER: bad control file, will overwrite it\n"); |
316 | 0 | } |
317 | 0 | } |
318 | 0 |
|
319 | 0 | if (!NumAttempts) { |
320 | 0 | // The supplied control file is empty or bad, create a fresh one. |
321 | 0 | Vector<SizedFile> AllFiles; |
322 | 0 | GetSizedFilesFromDir(Corpora[0], &AllFiles); |
323 | 0 | size_t NumFilesInFirstCorpus = AllFiles.size(); |
324 | 0 | std::sort(AllFiles.begin(), AllFiles.end()); |
325 | 0 | for (size_t i = 1; i < Corpora.size(); i++) |
326 | 0 | GetSizedFilesFromDir(Corpora[i], &AllFiles); |
327 | 0 | std::sort(AllFiles.begin() + NumFilesInFirstCorpus, AllFiles.end()); |
328 | 0 | Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n", |
329 | 0 | AllFiles.size(), NumFilesInFirstCorpus); |
330 | 0 | WriteNewControlFile(CFPath, AllFiles, NumFilesInFirstCorpus); |
331 | 0 | NumAttempts = AllFiles.size(); |
332 | 0 | } |
333 | 0 |
|
334 | 0 | // Execute the inner process until it passes. |
335 | 0 | // Every inner process should execute at least one input. |
336 | 0 | Command BaseCmd(Args); |
337 | 0 | BaseCmd.removeFlag("merge"); |
338 | 0 | bool Success = false; |
339 | 0 | for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) { |
340 | 0 | MaybeExitGracefully(); |
341 | 0 | Printf("MERGE-OUTER: attempt %zd\n", Attempt); |
342 | 0 | Command Cmd(BaseCmd); |
343 | 0 | Cmd.addFlag("merge_control_file", CFPath); |
344 | 0 | Cmd.addFlag("merge_inner", "1"); |
345 | 0 | auto ExitCode = ExecuteCommand(Cmd); |
346 | 0 | if (!ExitCode) { |
347 | 0 | Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt); |
348 | 0 | Success = true; |
349 | 0 | break; |
350 | 0 | } |
351 | 0 | } |
352 | 0 | if (!Success) { |
353 | 0 | Printf("MERGE-OUTER: zero succesfull attempts, exiting\n"); |
354 | 0 | exit(1); |
355 | 0 | } |
356 | 0 | // Read the control file and do the merge. |
357 | 0 | Merger M; |
358 | 0 | std::ifstream IF(CFPath); |
359 | 0 | IF.seekg(0, IF.end); |
360 | 0 | Printf("MERGE-OUTER: the control file has %zd bytes\n", (size_t)IF.tellg()); |
361 | 0 | IF.seekg(0, IF.beg); |
362 | 0 | M.ParseOrExit(IF, true); |
363 | 0 | IF.close(); |
364 | 0 | Printf("MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n", |
365 | 0 | M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb()); |
366 | 0 | if (CoverageSummaryOutputPathOrNull) { |
367 | 0 | Printf("MERGE-OUTER: writing coverage summary for %zd files to %s\n", |
368 | 0 | M.Files.size(), CoverageSummaryOutputPathOrNull); |
369 | 0 | std::ofstream SummaryOut(CoverageSummaryOutputPathOrNull); |
370 | 0 | M.PrintSummary(SummaryOut); |
371 | 0 | } |
372 | 0 | Vector<std::string> NewFiles; |
373 | 0 | Set<uint32_t> InitialFeatures; |
374 | 0 | if (CoverageSummaryInputPathOrNull) { |
375 | 0 | std::ifstream SummaryIn(CoverageSummaryInputPathOrNull); |
376 | 0 | InitialFeatures = M.ParseSummary(SummaryIn); |
377 | 0 | Printf("MERGE-OUTER: coverage summary loaded from %s, %zd features found\n", |
378 | 0 | CoverageSummaryInputPathOrNull, InitialFeatures.size()); |
379 | 0 | } |
380 | 0 | size_t NumNewFeatures = M.Merge(InitialFeatures, &NewFiles); |
381 | 0 | Printf("MERGE-OUTER: %zd new files with %zd new features added\n", |
382 | 0 | NewFiles.size(), NumNewFeatures); |
383 | 0 | for (auto &F: NewFiles) |
384 | 0 | WriteToOutputCorpus(FileToVector(F, MaxInputLen)); |
385 | 0 | // We are done, delete the control file if it was a temporary one. |
386 | 0 | if (!MergeControlFilePathOrNull) |
387 | 0 | RemoveFile(CFPath); |
388 | 0 | } |
389 | | |
390 | | } // namespace fuzzer |