xref: /llvm-project/compiler-rt/lib/fuzzer/FuzzerMerge.cpp (revision a1e7e401d2af002af26e1512a31e09eb2d0cf1dc)
1 //===- FuzzerMerge.cpp - merging corpora ----------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 // Merging corpora.
9 //===----------------------------------------------------------------------===//
10 
11 #include "FuzzerCommand.h"
12 #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 #include <unordered_set>
23 
24 namespace fuzzer {
25 
26 bool Merger::Parse(const std::string &Str, bool ParseCoverage) {
27   std::istringstream SS(Str);
28   return Parse(SS, ParseCoverage);
29 }
30 
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");
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 // FT 0 1 4 6 8  # FileID COV1 COV2 ...
47 // COV 0 7 8 9 # FileID COV1 COV1
48 // STARTED 1 456  # If FT is missing, the input crashed while processing.
49 // STARTED 2 567
50 // FT 2 8 9
51 // COV 2 11 12
52 bool Merger::Parse(std::istream &IS, bool ParseCoverage) {
53   LastFailure.clear();
54   std::string Line;
55 
56   // Parse NumFiles.
57   if (!std::getline(IS, Line, '\n')) return false;
58   std::istringstream L1(Line);
59   size_t NumFiles = 0;
60   L1 >> NumFiles;
61   if (NumFiles == 0 || NumFiles > 10000000) return false;
62 
63   // Parse NumFilesInFirstCorpus.
64   if (!std::getline(IS, Line, '\n')) return false;
65   std::istringstream L2(Line);
66   NumFilesInFirstCorpus = NumFiles + 1;
67   L2 >> NumFilesInFirstCorpus;
68   if (NumFilesInFirstCorpus > NumFiles) return false;
69 
70   // Parse file names.
71   Files.resize(NumFiles);
72   for (size_t i = 0; i < NumFiles; i++)
73     if (!std::getline(IS, Files[i].Name, '\n'))
74       return false;
75 
76   // Parse STARTED, FT, and COV lines.
77   size_t ExpectedStartMarker = 0;
78   const size_t kInvalidStartMarker = -1;
79   size_t LastSeenStartMarker = kInvalidStartMarker;
80   std::vector<uint32_t> TmpFeatures;
81   std::set<uint32_t> PCs;
82   while (std::getline(IS, Line, '\n')) {
83     std::istringstream ISS1(Line);
84     std::string Marker;
85     uint32_t N;
86     if (!(ISS1 >> Marker) || !(ISS1 >> N))
87       return false;
88     if (Marker == "STARTED") {
89       // STARTED FILE_ID FILE_SIZE
90       if (ExpectedStartMarker != N)
91         return false;
92       ISS1 >> Files[ExpectedStartMarker].Size;
93       LastSeenStartMarker = ExpectedStartMarker;
94       assert(ExpectedStartMarker < Files.size());
95       ExpectedStartMarker++;
96     } else if (Marker == "FT") {
97       // FT FILE_ID COV1 COV2 COV3 ...
98       size_t CurrentFileIdx = N;
99       if (CurrentFileIdx != LastSeenStartMarker)
100         return false;
101       LastSeenStartMarker = kInvalidStartMarker;
102       if (ParseCoverage) {
103         TmpFeatures.clear();  // use a vector from outer scope to avoid resizes.
104         while (ISS1 >> N)
105           TmpFeatures.push_back(N);
106         std::sort(TmpFeatures.begin(), TmpFeatures.end());
107         Files[CurrentFileIdx].Features = TmpFeatures;
108       }
109     } else if (Marker == "COV") {
110       size_t CurrentFileIdx = N;
111       if (ParseCoverage)
112         while (ISS1 >> N)
113           if (PCs.insert(N).second)
114             Files[CurrentFileIdx].Cov.push_back(N);
115     } else {
116       return false;
117     }
118   }
119   if (LastSeenStartMarker != kInvalidStartMarker)
120     LastFailure = Files[LastSeenStartMarker].Name;
121 
122   FirstNotProcessedFile = ExpectedStartMarker;
123   return true;
124 }
125 
126 size_t Merger::ApproximateMemoryConsumption() const  {
127   size_t Res = 0;
128   for (const auto &F: Files)
129     Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
130   return Res;
131 }
132 
133 // Decides which files need to be merged (add those to NewFiles).
134 // Returns the number of new features added.
135 size_t Merger::Merge(const std::set<uint32_t> &InitialFeatures,
136                      std::set<uint32_t> *NewFeatures,
137                      const std::set<uint32_t> &InitialCov,
138                      std::set<uint32_t> *NewCov,
139                      std::vector<std::string> *NewFiles) {
140   NewFiles->clear();
141   NewFeatures->clear();
142   NewCov->clear();
143   assert(NumFilesInFirstCorpus <= Files.size());
144   std::set<uint32_t> AllFeatures = InitialFeatures;
145 
146   // What features are in the initial corpus?
147   for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
148     auto &Cur = Files[i].Features;
149     AllFeatures.insert(Cur.begin(), Cur.end());
150   }
151   // Remove all features that we already know from all other inputs.
152   for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
153     auto &Cur = Files[i].Features;
154     std::vector<uint32_t> Tmp;
155     std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
156                         AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
157     Cur.swap(Tmp);
158   }
159 
160   // Sort. Give preference to
161   //   * smaller files
162   //   * files with more features.
163   std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
164             [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
165               if (a.Size != b.Size)
166                 return a.Size < b.Size;
167               return a.Features.size() > b.Features.size();
168             });
169 
170   // One greedy pass: add the file's features to AllFeatures.
171   // If new features were added, add this file to NewFiles.
172   for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
173     auto &Cur = Files[i].Features;
174     // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
175     //       Files[i].Size, Cur.size());
176     bool FoundNewFeatures = false;
177     for (auto Fe: Cur) {
178       if (AllFeatures.insert(Fe).second) {
179         FoundNewFeatures = true;
180         NewFeatures->insert(Fe);
181       }
182     }
183     if (FoundNewFeatures)
184       NewFiles->push_back(Files[i].Name);
185     for (auto Cov : Files[i].Cov)
186       if (InitialCov.find(Cov) == InitialCov.end())
187         NewCov->insert(Cov);
188   }
189   return NewFeatures->size();
190 }
191 
192 std::set<uint32_t> Merger::AllFeatures() const {
193   std::set<uint32_t> S;
194   for (auto &File : Files)
195     S.insert(File.Features.begin(), File.Features.end());
196   return S;
197 }
198 
199 // Inner process. May crash if the target crashes.
200 void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
201   Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
202   Merger M;
203   std::ifstream IF(CFPath);
204   M.ParseOrExit(IF, false);
205   IF.close();
206   if (!M.LastFailure.empty())
207     Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
208            M.LastFailure.c_str());
209 
210   Printf("MERGE-INNER: %zd total files;"
211          " %zd processed earlier; will process %zd files now\n",
212          M.Files.size(), M.FirstNotProcessedFile,
213          M.Files.size() - M.FirstNotProcessedFile);
214 
215   std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
216   std::set<size_t> AllFeatures;
217   auto PrintStatsWrapper = [this, &AllFeatures](const char* Where) {
218     this->PrintStats(Where, "\n", 0, AllFeatures.size());
219   };
220   std::set<const TracePC::PCTableEntry *> AllPCs;
221   for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
222     Fuzzer::MaybeExitGracefully();
223     auto U = FileToVector(M.Files[i].Name);
224     if (U.size() > MaxInputLen) {
225       U.resize(MaxInputLen);
226       U.shrink_to_fit();
227     }
228 
229     // Write the pre-run marker.
230     OF << "STARTED " << i << " " << U.size() << "\n";
231     OF.flush();  // Flush is important since Command::Execute may crash.
232     // Run.
233     TPC.ResetMaps();
234     ExecuteCallback(U.data(), U.size());
235     // Collect coverage. We are iterating over the files in this order:
236     // * First, files in the initial corpus ordered by size, smallest first.
237     // * Then, all other files, smallest first.
238     // So it makes no sense to record all features for all files, instead we
239     // only record features that were not seen before.
240     std::set<size_t> UniqFeatures;
241     TPC.CollectFeatures([&](size_t Feature) {
242       if (AllFeatures.insert(Feature).second)
243         UniqFeatures.insert(Feature);
244     });
245     TPC.UpdateObservedPCs();
246     // Show stats.
247     if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
248       PrintStatsWrapper("pulse ");
249     if (TotalNumberOfRuns == M.NumFilesInFirstCorpus)
250       PrintStatsWrapper("LOADED");
251     // Write the post-run marker and the coverage.
252     OF << "FT " << i;
253     for (size_t F : UniqFeatures)
254       OF << " " << F;
255     OF << "\n";
256     OF << "COV " << i;
257     TPC.ForEachObservedPC([&](const TracePC::PCTableEntry *TE) {
258       if (AllPCs.insert(TE).second)
259         OF << " " << TPC.PCTableEntryIdx(TE);
260     });
261     OF << "\n";
262     OF.flush();
263   }
264   PrintStatsWrapper("DONE  ");
265 }
266 
267 static size_t
268 WriteNewControlFile(const std::string &CFPath,
269                     const std::vector<SizedFile> &OldCorpus,
270                     const std::vector<SizedFile> &NewCorpus,
271                     const std::vector<MergeFileInfo> &KnownFiles) {
272   std::unordered_set<std::string> FilesToSkip;
273   for (auto &SF: KnownFiles)
274     FilesToSkip.insert(SF.Name);
275 
276   std::vector<std::string> FilesToUse;
277   auto MaybeUseFile = [=, &FilesToUse](std::string Name) {
278     if (FilesToSkip.find(Name) == FilesToSkip.end())
279       FilesToUse.push_back(Name);
280   };
281   for (auto &SF: OldCorpus)
282     MaybeUseFile(SF.File);
283   auto FilesToUseFromOldCorpus = FilesToUse.size();
284   for (auto &SF: NewCorpus)
285     MaybeUseFile(SF.File);
286 
287   RemoveFile(CFPath);
288   std::ofstream ControlFile(CFPath);
289   ControlFile << FilesToUse.size() << "\n";
290   ControlFile << FilesToUseFromOldCorpus << "\n";
291   for (auto &FN: FilesToUse)
292     ControlFile << FN << "\n";
293 
294   if (!ControlFile) {
295     Printf("MERGE-OUTER: failed to write to the control file: %s\n",
296            CFPath.c_str());
297     exit(1);
298   }
299 
300   return FilesToUse.size();
301 }
302 
303 // Outer process. Does not call the target code and thus should not fail.
304 void CrashResistantMerge(const std::vector<std::string> &Args,
305                          const std::vector<SizedFile> &OldCorpus,
306                          const std::vector<SizedFile> &NewCorpus,
307                          std::vector<std::string> *NewFiles,
308                          const std::set<uint32_t> &InitialFeatures,
309                          std::set<uint32_t> *NewFeatures,
310                          const std::set<uint32_t> &InitialCov,
311                          std::set<uint32_t> *NewCov, const std::string &CFPath,
312                          bool V /*Verbose*/) {
313   if (NewCorpus.empty() && OldCorpus.empty()) return;  // Nothing to merge.
314   size_t NumAttempts = 0;
315   std::vector<MergeFileInfo> KnownFiles;
316   if (FileSize(CFPath)) {
317     VPrintf(V, "MERGE-OUTER: non-empty control file provided: '%s'\n",
318            CFPath.c_str());
319     Merger M;
320     std::ifstream IF(CFPath);
321     if (M.Parse(IF, /*ParseCoverage=*/true)) {
322       VPrintf(V, "MERGE-OUTER: control file ok, %zd files total,"
323              " first not processed file %zd\n",
324              M.Files.size(), M.FirstNotProcessedFile);
325       if (!M.LastFailure.empty())
326         VPrintf(V, "MERGE-OUTER: '%s' will be skipped as unlucky "
327                "(merge has stumbled on it the last time)\n",
328                M.LastFailure.c_str());
329       if (M.FirstNotProcessedFile >= M.Files.size()) {
330         // Merge has already been completed with the given merge control file.
331         if (M.Files.size() == OldCorpus.size() + NewCorpus.size()) {
332           VPrintf(
333               V,
334               "MERGE-OUTER: nothing to do, merge has been completed before\n");
335           exit(0);
336         }
337 
338         // Number of input files likely changed, start merge from scratch, but
339         // reuse coverage information from the given merge control file.
340         VPrintf(
341             V,
342             "MERGE-OUTER: starting merge from scratch, but reusing coverage "
343             "information from the given control file\n");
344         KnownFiles = M.Files;
345       } else {
346         // There is a merge in progress, continue.
347         NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
348       }
349     } else {
350       VPrintf(V, "MERGE-OUTER: bad control file, will overwrite it\n");
351     }
352   }
353 
354   if (!NumAttempts) {
355     // The supplied control file is empty or bad, create a fresh one.
356     VPrintf(V, "MERGE-OUTER: "
357             "%zd files, %zd in the initial corpus, %zd processed earlier\n",
358             OldCorpus.size() + NewCorpus.size(), OldCorpus.size(),
359             KnownFiles.size());
360     NumAttempts = WriteNewControlFile(CFPath, OldCorpus, NewCorpus, KnownFiles);
361   }
362 
363   // Execute the inner process until it passes.
364   // Every inner process should execute at least one input.
365   Command BaseCmd(Args);
366   BaseCmd.removeFlag("merge");
367   BaseCmd.removeFlag("fork");
368   BaseCmd.removeFlag("collect_data_flow");
369   for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
370     Fuzzer::MaybeExitGracefully();
371     VPrintf(V, "MERGE-OUTER: attempt %zd\n", Attempt);
372     Command Cmd(BaseCmd);
373     Cmd.addFlag("merge_control_file", CFPath);
374     Cmd.addFlag("merge_inner", "1");
375     if (!V) {
376       Cmd.setOutputFile(getDevNull());
377       Cmd.combineOutAndErr();
378     }
379     auto ExitCode = ExecuteCommand(Cmd);
380     if (!ExitCode) {
381       VPrintf(V, "MERGE-OUTER: successful in %zd attempt(s)\n", Attempt);
382       break;
383     }
384   }
385   // Read the control file and do the merge.
386   Merger M;
387   std::ifstream IF(CFPath);
388   IF.seekg(0, IF.end);
389   VPrintf(V, "MERGE-OUTER: the control file has %zd bytes\n",
390           (size_t)IF.tellg());
391   IF.seekg(0, IF.beg);
392   M.ParseOrExit(IF, true);
393   IF.close();
394   VPrintf(V,
395           "MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
396           M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
397 
398   M.Files.insert(M.Files.end(), KnownFiles.begin(), KnownFiles.end());
399   M.Merge(InitialFeatures, NewFeatures, InitialCov, NewCov, NewFiles);
400   VPrintf(V, "MERGE-OUTER: %zd new files with %zd new features added; "
401           "%zd new coverage edges\n",
402          NewFiles->size(), NewFeatures->size(), NewCov->size());
403 }
404 
405 } // namespace fuzzer
406