blob: 9f315e8c1253e7b73790843e5fe33e107337b591 [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) {
kcc1c5afe22019-04-13 01:57:33 +0000153 Vector<SizedFile> TempFiles, MergeCandidates;
154 // Read all newly created inputs and their feature sets.
155 // Choose only those inputs that have new features.
kcc6526f1d2019-02-14 00:25:43 +0000156 GetSizedFilesFromDir(Job->CorpusDir, &TempFiles);
kcc1c5afe22019-04-13 01:57:33 +0000157 std::sort(TempFiles.begin(), TempFiles.end());
158 for (auto &F : TempFiles) {
159 auto FeatureFile = F.File;
160 FeatureFile.replace(0, Job->CorpusDir.size(), Job->FeaturesDir);
161 auto FeatureBytes = FileToVector(FeatureFile, 0, false);
162 assert((FeatureBytes.size() % sizeof(uint32_t)) == 0);
163 Vector<uint32_t> NewFeatures(FeatureBytes.size() / sizeof(uint32_t));
164 memcpy(NewFeatures.data(), FeatureBytes.data(), FeatureBytes.size());
165 for (auto Ft : NewFeatures) {
166 if (!Features.count(Ft)) {
167 MergeCandidates.push_back(F);
168 break;
169 }
170 }
171 }
172 if (MergeCandidates.empty()) return;
kcc6526f1d2019-02-14 00:25:43 +0000173
174 Vector<std::string> FilesToAdd;
kcc98a86242019-02-15 00:08:16 +0000175 Set<uint32_t> NewFeatures, NewCov;
kcc1c5afe22019-04-13 01:57:33 +0000176 CrashResistantMerge(Args, {}, MergeCandidates, &FilesToAdd, Features,
kcc98a86242019-02-15 00:08:16 +0000177 &NewFeatures, Cov, &NewCov, Job->CFPath, false);
kcc6526f1d2019-02-14 00:25:43 +0000178 for (auto &Path : FilesToAdd) {
179 auto U = FileToVector(Path);
180 auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
181 WriteToFile(U, NewPath);
182 Files.push_back(NewPath);
183 }
kcc6526f1d2019-02-14 00:25:43 +0000184 Features.insert(NewFeatures.begin(), NewFeatures.end());
kcc98a86242019-02-15 00:08:16 +0000185 Cov.insert(NewCov.begin(), NewCov.end());
kcc9c0ed932019-02-15 01:22:00 +0000186 for (auto Idx : NewCov)
187 if (auto *TE = TPC.PCTableEntryByIdx(Idx))
188 if (TPC.PcIsFuncEntry(TE))
189 PrintPC(" NEW_FUNC: %p %F %L\n", "",
190 TPC.GetNextInstructionPc(TE->PC));
191
kccdd391142019-02-14 21:09:32 +0000192 auto Stats = ParseFinalStatsFromLog(Job->LogPath);
193 NumRuns += Stats.number_of_executed_units;
kcc55e54ed2019-02-15 21:51:15 +0000194 if (!FilesToAdd.empty() || Job->ExitCode != 0)
195 Printf("#%zd: cov: %zd ft: %zd corp: %zd exec/s %zd "
196 "oom/timeout/crash: %zd/%zd/%zd time: %zds\n", NumRuns,
kcc98a86242019-02-15 00:08:16 +0000197 Cov.size(), Features.size(), Files.size(),
kcc55e54ed2019-02-15 21:51:15 +0000198 Stats.average_exec_per_sec,
199 NumOOMs, NumTimeouts, NumCrashes, secondsSinceProcessStartUp());
kcc6526f1d2019-02-14 00:25:43 +0000200 }
kcc64bcb922019-02-13 04:04:45 +0000201};
202
kcc6526f1d2019-02-14 00:25:43 +0000203struct JobQueue {
204 std::queue<FuzzJob *> Qu;
205 std::mutex Mu;
kcc64bcb922019-02-13 04:04:45 +0000206
kcc6526f1d2019-02-14 00:25:43 +0000207 void Push(FuzzJob *Job) {
208 std::lock_guard<std::mutex> Lock(Mu);
209 Qu.push(Job);
kcc64bcb922019-02-13 04:04:45 +0000210 }
kcc6526f1d2019-02-14 00:25:43 +0000211 FuzzJob *Pop() {
212 std::lock_guard<std::mutex> Lock(Mu);
213 if (Qu.empty()) return nullptr;
214 auto Job = Qu.front();
215 Qu.pop();
216 return Job;
217 }
218};
219
220void WorkerThread(std::atomic<bool> *Stop, JobQueue *FuzzQ, JobQueue *MergeQ) {
kccb1fa9e02019-02-14 01:11:29 +0000221 while (!Stop->load()) {
kcc6526f1d2019-02-14 00:25:43 +0000222 auto Job = FuzzQ->Pop();
223 // Printf("WorkerThread: job %p\n", Job);
224 if (!Job) {
225 SleepSeconds(1);
226 continue;
227 }
228 Job->ExitCode = ExecuteCommand(Job->Cmd);
229 MergeQ->Push(Job);
230 }
kcc64bcb922019-02-13 04:04:45 +0000231}
232
kcc2e6ca5c2019-02-12 22:48:55 +0000233// This is just a skeleton of an experimental -fork=1 feature.
234void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
235 const Vector<std::string> &Args,
kcc6526f1d2019-02-14 00:25:43 +0000236 const Vector<std::string> &CorpusDirs, int NumJobs) {
kcc55e54ed2019-02-15 21:51:15 +0000237 Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs);
kcc2e6ca5c2019-02-12 22:48:55 +0000238
kcc64bcb922019-02-13 04:04:45 +0000239 GlobalEnv Env;
kcc6526f1d2019-02-14 00:25:43 +0000240 Env.Args = Args;
241 Env.CorpusDirs = CorpusDirs;
242 Env.Rand = &Rand;
243 Env.Verbosity = Options.Verbosity;
kcc55e54ed2019-02-15 21:51:15 +0000244 Env.ProcessStartTime = std::chrono::system_clock::now();
kcc64bcb922019-02-13 04:04:45 +0000245
kcc2e6ca5c2019-02-12 22:48:55 +0000246 Vector<SizedFile> SeedFiles;
247 for (auto &Dir : CorpusDirs)
248 GetSizedFilesFromDir(Dir, &SeedFiles);
249 std::sort(SeedFiles.begin(), SeedFiles.end());
kcc6526f1d2019-02-14 00:25:43 +0000250 Env.TempDir = TempPath(".dir");
251 RmDirRecursive(Env.TempDir); // in case there is a leftover from old runs.
252 MkDir(Env.TempDir);
kcc2e6ca5c2019-02-12 22:48:55 +0000253
kcc2e6ca5c2019-02-12 22:48:55 +0000254
kcc64bcb922019-02-13 04:04:45 +0000255 if (CorpusDirs.empty())
kcc6526f1d2019-02-14 00:25:43 +0000256 MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
kcc64bcb922019-02-13 04:04:45 +0000257 else
258 Env.MainCorpusDir = CorpusDirs[0];
259
kcc6526f1d2019-02-14 00:25:43 +0000260 auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
261 CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, {}, &Env.Features,
kcc98a86242019-02-15 00:08:16 +0000262 {}, &Env.Cov,
kcc64bcb922019-02-13 04:04:45 +0000263 CFPath, false);
264 RemoveFile(CFPath);
kcc55e54ed2019-02-15 21:51:15 +0000265 Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs,
266 Env.Files.size(), Env.TempDir.c_str());
kcc64bcb922019-02-13 04:04:45 +0000267
kcc2e6ca5c2019-02-12 22:48:55 +0000268 int ExitCode = 0;
kcc64bcb922019-02-13 04:04:45 +0000269
kcc6526f1d2019-02-14 00:25:43 +0000270 JobQueue FuzzQ, MergeQ;
271 std::atomic<bool> Stop(false);
kcc64bcb922019-02-13 04:04:45 +0000272
kcc6526f1d2019-02-14 00:25:43 +0000273 size_t JobId = 1;
274 Vector<std::thread> Threads;
275 for (int t = 0; t < NumJobs; t++) {
276 Threads.push_back(std::thread(WorkerThread, &Stop, &FuzzQ, &MergeQ));
277 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc2e6ca5c2019-02-12 22:48:55 +0000278 }
279
kcc55e54ed2019-02-15 21:51:15 +0000280 while (true) {
kccedefdf32019-02-16 00:14:16 +0000281 std::unique_ptr<FuzzJob> Job(MergeQ.Pop());
kcc6526f1d2019-02-14 00:25:43 +0000282 if (!Job) {
kcc55e54ed2019-02-15 21:51:15 +0000283 if (Stop)
284 break;
kcc6526f1d2019-02-14 00:25:43 +0000285 SleepSeconds(1);
286 continue;
287 }
288 ExitCode = Job->ExitCode;
kccedefdf32019-02-16 00:14:16 +0000289 if (ExitCode == Options.InterruptExitCode) {
290 Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
291 Stop = true;
292 break;
293 }
kcc1c5afe22019-04-13 01:57:33 +0000294 Fuzzer::MaybeExitGracefully();
kccedefdf32019-02-16 00:14:16 +0000295
296 Env.RunOneMergeJob(Job.get());
kcc6526f1d2019-02-14 00:25:43 +0000297
298 // Continue if our crash is one of the ignorred ones.
299 if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000300 Env.NumTimeouts++;
kcc6526f1d2019-02-14 00:25:43 +0000301 else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000302 Env.NumOOMs++;
kcc6526f1d2019-02-14 00:25:43 +0000303 else if (ExitCode != 0) {
kcc55e54ed2019-02-15 21:51:15 +0000304 Env.NumCrashes++;
305 if (Options.IgnoreCrashes) {
306 std::ifstream In(Job->LogPath);
307 std::string Line;
308 while (std::getline(In, Line, '\n'))
kcc18b370a2019-04-12 20:20:57 +0000309 if (Line.find("ERROR:") != Line.npos ||
310 Line.find("runtime error:") != Line.npos)
kcc55e54ed2019-02-15 21:51:15 +0000311 Printf("%s\n", Line.c_str());
312 } else {
313 // And exit if we don't ignore this crash.
314 Printf("INFO: log from the inner process:\n%s",
315 FileToString(Job->LogPath).c_str());
316 Stop = true;
317 }
kcc6526f1d2019-02-14 00:25:43 +0000318 }
kcc55e54ed2019-02-15 21:51:15 +0000319
320 // Stop if we are over the time budget.
321 // This is not precise, since other threads are still running
322 // and we will wait while joining them.
323 // We also don't stop instantly: other jobs need to finish.
324 if (Options.MaxTotalTimeSec > 0 && !Stop &&
325 Env.secondsSinceProcessStartUp() >= (size_t)Options.MaxTotalTimeSec) {
326 Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
327 Env.secondsSinceProcessStartUp());
328 Stop = true;
329 }
kcc18b370a2019-04-12 20:20:57 +0000330 if (Options.MaxNumberOfRuns >= 0 && !Stop &&
331 Env.NumRuns >= Options.MaxNumberOfRuns) {
332 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