1 //===- FuzzerFork.cpp - run fuzzing in separate subprocesses --------------===//
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
7 //===----------------------------------------------------------------------===//
8 // Spawn and orchestrate separate fuzzing processes.
9 //===----------------------------------------------------------------------===//
11 #include "FuzzerCommand.h"
12 #include "FuzzerFork.h"
14 #include "FuzzerInternal.h"
15 #include "FuzzerMerge.h"
16 #include "FuzzerSHA1.h"
17 #include "FuzzerTracePC.h"
18 #include "FuzzerUtil.h"
22 #include <condition_variable>
33 size_t number_of_executed_units
= 0;
34 size_t peak_rss_mb
= 0;
35 size_t average_exec_per_sec
= 0;
38 static Stats
ParseFinalStatsFromLog(const std::string
&LogPath
) {
39 std::ifstream
In(LogPath
);
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
},
51 while (std::getline(In
, Line
, '\n')) {
52 if (Line
.find("stat::") != 0) continue;
53 std::istringstream
ISS(Line
);
57 for (size_t i
= 0; NameVarPairs
[i
].Name
; i
++)
58 if (Name
== NameVarPairs
[i
].Name
)
59 *NameVarPairs
[i
].Var
= Val
;
67 std::string CorpusDir
;
68 std::string FeaturesDir
;
70 std::string SeedListPath
;
74 int DftTimeInSeconds
= 0;
82 RemoveFile(SeedListPath
);
83 RmDirRecursive(CorpusDir
);
84 RmDirRecursive(FeaturesDir
);
89 Vector
<std::string
> Args
;
90 Vector
<std::string
> CorpusDirs
;
91 std::string MainCorpusDir
;
94 std::string DataFlowBinary
;
95 Set
<uint32_t> Features
, Cov
;
96 Set
<std::string
> FilesWithDFT
;
97 Vector
<std::string
> Files
;
99 std::chrono::system_clock::time_point ProcessStartTime
;
102 size_t NumTimeouts
= 0;
104 size_t NumCrashes
= 0;
109 std::string
StopFile() { return DirPlusFile(TempDir
, "STOP"); }
111 size_t secondsSinceProcessStartUp() const {
112 return std::chrono::duration_cast
<std::chrono::seconds
>(
113 std::chrono::system_clock::now() - ProcessStartTime
)
117 FuzzJob
*CreateNewJob(size_t JobId
) {
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");
134 auto Job
= new FuzzJob
;
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
;
144 auto Time2
= std::chrono::system_clock::now();
145 Job
->DftTimeInSeconds
= duration_cast
<seconds
>(Time2
- Time1
).count();
147 if (!Seeds
.empty()) {
149 DirPlusFile(TempDir
, std::to_string(JobId
) + ".seeds");
150 WriteToFile(Seeds
, Job
->SeedListPath
);
151 Cmd
.addFlag("seed_inputs", "@" + Job
->SeedListPath
);
153 Job
->LogPath
= DirPlusFile(TempDir
, std::to_string(JobId
) + ".log");
154 Job
->CorpusDir
= DirPlusFile(TempDir
, "C" + std::to_string(JobId
));
155 Job
->FeaturesDir
= DirPlusFile(TempDir
, "F" + std::to_string(JobId
));
156 Job
->CFPath
= DirPlusFile(TempDir
, std::to_string(JobId
) + ".merge");
160 Cmd
.addArgument(Job
->CorpusDir
);
161 Cmd
.addFlag("features_dir", Job
->FeaturesDir
);
163 for (auto &D
: {Job
->CorpusDir
, Job
->FeaturesDir
}) {
168 Cmd
.setOutputFile(Job
->LogPath
);
169 Cmd
.combineOutAndErr();
174 Printf("Job %zd/%p Created: %s\n", JobId
, Job
,
175 Job
->Cmd
.toString().c_str());
176 // Start from very short runs and gradually increase them.
180 void RunOneMergeJob(FuzzJob
*Job
) {
181 auto Stats
= ParseFinalStatsFromLog(Job
->LogPath
);
182 NumRuns
+= Stats
.number_of_executed_units
;
184 Vector
<SizedFile
> TempFiles
, MergeCandidates
;
185 // Read all newly created inputs and their feature sets.
186 // Choose only those inputs that have new features.
187 GetSizedFilesFromDir(Job
->CorpusDir
, &TempFiles
);
188 std::sort(TempFiles
.begin(), TempFiles
.end());
189 for (auto &F
: TempFiles
) {
190 auto FeatureFile
= F
.File
;
191 FeatureFile
.replace(0, Job
->CorpusDir
.size(), Job
->FeaturesDir
);
192 auto FeatureBytes
= FileToVector(FeatureFile
, 0, false);
193 assert((FeatureBytes
.size() % sizeof(uint32_t)) == 0);
194 Vector
<uint32_t> NewFeatures(FeatureBytes
.size() / sizeof(uint32_t));
195 memcpy(NewFeatures
.data(), FeatureBytes
.data(), FeatureBytes
.size());
196 for (auto Ft
: NewFeatures
) {
197 if (!Features
.count(Ft
)) {
198 MergeCandidates
.push_back(F
);
203 // if (!FilesToAdd.empty() || Job->ExitCode != 0)
204 Printf("#%zd: cov: %zd ft: %zd corp: %zd exec/s %zd "
205 "oom/timeout/crash: %zd/%zd/%zd time: %zds job: %zd dft_time: %d\n",
206 NumRuns
, Cov
.size(), Features
.size(), Files
.size(),
207 Stats
.average_exec_per_sec
, NumOOMs
, NumTimeouts
, NumCrashes
,
208 secondsSinceProcessStartUp(), Job
->JobId
, Job
->DftTimeInSeconds
);
210 if (MergeCandidates
.empty()) return;
212 Vector
<std::string
> FilesToAdd
;
213 Set
<uint32_t> NewFeatures
, NewCov
;
214 CrashResistantMerge(Args
, {}, MergeCandidates
, &FilesToAdd
, Features
,
215 &NewFeatures
, Cov
, &NewCov
, Job
->CFPath
, false);
216 for (auto &Path
: FilesToAdd
) {
217 auto U
= FileToVector(Path
);
218 auto NewPath
= DirPlusFile(MainCorpusDir
, Hash(U
));
219 WriteToFile(U
, NewPath
);
220 Files
.push_back(NewPath
);
222 Features
.insert(NewFeatures
.begin(), NewFeatures
.end());
223 Cov
.insert(NewCov
.begin(), NewCov
.end());
224 for (auto Idx
: NewCov
)
225 if (auto *TE
= TPC
.PCTableEntryByIdx(Idx
))
226 if (TPC
.PcIsFuncEntry(TE
))
227 PrintPC(" NEW_FUNC: %p %F %L\n", "",
228 TPC
.GetNextInstructionPc(TE
->PC
));
233 void CollectDFT(const std::string
&InputPath
) {
234 if (DataFlowBinary
.empty()) return;
235 if (!FilesWithDFT
.insert(InputPath
).second
) return;
237 Cmd
.removeFlag("fork");
238 Cmd
.removeFlag("runs");
239 Cmd
.addFlag("data_flow_trace", DFTDir
);
240 Cmd
.addArgument(InputPath
);
241 for (auto &C
: CorpusDirs
) // Remove all corpora from the args.
242 Cmd
.removeArgument(C
);
243 Cmd
.setOutputFile(DirPlusFile(TempDir
, "dft.log"));
244 Cmd
.combineOutAndErr();
245 // Printf("CollectDFT: %s\n", Cmd.toString().c_str());
252 std::queue
<FuzzJob
*> Qu
;
254 std::condition_variable Cv
;
256 void Push(FuzzJob
*Job
) {
258 std::lock_guard
<std::mutex
> Lock(Mu
);
264 std::unique_lock
<std::mutex
> Lk(Mu
);
265 // std::lock_guard<std::mutex> Lock(Mu);
266 Cv
.wait(Lk
, [&]{return !Qu
.empty();});
268 auto Job
= Qu
.front();
274 void WorkerThread(JobQueue
*FuzzQ
, JobQueue
*MergeQ
) {
275 while (auto Job
= FuzzQ
->Pop()) {
276 // Printf("WorkerThread: job %p\n", Job);
277 Job
->ExitCode
= ExecuteCommand(Job
->Cmd
);
282 // This is just a skeleton of an experimental -fork=1 feature.
283 void FuzzWithFork(Random
&Rand
, const FuzzingOptions
&Options
,
284 const Vector
<std::string
> &Args
,
285 const Vector
<std::string
> &CorpusDirs
, int NumJobs
) {
286 Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs
);
290 Env
.CorpusDirs
= CorpusDirs
;
292 Env
.Verbosity
= Options
.Verbosity
;
293 Env
.ProcessStartTime
= std::chrono::system_clock::now();
294 Env
.DataFlowBinary
= Options
.CollectDataFlow
;
296 Vector
<SizedFile
> SeedFiles
;
297 for (auto &Dir
: CorpusDirs
)
298 GetSizedFilesFromDir(Dir
, &SeedFiles
);
299 std::sort(SeedFiles
.begin(), SeedFiles
.end());
300 Env
.TempDir
= TempPath("FuzzWithFork", ".dir");
301 Env
.DFTDir
= DirPlusFile(Env
.TempDir
, "DFT");
302 RmDirRecursive(Env
.TempDir
); // in case there is a leftover from old runs.
307 if (CorpusDirs
.empty())
308 MkDir(Env
.MainCorpusDir
= DirPlusFile(Env
.TempDir
, "C"));
310 Env
.MainCorpusDir
= CorpusDirs
[0];
312 if (Options
.KeepSeed
) {
313 for (auto &File
: SeedFiles
)
314 Env
.Files
.push_back(File
.File
);
316 auto CFPath
= DirPlusFile(Env
.TempDir
, "merge.txt");
317 CrashResistantMerge(Env
.Args
, {}, SeedFiles
, &Env
.Files
, {}, &Env
.Features
,
318 {}, &Env
.Cov
, CFPath
, false);
321 Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs
,
322 Env
.Files
.size(), Env
.TempDir
.c_str());
326 JobQueue FuzzQ
, MergeQ
;
328 auto StopJobs
= [&]() {
329 for (int i
= 0; i
< NumJobs
; i
++)
331 MergeQ
.Push(nullptr);
332 WriteToFile(Unit({1}), Env
.StopFile());
336 Vector
<std::thread
> Threads
;
337 for (int t
= 0; t
< NumJobs
; t
++) {
338 Threads
.push_back(std::thread(WorkerThread
, &FuzzQ
, &MergeQ
));
339 FuzzQ
.Push(Env
.CreateNewJob(JobId
++));
343 std::unique_ptr
<FuzzJob
> Job(MergeQ
.Pop());
346 ExitCode
= Job
->ExitCode
;
347 if (ExitCode
== Options
.InterruptExitCode
) {
348 Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
352 Fuzzer::MaybeExitGracefully();
354 Env
.RunOneMergeJob(Job
.get());
356 // Continue if our crash is one of the ignorred ones.
357 if (Options
.IgnoreTimeouts
&& ExitCode
== Options
.TimeoutExitCode
)
359 else if (Options
.IgnoreOOMs
&& ExitCode
== Options
.OOMExitCode
)
361 else if (ExitCode
!= 0) {
363 if (Options
.IgnoreCrashes
) {
364 std::ifstream
In(Job
->LogPath
);
366 while (std::getline(In
, Line
, '\n'))
367 if (Line
.find("ERROR:") != Line
.npos
||
368 Line
.find("runtime error:") != Line
.npos
)
369 Printf("%s\n", Line
.c_str());
371 // And exit if we don't ignore this crash.
372 Printf("INFO: log from the inner process:\n%s",
373 FileToString(Job
->LogPath
).c_str());
379 // Stop if we are over the time budget.
380 // This is not precise, since other threads are still running
381 // and we will wait while joining them.
382 // We also don't stop instantly: other jobs need to finish.
383 if (Options
.MaxTotalTimeSec
> 0 &&
384 Env
.secondsSinceProcessStartUp() >= (size_t)Options
.MaxTotalTimeSec
) {
385 Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
386 Env
.secondsSinceProcessStartUp());
390 if (Env
.NumRuns
>= Options
.MaxNumberOfRuns
) {
391 Printf("INFO: fuzzed for %zd iterations, wrapping up soon\n",
397 FuzzQ
.Push(Env
.CreateNewJob(JobId
++));
400 for (auto &T
: Threads
)
403 // The workers have terminated. Don't try to remove the directory before they
404 // terminate to avoid a race condition preventing cleanup on Windows.
405 RmDirRecursive(Env
.TempDir
);
407 // Use the exit code from the last child process.
408 Printf("INFO: exiting: %d time: %zds\n", ExitCode
,
409 Env
.secondsSinceProcessStartUp());
413 } // namespace fuzzer