blob: 58a228bc3df6b2e85639b059a2e74192eef65825 [file] [log] [blame]
Kostya Serebryany111e1d62016-12-09 01:17:24 +00001//===- FuzzerMerge.cpp - merging corpora ----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// Merging corpora.
10//===----------------------------------------------------------------------===//
11
12#include "FuzzerInternal.h"
13#include "FuzzerIO.h"
14#include "FuzzerMerge.h"
15#include "FuzzerTracePC.h"
16#include "FuzzerUtil.h"
17
18#include <fstream>
Marcos Pividoric21b3c92016-12-13 17:46:48 +000019#include <iterator>
Kostya Serebryany81d17442017-03-11 02:26:20 +000020#include <set>
Kostya Serebryany111e1d62016-12-09 01:17:24 +000021#include <sstream>
22
23namespace fuzzer {
24
25bool Merger::Parse(const std::string &Str, bool ParseCoverage) {
26 std::istringstream SS(Str);
27 return Parse(SS, ParseCoverage);
28}
29
30void Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) {
31 if (!Parse(IS, ParseCoverage)) {
32 Printf("MERGE: failed to parse the control file (unexpected error)\n");
33 exit(1);
34 }
35}
36
37// The control file example:
38//
39// 3 # The number of inputs
40// 1 # The number of inputs in the first corpus, <= the previous number
41// file0
42// file1
43// file2 # One file name per line.
44// STARTED 0 123 # FileID, file size
45// DONE 0 1 4 6 8 # FileID COV1 COV2 ...
46// STARTED 1 456 # If DONE is missing, the input crashed while processing.
47// STARTED 2 567
48// DONE 2 8 9
49bool Merger::Parse(std::istream &IS, bool ParseCoverage) {
50 LastFailure.clear();
51 std::string Line;
52
53 // Parse NumFiles.
54 if (!std::getline(IS, Line, '\n')) return false;
55 std::istringstream L1(Line);
56 size_t NumFiles = 0;
57 L1 >> NumFiles;
58 if (NumFiles == 0 || NumFiles > 10000000) return false;
59
60 // Parse NumFilesInFirstCorpus.
61 if (!std::getline(IS, Line, '\n')) return false;
62 std::istringstream L2(Line);
63 NumFilesInFirstCorpus = NumFiles + 1;
64 L2 >> NumFilesInFirstCorpus;
65 if (NumFilesInFirstCorpus > NumFiles) return false;
66
67 // Parse file names.
68 Files.resize(NumFiles);
69 for (size_t i = 0; i < NumFiles; i++)
70 if (!std::getline(IS, Files[i].Name, '\n'))
71 return false;
72
73 // Parse STARTED and DONE lines.
74 size_t ExpectedStartMarker = 0;
75 const size_t kInvalidStartMarker = -1;
76 size_t LastSeenStartMarker = kInvalidStartMarker;
Kostya Serebryany5dfa9642017-03-11 02:50:47 +000077 std::vector<uint32_t> TmpFeatures;
Kostya Serebryany111e1d62016-12-09 01:17:24 +000078 while (std::getline(IS, Line, '\n')) {
79 std::istringstream ISS1(Line);
80 std::string Marker;
81 size_t N;
82 ISS1 >> Marker;
83 ISS1 >> N;
84 if (Marker == "STARTED") {
85 // STARTED FILE_ID FILE_SIZE
86 if (ExpectedStartMarker != N)
87 return false;
88 ISS1 >> Files[ExpectedStartMarker].Size;
89 LastSeenStartMarker = ExpectedStartMarker;
90 assert(ExpectedStartMarker < Files.size());
91 ExpectedStartMarker++;
92 } else if (Marker == "DONE") {
Kostya Serebryany81d17442017-03-11 02:26:20 +000093 // DONE FILE_ID COV1 COV2 COV3 ...
Kostya Serebryany111e1d62016-12-09 01:17:24 +000094 size_t CurrentFileIdx = N;
95 if (CurrentFileIdx != LastSeenStartMarker)
96 return false;
97 LastSeenStartMarker = kInvalidStartMarker;
98 if (ParseCoverage) {
Kostya Serebryany5dfa9642017-03-11 02:50:47 +000099 TmpFeatures.clear(); // use a vector from outer scope to avoid resizes.
Kostya Serebryany1e438a12016-12-17 08:20:24 +0000100 while (ISS1 >> std::hex >> N)
Kostya Serebryany5dfa9642017-03-11 02:50:47 +0000101 TmpFeatures.push_back(N);
102 std::sort(TmpFeatures.begin(), TmpFeatures.end());
103 Files[CurrentFileIdx].Features = TmpFeatures;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000104 }
105 } else {
106 return false;
107 }
108 }
109 if (LastSeenStartMarker != kInvalidStartMarker)
110 LastFailure = Files[LastSeenStartMarker].Name;
111
112 FirstNotProcessedFile = ExpectedStartMarker;
113 return true;
114}
115
Kostya Serebryany81d17442017-03-11 02:26:20 +0000116size_t Merger::ApproximateMemoryConsumption() const {
117 size_t Res = 0;
118 for (const auto &F: Files)
119 Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
120 return Res;
121}
122
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000123// Decides which files need to be merged (add thost to NewFiles).
124// Returns the number of new features added.
125size_t Merger::Merge(std::vector<std::string> *NewFiles) {
126 NewFiles->clear();
127 assert(NumFilesInFirstCorpus <= Files.size());
Kostya Serebryany1e438a12016-12-17 08:20:24 +0000128 std::set<uint32_t> AllFeatures;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000129
130 // What features are in the initial corpus?
131 for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
132 auto &Cur = Files[i].Features;
133 AllFeatures.insert(Cur.begin(), Cur.end());
134 }
135 size_t InitialNumFeatures = AllFeatures.size();
136
137 // Remove all features that we already know from all other inputs.
138 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
139 auto &Cur = Files[i].Features;
Kostya Serebryany1e438a12016-12-17 08:20:24 +0000140 std::vector<uint32_t> Tmp;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000141 std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
142 AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
143 Cur.swap(Tmp);
144 }
145
146 // Sort. Give preference to
147 // * smaller files
148 // * files with more features.
149 std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
150 [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
151 if (a.Size != b.Size)
152 return a.Size < b.Size;
153 return a.Features.size() > b.Features.size();
154 });
155
156 // One greedy pass: add the file's features to AllFeatures.
157 // If new features were added, add this file to NewFiles.
158 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
159 auto &Cur = Files[i].Features;
160 // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
161 // Files[i].Size, Cur.size());
162 size_t OldSize = AllFeatures.size();
163 AllFeatures.insert(Cur.begin(), Cur.end());
164 if (AllFeatures.size() > OldSize)
165 NewFiles->push_back(Files[i].Name);
166 }
167 return AllFeatures.size() - InitialNumFeatures;
168}
169
170// Inner process. May crash if the target crashes.
171void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
172 Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
173 Merger M;
174 std::ifstream IF(CFPath);
175 M.ParseOrExit(IF, false);
176 IF.close();
177 if (!M.LastFailure.empty())
178 Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
179 M.LastFailure.c_str());
180
181 Printf("MERGE-INNER: %zd total files;"
182 " %zd processed earlier; will process %zd files now\n",
183 M.Files.size(), M.FirstNotProcessedFile,
184 M.Files.size() - M.FirstNotProcessedFile);
185
186 std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
187 for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
188 auto U = FileToVector(M.Files[i].Name);
Kostya Serebryany628b43a2016-12-15 06:21:21 +0000189 if (U.size() > MaxInputLen) {
190 U.resize(MaxInputLen);
Kostya Serebryanyd4be8892016-12-12 20:39:35 +0000191 U.shrink_to_fit();
192 }
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000193 std::ostringstream StartedLine;
194 // Write the pre-run marker.
195 OF << "STARTED " << std::dec << i << " " << U.size() << "\n";
196 OF.flush(); // Flush is important since ExecuteCommand may crash.
197 // Run.
198 TPC.ResetMaps();
199 ExecuteCallback(U.data(), U.size());
200 // Collect coverage.
201 std::set<size_t> Features;
202 TPC.CollectFeatures([&](size_t Feature) -> bool {
203 Features.insert(Feature);
204 return true;
205 });
206 // Show stats.
207 TotalNumberOfRuns++;
208 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
209 PrintStats("pulse ");
210 // Write the post-run marker and the coverage.
211 OF << "DONE " << i;
212 for (size_t F : Features)
213 OF << " " << std::hex << F;
214 OF << "\n";
215 }
216}
217
218// Outer process. Does not call the target code and thus sohuld not fail.
219void Fuzzer::CrashResistantMerge(const std::vector<std::string> &Args,
220 const std::vector<std::string> &Corpora) {
221 if (Corpora.size() <= 1) {
222 Printf("Merge requires two or more corpus dirs\n");
223 return;
224 }
225 std::vector<std::string> AllFiles;
226 ListFilesInDirRecursive(Corpora[0], nullptr, &AllFiles, /*TopDir*/true);
227 size_t NumFilesInFirstCorpus = AllFiles.size();
228 for (size_t i = 1; i < Corpora.size(); i++)
229 ListFilesInDirRecursive(Corpora[i], nullptr, &AllFiles, /*TopDir*/true);
230 Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n",
231 AllFiles.size(), NumFilesInFirstCorpus);
Kostya Serebryany26482432017-01-05 04:32:19 +0000232 auto CFPath = DirPlusFile(TmpDir(),
233 "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000234 // Write the control file.
Marcos Pividori7c1defd2016-12-13 17:46:40 +0000235 RemoveFile(CFPath);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000236 std::ofstream ControlFile(CFPath);
237 ControlFile << AllFiles.size() << "\n";
238 ControlFile << NumFilesInFirstCorpus << "\n";
239 for (auto &Path: AllFiles)
240 ControlFile << Path << "\n";
Kostya Serebryany4aa05902017-01-05 22:05:47 +0000241 if (!ControlFile) {
242 Printf("MERGE-OUTER: failed to write to the control file: %s\n",
243 CFPath.c_str());
244 exit(1);
245 }
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000246 ControlFile.close();
247
248 // Execute the inner process untill it passes.
249 // Every inner process should execute at least one input.
250 std::string BaseCmd = CloneArgsWithoutX(Args, "keep-all-flags");
Kostya Serebryany9d0f02a2017-01-18 00:55:29 +0000251 bool Success = false;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000252 for (size_t i = 1; i <= AllFiles.size(); i++) {
253 Printf("MERGE-OUTER: attempt %zd\n", i);
254 auto ExitCode =
255 ExecuteCommand(BaseCmd + " -merge_control_file=" + CFPath);
256 if (!ExitCode) {
257 Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", i);
Kostya Serebryany9d0f02a2017-01-18 00:55:29 +0000258 Success = true;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000259 break;
260 }
261 }
Kostya Serebryany9d0f02a2017-01-18 00:55:29 +0000262 if (!Success) {
263 Printf("MERGE-OUTER: zero succesfull attempts, exiting\n");
264 exit(1);
265 }
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000266 // Read the control file and do the merge.
267 Merger M;
268 std::ifstream IF(CFPath);
Kostya Serebryany4aa05902017-01-05 22:05:47 +0000269 IF.seekg(0, IF.end);
270 Printf("MERGE-OUTER: the control file has %zd bytes\n", (size_t)IF.tellg());
271 IF.seekg(0, IF.beg);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000272 M.ParseOrExit(IF, true);
273 IF.close();
Kostya Serebryany5dfa9642017-03-11 02:50:47 +0000274 Printf("MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n",
275 M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb());
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000276 std::vector<std::string> NewFiles;
277 size_t NumNewFeatures = M.Merge(&NewFiles);
278 Printf("MERGE-OUTER: %zd new files with %zd new features added\n",
279 NewFiles.size(), NumNewFeatures);
280 for (auto &F: NewFiles)
281 WriteToOutputCorpus(FileToVector(F));
282 // We are done, delete the control file.
Marcos Pividori7c1defd2016-12-13 17:46:40 +0000283 RemoveFile(CFPath);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000284}
285
286} // namespace fuzzer