blob: 7c82f3f046e288db68e0d4a8033c0be694017fe5 [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"
14#include "FuzzerMerge.h"
15#include "FuzzerSHA1.h"
16#include "FuzzerUtil.h"
17
kccb1fa9e02019-02-14 01:11:29 +000018#include <atomic>
kccdd391142019-02-14 21:09:32 +000019#include <fstream>
kcc6526f1d2019-02-14 00:25:43 +000020#include <mutex>
kcc6526f1d2019-02-14 00:25:43 +000021#include <queue>
kccdd391142019-02-14 21:09:32 +000022#include <sstream>
23#include <thread>
kcc6526f1d2019-02-14 00:25:43 +000024
kcc2e6ca5c2019-02-12 22:48:55 +000025namespace fuzzer {
26
kccdd391142019-02-14 21:09:32 +000027struct Stats {
28 size_t number_of_executed_units = 0;
29 size_t peak_rss_mb = 0;
30 size_t average_exec_per_sec = 0;
31};
32
33static Stats ParseFinalStatsFromLog(const std::string &LogPath) {
34 std::ifstream In(LogPath);
35 std::string Line;
36 Stats Res;
37 struct {
38 const char *Name;
39 size_t *Var;
40 } NameVarPairs[] = {
41 {"stat::number_of_executed_units:", &Res.number_of_executed_units},
42 {"stat::peak_rss_mb:", &Res.peak_rss_mb},
43 {"stat::average_exec_per_sec:", &Res.average_exec_per_sec},
44 {nullptr, nullptr},
45 };
46 while (std::getline(In, Line, '\n')) {
47 if (Line.find("stat::") != 0) continue;
48 std::istringstream ISS(Line);
49 std::string Name;
50 size_t Val;
51 ISS >> Name >> Val;
52 for (size_t i = 0; NameVarPairs[i].Name; i++)
53 if (Name == NameVarPairs[i].Name)
54 *NameVarPairs[i].Var = Val;
55 }
56 return Res;
57}
58
kcc64bcb922019-02-13 04:04:45 +000059struct FuzzJob {
60 // Inputs.
61 Command Cmd;
kcc64bcb922019-02-13 04:04:45 +000062 std::string CorpusDir;
63 std::string LogPath;
64 std::string CFPath;
kcc64bcb922019-02-13 04:04:45 +000065
66 // Fuzzing Outputs.
67 int ExitCode;
68};
69
70struct GlobalEnv {
kcc6526f1d2019-02-14 00:25:43 +000071 Vector<std::string> Args;
72 Vector<std::string> CorpusDirs;
kcc64bcb922019-02-13 04:04:45 +000073 std::string MainCorpusDir;
kcc6526f1d2019-02-14 00:25:43 +000074 std::string TempDir;
kcc64bcb922019-02-13 04:04:45 +000075 Set<uint32_t> Features;
76 Vector<std::string> Files;
kcc6526f1d2019-02-14 00:25:43 +000077 Random *Rand;
78 int Verbosity = 0;
79
kccdd391142019-02-14 21:09:32 +000080 size_t NumRuns = 0;
81
kcc6526f1d2019-02-14 00:25:43 +000082 FuzzJob *CreateNewJob(size_t JobId) {
83 Command Cmd(Args);
84 Cmd.removeFlag("fork");
85 for (auto &C : CorpusDirs) // Remove all corpora from the args.
86 Cmd.removeArgument(C);
87 Cmd.addFlag("reload", "0"); // working in an isolated dir, no reload.
kccdd391142019-02-14 21:09:32 +000088 Cmd.addFlag("print_final_stats", "1");
kcc6526f1d2019-02-14 00:25:43 +000089 Cmd.addFlag("max_total_time", std::to_string(std::min((size_t)300, JobId)));
90
91 auto Job = new FuzzJob;
92 std::string Seeds;
93 if (size_t CorpusSubsetSize = std::min(Files.size(), (size_t)100))
94 for (size_t i = 0; i < CorpusSubsetSize; i++)
95 Seeds += (Seeds.empty() ? "" : ",") +
96 Files[Rand->SkewTowardsLast(Files.size())];
97 if (!Seeds.empty())
98 Cmd.addFlag("seed_inputs", Seeds);
99 Job->LogPath = DirPlusFile(TempDir, std::to_string(JobId) + ".log");
100 Job->CorpusDir = DirPlusFile(TempDir, "C" + std::to_string(JobId));
101 Job->CFPath = DirPlusFile(TempDir, std::to_string(JobId) + ".merge");
102
103
104 Cmd.addArgument(Job->CorpusDir);
105 RmDirRecursive(Job->CorpusDir);
106 MkDir(Job->CorpusDir);
107
108 Cmd.setOutputFile(Job->LogPath);
109 Cmd.combineOutAndErr();
110
111 Job->Cmd = Cmd;
112
113 if (Verbosity >= 2)
114 Printf("Job %zd/%p Created: %s\n", JobId, Job,
115 Job->Cmd.toString().c_str());
116 // Start from very short runs and gradually increase them.
117 return Job;
118 }
119
120 void RunOneMergeJob(FuzzJob *Job) {
121 Vector<SizedFile> TempFiles;
122 GetSizedFilesFromDir(Job->CorpusDir, &TempFiles);
123
124 Vector<std::string> FilesToAdd;
125 Set<uint32_t> NewFeatures;
126 CrashResistantMerge(Args, {}, TempFiles, &FilesToAdd, Features,
127 &NewFeatures, Job->CFPath, false);
128 RemoveFile(Job->CFPath);
129 for (auto &Path : FilesToAdd) {
130 auto U = FileToVector(Path);
131 auto NewPath = DirPlusFile(MainCorpusDir, Hash(U));
132 WriteToFile(U, NewPath);
133 Files.push_back(NewPath);
134 }
kcc6526f1d2019-02-14 00:25:43 +0000135 RmDirRecursive(Job->CorpusDir);
136 Features.insert(NewFeatures.begin(), NewFeatures.end());
kccdd391142019-02-14 21:09:32 +0000137 auto Stats = ParseFinalStatsFromLog(Job->LogPath);
138 NumRuns += Stats.number_of_executed_units;
139 if (!FilesToAdd.empty())
140 Printf("#%zd: ft: %zd corp: %zd exec/s %zd\n", NumRuns,
141 Features.size(), Files.size(),
142 Stats.average_exec_per_sec);
kcc6526f1d2019-02-14 00:25:43 +0000143 }
kcc64bcb922019-02-13 04:04:45 +0000144};
145
kcc6526f1d2019-02-14 00:25:43 +0000146struct JobQueue {
147 std::queue<FuzzJob *> Qu;
148 std::mutex Mu;
kcc64bcb922019-02-13 04:04:45 +0000149
kcc6526f1d2019-02-14 00:25:43 +0000150 void Push(FuzzJob *Job) {
151 std::lock_guard<std::mutex> Lock(Mu);
152 Qu.push(Job);
kcc64bcb922019-02-13 04:04:45 +0000153 }
kcc6526f1d2019-02-14 00:25:43 +0000154 FuzzJob *Pop() {
155 std::lock_guard<std::mutex> Lock(Mu);
156 if (Qu.empty()) return nullptr;
157 auto Job = Qu.front();
158 Qu.pop();
159 return Job;
160 }
161};
162
163void WorkerThread(std::atomic<bool> *Stop, JobQueue *FuzzQ, JobQueue *MergeQ) {
kccb1fa9e02019-02-14 01:11:29 +0000164 while (!Stop->load()) {
kcc6526f1d2019-02-14 00:25:43 +0000165 auto Job = FuzzQ->Pop();
166 // Printf("WorkerThread: job %p\n", Job);
167 if (!Job) {
168 SleepSeconds(1);
169 continue;
170 }
171 Job->ExitCode = ExecuteCommand(Job->Cmd);
172 MergeQ->Push(Job);
173 }
kcc64bcb922019-02-13 04:04:45 +0000174}
175
kcc2e6ca5c2019-02-12 22:48:55 +0000176// This is just a skeleton of an experimental -fork=1 feature.
177void FuzzWithFork(Random &Rand, const FuzzingOptions &Options,
178 const Vector<std::string> &Args,
kcc6526f1d2019-02-14 00:25:43 +0000179 const Vector<std::string> &CorpusDirs, int NumJobs) {
180 Printf("INFO: -fork=%d: doing fuzzing in a separate process in order to "
181 "be more resistant to crashes, timeouts, and OOMs\n", NumJobs);
kcc2e6ca5c2019-02-12 22:48:55 +0000182
kcc64bcb922019-02-13 04:04:45 +0000183 GlobalEnv Env;
kcc6526f1d2019-02-14 00:25:43 +0000184 Env.Args = Args;
185 Env.CorpusDirs = CorpusDirs;
186 Env.Rand = &Rand;
187 Env.Verbosity = Options.Verbosity;
kcc64bcb922019-02-13 04:04:45 +0000188
kcc2e6ca5c2019-02-12 22:48:55 +0000189 Vector<SizedFile> SeedFiles;
190 for (auto &Dir : CorpusDirs)
191 GetSizedFilesFromDir(Dir, &SeedFiles);
192 std::sort(SeedFiles.begin(), SeedFiles.end());
kcc6526f1d2019-02-14 00:25:43 +0000193 Env.TempDir = TempPath(".dir");
194 RmDirRecursive(Env.TempDir); // in case there is a leftover from old runs.
195 MkDir(Env.TempDir);
kcc2e6ca5c2019-02-12 22:48:55 +0000196
kcc2e6ca5c2019-02-12 22:48:55 +0000197
kcc64bcb922019-02-13 04:04:45 +0000198 if (CorpusDirs.empty())
kcc6526f1d2019-02-14 00:25:43 +0000199 MkDir(Env.MainCorpusDir = DirPlusFile(Env.TempDir, "C"));
kcc64bcb922019-02-13 04:04:45 +0000200 else
201 Env.MainCorpusDir = CorpusDirs[0];
202
kcc6526f1d2019-02-14 00:25:43 +0000203 auto CFPath = DirPlusFile(Env.TempDir, "merge.txt");
204 CrashResistantMerge(Env.Args, {}, SeedFiles, &Env.Files, {}, &Env.Features,
kcc64bcb922019-02-13 04:04:45 +0000205 CFPath, false);
206 RemoveFile(CFPath);
kcc6526f1d2019-02-14 00:25:43 +0000207 Printf("INFO: -fork=%d: %zd seeds, starting to fuzz; scratch: %s\n",
208 NumJobs, Env.Files.size(), Env.TempDir.c_str());
kcc64bcb922019-02-13 04:04:45 +0000209
kcc2e6ca5c2019-02-12 22:48:55 +0000210 int ExitCode = 0;
kcc64bcb922019-02-13 04:04:45 +0000211
kcc6526f1d2019-02-14 00:25:43 +0000212 JobQueue FuzzQ, MergeQ;
213 std::atomic<bool> Stop(false);
kcc64bcb922019-02-13 04:04:45 +0000214
kcc6526f1d2019-02-14 00:25:43 +0000215 size_t JobId = 1;
216 Vector<std::thread> Threads;
217 for (int t = 0; t < NumJobs; t++) {
218 Threads.push_back(std::thread(WorkerThread, &Stop, &FuzzQ, &MergeQ));
219 FuzzQ.Push(Env.CreateNewJob(JobId++));
kcc2e6ca5c2019-02-12 22:48:55 +0000220 }
221
kcc6526f1d2019-02-14 00:25:43 +0000222 while (!Stop) {
223 auto Job = MergeQ.Pop();
224 if (!Job) {
225 SleepSeconds(1);
226 continue;
227 }
228 ExitCode = Job->ExitCode;
229 if (ExitCode != Options.InterruptExitCode)
230 Env.RunOneMergeJob(Job);
231
232 // Continue if our crash is one of the ignorred ones.
233 if (Options.IgnoreTimeouts && ExitCode == Options.TimeoutExitCode)
234 ;
235 else if (Options.IgnoreOOMs && ExitCode == Options.OOMExitCode)
236 ;
237 else if (ExitCode == Options.InterruptExitCode)
238 Stop = true;
239 else if (ExitCode != 0) {
240 // And exit if we don't ignore this crash.
241 Printf("INFO: log from the inner process:\n%s",
242 FileToString(Job->LogPath).c_str());
243 Stop = true;
244 }
245 RemoveFile(Job->LogPath);
246 delete Job;
247 FuzzQ.Push(Env.CreateNewJob(JobId++));
248 }
249 Stop = true;
250
251 for (auto &T : Threads)
252 T.join();
253
254 RmDirRecursive(Env.TempDir);
kcc2e6ca5c2019-02-12 22:48:55 +0000255
256 // Use the exit code from the last child process.
257 Printf("Fork: exiting: %d\n", ExitCode);
258 exit(ExitCode);
259}
260
261} // namespace fuzzer
262