blob: 870a2244850427d7c53302611fe060389fbf9330 [file] [log] [blame]
kcc2e6ca5c2019-02-12 22:48:55 +00001//===- 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//===----------------------------------------------------------------------===//
kcc64bcb922019-02-13 04:04:45 +00008// Spawn and orchestrate separate fuzzing processes.
kcc2e6ca5c2019-02-12 22:48:55 +00009//===----------------------------------------------------------------------===//
10
11#include "FuzzerCommand.h"
12#include "FuzzerFork.h"
13#include "FuzzerIO.h"
kcc1c5afe22019-04-13 01:57:33 +000014#include "FuzzerInternal.h"
kcc2e6ca5c2019-02-12 22:48:55 +000015#include "FuzzerMerge.h"
16#include "FuzzerSHA1.h"
kcc9c0ed932019-02-15 01:22:00 +000017#include "FuzzerTracePC.h"
kcc2e6ca5c2019-02-12 22:48:55 +000018#include "FuzzerUtil.h"
19
kccb1fa9e02019-02-14 01:11:29 +000020#include <atomic>
kcc55e54ed2019-02-15 21:51:15 +000021#include <chrono>
kccdd391142019-02-14 21:09:32 +000022#include <fstream>
kccedefdf32019-02-16 00:14:16 +000023#include <memory>
kcc6526f1d2019-02-14 00:25:43 +000024#include <mutex>
kcc6526f1d2019-02-14 00:25:43 +000025#include <queue>
kccdd391142019-02-14 21:09:32 +000026#include <sstream>
27#include <thread>
kcc6526f1d2019-02-14 00:25:43 +000028
kcc2e6ca5c2019-02-12 22:48:55 +000029namespace fuzzer {
30
kccdd391142019-02-14 21:09:32 +000031struct Stats {
32 size_t number_of_executed_units = 0;
33 size_t peak_rss_mb = 0;
34 size_t average_exec_per_sec = 0;
35};
36
37static Stats ParseFinalStatsFromLog(const std::string &LogPath) {
38 std::ifstream In(LogPath);
39 std::string Line;
40 Stats Res;
41 struct {
42 const char *Name;
43 size_t *Var;
44 } NameVarPairs[] = {
45 {"stat::number_of_executed_units:", &Res.number_of_executed_units},
46 {"stat::peak_rss_mb:", &Res.peak_rss_mb},
47 {"stat::average_exec_per_sec:", &Res.average_exec_per_sec},
48 {nullptr, nullptr},
49 };
50 while (std::getline(In, Line, '\n')) {
51 if (Line.find("stat::") != 0) continue;
52 std::istringstream ISS(Line);
53 std::string Name;
54 size_t Val;
55 ISS >> Name >> Val;
56 for (size_t i = 0; NameVarPairs[i].Name; i++)
57 if (Name == NameVarPairs[i].Name)
58 *NameVarPairs[i].Var = Val;
59 }
60 return Res;
61}
62
kcc64bcb922019-02-13 04:04:45 +000063struct FuzzJob {
64 // Inputs.
65 Command Cmd;
kcc64bcb922019-02-13 04:04:45 +000066 std::string CorpusDir;
kcc1c5afe22019-04-13 01:57:33 +000067 std::string FeaturesDir;
kcc64bcb922019-02-13 04:04:45 +000068 std::string LogPath;
metzmane9b95bc2019-04-30 20:56:18 +000069 std::string SeedListPath;
kcc64bcb922019-02-13 04:04:45 +000070 std::string CFPath;
kcc64bcb922019-02-13 04:04:45 +000071
72 // Fuzzing Outputs.
73 int ExitCode;
kccedefdf32019-02-16 00:14:16 +000074
75 ~FuzzJob() {
76 RemoveFile(CFPath);
77 RemoveFile(LogPath);
metzmane9b95bc2019-04-30 20:56:18 +000078 RemoveFile(SeedListPath);
kccedefdf32019-02-16 00:14:16 +000079 RmDirRecursive(CorpusDir);
kcc1c5afe22019-04-13 01:57:33 +000080 RmDirRecursive(FeaturesDir);
kccedefdf32019-02-16 00:14:16 +000081 }
kcc64bcb922019-02-13 04:04:45 +000082};
83
84struct GlobalEnv {
kcc6526f1d2019-02-14 00:25:43 +000085 Vector<std::string> Args;
86 Vector<std::string> CorpusDirs;
kcc64bcb922019-02-13 04:04:45 +000087 std::string MainCorpusDir;
kcc6526f1d2019-02-14 00:25:43 +000088 std::string TempDir;
kccd701d9e2019-05-23 00:22:46 +000089 std::string DFTDir;
90 std::string DataFlowBinary;
kcc98a86242019-02-15 00:08:16 +000091 Set<uint32_t> Features, Cov;
kcc64bcb922019-02-13 04:04:45 +000092 Vector<std::string> Files;
kcc6526f1d2019-02-14 00:25:43 +000093 Random *Rand;
kcc55e54ed2019-02-15 21:51:15 +000094 std::chrono::system_clock::time_point ProcessStartTime;
kcc6526f1d2019-02-14 00:25:43 +000095 int Verbosity = 0;
96
kcc55e54ed2019-02-15 21:51:15 +000097 size_t NumTimeouts = 0;
98 size_t NumOOMs = 0;
99 size_t NumCrashes = 0;
100
101
kccdd391142019-02-14 21:09:32 +0000102 size_t NumRuns = 0;
103
kcc55e54ed2019-02-15 21:51:15 +0000104 size_t secondsSinceProcessStartUp() const {
105 return std::chrono::duration_cast<std::chrono::seconds>(
106 std::chrono::system_clock::now() - ProcessStartTime)
107 .count();
108 }
109
kcc6526f1d2019-02-14 00:25:43 +0000110 FuzzJob *CreateNewJob(size_t JobId) {
111 Command Cmd(Args);
112 Cmd.removeFlag("fork");
kcc18b370a2019-04-12 20:20:57 +0000113 Cmd.removeFlag("runs");
kccd701d9e2019-05-23 00:22:46 +0000114 Cmd.removeFlag("collect_data_flow");
kcc6526f1d2019-02-14 00:25:43 +0000115 for (auto &C : CorpusDirs) // Remove all corpora from the args.
116 Cmd.removeArgument(C);
117 Cmd.addFlag("reload", "0"); // working in an isolated dir, no reload.
kccdd391142019-02-14 21:09:32 +0000118 Cmd.addFlag("print_final_stats", "1");
kcc9c0ed932019-02-15 01:22:00 +0000119 Cmd.addFlag("print_funcs", "0"); // no need to spend time symbolizing.
kcc6526f1d2019-02-14 00:25:43 +0000120 Cmd.addFlag("max_total_time", std::to_string(std::min((size_t)300, JobId)));
kccd701d9e2019-05-23 00:22:46 +0000121 if (!DataFlowBinary.empty()) {
122 Cmd.addFlag("data_flow_trace", DFTDir);
123 if (!Cmd.hasFlag("focus_function"))
124 Cmd.addFlag("focus_function", "auto");
125 }
kcc6526f1d2019-02-14 00:25:43 +0000126 auto Job = new FuzzJob;
127 std::string Seeds;
kcc9c0ed932019-02-15 01:22:00 +0000128 if (size_t CorpusSubsetSize =
129 std::min(Files.size(), (size_t)sqrt(Files.size() + 2)))
kcc6526f1d2019-02-14 00:25:43 +0000130 for (size_t i = 0; i < CorpusSubsetSize; i++)
131 Seeds += (Seeds.empty() ? "" : ",") +
132 Files[Rand->SkewTowardsLast(Files.size())];
metzmane9b95bc2019-04-30 20:56:18 +0000133 if (!Seeds.empty()) {
kccd701d9e2019-05-23 00:22:46 +0000134 Job->SeedListPath =
135 DirPlusFile(TempDir, std::to_string(JobId) + ".seeds");
metzmane9b95bc2019-04-30 20:56:18 +0000136 WriteToFile(Seeds, Job->SeedListPath);
137 Cmd.addFlag("seed_inputs", "@" + Job->SeedListPath);
138 }
kcc6526f1d2019-02-14 00:25:43 +0000139 Job->LogPath = DirPlusFile(TempDir, std::to_string(JobId) + ".log");
140 Job->CorpusDir = DirPlusFile(TempDir, "C" + std::to_string(JobId));
kcc1c5afe22019-04-13 01:57:33 +0000141 Job->FeaturesDir = DirPlusFile(TempDir, "F" + std::to_string(JobId));
kcc6526f1d2019-02-14 00:25:43 +0000142 Job->CFPath = DirPlusFile(TempDir, std::to_string(JobId) + ".merge");
143
144
145 Cmd.addArgument(Job->CorpusDir);
kcc1c5afe22019-04-13 01:57:33 +0000146 Cmd.addFlag("features_dir", Job->FeaturesDir);
147
148 for (auto &D : {Job->CorpusDir, Job->FeaturesDir}) {
149 RmDirRecursive(D);
150 MkDir(D);
151 }
kcc6526f1d2019-02-14 00:25:43 +0000152
153 Cmd.setOutputFile(Job->LogPath);
154 Cmd.combineOutAndErr();
155
156 Job->Cmd = Cmd;
157
158 if (Verbosity >= 2)
159 Printf("Job %zd/%p Created: %s\n", JobId, Job,
160 Job->Cmd.toString().c_str());
161 // Start from very short runs and gradually increase them.
162 return Job;
163 }
164
165 void RunOneMergeJob(FuzzJob *Job) {
kcce5ef7c02019-04-19 01:39:14 +0000166 auto Stats = ParseFinalStatsFromLog(Job->LogPath);
167 NumRuns += Stats.number_of_executed_units;
168
kcc1c5afe22019-04-13 01:57:33 +0000169 Vector<SizedFile> TempFiles, MergeCandidates;
170 // Read all newly created inputs and their feature sets.
171 // Choose only those inputs that have new features.
kcc6526f1d2019-02-14 00:25:43 +0000172 GetSizedFilesFromDir(Job->CorpusDir, &TempFiles);
kcc1c5afe22019-04-13 01:57:33 +0000173 std::sort(TempFiles.begin(), TempFiles.end());
174 for (auto &F : TempFiles) {
175 auto FeatureFile = F.File;
176 FeatureFile.replace(0, Job->CorpusDir.size(), Job->FeaturesDir);
177 auto FeatureBytes = FileToVector(FeatureFile, 0, false);
178 assert((FeatureBytes.size() % sizeof(uint32_t)) == 0);
179 Vector<uint32_t> NewFeatures(FeatureBytes.size() / sizeof(uint32_t));
180 memcpy(NewFeatures.data(), FeatureBytes.data(), FeatureBytes.size());
181 for (auto Ft : NewFeatures) {
182 if (!Features.count(Ft)) {
183 MergeCandidates.push_back(F);
184 break;
185 }
186 }
187 }
188 if (MergeCandidates.empty()) return;
kcc6526f1d2019-02-14 00:25:43 +0000189
190 Vector<std::string> FilesToAdd;
kcc98a86242019-02-15 00:08:16 +0000191 Set<uint32_t> NewFeatures, NewCov;
kcc1c5afe22019-04-13 01:57:33 +0000192 CrashResistantMerge(Args, {}, MergeCandidates, &FilesToAdd, Features,
kcc98a86242019-02-15 00:08:16 +0000193 &NewFeatures, Cov, &NewCov, Job->CFPath, false);
kcc6526f1d2019-02-14 00:25:43 +0000194 for (auto &Path : FilesToAdd) {
195 auto U = FileToVector(Path);
196 auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
197 WriteToFile(U, NewPath);
198 Files.push_back(NewPath);
kccd701d9e2019-05-23 00:22:46 +0000199 CollectDFT(NewPath);
kcc6526f1d2019-02-14 00:25:43 +0000200 }
kcc6526f1d2019-02-14 00:25:43 +0000201 Features.insert(NewFeatures.begin(), NewFeatures.end());
kcc98a86242019-02-15 00:08:16 +0000202 Cov.insert(NewCov.begin(), NewCov.end());
kcc9c0ed932019-02-15 01:22:00 +0000203 for (auto Idx : NewCov)
204 if (auto *TE = TPC.PCTableEntryByIdx(Idx))
205 if (TPC.PcIsFuncEntry(TE))
206 PrintPC(" NEW_FUNC: %p %F %L\n", "",
207 TPC.GetNextInstructionPc(TE->PC));
208
kcc55e54ed2019-02-15 21:51:15 +0000209 if (!FilesToAdd.empty() || Job->ExitCode != 0)
210 Printf("#%zd: cov: %zd ft: %zd corp: %zd exec/s %zd "
211 "oom/timeout/crash: %zd/%zd/%zd time: %zds\n", NumRuns,
kcc98a86242019-02-15 00:08:16 +0000212 Cov.size(), Features.size(), Files.size(),
kcc55e54ed2019-02-15 21:51:15 +0000213 Stats.average_exec_per_sec,
214 NumOOMs, NumTimeouts, NumCrashes, secondsSinceProcessStartUp());
kcc6526f1d2019-02-14 00:25:43 +0000215 }
kccd701d9e2019-05-23 00:22:46 +0000216
217
218 void CollectDFT(const std::string &InputPath) {
219 if (DataFlowBinary.empty()) return;
220 Command Cmd(Args);
221 Cmd.removeFlag("fork");
222 Cmd.removeFlag("runs");
223 Cmd.addFlag("data_flow_trace", DFTDir);
224 Cmd.addArgument(InputPath);
225 for (auto &C : CorpusDirs) // Remove all corpora from the args.
226 Cmd.removeArgument(C);
227 Cmd.setOutputFile(DirPlusFile(TempDir, "dft.log"));
228 Cmd.combineOutAndErr();
229 // Printf("CollectDFT: %s %s\n", InputPath.c_str(), Cmd.toString().c_str());
230 ExecuteCommand(Cmd);
231 }
232
kcc64bcb922019-02-13 04:04:45 +0000233};
234
kcc6526f1d2019-02-14 00:25:43 +0000235struct JobQueue {
236 std::queue<FuzzJob *> Qu;
237 std::mutex Mu;
kcc64bcb922019-02-13 04:04:45 +0000238
kcc6526f1d2019-02-14 00:25:43 +0000239 void Push(FuzzJob *Job) {
240 std::lock_guard<std::mutex> Lock(Mu);
241 Qu.push(Job);
kcc64bcb922019-02-13 04:04:45 +0000242 }
kcc6526f1d2019-02-14 00:25:43 +0000243 FuzzJob *Pop() {
244 std::lock_guard<std::mutex> Lock(Mu);
245 if (Qu.empty()) return nullptr;
246 auto Job = Qu.front();
247 Qu.pop();
248 return Job;
249 }
250};
251
252void WorkerThread(std::atomic<bool> *Stop, JobQueue *FuzzQ, JobQueue *MergeQ) {
kccb1fa9e02019-02-14 01:11:29 +0000253 while (!Stop->load()) {
kcc6526f1d2019-02-14 00:25:43 +0000254 auto Job = FuzzQ->Pop();
255 // Printf("WorkerThread: job %p\n", Job);
256 if (!Job) {
257 SleepSeconds(1);
258 continue;
259 }
260 Job->ExitCode = ExecuteCommand(Job->Cmd);
261 MergeQ->Push(Job);
262 }
kcc64bcb922019-02-13 04:04:45 +0000263}
264
kcc2e6ca5c2019-02-12 22:48:55 +0000265// This is just a skeleton of an experimental -fork=1 feature.
266void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
267 const Vector<std::string> &Args,
kcc6526f1d2019-02-14 00:25:43 +0000268 const Vector<std::string> &CorpusDirs, int NumJobs) {
kcc55e54ed2019-02-15 21:51:15 +0000269 Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs);
kcc2e6ca5c2019-02-12 22:48:55 +0000270
kcc64bcb922019-02-13 04:04:45 +0000271 GlobalEnv Env;
kcc6526f1d2019-02-14 00:25:43 +0000272 Env.Args = Args;
273 Env.CorpusDirs = CorpusDirs;
274 Env.Rand = &Rand;
275 Env.Verbosity = Options.Verbosity;
kcc55e54ed2019-02-15 21:51:15 +0000276 Env.ProcessStartTime = std::chrono::system_clock::now();
kccd701d9e2019-05-23 00:22:46 +0000277 Env.DataFlowBinary = Options.CollectDataFlow;
kcc64bcb922019-02-13 04:04:45 +0000278
kcc2e6ca5c2019-02-12 22:48:55 +0000279 Vector<SizedFile> SeedFiles;
280 for (auto &Dir : CorpusDirs)
281 GetSizedFilesFromDir(Dir, &SeedFiles);
282 std::sort(SeedFiles.begin(), SeedFiles.end());
kcc6526f1d2019-02-14 00:25:43 +0000283 Env.TempDir = TempPath(".dir");
kccd701d9e2019-05-23 00:22:46 +0000284 Env.DFTDir = DirPlusFile(Env.TempDir, "DFT");
kcc6526f1d2019-02-14 00:25:43 +0000285 RmDirRecursive(Env.TempDir); // in case there is a leftover from old runs.
286 MkDir(Env.TempDir);
kccd701d9e2019-05-23 00:22:46 +0000287 MkDir(Env.DFTDir);
kcc2e6ca5c2019-02-12 22:48:55 +0000288
kcc2e6ca5c2019-02-12 22:48:55 +0000289
kcc64bcb922019-02-13 04:04:45 +0000290 if (CorpusDirs.empty())
kcc6526f1d2019-02-14 00:25:43 +0000291 MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
kcc64bcb922019-02-13 04:04:45 +0000292 else
293 Env.MainCorpusDir = CorpusDirs[0];
294
kcc6526f1d2019-02-14 00:25:43 +0000295 auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
296 CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, {}, &Env.Features,
kcc98a86242019-02-15 00:08:16 +0000297 {}, &Env.Cov,
kcc64bcb922019-02-13 04:04:45 +0000298 CFPath, false);
kccd701d9e2019-05-23 00:22:46 +0000299 for (auto &F : Env.Files)
300 Env.CollectDFT(F);
301
kcc64bcb922019-02-13 04:04:45 +0000302 RemoveFile(CFPath);
kcc55e54ed2019-02-15 21:51:15 +0000303 Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs,
304 Env.Files.size(), Env.TempDir.c_str());
kcc64bcb922019-02-13 04:04:45 +0000305
kcc2e6ca5c2019-02-12 22:48:55 +0000306 int ExitCode = 0;
kcc64bcb922019-02-13 04:04:45 +0000307
kcc6526f1d2019-02-14 00:25:43 +0000308 JobQueue FuzzQ, MergeQ;
309 std::atomic<bool> Stop(false);
kcc64bcb922019-02-13 04:04:45 +0000310
kcc6526f1d2019-02-14 00:25:43 +0000311 size_t JobId = 1;
312 Vector<std::thread> Threads;
313 for (int t = 0; t < NumJobs; t++) {
314 Threads.push_back(std::thread(WorkerThread, &Stop, &FuzzQ, &MergeQ));
315 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc2e6ca5c2019-02-12 22:48:55 +0000316 }
317
kcc55e54ed2019-02-15 21:51:15 +0000318 while (true) {
kccedefdf32019-02-16 00:14:16 +0000319 std::unique_ptr<FuzzJob> Job(MergeQ.Pop());
kcc6526f1d2019-02-14 00:25:43 +0000320 if (!Job) {
kcc55e54ed2019-02-15 21:51:15 +0000321 if (Stop)
322 break;
kcc6526f1d2019-02-14 00:25:43 +0000323 SleepSeconds(1);
324 continue;
325 }
326 ExitCode = Job->ExitCode;
kccedefdf32019-02-16 00:14:16 +0000327 if (ExitCode == Options.InterruptExitCode) {
328 Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
329 Stop = true;
330 break;
331 }
kcc1c5afe22019-04-13 01:57:33 +0000332 Fuzzer::MaybeExitGracefully();
kccedefdf32019-02-16 00:14:16 +0000333
334 Env.RunOneMergeJob(Job.get());
kcc6526f1d2019-02-14 00:25:43 +0000335
336 // Continue if our crash is one of the ignorred ones.
337 if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000338 Env.NumTimeouts++;
kcc6526f1d2019-02-14 00:25:43 +0000339 else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000340 Env.NumOOMs++;
kcc6526f1d2019-02-14 00:25:43 +0000341 else if (ExitCode != 0) {
kcc55e54ed2019-02-15 21:51:15 +0000342 Env.NumCrashes++;
343 if (Options.IgnoreCrashes) {
344 std::ifstream In(Job->LogPath);
345 std::string Line;
346 while (std::getline(In, Line, '\n'))
kcc18b370a2019-04-12 20:20:57 +0000347 if (Line.find("ERROR:") != Line.npos ||
348 Line.find("runtime error:") != Line.npos)
kcc55e54ed2019-02-15 21:51:15 +0000349 Printf("%s\n", Line.c_str());
350 } else {
351 // And exit if we don't ignore this crash.
352 Printf("INFO: log from the inner process:\n%s",
353 FileToString(Job->LogPath).c_str());
354 Stop = true;
355 }
kcc6526f1d2019-02-14 00:25:43 +0000356 }
kcc55e54ed2019-02-15 21:51:15 +0000357
358 // Stop if we are over the time budget.
359 // This is not precise, since other threads are still running
360 // and we will wait while joining them.
361 // We also don't stop instantly: other jobs need to finish.
362 if (Options.MaxTotalTimeSec > 0 && !Stop &&
363 Env.secondsSinceProcessStartUp() >= (size_t)Options.MaxTotalTimeSec) {
364 Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
365 Env.secondsSinceProcessStartUp());
366 Stop = true;
367 }
morehousea3f53122019-04-16 17:38:19 +0000368 if (!Stop && Env.NumRuns >= Options.MaxNumberOfRuns) {
kcc18b370a2019-04-12 20:20:57 +0000369 Printf("INFO: fuzzed for %zd iterations, wrapping up soon\n",
370 Env.NumRuns);
371 Stop = true;
372 }
kcc55e54ed2019-02-15 21:51:15 +0000373
374 if (!Stop)
375 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc6526f1d2019-02-14 00:25:43 +0000376 }
377 Stop = true;
378
379 for (auto &T : Threads)
380 T.join();
381
metzmane847d8a2019-02-27 19:27:16 +0000382 // The workers have terminated. Don't try to remove the directory before they
383 // terminate to avoid a race condition preventing cleanup on Windows.
384 RmDirRecursive(Env.TempDir);
385
kcc2e6ca5c2019-02-12 22:48:55 +0000386 // Use the exit code from the last child process.
kcc55e54ed2019-02-15 21:51:15 +0000387 Printf("INFO: exiting: %d time: %zds\n", ExitCode,
388 Env.secondsSinceProcessStartUp());
kcc2e6ca5c2019-02-12 22:48:55 +0000389 exit(ExitCode);
390}
391
392} // namespace fuzzer