blob: 0d4971af09bce11f501546847269dac8c8794dc8 [file] [log] [blame]
george.karpenkov29efa6d2017-08-21 23:25:50 +00001//===- FuzzerMerge.cpp - merging corpora ----------------------------------===//
2//
chandlerc40284492019-01-19 08:50:56 +00003// 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
george.karpenkov29efa6d2017-08-21 23:25:50 +00006//
7//===----------------------------------------------------------------------===//
8// Merging corpora.
9//===----------------------------------------------------------------------===//
10
morehousea80f6452017-12-04 19:25:59 +000011#include "FuzzerCommand.h"
george.karpenkov29efa6d2017-08-21 23:25:50 +000012#include "FuzzerMerge.h"
13#include "FuzzerIO.h"
14#include "FuzzerInternal.h"
15#include "FuzzerTracePC.h"
16#include "FuzzerUtil.h"
17
18#include <fstream>
19#include <iterator>
20#include <set>
21#include <sstream>
22
23namespace fuzzer {
24
25bool Merger::Parse(const std::string &Str, bool ParseCoverage) {
26 std::istringstream SS(Str);
27 return Parse(SS, ParseCoverage);
28}
29
30void Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) {
31 if (!Parse(IS, ParseCoverage)) {
32 Printf("MERGE: failed to parse the control file (unexpected error)\n");
33 exit(1);
34 }
35}
36
37// The control file example:
38//
39// 3 # The number of inputs
40// 1 # The number of inputs in the first corpus, <= the previous number
41// file0
42// file1
43// file2 # One file name per line.
44// STARTED 0 123 # FileID, file size
45// DONE 0 1 4 6 8 # FileID COV1 COV2 ...
46// STARTED 1 456 # If DONE is missing, the input crashed while processing.
47// STARTED 2 567
48// DONE 2 8 9
49bool Merger::Parse(std::istream &IS, bool ParseCoverage) {
50 LastFailure.clear();
51 std::string Line;
52
53 // Parse NumFiles.
54 if (!std::getline(IS, Line, '\n')) return false;
55 std::istringstream L1(Line);
56 size_t NumFiles = 0;
57 L1 >> NumFiles;
58 if (NumFiles == 0 || NumFiles > 10000000) return false;
59
60 // Parse NumFilesInFirstCorpus.
61 if (!std::getline(IS, Line, '\n')) return false;
62 std::istringstream L2(Line);
63 NumFilesInFirstCorpus = NumFiles + 1;
64 L2 >> NumFilesInFirstCorpus;
65 if (NumFilesInFirstCorpus > NumFiles) return false;
66
67 // Parse file names.
68 Files.resize(NumFiles);
69 for (size_t i = 0; i < NumFiles; i++)
70 if (!std::getline(IS, Files[i].Name, '\n'))
71 return false;
72
73 // Parse STARTED and DONE lines.
74 size_t ExpectedStartMarker = 0;
75 const size_t kInvalidStartMarker = -1;
76 size_t LastSeenStartMarker = kInvalidStartMarker;
george.karpenkovfbfa45c2017-08-27 23:20:09 +000077 Vector<uint32_t> TmpFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +000078 while (std::getline(IS, Line, '\n')) {
79 std::istringstream ISS1(Line);
80 std::string Marker;
81 size_t N;
82 ISS1 >> Marker;
83 ISS1 >> N;
84 if (Marker == "STARTED") {
85 // STARTED FILE_ID FILE_SIZE
86 if (ExpectedStartMarker != N)
87 return false;
88 ISS1 >> Files[ExpectedStartMarker].Size;
89 LastSeenStartMarker = ExpectedStartMarker;
90 assert(ExpectedStartMarker < Files.size());
91 ExpectedStartMarker++;
92 } else if (Marker == "DONE") {
93 // DONE FILE_ID COV1 COV2 COV3 ...
94 size_t CurrentFileIdx = N;
95 if (CurrentFileIdx != LastSeenStartMarker)
96 return false;
97 LastSeenStartMarker = kInvalidStartMarker;
98 if (ParseCoverage) {
99 TmpFeatures.clear(); // use a vector from outer scope to avoid resizes.
100 while (ISS1 >> std::hex >> N)
101 TmpFeatures.push_back(N);
mgrang2c1f00d2018-03-20 01:17:18 +0000102 std::sort(TmpFeatures.begin(), TmpFeatures.end());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000103 Files[CurrentFileIdx].Features = TmpFeatures;
104 }
105 } else {
106 return false;
107 }
108 }
109 if (LastSeenStartMarker != kInvalidStartMarker)
110 LastFailure = Files[LastSeenStartMarker].Name;
111
112 FirstNotProcessedFile = ExpectedStartMarker;
113 return true;
114}
115
116size_t Merger::ApproximateMemoryConsumption() const {
117 size_t Res = 0;
118 for (const auto &F: Files)
119 Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
120 return Res;
121}
122
123// Decides which files need to be merged (add thost to NewFiles).
124// Returns the number of new features added.
kcca3815862019-02-08 21:27:23 +0000125size_t Merger::Merge(const Set<uint32_t> &InitialFeatures,
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000126 Vector<std::string> *NewFiles) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000127 NewFiles->clear();
128 assert(NumFilesInFirstCorpus <= Files.size());
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000129 Set<uint32_t> AllFeatures(InitialFeatures);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000130
131 // What features are in the initial corpus?
132 for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
133 auto &Cur = Files[i].Features;
134 AllFeatures.insert(Cur.begin(), Cur.end());
135 }
136 size_t InitialNumFeatures = AllFeatures.size();
137
138 // Remove all features that we already know from all other inputs.
139 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
140 auto &Cur = Files[i].Features;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000141 Vector<uint32_t> Tmp;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000142 std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
143 AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
144 Cur.swap(Tmp);
145 }
146
147 // Sort. Give preference to
148 // * smaller files
149 // * files with more features.
mgrang2c1f00d2018-03-20 01:17:18 +0000150 std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
151 [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
152 if (a.Size != b.Size)
153 return a.Size < b.Size;
154 return a.Features.size() > b.Features.size();
155 });
george.karpenkov29efa6d2017-08-21 23:25:50 +0000156
157 // One greedy pass: add the file's features to AllFeatures.
158 // If new features were added, add this file to NewFiles.
159 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
160 auto &Cur = Files[i].Features;
161 // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
162 // Files[i].Size, Cur.size());
163 size_t OldSize = AllFeatures.size();
164 AllFeatures.insert(Cur.begin(), Cur.end());
165 if (AllFeatures.size() > OldSize)
166 NewFiles->push_back(Files[i].Name);
167 }
168 return AllFeatures.size() - InitialNumFeatures;
169}
170
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000171Set<uint32_t> Merger::AllFeatures() const {
172 Set<uint32_t> S;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000173 for (auto &File : Files)
174 S.insert(File.Features.begin(), File.Features.end());
175 return S;
176}
177
george.karpenkov29efa6d2017-08-21 23:25:50 +0000178// Inner process. May crash if the target crashes.
179void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
180 Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
181 Merger M;
182 std::ifstream IF(CFPath);
183 M.ParseOrExit(IF, false);
184 IF.close();
185 if (!M.LastFailure.empty())
186 Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
187 M.LastFailure.c_str());
188
189 Printf("MERGE-INNER: %zd total files;"
190 " %zd processed earlier; will process %zd files now\n",
191 M.Files.size(), M.FirstNotProcessedFile,
192 M.Files.size() - M.FirstNotProcessedFile);
193
194 std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
kccb966c9e2017-09-15 22:02:26 +0000195 Set<size_t> AllFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000196 for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
kcca3815862019-02-08 21:27:23 +0000197 Fuzzer::MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000198 auto U = FileToVector(M.Files[i].Name);
199 if (U.size() > MaxInputLen) {
200 U.resize(MaxInputLen);
201 U.shrink_to_fit();
202 }
203 std::ostringstream StartedLine;
204 // Write the pre-run marker.
205 OF << "STARTED " << std::dec << i << " " << U.size() << "\n";
morehousea80f6452017-12-04 19:25:59 +0000206 OF.flush(); // Flush is important since Command::Execute may crash.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000207 // Run.
208 TPC.ResetMaps();
209 ExecuteCallback(U.data(), U.size());
kccb966c9e2017-09-15 22:02:26 +0000210 // Collect coverage. We are iterating over the files in this order:
211 // * First, files in the initial corpus ordered by size, smallest first.
212 // * Then, all other files, smallest first.
213 // So it makes no sense to record all features for all files, instead we
214 // only record features that were not seen before.
215 Set<size_t> UniqFeatures;
kccc924e382017-09-15 22:10:36 +0000216 TPC.CollectFeatures([&](size_t Feature) {
kccb966c9e2017-09-15 22:02:26 +0000217 if (AllFeatures.insert(Feature).second)
218 UniqFeatures.insert(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000219 });
220 // Show stats.
221 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
222 PrintStats("pulse ");
223 // Write the post-run marker and the coverage.
224 OF << "DONE " << i;
kccb966c9e2017-09-15 22:02:26 +0000225 for (size_t F : UniqFeatures)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000226 OF << " " << std::hex << F;
227 OF << "\n";
kcca00e8072017-11-09 21:30:33 +0000228 OF.flush();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000229 }
230}
231
kcc99a71a12017-11-09 05:49:28 +0000232static void WriteNewControlFile(const std::string &CFPath,
233 const Vector<SizedFile> &AllFiles,
234 size_t NumFilesInFirstCorpus) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000235 RemoveFile(CFPath);
236 std::ofstream ControlFile(CFPath);
237 ControlFile << AllFiles.size() << "\n";
238 ControlFile << NumFilesInFirstCorpus << "\n";
kccb966c9e2017-09-15 22:02:26 +0000239 for (auto &SF: AllFiles)
240 ControlFile << SF.File << "\n";
george.karpenkov29efa6d2017-08-21 23:25:50 +0000241 if (!ControlFile) {
242 Printf("MERGE-OUTER: failed to write to the control file: %s\n",
243 CFPath.c_str());
244 exit(1);
245 }
kcc99a71a12017-11-09 05:49:28 +0000246}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000247
kcc99a71a12017-11-09 05:49:28 +0000248// Outer process. Does not call the target code and thus sohuld not fail.
kcca3815862019-02-08 21:27:23 +0000249Vector<std::string>
250CrashResistantMerge(const Vector<std::string> &Args,
251 const Vector<std::string> &Corpora,
kccf2593592019-02-08 22:02:37 +0000252 const std::string &CFPath) {
kcc99a71a12017-11-09 05:49:28 +0000253 size_t NumAttempts = 0;
kcca3815862019-02-08 21:27:23 +0000254 if (FileSize(CFPath)) {
kcc99a71a12017-11-09 05:49:28 +0000255 Printf("MERGE-OUTER: non-empty control file provided: '%s'\n",
kcca3815862019-02-08 21:27:23 +0000256 CFPath.c_str());
kcc99a71a12017-11-09 05:49:28 +0000257 Merger M;
kcca3815862019-02-08 21:27:23 +0000258 std::ifstream IF(CFPath);
kcc99a71a12017-11-09 05:49:28 +0000259 if (M.Parse(IF, /*ParseCoverage=*/false)) {
260 Printf("MERGE-OUTER: control file ok, %zd files total,"
261 " first not processed file %zd\n",
262 M.Files.size(), M.FirstNotProcessedFile);
263 if (!M.LastFailure.empty())
264 Printf("MERGE-OUTER: '%s' will be skipped as unlucky "
265 "(merge has stumbled on it the last time)\n",
266 M.LastFailure.c_str());
267 if (M.FirstNotProcessedFile >= M.Files.size()) {
268 Printf("MERGE-OUTER: nothing to do, merge has been completed before\n");
269 exit(0);
270 }
271
272 NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
273 } else {
274 Printf("MERGE-OUTER: bad control file, will overwrite it\n");
275 }
276 }
277
278 if (!NumAttempts) {
279 // The supplied control file is empty or bad, create a fresh one.
280 Vector<SizedFile> AllFiles;
281 GetSizedFilesFromDir(Corpora[0], &AllFiles);
282 size_t NumFilesInFirstCorpus = AllFiles.size();
mgrang2c1f00d2018-03-20 01:17:18 +0000283 std::sort(AllFiles.begin(), AllFiles.end());
kcc99a71a12017-11-09 05:49:28 +0000284 for (size_t i = 1; i < Corpora.size(); i++)
285 GetSizedFilesFromDir(Corpora[i], &AllFiles);
mgrang2c1f00d2018-03-20 01:17:18 +0000286 std::sort(AllFiles.begin() + NumFilesInFirstCorpus, AllFiles.end());
kcc99a71a12017-11-09 05:49:28 +0000287 Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n",
288 AllFiles.size(), NumFilesInFirstCorpus);
289 WriteNewControlFile(CFPath, AllFiles, NumFilesInFirstCorpus);
290 NumAttempts = AllFiles.size();
291 }
292
293 // Execute the inner process until it passes.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000294 // Every inner process should execute at least one input.
morehousea80f6452017-12-04 19:25:59 +0000295 Command BaseCmd(Args);
296 BaseCmd.removeFlag("merge");
kcca3815862019-02-08 21:27:23 +0000297 BaseCmd.removeFlag("fork");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000298 bool Success = false;
kcc99a71a12017-11-09 05:49:28 +0000299 for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
kcca3815862019-02-08 21:27:23 +0000300 Fuzzer::MaybeExitGracefully();
kcc99a71a12017-11-09 05:49:28 +0000301 Printf("MERGE-OUTER: attempt %zd\n", Attempt);
morehousea80f6452017-12-04 19:25:59 +0000302 Command Cmd(BaseCmd);
303 Cmd.addFlag("merge_control_file", CFPath);
304 Cmd.addFlag("merge_inner", "1");
305 auto ExitCode = ExecuteCommand(Cmd);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000306 if (!ExitCode) {
kcc99a71a12017-11-09 05:49:28 +0000307 Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000308 Success = true;
309 break;
310 }
311 }
312 if (!Success) {
313 Printf("MERGE-OUTER: zero succesfull attempts, exiting\n");
314 exit(1);
315 }
316 // Read the control file and do the merge.
317 Merger M;
318 std::ifstream IF(CFPath);
319 IF.seekg(0, IF.end);
320 Printf("MERGE-OUTER: the control file has %zd bytes\n", (size_t)IF.tellg());
321 IF.seekg(0, IF.beg);
322 M.ParseOrExit(IF, true);
323 IF.close();
324 Printf("MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
325 M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000326 Set<uint32_t> InitialFeatures;
kcca3815862019-02-08 21:27:23 +0000327 Vector<std::string> NewFiles;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000328 size_t NumNewFeatures = M.Merge(InitialFeatures, &NewFiles);
329 Printf("MERGE-OUTER: %zd new files with %zd new features added\n",
330 NewFiles.size(), NumNewFeatures);
kcca3815862019-02-08 21:27:23 +0000331 return NewFiles;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000332}
333
334} // namespace fuzzer