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
ParseFinalStatsFromLog(const std::string & LogPath)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
~FuzzJobfuzzer::FuzzJob79 ~FuzzJob() {
80 RemoveFile(CFPath);
81 RemoveFile(LogPath);
82 RemoveFile(SeedListPath);
83 RmDirRecursive(CorpusDir);
84 RmDirRecursive(FeaturesDir);
85 }
86 };
87
88 struct GlobalEnv {
89 Vector<std::string> Args;
90 Vector<std::string> CorpusDirs;
91 std::string MainCorpusDir;
92 std::string TempDir;
93 std::string DFTDir;
94 std::string DataFlowBinary;
95 Set<uint32_t> Features, Cov;
96 Set<std::string> FilesWithDFT;
97 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
StopFilefuzzer::GlobalEnv109 std::string StopFile() { return DirPlusFile(TempDir, "STOP"); }
110
secondsSinceProcessStartUpfuzzer::GlobalEnv111 size_t secondsSinceProcessStartUp() const {
112 return std::chrono::duration_cast<std::chrono::seconds>(
113 std::chrono::system_clock::now() - ProcessStartTime)
114 .count();
115 }
116
CreateNewJobfuzzer::GlobalEnv117 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
RunOneMergeJobfuzzer::GlobalEnv182 void RunOneMergeJob(FuzzJob *Job) {
183 auto Stats = ParseFinalStatsFromLog(Job->LogPath);
184 NumRuns += Stats.number_of_executed_units;
185
186 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 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 Vector<std::string> FilesToAdd;
215 Set<uint32_t> NewFeatures, NewCov;
216 CrashResistantMerge(Args, {}, MergeCandidates, &FilesToAdd, Features,
217 &NewFeatures, Cov, &NewCov, Job->CFPath, false);
218 for (auto &Path : FilesToAdd) {
219 auto U = FileToVector(Path);
220 auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
221 WriteToFile(U, NewPath);
222 Files.push_back(NewPath);
223 }
224 Features.insert(NewFeatures.begin(), NewFeatures.end());
225 Cov.insert(NewCov.begin(), NewCov.end());
226 for (auto Idx : NewCov)
227 if (auto *TE = TPC.PCTableEntryByIdx(Idx))
228 if (TPC.PcIsFuncEntry(TE))
229 PrintPC(" NEW_FUNC: %p %F %L\n", "",
230 TPC.GetNextInstructionPc(TE->PC));
231
232 }
233
234
CollectDFTfuzzer::GlobalEnv235 void CollectDFT(const std::string &InputPath) {
236 if (DataFlowBinary.empty()) return;
237 if (!FilesWithDFT.insert(InputPath).second) return;
238 Command Cmd(Args);
239 Cmd.removeFlag("fork");
240 Cmd.removeFlag("runs");
241 Cmd.addFlag("data_flow_trace", DFTDir);
242 Cmd.addArgument(InputPath);
243 for (auto &C : CorpusDirs) // Remove all corpora from the args.
244 Cmd.removeArgument(C);
245 Cmd.setOutputFile(DirPlusFile(TempDir, "dft.log"));
246 Cmd.combineOutAndErr();
247 // Printf("CollectDFT: %s\n", Cmd.toString().c_str());
248 ExecuteCommand(Cmd);
249 }
250
251 };
252
253 struct JobQueue {
254 std::queue<FuzzJob *> Qu;
255 std::mutex Mu;
256 std::condition_variable Cv;
257
Pushfuzzer::JobQueue258 void Push(FuzzJob *Job) {
259 {
260 std::lock_guard<std::mutex> Lock(Mu);
261 Qu.push(Job);
262 }
263 Cv.notify_one();
264 }
Popfuzzer::JobQueue265 FuzzJob *Pop() {
266 std::unique_lock<std::mutex> Lk(Mu);
267 // std::lock_guard<std::mutex> Lock(Mu);
268 Cv.wait(Lk, [&]{return !Qu.empty();});
269 assert(!Qu.empty());
270 auto Job = Qu.front();
271 Qu.pop();
272 return Job;
273 }
274 };
275
WorkerThread(JobQueue * FuzzQ,JobQueue * MergeQ)276 void WorkerThread(JobQueue *FuzzQ, JobQueue *MergeQ) {
277 while (auto Job = FuzzQ->Pop()) {
278 // Printf("WorkerThread: job %p\n", Job);
279 Job->ExitCode = ExecuteCommand(Job->Cmd);
280 MergeQ->Push(Job);
281 }
282 }
283
284 // This is just a skeleton of an experimental -fork=1 feature.
FuzzWithFork(Random & Rand,const FuzzingOptions & Options,const Vector<std::string> & Args,const Vector<std::string> & CorpusDirs,int NumJobs)285 void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
286 const Vector<std::string> &Args,
287 const Vector<std::string> &CorpusDirs, int NumJobs) {
288 Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs);
289
290 GlobalEnv Env;
291 Env.Args = Args;
292 Env.CorpusDirs = CorpusDirs;
293 Env.Rand = &Rand;
294 Env.Verbosity = Options.Verbosity;
295 Env.ProcessStartTime = std::chrono::system_clock::now();
296 Env.DataFlowBinary = Options.CollectDataFlow;
297
298 Vector<SizedFile> SeedFiles;
299 for (auto &Dir : CorpusDirs)
300 GetSizedFilesFromDir(Dir, &SeedFiles);
301 std::sort(SeedFiles.begin(), SeedFiles.end());
302 Env.TempDir = TempPath("FuzzWithFork", ".dir");
303 Env.DFTDir = DirPlusFile(Env.TempDir, "DFT");
304 RmDirRecursive(Env.TempDir); // in case there is a leftover from old runs.
305 MkDir(Env.TempDir);
306 MkDir(Env.DFTDir);
307
308
309 if (CorpusDirs.empty())
310 MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
311 else
312 Env.MainCorpusDir = CorpusDirs[0];
313
314 if (Options.KeepSeed) {
315 for (auto &File : SeedFiles)
316 Env.Files.push_back(File.File);
317 } else {
318 auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
319 Set<uint32_t> NewFeatures, NewCov;
320 CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, Env.Features,
321 &NewFeatures, Env.Cov, &NewCov, CFPath, false);
322 Env.Features.insert(NewFeatures.begin(), NewFeatures.end());
323 Env.Cov.insert(NewFeatures.begin(), NewFeatures.end());
324 RemoveFile(CFPath);
325 }
326 Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs,
327 Env.Files.size(), Env.TempDir.c_str());
328
329 int ExitCode = 0;
330
331 JobQueue FuzzQ, MergeQ;
332
333 auto StopJobs = [&]() {
334 for (int i = 0; i < NumJobs; i++)
335 FuzzQ.Push(nullptr);
336 MergeQ.Push(nullptr);
337 WriteToFile(Unit({1}), Env.StopFile());
338 };
339
340 size_t JobId = 1;
341 Vector<std::thread> Threads;
342 for (int t = 0; t < NumJobs; t++) {
343 Threads.push_back(std::thread(WorkerThread, &FuzzQ, &MergeQ));
344 FuzzQ.Push(Env.CreateNewJob(JobId++));
345 }
346
347 while (true) {
348 std::unique_ptr<FuzzJob> Job(MergeQ.Pop());
349 if (!Job)
350 break;
351 ExitCode = Job->ExitCode;
352 if (ExitCode == Options.InterruptExitCode) {
353 Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
354 StopJobs();
355 break;
356 }
357 Fuzzer::MaybeExitGracefully();
358
359 Env.RunOneMergeJob(Job.get());
360
361 // Continue if our crash is one of the ignorred ones.
362 if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
363 Env.NumTimeouts++;
364 else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
365 Env.NumOOMs++;
366 else if (ExitCode != 0) {
367 Env.NumCrashes++;
368 if (Options.IgnoreCrashes) {
369 std::ifstream In(Job->LogPath);
370 std::string Line;
371 while (std::getline(In, Line, '\n'))
372 if (Line.find("ERROR:") != Line.npos ||
373 Line.find("runtime error:") != Line.npos)
374 Printf("%s\n", Line.c_str());
375 } else {
376 // And exit if we don't ignore this crash.
377 Printf("INFO: log from the inner process:\n%s",
378 FileToString(Job->LogPath).c_str());
379 StopJobs();
380 break;
381 }
382 }
383
384 // Stop if we are over the time budget.
385 // This is not precise, since other threads are still running
386 // and we will wait while joining them.
387 // We also don't stop instantly: other jobs need to finish.
388 if (Options.MaxTotalTimeSec > 0 &&
389 Env.secondsSinceProcessStartUp() >= (size_t)Options.MaxTotalTimeSec) {
390 Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
391 Env.secondsSinceProcessStartUp());
392 StopJobs();
393 break;
394 }
395 if (Env.NumRuns >= Options.MaxNumberOfRuns) {
396 Printf("INFO: fuzzed for %zd iterations, wrapping up soon\n",
397 Env.NumRuns);
398 StopJobs();
399 break;
400 }
401
402 FuzzQ.Push(Env.CreateNewJob(JobId++));
403 }
404
405 for (auto &T : Threads)
406 T.join();
407
408 // The workers have terminated. Don't try to remove the directory before they
409 // terminate to avoid a race condition preventing cleanup on Windows.
410 RmDirRecursive(Env.TempDir);
411
412 // Use the exit code from the last child process.
413 Printf("INFO: exiting: %d time: %zds\n", ExitCode,
414 Env.secondsSinceProcessStartUp());
415 exit(ExitCode);
416 }
417
418 } // namespace fuzzer
419