blob: 549d180d4c812d95053e9d4e0e7b75148f6d02f4 [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
kcc001e5f72019-02-14 23:12:33 +000045// FT 0 1 4 6 8 # FileID COV1 COV2 ...
46// COV 0 7 8 9 # FileID COV1 COV1
47// STARTED 1 456 # If FT is missing, the input crashed while processing.
george.karpenkov29efa6d2017-08-21 23:25:50 +000048// STARTED 2 567
kcc001e5f72019-02-14 23:12:33 +000049// FT 2 8 9
50// COV 2 11 12
george.karpenkov29efa6d2017-08-21 23:25:50 +000051bool Merger::Parse(std::istream &IS, bool ParseCoverage) {
52 LastFailure.clear();
53 std::string Line;
54
55 // Parse NumFiles.
56 if (!std::getline(IS, Line, '\n')) return false;
57 std::istringstream L1(Line);
58 size_t NumFiles = 0;
59 L1 >> NumFiles;
60 if (NumFiles == 0 || NumFiles > 10000000) return false;
61
62 // Parse NumFilesInFirstCorpus.
63 if (!std::getline(IS, Line, '\n')) return false;
64 std::istringstream L2(Line);
65 NumFilesInFirstCorpus = NumFiles + 1;
66 L2 >> NumFilesInFirstCorpus;
67 if (NumFilesInFirstCorpus > NumFiles) return false;
68
69 // Parse file names.
70 Files.resize(NumFiles);
71 for (size_t i = 0; i < NumFiles; i++)
72 if (!std::getline(IS, Files[i].Name, '\n'))
73 return false;
74
kcc001e5f72019-02-14 23:12:33 +000075 // Parse STARTED, FT, and COV lines.
george.karpenkov29efa6d2017-08-21 23:25:50 +000076 size_t ExpectedStartMarker = 0;
77 const size_t kInvalidStartMarker = -1;
78 size_t LastSeenStartMarker = kInvalidStartMarker;
george.karpenkovfbfa45c2017-08-27 23:20:09 +000079 Vector<uint32_t> TmpFeatures;
kcc98a86242019-02-15 00:08:16 +000080 Set<uint32_t> PCs;
george.karpenkov29efa6d2017-08-21 23:25:50 +000081 while (std::getline(IS, Line, '\n')) {
82 std::istringstream ISS1(Line);
83 std::string Marker;
84 size_t N;
85 ISS1 >> Marker;
86 ISS1 >> N;
87 if (Marker == "STARTED") {
88 // STARTED FILE_ID FILE_SIZE
89 if (ExpectedStartMarker != N)
90 return false;
91 ISS1 >> Files[ExpectedStartMarker].Size;
92 LastSeenStartMarker = ExpectedStartMarker;
93 assert(ExpectedStartMarker < Files.size());
94 ExpectedStartMarker++;
kcc001e5f72019-02-14 23:12:33 +000095 } else if (Marker == "FT") {
96 // FT FILE_ID COV1 COV2 COV3 ...
george.karpenkov29efa6d2017-08-21 23:25:50 +000097 size_t CurrentFileIdx = N;
98 if (CurrentFileIdx != LastSeenStartMarker)
99 return false;
100 LastSeenStartMarker = kInvalidStartMarker;
101 if (ParseCoverage) {
102 TmpFeatures.clear(); // use a vector from outer scope to avoid resizes.
103 while (ISS1 >> std::hex >> N)
104 TmpFeatures.push_back(N);
mgrang2c1f00d2018-03-20 01:17:18 +0000105 std::sort(TmpFeatures.begin(), TmpFeatures.end());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000106 Files[CurrentFileIdx].Features = TmpFeatures;
107 }
kcc001e5f72019-02-14 23:12:33 +0000108 } else if (Marker == "COV") {
kcc98a86242019-02-15 00:08:16 +0000109 size_t CurrentFileIdx = N;
kcc001e5f72019-02-14 23:12:33 +0000110 if (ParseCoverage)
111 while (ISS1 >> std::hex >> N)
112 if (PCs.insert(N).second)
kcc98a86242019-02-15 00:08:16 +0000113 Files[CurrentFileIdx].Cov.push_back(N);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000114 } else {
115 return false;
116 }
117 }
118 if (LastSeenStartMarker != kInvalidStartMarker)
119 LastFailure = Files[LastSeenStartMarker].Name;
120
121 FirstNotProcessedFile = ExpectedStartMarker;
122 return true;
123}
124
125size_t Merger::ApproximateMemoryConsumption() const {
126 size_t Res = 0;
127 for (const auto &F: Files)
128 Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
129 return Res;
130}
131
kcc243006d2019-02-12 00:12:33 +0000132// Decides which files need to be merged (add those to NewFiles).
george.karpenkov29efa6d2017-08-21 23:25:50 +0000133// Returns the number of new features added.
kcc98a86242019-02-15 00:08:16 +0000134void Merger::Merge(const Set<uint32_t> &InitialFeatures,
135 Set<uint32_t> *NewFeatures, const Set<uint32_t> &InitialCov,
136 Set<uint32_t> *NewCov, Vector<std::string> *NewFiles) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000137 NewFiles->clear();
138 assert(NumFilesInFirstCorpus <= Files.size());
kcc243006d2019-02-12 00:12:33 +0000139 Set<uint32_t> AllFeatures = InitialFeatures;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000140
141 // What features are in the initial corpus?
142 for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
143 auto &Cur = Files[i].Features;
kcc243006d2019-02-12 00:12:33 +0000144 AllFeatures.insert(Cur.begin(), Cur.end());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000145 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000146 // Remove all features that we already know from all other inputs.
147 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
148 auto &Cur = Files[i].Features;
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000149 Vector<uint32_t> Tmp;
kcc243006d2019-02-12 00:12:33 +0000150 std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
151 AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
george.karpenkov29efa6d2017-08-21 23:25:50 +0000152 Cur.swap(Tmp);
153 }
154
155 // Sort. Give preference to
156 // * smaller files
157 // * files with more features.
mgrang2c1f00d2018-03-20 01:17:18 +0000158 std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
159 [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
160 if (a.Size != b.Size)
161 return a.Size < b.Size;
162 return a.Features.size() > b.Features.size();
163 });
george.karpenkov29efa6d2017-08-21 23:25:50 +0000164
165 // One greedy pass: add the file's features to AllFeatures.
166 // If new features were added, add this file to NewFiles.
167 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
168 auto &Cur = Files[i].Features;
169 // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
170 // Files[i].Size, Cur.size());
kcc243006d2019-02-12 00:12:33 +0000171 bool FoundNewFeatures = false;
172 for (auto Fe: Cur) {
173 if (AllFeatures.insert(Fe).second) {
174 FoundNewFeatures = true;
175 NewFeatures->insert(Fe);
176 }
177 }
178 if (FoundNewFeatures)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000179 NewFiles->push_back(Files[i].Name);
kcc98a86242019-02-15 00:08:16 +0000180 for (auto Cov : Files[i].Cov)
181 if (InitialCov.find(Cov) == InitialCov.end())
182 NewCov->insert(Cov);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000183 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000184}
185
george.karpenkovfbfa45c2017-08-27 23:20:09 +0000186Set<uint32_t> Merger::AllFeatures() const {
187 Set<uint32_t> S;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000188 for (auto &File : Files)
189 S.insert(File.Features.begin(), File.Features.end());
190 return S;
191}
192
george.karpenkov29efa6d2017-08-21 23:25:50 +0000193// Inner process. May crash if the target crashes.
194void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
195 Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
196 Merger M;
197 std::ifstream IF(CFPath);
198 M.ParseOrExit(IF, false);
199 IF.close();
200 if (!M.LastFailure.empty())
201 Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
202 M.LastFailure.c_str());
203
204 Printf("MERGE-INNER: %zd total files;"
205 " %zd processed earlier; will process %zd files now\n",
206 M.Files.size(), M.FirstNotProcessedFile,
207 M.Files.size() - M.FirstNotProcessedFile);
208
209 std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
kccb966c9e2017-09-15 22:02:26 +0000210 Set<size_t> AllFeatures;
kcc001e5f72019-02-14 23:12:33 +0000211 Set<const TracePC::PCTableEntry *> AllPCs;
george.karpenkov29efa6d2017-08-21 23:25:50 +0000212 for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
kcca3815862019-02-08 21:27:23 +0000213 Fuzzer::MaybeExitGracefully();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000214 auto U = FileToVector(M.Files[i].Name);
215 if (U.size() > MaxInputLen) {
216 U.resize(MaxInputLen);
217 U.shrink_to_fit();
218 }
219 std::ostringstream StartedLine;
220 // Write the pre-run marker.
221 OF << "STARTED " << std::dec << i << " " << U.size() << "\n";
morehousea80f6452017-12-04 19:25:59 +0000222 OF.flush(); // Flush is important since Command::Execute may crash.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000223 // Run.
224 TPC.ResetMaps();
225 ExecuteCallback(U.data(), U.size());
kccb966c9e2017-09-15 22:02:26 +0000226 // Collect coverage. We are iterating over the files in this order:
227 // * First, files in the initial corpus ordered by size, smallest first.
228 // * Then, all other files, smallest first.
229 // So it makes no sense to record all features for all files, instead we
230 // only record features that were not seen before.
231 Set<size_t> UniqFeatures;
kccc924e382017-09-15 22:10:36 +0000232 TPC.CollectFeatures([&](size_t Feature) {
kccb966c9e2017-09-15 22:02:26 +0000233 if (AllFeatures.insert(Feature).second)
234 UniqFeatures.insert(Feature);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000235 });
kcc001e5f72019-02-14 23:12:33 +0000236 TPC.UpdateObservedPCs();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000237 // Show stats.
238 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
239 PrintStats("pulse ");
240 // Write the post-run marker and the coverage.
kcc001e5f72019-02-14 23:12:33 +0000241 OF << "FT " << i;
kccb966c9e2017-09-15 22:02:26 +0000242 for (size_t F : UniqFeatures)
george.karpenkov29efa6d2017-08-21 23:25:50 +0000243 OF << " " << std::hex << F;
244 OF << "\n";
kcc98a86242019-02-15 00:08:16 +0000245 OF << "COV " << std::dec << i;
kcc001e5f72019-02-14 23:12:33 +0000246 TPC.ForEachObservedPC([&](const TracePC::PCTableEntry *TE) {
247 if (AllPCs.insert(TE).second)
248 OF << " " << TPC.PCTableEntryIdx(TE);
249 });
250 OF << "\n";
kcca00e8072017-11-09 21:30:33 +0000251 OF.flush();
george.karpenkov29efa6d2017-08-21 23:25:50 +0000252 }
kcc001e5f72019-02-14 23:12:33 +0000253 PrintStats("DONE ");
george.karpenkov29efa6d2017-08-21 23:25:50 +0000254}
255
kcc99a71a12017-11-09 05:49:28 +0000256static void WriteNewControlFile(const std::string &CFPath,
kccd1449be2019-02-08 22:59:03 +0000257 const Vector<SizedFile> &OldCorpus,
258 const Vector<SizedFile> &NewCorpus) {
george.karpenkov29efa6d2017-08-21 23:25:50 +0000259 RemoveFile(CFPath);
260 std::ofstream ControlFile(CFPath);
kccd1449be2019-02-08 22:59:03 +0000261 ControlFile << (OldCorpus.size() + NewCorpus.size()) << "\n";
262 ControlFile << OldCorpus.size() << "\n";
263 for (auto &SF: OldCorpus)
264 ControlFile << SF.File << "\n";
265 for (auto &SF: NewCorpus)
kccb966c9e2017-09-15 22:02:26 +0000266 ControlFile << SF.File << "\n";
george.karpenkov29efa6d2017-08-21 23:25:50 +0000267 if (!ControlFile) {
268 Printf("MERGE-OUTER: failed to write to the control file: %s\n",
269 CFPath.c_str());
270 exit(1);
271 }
kcc99a71a12017-11-09 05:49:28 +0000272}
george.karpenkov29efa6d2017-08-21 23:25:50 +0000273
kccd1449be2019-02-08 22:59:03 +0000274// Outer process. Does not call the target code and thus should not fail.
kcc4b5aa122019-02-09 00:16:21 +0000275void CrashResistantMerge(const Vector<std::string> &Args,
kccbfb59752019-02-12 03:12:40 +0000276 const Vector<SizedFile> &OldCorpus,
277 const Vector<SizedFile> &NewCorpus,
278 Vector<std::string> *NewFiles,
279 const Set<uint32_t> &InitialFeatures,
kcc98a86242019-02-15 00:08:16 +0000280 Set<uint32_t> *NewFeatures,
281 const Set<uint32_t> &InitialCov,
282 Set<uint32_t> *NewCov,
283 const std::string &CFPath,
kccbfb59752019-02-12 03:12:40 +0000284 bool V /*Verbose*/) {
kcc64bcb922019-02-13 04:04:45 +0000285 if (NewCorpus.empty() && OldCorpus.empty()) return; // Nothing to merge.
kcc99a71a12017-11-09 05:49:28 +0000286 size_t NumAttempts = 0;
kcca3815862019-02-08 21:27:23 +0000287 if (FileSize(CFPath)) {
kccbfb59752019-02-12 03:12:40 +0000288 VPrintf(V, "MERGE-OUTER: non-empty control file provided: '%s'\n",
kcca3815862019-02-08 21:27:23 +0000289 CFPath.c_str());
kcc99a71a12017-11-09 05:49:28 +0000290 Merger M;
kcca3815862019-02-08 21:27:23 +0000291 std::ifstream IF(CFPath);
kcc99a71a12017-11-09 05:49:28 +0000292 if (M.Parse(IF, /*ParseCoverage=*/false)) {
kccbfb59752019-02-12 03:12:40 +0000293 VPrintf(V, "MERGE-OUTER: control file ok, %zd files total,"
kcc99a71a12017-11-09 05:49:28 +0000294 " first not processed file %zd\n",
295 M.Files.size(), M.FirstNotProcessedFile);
296 if (!M.LastFailure.empty())
kccbfb59752019-02-12 03:12:40 +0000297 VPrintf(V, "MERGE-OUTER: '%s' will be skipped as unlucky "
kcc99a71a12017-11-09 05:49:28 +0000298 "(merge has stumbled on it the last time)\n",
299 M.LastFailure.c_str());
300 if (M.FirstNotProcessedFile >= M.Files.size()) {
kccbfb59752019-02-12 03:12:40 +0000301 VPrintf(
302 V, "MERGE-OUTER: nothing to do, merge has been completed before\n");
kcc99a71a12017-11-09 05:49:28 +0000303 exit(0);
304 }
305
306 NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
307 } else {
kccbfb59752019-02-12 03:12:40 +0000308 VPrintf(V, "MERGE-OUTER: bad control file, will overwrite it\n");
kcc99a71a12017-11-09 05:49:28 +0000309 }
310 }
311
312 if (!NumAttempts) {
313 // The supplied control file is empty or bad, create a fresh one.
kccd1449be2019-02-08 22:59:03 +0000314 NumAttempts = OldCorpus.size() + NewCorpus.size();
kccbfb59752019-02-12 03:12:40 +0000315 VPrintf(V, "MERGE-OUTER: %zd files, %zd in the initial corpus\n",
316 NumAttempts, OldCorpus.size());
kccd1449be2019-02-08 22:59:03 +0000317 WriteNewControlFile(CFPath, OldCorpus, NewCorpus);
kcc99a71a12017-11-09 05:49:28 +0000318 }
319
320 // Execute the inner process until it passes.
george.karpenkov29efa6d2017-08-21 23:25:50 +0000321 // Every inner process should execute at least one input.
morehousea80f6452017-12-04 19:25:59 +0000322 Command BaseCmd(Args);
323 BaseCmd.removeFlag("merge");
kcca3815862019-02-08 21:27:23 +0000324 BaseCmd.removeFlag("fork");
kcc99a71a12017-11-09 05:49:28 +0000325 for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
kcca3815862019-02-08 21:27:23 +0000326 Fuzzer::MaybeExitGracefully();
kccbfb59752019-02-12 03:12:40 +0000327 VPrintf(V, "MERGE-OUTER: attempt %zd\n", Attempt);
morehousea80f6452017-12-04 19:25:59 +0000328 Command Cmd(BaseCmd);
329 Cmd.addFlag("merge_control_file", CFPath);
330 Cmd.addFlag("merge_inner", "1");
kccbfb59752019-02-12 03:12:40 +0000331 if (!V) {
332 Cmd.setOutputFile("/dev/null"); // TODO: need to handle this on Windows?
333 Cmd.combineOutAndErr();
334 }
morehousea80f6452017-12-04 19:25:59 +0000335 auto ExitCode = ExecuteCommand(Cmd);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000336 if (!ExitCode) {
kccbfb59752019-02-12 03:12:40 +0000337 VPrintf(V, "MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt);
george.karpenkov29efa6d2017-08-21 23:25:50 +0000338 break;
339 }
340 }
george.karpenkov29efa6d2017-08-21 23:25:50 +0000341 // Read the control file and do the merge.
342 Merger M;
343 std::ifstream IF(CFPath);
344 IF.seekg(0, IF.end);
kccbfb59752019-02-12 03:12:40 +0000345 VPrintf(V, "MERGE-OUTER: the control file has %zd bytes\n",
346 (size_t)IF.tellg());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000347 IF.seekg(0, IF.beg);
348 M.ParseOrExit(IF, true);
349 IF.close();
kccbfb59752019-02-12 03:12:40 +0000350 VPrintf(V,
351 "MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
352 M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
kcc98a86242019-02-15 00:08:16 +0000353 M.Merge(InitialFeatures, NewFeatures, InitialCov, NewCov, NewFiles);
354 VPrintf(V, "MERGE-OUTER: %zd new files with %zd new features added; "
355 "%zd new coverage edges\n",
356 NewFiles->size(), NewFeatures->size(), NewCov->size());
george.karpenkov29efa6d2017-08-21 23:25:50 +0000357}
358
359} // namespace fuzzer