xref: /freebsd/contrib/llvm-project/compiler-rt/lib/fuzzer/FuzzerMerge.cpp (revision 963f5dc7a30624e95d72fb7f87b8892651164e46)
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   Vector<uint32_t> TmpFeatures;
81   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 Set<uint32_t> &InitialFeatures,
136                      Set<uint32_t> *NewFeatures,
137                      const Set<uint32_t> &InitialCov, Set<uint32_t> *NewCov,
138                      Vector<std::string> *NewFiles) {
139   NewFiles->clear();
140   NewFeatures->clear();
141   NewCov->clear();
142   assert(NumFilesInFirstCorpus <= Files.size());
143   Set<uint32_t> AllFeatures = InitialFeatures;
144 
145   // What features are in the initial corpus?
146   for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
147     auto &Cur = Files[i].Features;
148     AllFeatures.insert(Cur.begin(), Cur.end());
149   }
150   // Remove all features that we already know from all other inputs.
151   for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
152     auto &Cur = Files[i].Features;
153     Vector<uint32_t> Tmp;
154     std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
155                         AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
156     Cur.swap(Tmp);
157   }
158 
159   // Sort. Give preference to
160   //   * smaller files
161   //   * files with more features.
162   std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
163             [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
164               if (a.Size != b.Size)
165                 return a.Size < b.Size;
166               return a.Features.size() > b.Features.size();
167             });
168 
169   // One greedy pass: add the file's features to AllFeatures.
170   // If new features were added, add this file to NewFiles.
171   for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
172     auto &Cur = Files[i].Features;
173     // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
174     //       Files[i].Size, Cur.size());
175     bool FoundNewFeatures = false;
176     for (auto Fe: Cur) {
177       if (AllFeatures.insert(Fe).second) {
178         FoundNewFeatures = true;
179         NewFeatures->insert(Fe);
180       }
181     }
182     if (FoundNewFeatures)
183       NewFiles->push_back(Files[i].Name);
184     for (auto Cov : Files[i].Cov)
185       if (InitialCov.find(Cov) == InitialCov.end())
186         NewCov->insert(Cov);
187   }
188   return NewFeatures->size();
189 }
190 
191 Set<uint32_t> Merger::AllFeatures() const {
192   Set<uint32_t> S;
193   for (auto &File : Files)
194     S.insert(File.Features.begin(), File.Features.end());
195   return S;
196 }
197 
198 // Inner process. May crash if the target crashes.
199 void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
200   Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
201   Merger M;
202   std::ifstream IF(CFPath);
203   M.ParseOrExit(IF, false);
204   IF.close();
205   if (!M.LastFailure.empty())
206     Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
207            M.LastFailure.c_str());
208 
209   Printf("MERGE-INNER: %zd total files;"
210          " %zd processed earlier; will process %zd files now\n",
211          M.Files.size(), M.FirstNotProcessedFile,
212          M.Files.size() - M.FirstNotProcessedFile);
213 
214   std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
215   Set<size_t> AllFeatures;
216   auto PrintStatsWrapper = [this, &AllFeatures](const char* Where) {
217     this->PrintStats(Where, "\n", 0, AllFeatures.size());
218   };
219   Set<const TracePC::PCTableEntry *> AllPCs;
220   for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
221     Fuzzer::MaybeExitGracefully();
222     auto U = FileToVector(M.Files[i].Name);
223     if (U.size() > MaxInputLen) {
224       U.resize(MaxInputLen);
225       U.shrink_to_fit();
226     }
227 
228     // Write the pre-run marker.
229     OF << "STARTED " << i << " " << U.size() << "\n";
230     OF.flush();  // Flush is important since Command::Execute may crash.
231     // Run.
232     TPC.ResetMaps();
233     ExecuteCallback(U.data(), U.size());
234     // Collect coverage. We are iterating over the files in this order:
235     // * First, files in the initial corpus ordered by size, smallest first.
236     // * Then, all other files, smallest first.
237     // So it makes no sense to record all features for all files, instead we
238     // only record features that were not seen before.
239     Set<size_t> UniqFeatures;
240     TPC.CollectFeatures([&](size_t Feature) {
241       if (AllFeatures.insert(Feature).second)
242         UniqFeatures.insert(Feature);
243     });
244     TPC.UpdateObservedPCs();
245     // Show stats.
246     if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
247       PrintStatsWrapper("pulse ");
248     if (TotalNumberOfRuns == M.NumFilesInFirstCorpus)
249       PrintStatsWrapper("LOADED");
250     // Write the post-run marker and the coverage.
251     OF << "FT " << i;
252     for (size_t F : UniqFeatures)
253       OF << " " << F;
254     OF << "\n";
255     OF << "COV " << i;
256     TPC.ForEachObservedPC([&](const TracePC::PCTableEntry *TE) {
257       if (AllPCs.insert(TE).second)
258         OF << " " << TPC.PCTableEntryIdx(TE);
259     });
260     OF << "\n";
261     OF.flush();
262   }
263   PrintStatsWrapper("DONE  ");
264 }
265 
266 static size_t WriteNewControlFile(const std::string &CFPath,
267                                   const Vector<SizedFile> &OldCorpus,
268                                   const Vector<SizedFile> &NewCorpus,
269                                   const Vector<MergeFileInfo> &KnownFiles) {
270   std::unordered_set<std::string> FilesToSkip;
271   for (auto &SF: KnownFiles)
272     FilesToSkip.insert(SF.Name);
273 
274   Vector<std::string> FilesToUse;
275   auto MaybeUseFile = [=, &FilesToUse](std::string Name) {
276     if (FilesToSkip.find(Name) == FilesToSkip.end())
277       FilesToUse.push_back(Name);
278   };
279   for (auto &SF: OldCorpus)
280     MaybeUseFile(SF.File);
281   auto FilesToUseFromOldCorpus = FilesToUse.size();
282   for (auto &SF: NewCorpus)
283     MaybeUseFile(SF.File);
284 
285   RemoveFile(CFPath);
286   std::ofstream ControlFile(CFPath);
287   ControlFile << FilesToUse.size() << "\n";
288   ControlFile << FilesToUseFromOldCorpus << "\n";
289   for (auto &FN: FilesToUse)
290     ControlFile << FN << "\n";
291 
292   if (!ControlFile) {
293     Printf("MERGE-OUTER: failed to write to the control file: %s\n",
294            CFPath.c_str());
295     exit(1);
296   }
297 
298   return FilesToUse.size();
299 }
300 
301 // Outer process. Does not call the target code and thus should not fail.
302 void CrashResistantMerge(const Vector<std::string> &Args,
303                          const Vector<SizedFile> &OldCorpus,
304                          const Vector<SizedFile> &NewCorpus,
305                          Vector<std::string> *NewFiles,
306                          const Set<uint32_t> &InitialFeatures,
307                          Set<uint32_t> *NewFeatures,
308                          const Set<uint32_t> &InitialCov,
309                          Set<uint32_t> *NewCov,
310                          const std::string &CFPath,
311                          bool V /*Verbose*/) {
312   if (NewCorpus.empty() && OldCorpus.empty()) return;  // Nothing to merge.
313   size_t NumAttempts = 0;
314   Vector<MergeFileInfo> KnownFiles;
315   if (FileSize(CFPath)) {
316     VPrintf(V, "MERGE-OUTER: non-empty control file provided: '%s'\n",
317            CFPath.c_str());
318     Merger M;
319     std::ifstream IF(CFPath);
320     if (M.Parse(IF, /*ParseCoverage=*/true)) {
321       VPrintf(V, "MERGE-OUTER: control file ok, %zd files total,"
322              " first not processed file %zd\n",
323              M.Files.size(), M.FirstNotProcessedFile);
324       if (!M.LastFailure.empty())
325         VPrintf(V, "MERGE-OUTER: '%s' will be skipped as unlucky "
326                "(merge has stumbled on it the last time)\n",
327                M.LastFailure.c_str());
328       if (M.FirstNotProcessedFile >= M.Files.size()) {
329         // Merge has already been completed with the given merge control file.
330         if (M.Files.size() == OldCorpus.size() + NewCorpus.size()) {
331           VPrintf(
332               V,
333               "MERGE-OUTER: nothing to do, merge has been completed before\n");
334           exit(0);
335         }
336 
337         // Number of input files likely changed, start merge from scratch, but
338         // reuse coverage information from the given merge control file.
339         VPrintf(
340             V,
341             "MERGE-OUTER: starting merge from scratch, but reusing coverage "
342             "information from the given control file\n");
343         KnownFiles = M.Files;
344       } else {
345         // There is a merge in progress, continue.
346         NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
347       }
348     } else {
349       VPrintf(V, "MERGE-OUTER: bad control file, will overwrite it\n");
350     }
351   }
352 
353   if (!NumAttempts) {
354     // The supplied control file is empty or bad, create a fresh one.
355     VPrintf(V, "MERGE-OUTER: "
356             "%zd files, %zd in the initial corpus, %zd processed earlier\n",
357             OldCorpus.size() + NewCorpus.size(), OldCorpus.size(),
358             KnownFiles.size());
359     NumAttempts = WriteNewControlFile(CFPath, OldCorpus, NewCorpus, KnownFiles);
360   }
361 
362   // Execute the inner process until it passes.
363   // Every inner process should execute at least one input.
364   Command BaseCmd(Args);
365   BaseCmd.removeFlag("merge");
366   BaseCmd.removeFlag("fork");
367   BaseCmd.removeFlag("collect_data_flow");
368   for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
369     Fuzzer::MaybeExitGracefully();
370     VPrintf(V, "MERGE-OUTER: attempt %zd\n", Attempt);
371     Command Cmd(BaseCmd);
372     Cmd.addFlag("merge_control_file", CFPath);
373     Cmd.addFlag("merge_inner", "1");
374     if (!V) {
375       Cmd.setOutputFile(getDevNull());
376       Cmd.combineOutAndErr();
377     }
378     auto ExitCode = ExecuteCommand(Cmd);
379     if (!ExitCode) {
380       VPrintf(V, "MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt);
381       break;
382     }
383   }
384   // Read the control file and do the merge.
385   Merger M;
386   std::ifstream IF(CFPath);
387   IF.seekg(0, IF.end);
388   VPrintf(V, "MERGE-OUTER: the control file has %zd bytes\n",
389           (size_t)IF.tellg());
390   IF.seekg(0, IF.beg);
391   M.ParseOrExit(IF, true);
392   IF.close();
393   VPrintf(V,
394           "MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
395           M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
396 
397   M.Files.insert(M.Files.end(), KnownFiles.begin(), KnownFiles.end());
398   M.Merge(InitialFeatures, NewFeatures, InitialCov, NewCov, NewFiles);
399   VPrintf(V, "MERGE-OUTER: %zd new files with %zd new features added; "
400           "%zd new coverage edges\n",
401          NewFiles->size(), NewFeatures->size(), NewCov->size());
402 }
403 
404 } // namespace fuzzer
405