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 
23 namespace fuzzer {
24 
25 bool Merger::Parse(const std::string &Str, bool ParseCoverage) {
26   std::istringstream SS(Str);
27   return Parse(SS, ParseCoverage);
28 }
29 
30 void 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
49 bool 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;
77   Vector<uint32_t> TmpFeatures;
78   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);
102         std::sort(TmpFeatures.begin(), TmpFeatures.end());
103         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 
116 size_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.
125 size_t Merger::Merge(const Set<uint32_t> &InitialFeatures,
126                      Set<uint32_t> *AllFeatures,
127                      Vector<std::string> *NewFiles) {
128   NewFiles->clear();
129   assert(NumFilesInFirstCorpus <= Files.size());
130   *AllFeatures = InitialFeatures;
131 
132   // What features are in the initial corpus?
133   for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
134     auto &Cur = Files[i].Features;
135     AllFeatures->insert(Cur.begin(), Cur.end());
136   }
137   size_t InitialNumFeatures = AllFeatures->size();
138 
139   // Remove all features that we already know from all other inputs.
140   for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
141     auto &Cur = Files[i].Features;
142     Vector<uint32_t> Tmp;
143     std::set_difference(Cur.begin(), Cur.end(), AllFeatures->begin(),
144                         AllFeatures->end(), std::inserter(Tmp, Tmp.begin()));
145     Cur.swap(Tmp);
146   }
147 
148   // Sort. Give preference to
149   //   * smaller files
150   //   * files with more features.
151   std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
152             [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
153               if (a.Size != b.Size)
154                 return a.Size < b.Size;
155               return a.Features.size() > b.Features.size();
156             });
157 
158   // One greedy pass: add the file's features to AllFeatures.
159   // If new features were added, add this file to NewFiles.
160   for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
161     auto &Cur = Files[i].Features;
162     // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
163     //       Files[i].Size, Cur.size());
164     size_t OldSize = AllFeatures->size();
165     AllFeatures->insert(Cur.begin(), Cur.end());
166     if (AllFeatures->size() > OldSize)
167       NewFiles->push_back(Files[i].Name);
168   }
169   return AllFeatures->size() - InitialNumFeatures;
170 }
171 
172 Set<uint32_t> Merger::AllFeatures() const {
173   Set<uint32_t> S;
174   for (auto &File : Files)
175     S.insert(File.Features.begin(), File.Features.end());
176   return S;
177 }
178 
179 // Inner process. May crash if the target crashes.
180 void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
181   Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
182   Merger M;
183   std::ifstream IF(CFPath);
184   M.ParseOrExit(IF, false);
185   IF.close();
186   if (!M.LastFailure.empty())
187     Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
188            M.LastFailure.c_str());
189 
190   Printf("MERGE-INNER: %zd total files;"
191          " %zd processed earlier; will process %zd files now\n",
192          M.Files.size(), M.FirstNotProcessedFile,
193          M.Files.size() - M.FirstNotProcessedFile);
194 
195   std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
196   Set<size_t> AllFeatures;
197   for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
198     Fuzzer::MaybeExitGracefully();
199     auto U = FileToVector(M.Files[i].Name);
200     if (U.size() > MaxInputLen) {
201       U.resize(MaxInputLen);
202       U.shrink_to_fit();
203     }
204     std::ostringstream StartedLine;
205     // Write the pre-run marker.
206     OF << "STARTED " << std::dec << i << " " << U.size() << "\n";
207     OF.flush();  // Flush is important since Command::Execute may crash.
208     // Run.
209     TPC.ResetMaps();
210     ExecuteCallback(U.data(), U.size());
211     // Collect coverage. We are iterating over the files in this order:
212     // * First, files in the initial corpus ordered by size, smallest first.
213     // * Then, all other files, smallest first.
214     // So it makes no sense to record all features for all files, instead we
215     // only record features that were not seen before.
216     Set<size_t> UniqFeatures;
217     TPC.CollectFeatures([&](size_t Feature) {
218       if (AllFeatures.insert(Feature).second)
219         UniqFeatures.insert(Feature);
220     });
221     // Show stats.
222     if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
223       PrintStats("pulse ");
224     // Write the post-run marker and the coverage.
225     OF << "DONE " << i;
226     for (size_t F : UniqFeatures)
227       OF << " " << std::hex << F;
228     OF << "\n";
229     OF.flush();
230   }
231 }
232 
233 static void WriteNewControlFile(const std::string &CFPath,
234                                 const Vector<SizedFile> &OldCorpus,
235                                 const Vector<SizedFile> &NewCorpus) {
236   RemoveFile(CFPath);
237   std::ofstream ControlFile(CFPath);
238   ControlFile << (OldCorpus.size() + NewCorpus.size()) << "\n";
239   ControlFile << OldCorpus.size() << "\n";
240   for (auto &SF: OldCorpus)
241     ControlFile << SF.File << "\n";
242   for (auto &SF: NewCorpus)
243     ControlFile << SF.File << "\n";
244   if (!ControlFile) {
245     Printf("MERGE-OUTER: failed to write to the control file: %s\n",
246            CFPath.c_str());
247     exit(1);
248   }
249 }
250 
251 // Outer process. Does not call the target code and thus should not fail.
252 void CrashResistantMerge(const Vector<std::string> &Args,
253                     const Vector<SizedFile> &OldCorpus,
254                     const Vector<SizedFile> &NewCorpus,
255                     Vector<std::string> *NewFiles,
256                     const Set<uint32_t> &InitialFeatures,
257                     Set<uint32_t> *NewFeatures,
258                     const std::string &CFPath) {
259   size_t NumAttempts = 0;
260   if (FileSize(CFPath)) {
261     Printf("MERGE-OUTER: non-empty control file provided: '%s'\n",
262            CFPath.c_str());
263     Merger M;
264     std::ifstream IF(CFPath);
265     if (M.Parse(IF, /*ParseCoverage=*/false)) {
266       Printf("MERGE-OUTER: control file ok, %zd files total,"
267              " first not processed file %zd\n",
268              M.Files.size(), M.FirstNotProcessedFile);
269       if (!M.LastFailure.empty())
270         Printf("MERGE-OUTER: '%s' will be skipped as unlucky "
271                "(merge has stumbled on it the last time)\n",
272                M.LastFailure.c_str());
273       if (M.FirstNotProcessedFile >= M.Files.size()) {
274         Printf("MERGE-OUTER: nothing to do, merge has been completed before\n");
275         exit(0);
276       }
277 
278       NumAttempts = M.Files.size() - M.FirstNotProcessedFile;
279     } else {
280       Printf("MERGE-OUTER: bad control file, will overwrite it\n");
281     }
282   }
283 
284   if (!NumAttempts) {
285     // The supplied control file is empty or bad, create a fresh one.
286     NumAttempts = OldCorpus.size() + NewCorpus.size();
287     Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n", NumAttempts,
288            OldCorpus.size());
289     WriteNewControlFile(CFPath, OldCorpus, NewCorpus);
290   }
291 
292   // Execute the inner process until it passes.
293   // Every inner process should execute at least one input.
294   Command BaseCmd(Args);
295   BaseCmd.removeFlag("merge");
296   BaseCmd.removeFlag("fork");
297   bool Success = false;
298   for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) {
299     Fuzzer::MaybeExitGracefully();
300     Printf("MERGE-OUTER: attempt %zd\n", Attempt);
301     Command Cmd(BaseCmd);
302     Cmd.addFlag("merge_control_file", CFPath);
303     Cmd.addFlag("merge_inner", "1");
304     auto ExitCode = ExecuteCommand(Cmd);
305     if (!ExitCode) {
306       Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt);
307       Success = true;
308       break;
309     }
310   }
311   if (!Success) {
312     Printf("MERGE-OUTER: zero succesfull attempts, exiting\n");
313     exit(1);
314   }
315   // Read the control file and do the merge.
316   Merger M;
317   std::ifstream IF(CFPath);
318   IF.seekg(0, IF.end);
319   Printf("MERGE-OUTER: the control file has %zd bytes\n", (size_t)IF.tellg());
320   IF.seekg(0, IF.beg);
321   M.ParseOrExit(IF, true);
322   IF.close();
323   Printf("MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
324          M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
325   size_t NumNewFeatures = M.Merge(InitialFeatures, NewFeatures, NewFiles);
326   Printf("MERGE-OUTER: %zd new files with %zd new features added\n",
327          NewFiles->size(), NumNewFeatures);
328 }
329 
330 } // namespace fuzzer
331