1 //===- FuzzerFork.cpp - run fuzzing in separate subprocesses --------------===//
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 // Spawn and orchestrate separate fuzzing processes.
9 //===----------------------------------------------------------------------===//
10 
11 #include "FuzzerCommand.h"
12 #include "FuzzerFork.h"
13 #include "FuzzerIO.h"
14 #include "FuzzerInternal.h"
15 #include "FuzzerMerge.h"
16 #include "FuzzerSHA1.h"
17 #include "FuzzerTracePC.h"
18 #include "FuzzerUtil.h"
19 
20 #include <atomic>
21 #include <chrono>
22 #include <condition_variable>
23 #include <fstream>
24 #include <memory>
25 #include <mutex>
26 #include <queue>
27 #include <sstream>
28 #include <thread>
29 
30 namespace fuzzer {
31 
32 struct Stats {
33   size_t number_of_executed_units = 0;
34   size_t peak_rss_mb = 0;
35   size_t average_exec_per_sec = 0;
36 };
37 
38 static Stats ParseFinalStatsFromLog(const std::string &LogPath) {
39   std::ifstream In(LogPath);
40   std::string Line;
41   Stats Res;
42   struct {
43     const char *Name;
44     size_t *Var;
45   } NameVarPairs[] = {
46       {"stat::number_of_executed_units:", &Res.number_of_executed_units},
47       {"stat::peak_rss_mb:", &Res.peak_rss_mb},
48       {"stat::average_exec_per_sec:", &Res.average_exec_per_sec},
49       {nullptr, nullptr},
50   };
51   while (std::getline(In, Line, '\n')) {
52     if (Line.find("stat::") != 0) continue;
53     std::istringstream ISS(Line);
54     std::string Name;
55     size_t Val;
56     ISS >> Name >> Val;
57     for (size_t i = 0; NameVarPairs[i].Name; i++)
58       if (Name == NameVarPairs[i].Name)
59         *NameVarPairs[i].Var = Val;
60   }
61   return Res;
62 }
63 
64 struct FuzzJob {
65   // Inputs.
66   Command Cmd;
67   std::string CorpusDir;
68   std::string FeaturesDir;
69   std::string LogPath;
70   std::string SeedListPath;
71   std::string CFPath;
72   size_t      JobId;
73 
74   int         DftTimeInSeconds = 0;
75 
76   // Fuzzing Outputs.
77   int ExitCode;
78 
79   ~FuzzJob() {
80     RemoveFile(CFPath);
81     RemoveFile(LogPath);
82     RemoveFile(SeedListPath);
83     RmDirRecursive(CorpusDir);
84     RmDirRecursive(FeaturesDir);
85   }
86 };
87 
88 struct GlobalEnv {
89   std::vector<std::string> Args;
90   std::vector<std::string> CorpusDirs;
91   std::string MainCorpusDir;
92   std::string TempDir;
93   std::string DFTDir;
94   std::string DataFlowBinary;
95   std::set<uint32_t> Features, Cov;
96   std::set<std::string> FilesWithDFT;
97   std::vector<std::string> Files;
98   Random *Rand;
99   std::chrono::system_clock::time_point ProcessStartTime;
100   int Verbosity = 0;
101 
102   size_t NumTimeouts = 0;
103   size_t NumOOMs = 0;
104   size_t NumCrashes = 0;
105 
106 
107   size_t NumRuns = 0;
108 
109   std::string StopFile() { return DirPlusFile(TempDir, "STOP"); }
110 
111   size_t secondsSinceProcessStartUp() const {
112     return std::chrono::duration_cast<std::chrono::seconds>(
113                std::chrono::system_clock::now() - ProcessStartTime)
114         .count();
115   }
116 
117   FuzzJob *CreateNewJob(size_t JobId) {
118     Command Cmd(Args);
119     Cmd.removeFlag("fork");
120     Cmd.removeFlag("runs");
121     Cmd.removeFlag("collect_data_flow");
122     for (auto &C : CorpusDirs) // Remove all corpora from the args.
123       Cmd.removeArgument(C);
124     Cmd.addFlag("reload", "0");  // working in an isolated dir, no reload.
125     Cmd.addFlag("print_final_stats", "1");
126     Cmd.addFlag("print_funcs", "0");  // no need to spend time symbolizing.
127     Cmd.addFlag("max_total_time", std::to_string(std::min((size_t)300, JobId)));
128     Cmd.addFlag("stop_file", StopFile());
129     if (!DataFlowBinary.empty()) {
130       Cmd.addFlag("data_flow_trace", DFTDir);
131       if (!Cmd.hasFlag("focus_function"))
132         Cmd.addFlag("focus_function", "auto");
133     }
134     auto Job = new FuzzJob;
135     std::string Seeds;
136     if (size_t CorpusSubsetSize =
137             std::min(Files.size(), (size_t)sqrt(Files.size() + 2))) {
138       auto Time1 = std::chrono::system_clock::now();
139       for (size_t i = 0; i < CorpusSubsetSize; i++) {
140         auto &SF = Files[Rand->SkewTowardsLast(Files.size())];
141         Seeds += (Seeds.empty() ? "" : ",") + SF;
142         CollectDFT(SF);
143       }
144       auto Time2 = std::chrono::system_clock::now();
145       auto DftTimeInSeconds = duration_cast<seconds>(Time2 - Time1).count();
146       assert(DftTimeInSeconds < std::numeric_limits<int>::max());
147       Job->DftTimeInSeconds = static_cast<int>(DftTimeInSeconds);
148     }
149     if (!Seeds.empty()) {
150       Job->SeedListPath =
151           DirPlusFile(TempDir, std::to_string(JobId) + ".seeds");
152       WriteToFile(Seeds, Job->SeedListPath);
153       Cmd.addFlag("seed_inputs", "@" + Job->SeedListPath);
154     }
155     Job->LogPath = DirPlusFile(TempDir, std::to_string(JobId) + ".log");
156     Job->CorpusDir = DirPlusFile(TempDir, "C" + std::to_string(JobId));
157     Job->FeaturesDir = DirPlusFile(TempDir, "F" + std::to_string(JobId));
158     Job->CFPath = DirPlusFile(TempDir, std::to_string(JobId) + ".merge");
159     Job->JobId = JobId;
160 
161 
162     Cmd.addArgument(Job->CorpusDir);
163     Cmd.addFlag("features_dir", Job->FeaturesDir);
164 
165     for (auto &D : {Job->CorpusDir, Job->FeaturesDir}) {
166       RmDirRecursive(D);
167       MkDir(D);
168     }
169 
170     Cmd.setOutputFile(Job->LogPath);
171     Cmd.combineOutAndErr();
172 
173     Job->Cmd = Cmd;
174 
175     if (Verbosity >= 2)
176       Printf("Job %zd/%p Created: %s\n", JobId, Job,
177              Job->Cmd.toString().c_str());
178     // Start from very short runs and gradually increase them.
179     return Job;
180   }
181 
182   void RunOneMergeJob(FuzzJob *Job) {
183     auto Stats = ParseFinalStatsFromLog(Job->LogPath);
184     NumRuns += Stats.number_of_executed_units;
185 
186     std::vector<SizedFile> TempFiles, MergeCandidates;
187     // Read all newly created inputs and their feature sets.
188     // Choose only those inputs that have new features.
189     GetSizedFilesFromDir(Job->CorpusDir, &TempFiles);
190     std::sort(TempFiles.begin(), TempFiles.end());
191     for (auto &F : TempFiles) {
192       auto FeatureFile = F.File;
193       FeatureFile.replace(0, Job->CorpusDir.size(), Job->FeaturesDir);
194       auto FeatureBytes = FileToVector(FeatureFile, 0, false);
195       assert((FeatureBytes.size() % sizeof(uint32_t)) == 0);
196       std::vector<uint32_t> NewFeatures(FeatureBytes.size() / sizeof(uint32_t));
197       memcpy(NewFeatures.data(), FeatureBytes.data(), FeatureBytes.size());
198       for (auto Ft : NewFeatures) {
199         if (!Features.count(Ft)) {
200           MergeCandidates.push_back(F);
201           break;
202         }
203       }
204     }
205     // if (!FilesToAdd.empty() || Job->ExitCode != 0)
206     Printf("#%zd: cov: %zd ft: %zd corp: %zd exec/s %zd "
207            "oom/timeout/crash: %zd/%zd/%zd time: %zds job: %zd dft_time: %d\n",
208            NumRuns, Cov.size(), Features.size(), Files.size(),
209            Stats.average_exec_per_sec, NumOOMs, NumTimeouts, NumCrashes,
210            secondsSinceProcessStartUp(), Job->JobId, Job->DftTimeInSeconds);
211 
212     if (MergeCandidates.empty()) return;
213 
214     std::vector<std::string> FilesToAdd;
215     std::set<uint32_t> NewFeatures, NewCov;
216     bool IsSetCoverMerge =
217         !Job->Cmd.getFlagValue("set_cover_merge").compare("1");
218     CrashResistantMerge(Args, {}, MergeCandidates, &FilesToAdd, Features,
219                         &NewFeatures, Cov, &NewCov, Job->CFPath, false,
220                         IsSetCoverMerge);
221     for (auto &Path : FilesToAdd) {
222       auto U = FileToVector(Path);
223       auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
224       WriteToFile(U, NewPath);
225       Files.push_back(NewPath);
226     }
227     Features.insert(NewFeatures.begin(), NewFeatures.end());
228     Cov.insert(NewCov.begin(), NewCov.end());
229     for (auto Idx : NewCov)
230       if (auto *TE = TPC.PCTableEntryByIdx(Idx))
231         if (TPC.PcIsFuncEntry(TE))
232           PrintPC("  NEW_FUNC: %p %F %L\n", "",
233                   TPC.GetNextInstructionPc(TE->PC));
234 
235   }
236 
237 
238   void CollectDFT(const std::string &InputPath) {
239     if (DataFlowBinary.empty()) return;
240     if (!FilesWithDFT.insert(InputPath).second) return;
241     Command Cmd(Args);
242     Cmd.removeFlag("fork");
243     Cmd.removeFlag("runs");
244     Cmd.addFlag("data_flow_trace", DFTDir);
245     Cmd.addArgument(InputPath);
246     for (auto &C : CorpusDirs) // Remove all corpora from the args.
247       Cmd.removeArgument(C);
248     Cmd.setOutputFile(DirPlusFile(TempDir, "dft.log"));
249     Cmd.combineOutAndErr();
250     // Printf("CollectDFT: %s\n", Cmd.toString().c_str());
251     ExecuteCommand(Cmd);
252   }
253 
254 };
255 
256 struct JobQueue {
257   std::queue<FuzzJob *> Qu;
258   std::mutex Mu;
259   std::condition_variable Cv;
260 
261   void Push(FuzzJob *Job) {
262     {
263       std::lock_guard<std::mutex> Lock(Mu);
264       Qu.push(Job);
265     }
266     Cv.notify_one();
267   }
268   FuzzJob *Pop() {
269     std::unique_lock<std::mutex> Lk(Mu);
270     // std::lock_guard<std::mutex> Lock(Mu);
271     Cv.wait(Lk, [&]{return !Qu.empty();});
272     assert(!Qu.empty());
273     auto Job = Qu.front();
274     Qu.pop();
275     return Job;
276   }
277 };
278 
279 void WorkerThread(JobQueue *FuzzQ, JobQueue *MergeQ) {
280   while (auto Job = FuzzQ->Pop()) {
281     // Printf("WorkerThread: job %p\n", Job);
282     Job->ExitCode = ExecuteCommand(Job->Cmd);
283     MergeQ->Push(Job);
284   }
285 }
286 
287 // This is just a skeleton of an experimental -fork=1 feature.
288 void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
289                   const std::vector<std::string> &Args,
290                   const std::vector<std::string> &CorpusDirs, int NumJobs) {
291   Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs);
292 
293   GlobalEnv Env;
294   Env.Args = Args;
295   Env.CorpusDirs = CorpusDirs;
296   Env.Rand = &Rand;
297   Env.Verbosity = Options.Verbosity;
298   Env.ProcessStartTime = std::chrono::system_clock::now();
299   Env.DataFlowBinary = Options.CollectDataFlow;
300 
301   std::vector<SizedFile> SeedFiles;
302   for (auto &Dir : CorpusDirs)
303     GetSizedFilesFromDir(Dir, &SeedFiles);
304   std::sort(SeedFiles.begin(), SeedFiles.end());
305   Env.TempDir = TempPath("FuzzWithFork", ".dir");
306   Env.DFTDir = DirPlusFile(Env.TempDir, "DFT");
307   RmDirRecursive(Env.TempDir);  // in case there is a leftover from old runs.
308   MkDir(Env.TempDir);
309   MkDir(Env.DFTDir);
310 
311 
312   if (CorpusDirs.empty())
313     MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
314   else
315     Env.MainCorpusDir = CorpusDirs[0];
316 
317   if (Options.KeepSeed) {
318     for (auto &File : SeedFiles)
319       Env.Files.push_back(File.File);
320   } else {
321     auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
322     std::set<uint32_t> NewFeatures, NewCov;
323     CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, Env.Features,
324                         &NewFeatures, Env.Cov, &NewCov, CFPath,
325                         /*Verbose=*/false, /*IsSetCoverMerge=*/false);
326     Env.Features.insert(NewFeatures.begin(), NewFeatures.end());
327     Env.Cov.insert(NewFeatures.begin(), NewFeatures.end());
328     RemoveFile(CFPath);
329   }
330   Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs,
331          Env.Files.size(), Env.TempDir.c_str());
332 
333   int ExitCode = 0;
334 
335   JobQueue FuzzQ, MergeQ;
336 
337   auto StopJobs = [&]() {
338     for (int i = 0; i < NumJobs; i++)
339       FuzzQ.Push(nullptr);
340     MergeQ.Push(nullptr);
341     WriteToFile(Unit({1}), Env.StopFile());
342   };
343 
344   size_t JobId = 1;
345   std::vector<std::thread> Threads;
346   for (int t = 0; t < NumJobs; t++) {
347     Threads.push_back(std::thread(WorkerThread, &FuzzQ, &MergeQ));
348     FuzzQ.Push(Env.CreateNewJob(JobId++));
349   }
350 
351   while (true) {
352     std::unique_ptr<FuzzJob> Job(MergeQ.Pop());
353     if (!Job)
354       break;
355     ExitCode = Job->ExitCode;
356     if (ExitCode == Options.InterruptExitCode) {
357       Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
358       StopJobs();
359       break;
360     }
361     Fuzzer::MaybeExitGracefully();
362 
363     Env.RunOneMergeJob(Job.get());
364 
365     // Continue if our crash is one of the ignored ones.
366     if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
367       Env.NumTimeouts++;
368     else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
369       Env.NumOOMs++;
370     else if (ExitCode != 0) {
371       Env.NumCrashes++;
372       if (Options.IgnoreCrashes) {
373         std::ifstream In(Job->LogPath);
374         std::string Line;
375         while (std::getline(In, Line, '\n'))
376           if (Line.find("ERROR:") != Line.npos ||
377               Line.find("runtime error:") != Line.npos)
378             Printf("%s\n", Line.c_str());
379       } else {
380         // And exit if we don't ignore this crash.
381         Printf("INFO: log from the inner process:\n%s",
382                FileToString(Job->LogPath).c_str());
383         StopJobs();
384         break;
385       }
386     }
387 
388     // Stop if we are over the time budget.
389     // This is not precise, since other threads are still running
390     // and we will wait while joining them.
391     // We also don't stop instantly: other jobs need to finish.
392     if (Options.MaxTotalTimeSec > 0 &&
393         Env.secondsSinceProcessStartUp() >= (size_t)Options.MaxTotalTimeSec) {
394       Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
395              Env.secondsSinceProcessStartUp());
396       StopJobs();
397       break;
398     }
399     if (Env.NumRuns >= Options.MaxNumberOfRuns) {
400       Printf("INFO: fuzzed for %zd iterations, wrapping up soon\n",
401              Env.NumRuns);
402       StopJobs();
403       break;
404     }
405 
406     FuzzQ.Push(Env.CreateNewJob(JobId++));
407   }
408 
409   for (auto &T : Threads)
410     T.join();
411 
412   // The workers have terminated. Don't try to remove the directory before they
413   // terminate to avoid a race condition preventing cleanup on Windows.
414   RmDirRecursive(Env.TempDir);
415 
416   // Use the exit code from the last child process.
417   Printf("INFO: exiting: %d time: %zds\n", ExitCode,
418          Env.secondsSinceProcessStartUp());
419   exit(ExitCode);
420 }
421 
422 } // namespace fuzzer
423