blob: 5c17f66940a9d8f1b170a44d9179ef99a84c4b95 [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;
77 while (std::getline(IS, Line, '\n')) {
78 std::istringstream ISS1(Line);
79 std::string Marker;
80 size_t N;
81 ISS1 >> Marker;
82 ISS1 >> N;
83 if (Marker == "STARTED") {
84 // STARTED FILE_ID FILE_SIZE
85 if (ExpectedStartMarker != N)
86 return false;
87 ISS1 >> Files[ExpectedStartMarker].Size;
88 LastSeenStartMarker = ExpectedStartMarker;
89 assert(ExpectedStartMarker < Files.size());
90 ExpectedStartMarker++;
91 } else if (Marker == "DONE") {
Kostya Serebryany81d17442017-03-11 02:26:20 +000092 // DONE FILE_ID COV1 COV2 COV3 ...
Kostya Serebryany111e1d62016-12-09 01:17:24 +000093 size_t CurrentFileIdx = N;
94 if (CurrentFileIdx != LastSeenStartMarker)
95 return false;
96 LastSeenStartMarker = kInvalidStartMarker;
97 if (ParseCoverage) {
Kostya Serebryany1e438a12016-12-17 08:20:24 +000098 auto &V = Files[CurrentFileIdx].Features;
99 V.clear();
100 while (ISS1 >> std::hex >> N)
101 V.push_back(N);
102 std::sort(V.begin(), V.end());
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000103 }
104 } else {
105 return false;
106 }
107 }
108 if (LastSeenStartMarker != kInvalidStartMarker)
109 LastFailure = Files[LastSeenStartMarker].Name;
110
111 FirstNotProcessedFile = ExpectedStartMarker;
112 return true;
113}
114
Kostya Serebryany81d17442017-03-11 02:26:20 +0000115size_t Merger::ApproximateMemoryConsumption() const {
116 size_t Res = 0;
117 for (const auto &F: Files)
118 Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]);
119 return Res;
120}
121
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000122// Decides which files need to be merged (add thost to NewFiles).
123// Returns the number of new features added.
124size_t Merger::Merge(std::vector<std::string> *NewFiles) {
125 NewFiles->clear();
126 assert(NumFilesInFirstCorpus <= Files.size());
Kostya Serebryany1e438a12016-12-17 08:20:24 +0000127 std::set<uint32_t> AllFeatures;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000128
129 // What features are in the initial corpus?
130 for (size_t i = 0; i < NumFilesInFirstCorpus; i++) {
131 auto &Cur = Files[i].Features;
132 AllFeatures.insert(Cur.begin(), Cur.end());
133 }
134 size_t InitialNumFeatures = AllFeatures.size();
135
136 // Remove all features that we already know from all other inputs.
137 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
138 auto &Cur = Files[i].Features;
Kostya Serebryany1e438a12016-12-17 08:20:24 +0000139 std::vector<uint32_t> Tmp;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000140 std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(),
141 AllFeatures.end(), std::inserter(Tmp, Tmp.begin()));
142 Cur.swap(Tmp);
143 }
144
145 // Sort. Give preference to
146 // * smaller files
147 // * files with more features.
148 std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(),
149 [&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool {
150 if (a.Size != b.Size)
151 return a.Size < b.Size;
152 return a.Features.size() > b.Features.size();
153 });
154
155 // One greedy pass: add the file's features to AllFeatures.
156 // If new features were added, add this file to NewFiles.
157 for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) {
158 auto &Cur = Files[i].Features;
159 // Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(),
160 // Files[i].Size, Cur.size());
161 size_t OldSize = AllFeatures.size();
162 AllFeatures.insert(Cur.begin(), Cur.end());
163 if (AllFeatures.size() > OldSize)
164 NewFiles->push_back(Files[i].Name);
165 }
166 return AllFeatures.size() - InitialNumFeatures;
167}
168
169// Inner process. May crash if the target crashes.
170void Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) {
171 Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str());
172 Merger M;
173 std::ifstream IF(CFPath);
174 M.ParseOrExit(IF, false);
175 IF.close();
176 if (!M.LastFailure.empty())
177 Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n",
178 M.LastFailure.c_str());
179
180 Printf("MERGE-INNER: %zd total files;"
181 " %zd processed earlier; will process %zd files now\n",
182 M.Files.size(), M.FirstNotProcessedFile,
183 M.Files.size() - M.FirstNotProcessedFile);
184
185 std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app);
186 for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) {
187 auto U = FileToVector(M.Files[i].Name);
Kostya Serebryany628b43a2016-12-15 06:21:21 +0000188 if (U.size() > MaxInputLen) {
189 U.resize(MaxInputLen);
Kostya Serebryanyd4be8892016-12-12 20:39:35 +0000190 U.shrink_to_fit();
191 }
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000192 std::ostringstream StartedLine;
193 // Write the pre-run marker.
194 OF << "STARTED " << std::dec << i << " " << U.size() << "\n";
195 OF.flush(); // Flush is important since ExecuteCommand may crash.
196 // Run.
197 TPC.ResetMaps();
198 ExecuteCallback(U.data(), U.size());
199 // Collect coverage.
200 std::set<size_t> Features;
201 TPC.CollectFeatures([&](size_t Feature) -> bool {
202 Features.insert(Feature);
203 return true;
204 });
205 // Show stats.
206 TotalNumberOfRuns++;
207 if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1)))
208 PrintStats("pulse ");
209 // Write the post-run marker and the coverage.
210 OF << "DONE " << i;
211 for (size_t F : Features)
212 OF << " " << std::hex << F;
213 OF << "\n";
214 }
215}
216
217// Outer process. Does not call the target code and thus sohuld not fail.
218void Fuzzer::CrashResistantMerge(const std::vector<std::string> &Args,
219 const std::vector<std::string> &Corpora) {
220 if (Corpora.size() <= 1) {
221 Printf("Merge requires two or more corpus dirs\n");
222 return;
223 }
224 std::vector<std::string> AllFiles;
225 ListFilesInDirRecursive(Corpora[0], nullptr, &AllFiles, /*TopDir*/true);
226 size_t NumFilesInFirstCorpus = AllFiles.size();
227 for (size_t i = 1; i < Corpora.size(); i++)
228 ListFilesInDirRecursive(Corpora[i], nullptr, &AllFiles, /*TopDir*/true);
229 Printf("MERGE-OUTER: %zd files, %zd in the initial corpus\n",
230 AllFiles.size(), NumFilesInFirstCorpus);
Kostya Serebryany26482432017-01-05 04:32:19 +0000231 auto CFPath = DirPlusFile(TmpDir(),
232 "libFuzzerTemp." + std::to_string(GetPid()) + ".txt");
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000233 // Write the control file.
Marcos Pividori7c1defd2016-12-13 17:46:40 +0000234 RemoveFile(CFPath);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000235 std::ofstream ControlFile(CFPath);
236 ControlFile << AllFiles.size() << "\n";
237 ControlFile << NumFilesInFirstCorpus << "\n";
238 for (auto &Path: AllFiles)
239 ControlFile << Path << "\n";
Kostya Serebryany4aa05902017-01-05 22:05:47 +0000240 if (!ControlFile) {
241 Printf("MERGE-OUTER: failed to write to the control file: %s\n",
242 CFPath.c_str());
243 exit(1);
244 }
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000245 ControlFile.close();
246
247 // Execute the inner process untill it passes.
248 // Every inner process should execute at least one input.
249 std::string BaseCmd = CloneArgsWithoutX(Args, "keep-all-flags");
Kostya Serebryany9d0f02a2017-01-18 00:55:29 +0000250 bool Success = false;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000251 for (size_t i = 1; i <= AllFiles.size(); i++) {
252 Printf("MERGE-OUTER: attempt %zd\n", i);
253 auto ExitCode =
254 ExecuteCommand(BaseCmd + " -merge_control_file=" + CFPath);
255 if (!ExitCode) {
256 Printf("MERGE-OUTER: succesfull in %zd attempt(s)\n", i);
Kostya Serebryany9d0f02a2017-01-18 00:55:29 +0000257 Success = true;
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000258 break;
259 }
260 }
Kostya Serebryany9d0f02a2017-01-18 00:55:29 +0000261 if (!Success) {
262 Printf("MERGE-OUTER: zero succesfull attempts, exiting\n");
263 exit(1);
264 }
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000265 // Read the control file and do the merge.
266 Merger M;
267 std::ifstream IF(CFPath);
Kostya Serebryany4aa05902017-01-05 22:05:47 +0000268 IF.seekg(0, IF.end);
269 Printf("MERGE-OUTER: the control file has %zd bytes\n", (size_t)IF.tellg());
270 IF.seekg(0, IF.beg);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000271 M.ParseOrExit(IF, true);
272 IF.close();
Kostya Serebryany81d17442017-03-11 02:26:20 +0000273 Printf("MERGE-OUTER: consumed %zd bytes to parse the control file\n",
274 M.ApproximateMemoryConsumption());
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000275 std::vector<std::string> NewFiles;
276 size_t NumNewFeatures = M.Merge(&NewFiles);
277 Printf("MERGE-OUTER: %zd new files with %zd new features added\n",
278 NewFiles.size(), NumNewFeatures);
279 for (auto &F: NewFiles)
280 WriteToOutputCorpus(FileToVector(F));
281 // We are done, delete the control file.
Marcos Pividori7c1defd2016-12-13 17:46:40 +0000282 RemoveFile(CFPath);
Kostya Serebryany111e1d62016-12-09 01:17:24 +0000283}
284
285} // namespace fuzzer