blob: 9d338aa47084fc7e910b3ba70cf144099b94e9af [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;
69 std::string CFPath;
kcc64bcb922019-02-13 04:04:45 +000070
71 // Fuzzing Outputs.
72 int ExitCode;
kccedefdf32019-02-16 00:14:16 +000073
74 ~FuzzJob() {
75 RemoveFile(CFPath);
76 RemoveFile(LogPath);
77 RmDirRecursive(CorpusDir);
kcc1c5afe22019-04-13 01:57:33 +000078 RmDirRecursive(FeaturesDir);
kccedefdf32019-02-16 00:14:16 +000079 }
kcc64bcb922019-02-13 04:04:45 +000080};
81
82struct GlobalEnv {
kcc6526f1d2019-02-14 00:25:43 +000083 Vector<std::string> Args;
84 Vector<std::string> CorpusDirs;
kcc64bcb922019-02-13 04:04:45 +000085 std::string MainCorpusDir;
kcc6526f1d2019-02-14 00:25:43 +000086 std::string TempDir;
kcc98a86242019-02-15 00:08:16 +000087 Set<uint32_t> Features, Cov;
kcc64bcb922019-02-13 04:04:45 +000088 Vector<std::string> Files;
kcc6526f1d2019-02-14 00:25:43 +000089 Random *Rand;
kcc55e54ed2019-02-15 21:51:15 +000090 std::chrono::system_clock::time_point ProcessStartTime;
kcc6526f1d2019-02-14 00:25:43 +000091 int Verbosity = 0;
92
kcc55e54ed2019-02-15 21:51:15 +000093 size_t NumTimeouts = 0;
94 size_t NumOOMs = 0;
95 size_t NumCrashes = 0;
96
97
kccdd391142019-02-14 21:09:32 +000098 size_t NumRuns = 0;
99
kcc55e54ed2019-02-15 21:51:15 +0000100 size_t secondsSinceProcessStartUp() const {
101 return std::chrono::duration_cast<std::chrono::seconds>(
102 std::chrono::system_clock::now() - ProcessStartTime)
103 .count();
104 }
105
kcc6526f1d2019-02-14 00:25:43 +0000106 FuzzJob *CreateNewJob(size_t JobId) {
107 Command Cmd(Args);
108 Cmd.removeFlag("fork");
kcc18b370a2019-04-12 20:20:57 +0000109 Cmd.removeFlag("runs");
kcc6526f1d2019-02-14 00:25:43 +0000110 for (auto &C : CorpusDirs) // Remove all corpora from the args.
111 Cmd.removeArgument(C);
112 Cmd.addFlag("reload", "0"); // working in an isolated dir, no reload.
kccdd391142019-02-14 21:09:32 +0000113 Cmd.addFlag("print_final_stats", "1");
kcc9c0ed932019-02-15 01:22:00 +0000114 Cmd.addFlag("print_funcs", "0"); // no need to spend time symbolizing.
kcc6526f1d2019-02-14 00:25:43 +0000115 Cmd.addFlag("max_total_time", std::to_string(std::min((size_t)300, JobId)));
116
117 auto Job = new FuzzJob;
118 std::string Seeds;
kcc9c0ed932019-02-15 01:22:00 +0000119 if (size_t CorpusSubsetSize =
120 std::min(Files.size(), (size_t)sqrt(Files.size() + 2)))
kcc6526f1d2019-02-14 00:25:43 +0000121 for (size_t i = 0; i < CorpusSubsetSize; i++)
122 Seeds += (Seeds.empty() ? "" : ",") +
123 Files[Rand->SkewTowardsLast(Files.size())];
124 if (!Seeds.empty())
125 Cmd.addFlag("seed_inputs", Seeds);
126 Job->LogPath = DirPlusFile(TempDir, std::to_string(JobId) + ".log");
127 Job->CorpusDir = DirPlusFile(TempDir, "C" + std::to_string(JobId));
kcc1c5afe22019-04-13 01:57:33 +0000128 Job->FeaturesDir = DirPlusFile(TempDir, "F" + std::to_string(JobId));
kcc6526f1d2019-02-14 00:25:43 +0000129 Job->CFPath = DirPlusFile(TempDir, std::to_string(JobId) + ".merge");
130
131
132 Cmd.addArgument(Job->CorpusDir);
kcc1c5afe22019-04-13 01:57:33 +0000133 Cmd.addFlag("features_dir", Job->FeaturesDir);
134
135 for (auto &D : {Job->CorpusDir, Job->FeaturesDir}) {
136 RmDirRecursive(D);
137 MkDir(D);
138 }
kcc6526f1d2019-02-14 00:25:43 +0000139
140 Cmd.setOutputFile(Job->LogPath);
141 Cmd.combineOutAndErr();
142
143 Job->Cmd = Cmd;
144
145 if (Verbosity >= 2)
146 Printf("Job %zd/%p Created: %s\n", JobId, Job,
147 Job->Cmd.toString().c_str());
148 // Start from very short runs and gradually increase them.
149 return Job;
150 }
151
152 void RunOneMergeJob(FuzzJob *Job) {
kcce5ef7c02019-04-19 01:39:14 +0000153 auto Stats = ParseFinalStatsFromLog(Job->LogPath);
154 NumRuns += Stats.number_of_executed_units;
155
kcc1c5afe22019-04-13 01:57:33 +0000156 Vector<SizedFile> TempFiles, MergeCandidates;
157 // Read all newly created inputs and their feature sets.
158 // Choose only those inputs that have new features.
kcc6526f1d2019-02-14 00:25:43 +0000159 GetSizedFilesFromDir(Job->CorpusDir, &TempFiles);
kcc1c5afe22019-04-13 01:57:33 +0000160 std::sort(TempFiles.begin(), TempFiles.end());
161 for (auto &F : TempFiles) {
162 auto FeatureFile = F.File;
163 FeatureFile.replace(0, Job->CorpusDir.size(), Job->FeaturesDir);
164 auto FeatureBytes = FileToVector(FeatureFile, 0, false);
165 assert((FeatureBytes.size() % sizeof(uint32_t)) == 0);
166 Vector<uint32_t> NewFeatures(FeatureBytes.size() / sizeof(uint32_t));
167 memcpy(NewFeatures.data(), FeatureBytes.data(), FeatureBytes.size());
168 for (auto Ft : NewFeatures) {
169 if (!Features.count(Ft)) {
170 MergeCandidates.push_back(F);
171 break;
172 }
173 }
174 }
175 if (MergeCandidates.empty()) return;
kcc6526f1d2019-02-14 00:25:43 +0000176
177 Vector<std::string> FilesToAdd;
kcc98a86242019-02-15 00:08:16 +0000178 Set<uint32_t> NewFeatures, NewCov;
kcc1c5afe22019-04-13 01:57:33 +0000179 CrashResistantMerge(Args, {}, MergeCandidates, &FilesToAdd, Features,
kcc98a86242019-02-15 00:08:16 +0000180 &NewFeatures, Cov, &NewCov, Job->CFPath, false);
kcc6526f1d2019-02-14 00:25:43 +0000181 for (auto &Path : FilesToAdd) {
182 auto U = FileToVector(Path);
183 auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
184 WriteToFile(U, NewPath);
185 Files.push_back(NewPath);
186 }
kcc6526f1d2019-02-14 00:25:43 +0000187 Features.insert(NewFeatures.begin(), NewFeatures.end());
kcc98a86242019-02-15 00:08:16 +0000188 Cov.insert(NewCov.begin(), NewCov.end());
kcc9c0ed932019-02-15 01:22:00 +0000189 for (auto Idx : NewCov)
190 if (auto *TE = TPC.PCTableEntryByIdx(Idx))
191 if (TPC.PcIsFuncEntry(TE))
192 PrintPC(" NEW_FUNC: %p %F %L\n", "",
193 TPC.GetNextInstructionPc(TE->PC));
194
kcc55e54ed2019-02-15 21:51:15 +0000195 if (!FilesToAdd.empty() || Job->ExitCode != 0)
196 Printf("#%zd: cov: %zd ft: %zd corp: %zd exec/s %zd "
197 "oom/timeout/crash: %zd/%zd/%zd time: %zds\n", NumRuns,
kcc98a86242019-02-15 00:08:16 +0000198 Cov.size(), Features.size(), Files.size(),
kcc55e54ed2019-02-15 21:51:15 +0000199 Stats.average_exec_per_sec,
200 NumOOMs, NumTimeouts, NumCrashes, secondsSinceProcessStartUp());
kcc6526f1d2019-02-14 00:25:43 +0000201 }
kcc64bcb922019-02-13 04:04:45 +0000202};
203
kcc6526f1d2019-02-14 00:25:43 +0000204struct JobQueue {
205 std::queue<FuzzJob *> Qu;
206 std::mutex Mu;
kcc64bcb922019-02-13 04:04:45 +0000207
kcc6526f1d2019-02-14 00:25:43 +0000208 void Push(FuzzJob *Job) {
209 std::lock_guard<std::mutex> Lock(Mu);
210 Qu.push(Job);
kcc64bcb922019-02-13 04:04:45 +0000211 }
kcc6526f1d2019-02-14 00:25:43 +0000212 FuzzJob *Pop() {
213 std::lock_guard<std::mutex> Lock(Mu);
214 if (Qu.empty()) return nullptr;
215 auto Job = Qu.front();
216 Qu.pop();
217 return Job;
218 }
219};
220
221void WorkerThread(std::atomic<bool> *Stop, JobQueue *FuzzQ, JobQueue *MergeQ) {
kccb1fa9e02019-02-14 01:11:29 +0000222 while (!Stop->load()) {
kcc6526f1d2019-02-14 00:25:43 +0000223 auto Job = FuzzQ->Pop();
224 // Printf("WorkerThread: job %p\n", Job);
225 if (!Job) {
226 SleepSeconds(1);
227 continue;
228 }
229 Job->ExitCode = ExecuteCommand(Job->Cmd);
230 MergeQ->Push(Job);
231 }
kcc64bcb922019-02-13 04:04:45 +0000232}
233
kcc2e6ca5c2019-02-12 22:48:55 +0000234// This is just a skeleton of an experimental -fork=1 feature.
235void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
236 const Vector<std::string> &Args,
kcc6526f1d2019-02-14 00:25:43 +0000237 const Vector<std::string> &CorpusDirs, int NumJobs) {
kcc55e54ed2019-02-15 21:51:15 +0000238 Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs);
kcc2e6ca5c2019-02-12 22:48:55 +0000239
kcc64bcb922019-02-13 04:04:45 +0000240 GlobalEnv Env;
kcc6526f1d2019-02-14 00:25:43 +0000241 Env.Args = Args;
242 Env.CorpusDirs = CorpusDirs;
243 Env.Rand = &Rand;
244 Env.Verbosity = Options.Verbosity;
kcc55e54ed2019-02-15 21:51:15 +0000245 Env.ProcessStartTime = std::chrono::system_clock::now();
kcc64bcb922019-02-13 04:04:45 +0000246
kcc2e6ca5c2019-02-12 22:48:55 +0000247 Vector<SizedFile> SeedFiles;
248 for (auto &Dir : CorpusDirs)
249 GetSizedFilesFromDir(Dir, &SeedFiles);
250 std::sort(SeedFiles.begin(), SeedFiles.end());
kcc6526f1d2019-02-14 00:25:43 +0000251 Env.TempDir = TempPath(".dir");
252 RmDirRecursive(Env.TempDir); // in case there is a leftover from old runs.
253 MkDir(Env.TempDir);
kcc2e6ca5c2019-02-12 22:48:55 +0000254
kcc2e6ca5c2019-02-12 22:48:55 +0000255
kcc64bcb922019-02-13 04:04:45 +0000256 if (CorpusDirs.empty())
kcc6526f1d2019-02-14 00:25:43 +0000257 MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
kcc64bcb922019-02-13 04:04:45 +0000258 else
259 Env.MainCorpusDir = CorpusDirs[0];
260
kcc6526f1d2019-02-14 00:25:43 +0000261 auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
262 CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, {}, &Env.Features,
kcc98a86242019-02-15 00:08:16 +0000263 {}, &Env.Cov,
kcc64bcb922019-02-13 04:04:45 +0000264 CFPath, false);
265 RemoveFile(CFPath);
kcc55e54ed2019-02-15 21:51:15 +0000266 Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs,
267 Env.Files.size(), Env.TempDir.c_str());
kcc64bcb922019-02-13 04:04:45 +0000268
kcc2e6ca5c2019-02-12 22:48:55 +0000269 int ExitCode = 0;
kcc64bcb922019-02-13 04:04:45 +0000270
kcc6526f1d2019-02-14 00:25:43 +0000271 JobQueue FuzzQ, MergeQ;
272 std::atomic<bool> Stop(false);
kcc64bcb922019-02-13 04:04:45 +0000273
kcc6526f1d2019-02-14 00:25:43 +0000274 size_t JobId = 1;
275 Vector<std::thread> Threads;
276 for (int t = 0; t < NumJobs; t++) {
277 Threads.push_back(std::thread(WorkerThread, &Stop, &FuzzQ, &MergeQ));
278 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc2e6ca5c2019-02-12 22:48:55 +0000279 }
280
kcc55e54ed2019-02-15 21:51:15 +0000281 while (true) {
kccedefdf32019-02-16 00:14:16 +0000282 std::unique_ptr<FuzzJob> Job(MergeQ.Pop());
kcc6526f1d2019-02-14 00:25:43 +0000283 if (!Job) {
kcc55e54ed2019-02-15 21:51:15 +0000284 if (Stop)
285 break;
kcc6526f1d2019-02-14 00:25:43 +0000286 SleepSeconds(1);
287 continue;
288 }
289 ExitCode = Job->ExitCode;
kccedefdf32019-02-16 00:14:16 +0000290 if (ExitCode == Options.InterruptExitCode) {
291 Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
292 Stop = true;
293 break;
294 }
kcc1c5afe22019-04-13 01:57:33 +0000295 Fuzzer::MaybeExitGracefully();
kccedefdf32019-02-16 00:14:16 +0000296
297 Env.RunOneMergeJob(Job.get());
kcc6526f1d2019-02-14 00:25:43 +0000298
299 // Continue if our crash is one of the ignorred ones.
300 if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000301 Env.NumTimeouts++;
kcc6526f1d2019-02-14 00:25:43 +0000302 else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000303 Env.NumOOMs++;
kcc6526f1d2019-02-14 00:25:43 +0000304 else if (ExitCode != 0) {
kcc55e54ed2019-02-15 21:51:15 +0000305 Env.NumCrashes++;
306 if (Options.IgnoreCrashes) {
307 std::ifstream In(Job->LogPath);
308 std::string Line;
309 while (std::getline(In, Line, '\n'))
kcc18b370a2019-04-12 20:20:57 +0000310 if (Line.find("ERROR:") != Line.npos ||
311 Line.find("runtime error:") != Line.npos)
kcc55e54ed2019-02-15 21:51:15 +0000312 Printf("%s\n", Line.c_str());
313 } else {
314 // And exit if we don't ignore this crash.
315 Printf("INFO: log from the inner process:\n%s",
316 FileToString(Job->LogPath).c_str());
317 Stop = true;
318 }
kcc6526f1d2019-02-14 00:25:43 +0000319 }
kcc55e54ed2019-02-15 21:51:15 +0000320
321 // Stop if we are over the time budget.
322 // This is not precise, since other threads are still running
323 // and we will wait while joining them.
324 // We also don't stop instantly: other jobs need to finish.
325 if (Options.MaxTotalTimeSec > 0 && !Stop &&
326 Env.secondsSinceProcessStartUp() >= (size_t)Options.MaxTotalTimeSec) {
327 Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
328 Env.secondsSinceProcessStartUp());
329 Stop = true;
330 }
morehousea3f53122019-04-16 17:38:19 +0000331 if (!Stop && Env.NumRuns >= Options.MaxNumberOfRuns) {
kcc18b370a2019-04-12 20:20:57 +0000332 Printf("INFO: fuzzed for %zd iterations, wrapping up soon\n",
333 Env.NumRuns);
334 Stop = true;
335 }
kcc55e54ed2019-02-15 21:51:15 +0000336
337 if (!Stop)
338 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc6526f1d2019-02-14 00:25:43 +0000339 }
340 Stop = true;
341
342 for (auto &T : Threads)
343 T.join();
344
metzmane847d8a2019-02-27 19:27:16 +0000345 // The workers have terminated. Don't try to remove the directory before they
346 // terminate to avoid a race condition preventing cleanup on Windows.
347 RmDirRecursive(Env.TempDir);
348
kcc2e6ca5c2019-02-12 22:48:55 +0000349 // Use the exit code from the last child process.
kcc55e54ed2019-02-15 21:51:15 +0000350 Printf("INFO: exiting: %d time: %zds\n", ExitCode,
351 Env.secondsSinceProcessStartUp());
kcc2e6ca5c2019-02-12 22:48:55 +0000352 exit(ExitCode);
353}
354
355} // namespace fuzzer