blob: dd16ec1e2884089f4d66c178bd453e88fd3501a6 [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;
kcc98a86242019-02-15 00:08:16 +000089 Set<uint32_t> Features, Cov;
kcc64bcb922019-02-13 04:04:45 +000090 Vector<std::string> Files;
kcc6526f1d2019-02-14 00:25:43 +000091 Random *Rand;
kcc55e54ed2019-02-15 21:51:15 +000092 std::chrono::system_clock::time_point ProcessStartTime;
kcc6526f1d2019-02-14 00:25:43 +000093 int Verbosity = 0;
94
kcc55e54ed2019-02-15 21:51:15 +000095 size_t NumTimeouts = 0;
96 size_t NumOOMs = 0;
97 size_t NumCrashes = 0;
98
99
kccdd391142019-02-14 21:09:32 +0000100 size_t NumRuns = 0;
101
kcc55e54ed2019-02-15 21:51:15 +0000102 size_t secondsSinceProcessStartUp() const {
103 return std::chrono::duration_cast<std::chrono::seconds>(
104 std::chrono::system_clock::now() - ProcessStartTime)
105 .count();
106 }
107
kcc6526f1d2019-02-14 00:25:43 +0000108 FuzzJob *CreateNewJob(size_t JobId) {
109 Command Cmd(Args);
110 Cmd.removeFlag("fork");
kcc18b370a2019-04-12 20:20:57 +0000111 Cmd.removeFlag("runs");
kcc6526f1d2019-02-14 00:25:43 +0000112 for (auto &C : CorpusDirs) // Remove all corpora from the args.
113 Cmd.removeArgument(C);
114 Cmd.addFlag("reload", "0"); // working in an isolated dir, no reload.
kccdd391142019-02-14 21:09:32 +0000115 Cmd.addFlag("print_final_stats", "1");
kcc9c0ed932019-02-15 01:22:00 +0000116 Cmd.addFlag("print_funcs", "0"); // no need to spend time symbolizing.
kcc6526f1d2019-02-14 00:25:43 +0000117 Cmd.addFlag("max_total_time", std::to_string(std::min((size_t)300, JobId)));
118
119 auto Job = new FuzzJob;
120 std::string Seeds;
kcc9c0ed932019-02-15 01:22:00 +0000121 if (size_t CorpusSubsetSize =
122 std::min(Files.size(), (size_t)sqrt(Files.size() + 2)))
kcc6526f1d2019-02-14 00:25:43 +0000123 for (size_t i = 0; i < CorpusSubsetSize; i++)
124 Seeds += (Seeds.empty() ? "" : ",") +
125 Files[Rand->SkewTowardsLast(Files.size())];
metzmane9b95bc2019-04-30 20:56:18 +0000126 if (!Seeds.empty()) {
127 Job->SeedListPath = std::to_string(JobId) + ".seeds";
128 WriteToFile(Seeds, Job->SeedListPath);
129 Cmd.addFlag("seed_inputs", "@" + Job->SeedListPath);
130 }
kcc6526f1d2019-02-14 00:25:43 +0000131 Job->LogPath = DirPlusFile(TempDir, std::to_string(JobId) + ".log");
132 Job->CorpusDir = DirPlusFile(TempDir, "C" + std::to_string(JobId));
kcc1c5afe22019-04-13 01:57:33 +0000133 Job->FeaturesDir = DirPlusFile(TempDir, "F" + std::to_string(JobId));
kcc6526f1d2019-02-14 00:25:43 +0000134 Job->CFPath = DirPlusFile(TempDir, std::to_string(JobId) + ".merge");
135
136
137 Cmd.addArgument(Job->CorpusDir);
kcc1c5afe22019-04-13 01:57:33 +0000138 Cmd.addFlag("features_dir", Job->FeaturesDir);
139
140 for (auto &D : {Job->CorpusDir, Job->FeaturesDir}) {
141 RmDirRecursive(D);
142 MkDir(D);
143 }
kcc6526f1d2019-02-14 00:25:43 +0000144
145 Cmd.setOutputFile(Job->LogPath);
146 Cmd.combineOutAndErr();
147
148 Job->Cmd = Cmd;
149
150 if (Verbosity >= 2)
151 Printf("Job %zd/%p Created: %s\n", JobId, Job,
152 Job->Cmd.toString().c_str());
153 // Start from very short runs and gradually increase them.
154 return Job;
155 }
156
157 void RunOneMergeJob(FuzzJob *Job) {
kcce5ef7c02019-04-19 01:39:14 +0000158 auto Stats = ParseFinalStatsFromLog(Job->LogPath);
159 NumRuns += Stats.number_of_executed_units;
160
kcc1c5afe22019-04-13 01:57:33 +0000161 Vector<SizedFile> TempFiles, MergeCandidates;
162 // Read all newly created inputs and their feature sets.
163 // Choose only those inputs that have new features.
kcc6526f1d2019-02-14 00:25:43 +0000164 GetSizedFilesFromDir(Job->CorpusDir, &TempFiles);
kcc1c5afe22019-04-13 01:57:33 +0000165 std::sort(TempFiles.begin(), TempFiles.end());
166 for (auto &F : TempFiles) {
167 auto FeatureFile = F.File;
168 FeatureFile.replace(0, Job->CorpusDir.size(), Job->FeaturesDir);
169 auto FeatureBytes = FileToVector(FeatureFile, 0, false);
170 assert((FeatureBytes.size() % sizeof(uint32_t)) == 0);
171 Vector<uint32_t> NewFeatures(FeatureBytes.size() / sizeof(uint32_t));
172 memcpy(NewFeatures.data(), FeatureBytes.data(), FeatureBytes.size());
173 for (auto Ft : NewFeatures) {
174 if (!Features.count(Ft)) {
175 MergeCandidates.push_back(F);
176 break;
177 }
178 }
179 }
180 if (MergeCandidates.empty()) return;
kcc6526f1d2019-02-14 00:25:43 +0000181
182 Vector<std::string> FilesToAdd;
kcc98a86242019-02-15 00:08:16 +0000183 Set<uint32_t> NewFeatures, NewCov;
kcc1c5afe22019-04-13 01:57:33 +0000184 CrashResistantMerge(Args, {}, MergeCandidates, &FilesToAdd, Features,
kcc98a86242019-02-15 00:08:16 +0000185 &NewFeatures, Cov, &NewCov, Job->CFPath, false);
kcc6526f1d2019-02-14 00:25:43 +0000186 for (auto &Path : FilesToAdd) {
187 auto U = FileToVector(Path);
188 auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
189 WriteToFile(U, NewPath);
190 Files.push_back(NewPath);
191 }
kcc6526f1d2019-02-14 00:25:43 +0000192 Features.insert(NewFeatures.begin(), NewFeatures.end());
kcc98a86242019-02-15 00:08:16 +0000193 Cov.insert(NewCov.begin(), NewCov.end());
kcc9c0ed932019-02-15 01:22:00 +0000194 for (auto Idx : NewCov)
195 if (auto *TE = TPC.PCTableEntryByIdx(Idx))
196 if (TPC.PcIsFuncEntry(TE))
197 PrintPC(" NEW_FUNC: %p %F %L\n", "",
198 TPC.GetNextInstructionPc(TE->PC));
199
kcc55e54ed2019-02-15 21:51:15 +0000200 if (!FilesToAdd.empty() || Job->ExitCode != 0)
201 Printf("#%zd: cov: %zd ft: %zd corp: %zd exec/s %zd "
202 "oom/timeout/crash: %zd/%zd/%zd time: %zds\n", NumRuns,
kcc98a86242019-02-15 00:08:16 +0000203 Cov.size(), Features.size(), Files.size(),
kcc55e54ed2019-02-15 21:51:15 +0000204 Stats.average_exec_per_sec,
205 NumOOMs, NumTimeouts, NumCrashes, secondsSinceProcessStartUp());
kcc6526f1d2019-02-14 00:25:43 +0000206 }
kcc64bcb922019-02-13 04:04:45 +0000207};
208
kcc6526f1d2019-02-14 00:25:43 +0000209struct JobQueue {
210 std::queue<FuzzJob *> Qu;
211 std::mutex Mu;
kcc64bcb922019-02-13 04:04:45 +0000212
kcc6526f1d2019-02-14 00:25:43 +0000213 void Push(FuzzJob *Job) {
214 std::lock_guard<std::mutex> Lock(Mu);
215 Qu.push(Job);
kcc64bcb922019-02-13 04:04:45 +0000216 }
kcc6526f1d2019-02-14 00:25:43 +0000217 FuzzJob *Pop() {
218 std::lock_guard<std::mutex> Lock(Mu);
219 if (Qu.empty()) return nullptr;
220 auto Job = Qu.front();
221 Qu.pop();
222 return Job;
223 }
224};
225
226void WorkerThread(std::atomic<bool> *Stop, JobQueue *FuzzQ, JobQueue *MergeQ) {
kccb1fa9e02019-02-14 01:11:29 +0000227 while (!Stop->load()) {
kcc6526f1d2019-02-14 00:25:43 +0000228 auto Job = FuzzQ->Pop();
229 // Printf("WorkerThread: job %p\n", Job);
230 if (!Job) {
231 SleepSeconds(1);
232 continue;
233 }
234 Job->ExitCode = ExecuteCommand(Job->Cmd);
235 MergeQ->Push(Job);
236 }
kcc64bcb922019-02-13 04:04:45 +0000237}
238
kcc2e6ca5c2019-02-12 22:48:55 +0000239// This is just a skeleton of an experimental -fork=1 feature.
240void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
241 const Vector<std::string> &Args,
kcc6526f1d2019-02-14 00:25:43 +0000242 const Vector<std::string> &CorpusDirs, int NumJobs) {
kcc55e54ed2019-02-15 21:51:15 +0000243 Printf("INFO: -fork=%d: fuzzing in separate process(s)\n", NumJobs);
kcc2e6ca5c2019-02-12 22:48:55 +0000244
kcc64bcb922019-02-13 04:04:45 +0000245 GlobalEnv Env;
kcc6526f1d2019-02-14 00:25:43 +0000246 Env.Args = Args;
247 Env.CorpusDirs = CorpusDirs;
248 Env.Rand = &Rand;
249 Env.Verbosity = Options.Verbosity;
kcc55e54ed2019-02-15 21:51:15 +0000250 Env.ProcessStartTime = std::chrono::system_clock::now();
kcc64bcb922019-02-13 04:04:45 +0000251
kcc2e6ca5c2019-02-12 22:48:55 +0000252 Vector<SizedFile> SeedFiles;
253 for (auto &Dir : CorpusDirs)
254 GetSizedFilesFromDir(Dir, &SeedFiles);
255 std::sort(SeedFiles.begin(), SeedFiles.end());
kcc6526f1d2019-02-14 00:25:43 +0000256 Env.TempDir = TempPath(".dir");
257 RmDirRecursive(Env.TempDir); // in case there is a leftover from old runs.
258 MkDir(Env.TempDir);
kcc2e6ca5c2019-02-12 22:48:55 +0000259
kcc2e6ca5c2019-02-12 22:48:55 +0000260
kcc64bcb922019-02-13 04:04:45 +0000261 if (CorpusDirs.empty())
kcc6526f1d2019-02-14 00:25:43 +0000262 MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
kcc64bcb922019-02-13 04:04:45 +0000263 else
264 Env.MainCorpusDir = CorpusDirs[0];
265
kcc6526f1d2019-02-14 00:25:43 +0000266 auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
267 CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, {}, &Env.Features,
kcc98a86242019-02-15 00:08:16 +0000268 {}, &Env.Cov,
kcc64bcb922019-02-13 04:04:45 +0000269 CFPath, false);
270 RemoveFile(CFPath);
kcc55e54ed2019-02-15 21:51:15 +0000271 Printf("INFO: -fork=%d: %zd seed inputs, starting to fuzz in %s\n", NumJobs,
272 Env.Files.size(), Env.TempDir.c_str());
kcc64bcb922019-02-13 04:04:45 +0000273
kcc2e6ca5c2019-02-12 22:48:55 +0000274 int ExitCode = 0;
kcc64bcb922019-02-13 04:04:45 +0000275
kcc6526f1d2019-02-14 00:25:43 +0000276 JobQueue FuzzQ, MergeQ;
277 std::atomic<bool> Stop(false);
kcc64bcb922019-02-13 04:04:45 +0000278
kcc6526f1d2019-02-14 00:25:43 +0000279 size_t JobId = 1;
280 Vector<std::thread> Threads;
281 for (int t = 0; t < NumJobs; t++) {
282 Threads.push_back(std::thread(WorkerThread, &Stop, &FuzzQ, &MergeQ));
283 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc2e6ca5c2019-02-12 22:48:55 +0000284 }
285
kcc55e54ed2019-02-15 21:51:15 +0000286 while (true) {
kccedefdf32019-02-16 00:14:16 +0000287 std::unique_ptr<FuzzJob> Job(MergeQ.Pop());
kcc6526f1d2019-02-14 00:25:43 +0000288 if (!Job) {
kcc55e54ed2019-02-15 21:51:15 +0000289 if (Stop)
290 break;
kcc6526f1d2019-02-14 00:25:43 +0000291 SleepSeconds(1);
292 continue;
293 }
294 ExitCode = Job->ExitCode;
kccedefdf32019-02-16 00:14:16 +0000295 if (ExitCode == Options.InterruptExitCode) {
296 Printf("==%lu== libFuzzer: a child was interrupted; exiting\n", GetPid());
297 Stop = true;
298 break;
299 }
kcc1c5afe22019-04-13 01:57:33 +0000300 Fuzzer::MaybeExitGracefully();
kccedefdf32019-02-16 00:14:16 +0000301
302 Env.RunOneMergeJob(Job.get());
kcc6526f1d2019-02-14 00:25:43 +0000303
304 // Continue if our crash is one of the ignorred ones.
305 if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000306 Env.NumTimeouts++;
kcc6526f1d2019-02-14 00:25:43 +0000307 else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
kcc55e54ed2019-02-15 21:51:15 +0000308 Env.NumOOMs++;
kcc6526f1d2019-02-14 00:25:43 +0000309 else if (ExitCode != 0) {
kcc55e54ed2019-02-15 21:51:15 +0000310 Env.NumCrashes++;
311 if (Options.IgnoreCrashes) {
312 std::ifstream In(Job->LogPath);
313 std::string Line;
314 while (std::getline(In, Line, '\n'))
kcc18b370a2019-04-12 20:20:57 +0000315 if (Line.find("ERROR:") != Line.npos ||
316 Line.find("runtime error:") != Line.npos)
kcc55e54ed2019-02-15 21:51:15 +0000317 Printf("%s\n", Line.c_str());
318 } else {
319 // And exit if we don't ignore this crash.
320 Printf("INFO: log from the inner process:\n%s",
321 FileToString(Job->LogPath).c_str());
322 Stop = true;
323 }
kcc6526f1d2019-02-14 00:25:43 +0000324 }
kcc55e54ed2019-02-15 21:51:15 +0000325
326 // Stop if we are over the time budget.
327 // This is not precise, since other threads are still running
328 // and we will wait while joining them.
329 // We also don't stop instantly: other jobs need to finish.
330 if (Options.MaxTotalTimeSec > 0 && !Stop &&
331 Env.secondsSinceProcessStartUp() >= (size_t)Options.MaxTotalTimeSec) {
332 Printf("INFO: fuzzed for %zd seconds, wrapping up soon\n",
333 Env.secondsSinceProcessStartUp());
334 Stop = true;
335 }
morehousea3f53122019-04-16 17:38:19 +0000336 if (!Stop && Env.NumRuns >= Options.MaxNumberOfRuns) {
kcc18b370a2019-04-12 20:20:57 +0000337 Printf("INFO: fuzzed for %zd iterations, wrapping up soon\n",
338 Env.NumRuns);
339 Stop = true;
340 }
kcc55e54ed2019-02-15 21:51:15 +0000341
342 if (!Stop)
343 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc6526f1d2019-02-14 00:25:43 +0000344 }
345 Stop = true;
346
347 for (auto &T : Threads)
348 T.join();
349
metzmane847d8a2019-02-27 19:27:16 +0000350 // The workers have terminated. Don't try to remove the directory before they
351 // terminate to avoid a race condition preventing cleanup on Windows.
352 RmDirRecursive(Env.TempDir);
353
kcc2e6ca5c2019-02-12 22:48:55 +0000354 // Use the exit code from the last child process.
kcc55e54ed2019-02-15 21:51:15 +0000355 Printf("INFO: exiting: %d time: %zds\n", ExitCode,
356 Env.secondsSinceProcessStartUp());
kcc2e6ca5c2019-02-12 22:48:55 +0000357 exit(ExitCode);
358}
359
360} // namespace fuzzer