| 1 |
//===- FuzzerMerge.cpp - merging corpora ----------------------------------===// |
| 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 |
//===----------------------------------------------------------------------===// |
| 8 |
// Merging corpora. |
| 9 |
//===----------------------------------------------------------------------===// |
| 10 |
|
| 11 |
#include "FuzzerCommand.h" |
| 12 |
#include "FuzzerMerge.h" |
| 13 |
#include "FuzzerIO.h" |
| 14 |
#include "FuzzerInternal.h" |
| 15 |
#include "FuzzerTracePC.h" |
| 16 |
#include "FuzzerUtil.h" |
| 17 |
|
| 18 |
#include <fstream> |
| 19 |
#include <iterator> |
| 20 |
#include <set> |
| 21 |
#include <sstream> |
| 22 |
#include <unordered_set> |
| 23 |
|
| 24 |
namespace fuzzer { |
| 25 |
|
| 26 |
bool Merger::Parse(const std::string &Str, bool ParseCoverage) { |
| 27 |
std::istringstream SS(Str); |
| 28 |
return Parse(SS, ParseCoverage); |
| 29 |
} |
| 30 |
|
| 31 |
int Merger::ParseOrExit(std::istream &IS, bool ParseCoverage) { |
| 32 |
if (!Parse(IS, ParseCoverage)) { |
| 33 |
Printf("MERGE: failed to parse the control file (unexpected error)\n"); |
| 34 |
return 1; |
| 35 |
} |
| 36 |
return 0; |
| 37 |
} |
| 38 |
|
| 39 |
// The control file example: |
| 40 |
// |
| 41 |
// 3 # The number of inputs |
| 42 |
// 1 # The number of inputs in the first corpus, <= the previous number |
| 43 |
// file0 |
| 44 |
// file1 |
| 45 |
// file2 # One file name per line. |
| 46 |
// STARTED 0 123 # FileID, file size |
| 47 |
// FT 0 1 4 6 8 # FileID COV1 COV2 ... |
| 48 |
// COV 0 7 8 9 # FileID COV1 COV1 |
| 49 |
// STARTED 1 456 # If FT is missing, the input crashed while processing. |
| 50 |
// STARTED 2 567 |
| 51 |
// FT 2 8 9 |
| 52 |
// COV 2 11 12 |
| 53 |
bool Merger::Parse(std::istream &IS, bool ParseCoverage) { |
| 54 |
LastFailure.clear(); |
| 55 |
std::string Line; |
| 56 |
|
| 57 |
// Parse NumFiles. |
| 58 |
if (!std::getline(IS, Line, '\n')) return false; |
| 59 |
std::istringstream L1(Line); |
| 60 |
size_t NumFiles = 0; |
| 61 |
L1 >> NumFiles; |
| 62 |
if (NumFiles == 0 || NumFiles > 10000000) return false; |
| 63 |
|
| 64 |
// Parse NumFilesInFirstCorpus. |
| 65 |
if (!std::getline(IS, Line, '\n')) return false; |
| 66 |
std::istringstream L2(Line); |
| 67 |
NumFilesInFirstCorpus = NumFiles + 1; |
| 68 |
L2 >> NumFilesInFirstCorpus; |
| 69 |
if (NumFilesInFirstCorpus > NumFiles) return false; |
| 70 |
|
| 71 |
// Parse file names. |
| 72 |
Files.resize(NumFiles); |
| 73 |
for (size_t i = 0; i < NumFiles; i++) |
| 74 |
if (!std::getline(IS, Files[i].Name, '\n')) |
| 75 |
return false; |
| 76 |
|
| 77 |
// Parse STARTED, FT, and COV lines. |
| 78 |
size_t ExpectedStartMarker = 0; |
| 79 |
const size_t kInvalidStartMarker = -1; |
| 80 |
size_t LastSeenStartMarker = kInvalidStartMarker; |
| 81 |
Vector<uint32_t> TmpFeatures; |
| 82 |
Set<uint32_t> PCs; |
| 83 |
while (std::getline(IS, Line, '\n')) { |
| 84 |
std::istringstream ISS1(Line); |
| 85 |
std::string Marker; |
| 86 |
size_t N; |
| 87 |
ISS1 >> Marker; |
| 88 |
ISS1 >> N; |
| 89 |
if (Marker == "STARTED") { |
| 90 |
// STARTED FILE_ID FILE_SIZE |
| 91 |
if (ExpectedStartMarker != N) |
| 92 |
return false; |
| 93 |
ISS1 >> Files[ExpectedStartMarker].Size; |
| 94 |
LastSeenStartMarker = ExpectedStartMarker; |
| 95 |
assert(ExpectedStartMarker < Files.size()); |
| 96 |
ExpectedStartMarker++; |
| 97 |
} else if (Marker == "FT") { |
| 98 |
// FT FILE_ID COV1 COV2 COV3 ... |
| 99 |
size_t CurrentFileIdx = N; |
| 100 |
if (CurrentFileIdx != LastSeenStartMarker) |
| 101 |
return false; |
| 102 |
LastSeenStartMarker = kInvalidStartMarker; |
| 103 |
if (ParseCoverage) { |
| 104 |
TmpFeatures.clear(); // use a vector from outer scope to avoid resizes. |
| 105 |
while (ISS1 >> N) |
| 106 |
TmpFeatures.push_back(N); |
| 107 |
std::sort(TmpFeatures.begin(), TmpFeatures.end()); |
| 108 |
Files[CurrentFileIdx].Features = TmpFeatures; |
| 109 |
} |
| 110 |
} else if (Marker == "COV") { |
| 111 |
size_t CurrentFileIdx = N; |
| 112 |
if (ParseCoverage) |
| 113 |
while (ISS1 >> N) |
| 114 |
if (PCs.insert(N).second) |
| 115 |
Files[CurrentFileIdx].Cov.push_back(N); |
| 116 |
} else { |
| 117 |
return false; |
| 118 |
} |
| 119 |
} |
| 120 |
if (LastSeenStartMarker != kInvalidStartMarker) |
| 121 |
LastFailure = Files[LastSeenStartMarker].Name; |
| 122 |
|
| 123 |
FirstNotProcessedFile = ExpectedStartMarker; |
| 124 |
return true; |
| 125 |
} |
| 126 |
|
| 127 |
size_t Merger::ApproximateMemoryConsumption() const { |
| 128 |
size_t Res = 0; |
| 129 |
for (const auto &F: Files) |
| 130 |
Res += sizeof(F) + F.Features.size() * sizeof(F.Features[0]); |
| 131 |
return Res; |
| 132 |
} |
| 133 |
|
| 134 |
// Decides which files need to be merged (add those to NewFiles). |
| 135 |
// Returns the number of new features added. |
| 136 |
size_t Merger::Merge(const Set<uint32_t> &InitialFeatures, |
| 137 |
Set<uint32_t> *NewFeatures, |
| 138 |
const Set<uint32_t> &InitialCov, Set<uint32_t> *NewCov, |
| 139 |
Vector<std::string> *NewFiles) { |
| 140 |
NewFiles->clear(); |
| 141 |
assert(NumFilesInFirstCorpus <= Files.size()); |
| 142 |
Set<uint32_t> AllFeatures = InitialFeatures; |
| 143 |
|
| 144 |
// What features are in the initial corpus? |
| 145 |
for (size_t i = 0; i < NumFilesInFirstCorpus; i++) { |
| 146 |
auto &Cur = Files[i].Features; |
| 147 |
AllFeatures.insert(Cur.begin(), Cur.end()); |
| 148 |
} |
| 149 |
// Remove all features that we already know from all other inputs. |
| 150 |
for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) { |
| 151 |
auto &Cur = Files[i].Features; |
| 152 |
Vector<uint32_t> Tmp; |
| 153 |
std::set_difference(Cur.begin(), Cur.end(), AllFeatures.begin(), |
| 154 |
AllFeatures.end(), std::inserter(Tmp, Tmp.begin())); |
| 155 |
Cur.swap(Tmp); |
| 156 |
} |
| 157 |
|
| 158 |
// Sort. Give preference to |
| 159 |
// * smaller files |
| 160 |
// * files with more features. |
| 161 |
std::sort(Files.begin() + NumFilesInFirstCorpus, Files.end(), |
| 162 |
[&](const MergeFileInfo &a, const MergeFileInfo &b) -> bool { |
| 163 |
if (a.Size != b.Size) |
| 164 |
return a.Size < b.Size; |
| 165 |
return a.Features.size() > b.Features.size(); |
| 166 |
}); |
| 167 |
|
| 168 |
// One greedy pass: add the file's features to AllFeatures. |
| 169 |
// If new features were added, add this file to NewFiles. |
| 170 |
for (size_t i = NumFilesInFirstCorpus; i < Files.size(); i++) { |
| 171 |
auto &Cur = Files[i].Features; |
| 172 |
// Printf("%s -> sz %zd ft %zd\n", Files[i].Name.c_str(), |
| 173 |
// Files[i].Size, Cur.size()); |
| 174 |
bool FoundNewFeatures = false; |
| 175 |
for (auto Fe: Cur) { |
| 176 |
if (AllFeatures.insert(Fe).second) { |
| 177 |
FoundNewFeatures = true; |
| 178 |
NewFeatures->insert(Fe); |
| 179 |
} |
| 180 |
} |
| 181 |
if (FoundNewFeatures) |
| 182 |
NewFiles->push_back(Files[i].Name); |
| 183 |
for (auto Cov : Files[i].Cov) |
| 184 |
if (InitialCov.find(Cov) == InitialCov.end()) |
| 185 |
NewCov->insert(Cov); |
| 186 |
} |
| 187 |
return NewFeatures->size(); |
| 188 |
} |
| 189 |
|
| 190 |
Set<uint32_t> Merger::AllFeatures() const { |
| 191 |
Set<uint32_t> S; |
| 192 |
for (auto &File : Files) |
| 193 |
S.insert(File.Features.begin(), File.Features.end()); |
| 194 |
return S; |
| 195 |
} |
| 196 |
|
| 197 |
// Inner process. May crash if the target crashes. |
| 198 |
int Fuzzer::CrashResistantMergeInternalStep(const std::string &CFPath) { |
| 199 |
Printf("MERGE-INNER: using the control file '%s'\n", CFPath.c_str()); |
| 200 |
Merger M; |
| 201 |
std::ifstream IF(CFPath); |
| 202 |
int Res = M.ParseOrExit(IF, false); |
| 203 |
if (Res != 0) |
| 204 |
return Res; |
| 205 |
IF.close(); |
| 206 |
if (!M.LastFailure.empty()) |
| 207 |
Printf("MERGE-INNER: '%s' caused a failure at the previous merge step\n", |
| 208 |
M.LastFailure.c_str()); |
| 209 |
|
| 210 |
Printf("MERGE-INNER: %zd total files;" |
| 211 |
" %zd processed earlier; will process %zd files now\n", |
| 212 |
M.Files.size(), M.FirstNotProcessedFile, |
| 213 |
M.Files.size() - M.FirstNotProcessedFile); |
| 214 |
|
| 215 |
std::ofstream OF(CFPath, std::ofstream::out | std::ofstream::app); |
| 216 |
Set<size_t> AllFeatures; |
| 217 |
auto PrintStatsWrapper = [this, &AllFeatures](const char* Where) { |
| 218 |
this->PrintStats(Where, "\n", 0, AllFeatures.size()); |
| 219 |
}; |
| 220 |
Set<const TracePC::PCTableEntry *> AllPCs; |
| 221 |
for (size_t i = M.FirstNotProcessedFile; i < M.Files.size(); i++) { |
| 222 |
if (Fuzzer::MaybeExitGracefully()) |
| 223 |
return 0; |
| 224 |
auto U = FileToVector(M.Files[i].Name); |
| 225 |
if (U.size() > MaxInputLen) { |
| 226 |
U.resize(MaxInputLen); |
| 227 |
U.shrink_to_fit(); |
| 228 |
} |
| 229 |
|
| 230 |
// Write the pre-run marker. |
| 231 |
OF << "STARTED " << i << " " << U.size() << "\n"; |
| 232 |
OF.flush(); // Flush is important since Command::Execute may crash. |
| 233 |
// Run. |
| 234 |
TPC.ResetMaps(); |
| 235 |
if (ExecuteCallback(U.data(), U.size())) { |
| 236 |
continue; |
| 237 |
} |
| 238 |
// Collect coverage. We are iterating over the files in this order: |
| 239 |
// * First, files in the initial corpus ordered by size, smallest first. |
| 240 |
// * Then, all other files, smallest first. |
| 241 |
// So it makes no sense to record all features for all files, instead we |
| 242 |
// only record features that were not seen before. |
| 243 |
Set<size_t> UniqFeatures; |
| 244 |
TPC.CollectFeatures([&](size_t Feature) { |
| 245 |
if (AllFeatures.insert(Feature).second) |
| 246 |
UniqFeatures.insert(Feature); |
| 247 |
}); |
| 248 |
TPC.UpdateObservedPCs(); |
| 249 |
// Show stats. |
| 250 |
if (!(TotalNumberOfRuns & (TotalNumberOfRuns - 1))) |
| 251 |
PrintStatsWrapper("pulse "); |
| 252 |
if (TotalNumberOfRuns == M.NumFilesInFirstCorpus) |
| 253 |
PrintStatsWrapper("LOADED"); |
| 254 |
// Write the post-run marker and the coverage. |
| 255 |
OF << "FT " << i; |
| 256 |
for (size_t F : UniqFeatures) |
| 257 |
OF << " " << F; |
| 258 |
OF << "\n"; |
| 259 |
OF << "COV " << i; |
| 260 |
TPC.ForEachObservedPC([&](const TracePC::PCTableEntry *TE) { |
| 261 |
if (AllPCs.insert(TE).second) |
| 262 |
OF << " " << TPC.PCTableEntryIdx(TE); |
| 263 |
}); |
| 264 |
OF << "\n"; |
| 265 |
OF.flush(); |
| 266 |
} |
| 267 |
PrintStatsWrapper("DONE "); |
| 268 |
return 0; |
| 269 |
} |
| 270 |
|
| 271 |
static int WriteNewControlFile(const std::string &CFPath, |
| 272 |
const Vector<SizedFile> &OldCorpus, |
| 273 |
const Vector<SizedFile> &NewCorpus, |
| 274 |
const Vector<MergeFileInfo> &KnownFiles, |
| 275 |
size_t &NumFiles) { |
| 276 |
std::unordered_set<std::string> FilesToSkip; |
| 277 |
for (auto &SF: KnownFiles) |
| 278 |
FilesToSkip.insert(SF.Name); |
| 279 |
|
| 280 |
Vector<std::string> FilesToUse; |
| 281 |
auto MaybeUseFile = [=, &FilesToUse](std::string Name) { |
| 282 |
if (FilesToSkip.find(Name) == FilesToSkip.end()) |
| 283 |
FilesToUse.push_back(Name); |
| 284 |
}; |
| 285 |
for (auto &SF: OldCorpus) |
| 286 |
MaybeUseFile(SF.File); |
| 287 |
auto FilesToUseFromOldCorpus = FilesToUse.size(); |
| 288 |
for (auto &SF: NewCorpus) |
| 289 |
MaybeUseFile(SF.File); |
| 290 |
|
| 291 |
RemoveFile(CFPath); |
| 292 |
std::ofstream ControlFile(CFPath); |
| 293 |
ControlFile << FilesToUse.size() << "\n"; |
| 294 |
ControlFile << FilesToUseFromOldCorpus << "\n"; |
| 295 |
for (auto &FN: FilesToUse) |
| 296 |
ControlFile << FN << "\n"; |
| 297 |
|
| 298 |
if (!ControlFile) { |
| 299 |
Printf("MERGE-OUTER: failed to write to the control file: %s\n", |
| 300 |
CFPath.c_str()); |
| 301 |
return 1; |
| 302 |
} |
| 303 |
|
| 304 |
NumFiles = FilesToUse.size(); |
| 305 |
return 0; |
| 306 |
} |
| 307 |
|
| 308 |
// Outer process. Does not call the target code and thus should not fail. |
| 309 |
int CrashResistantMerge(const Vector<std::string> &Args, |
| 310 |
const Vector<SizedFile> &OldCorpus, |
| 311 |
const Vector<SizedFile> &NewCorpus, |
| 312 |
Vector<std::string> *NewFiles, |
| 313 |
const Set<uint32_t> &InitialFeatures, |
| 314 |
Set<uint32_t> *NewFeatures, |
| 315 |
const Set<uint32_t> &InitialCov, |
| 316 |
Set<uint32_t> *NewCov, |
| 317 |
const std::string &CFPath, |
| 318 |
bool V /*Verbose*/) { |
| 319 |
if (NewCorpus.empty() && OldCorpus.empty()) return 0; // Nothing to merge. |
| 320 |
size_t NumAttempts = 0; |
| 321 |
int Res; |
| 322 |
Vector<MergeFileInfo> KnownFiles; |
| 323 |
if (FileSize(CFPath)) { |
| 324 |
VPrintf(V, "MERGE-OUTER: non-empty control file provided: '%s'\n", |
| 325 |
CFPath.c_str()); |
| 326 |
Merger M; |
| 327 |
std::ifstream IF(CFPath); |
| 328 |
if (M.Parse(IF, /*ParseCoverage=*/true)) { |
| 329 |
VPrintf(V, "MERGE-OUTER: control file ok, %zd files total," |
| 330 |
" first not processed file %zd\n", |
| 331 |
M.Files.size(), M.FirstNotProcessedFile); |
| 332 |
if (!M.LastFailure.empty()) |
| 333 |
VPrintf(V, "MERGE-OUTER: '%s' will be skipped as unlucky " |
| 334 |
"(merge has stumbled on it the last time)\n", |
| 335 |
M.LastFailure.c_str()); |
| 336 |
if (M.FirstNotProcessedFile >= M.Files.size()) { |
| 337 |
// Merge has already been completed with the given merge control file. |
| 338 |
if (M.Files.size() == OldCorpus.size() + NewCorpus.size()) { |
| 339 |
VPrintf( |
| 340 |
V, |
| 341 |
"MERGE-OUTER: nothing to do, merge has been completed before\n"); |
| 342 |
Fuzzer::GracefullyExit(); |
| 343 |
return 0; |
| 344 |
} |
| 345 |
|
| 346 |
// Number of input files likely changed, start merge from scratch, but |
| 347 |
// reuse coverage information from the given merge control file. |
| 348 |
VPrintf( |
| 349 |
V, |
| 350 |
"MERGE-OUTER: starting merge from scratch, but reusing coverage " |
| 351 |
"information from the given control file\n"); |
| 352 |
KnownFiles = M.Files; |
| 353 |
} else { |
| 354 |
// There is a merge in progress, continue. |
| 355 |
NumAttempts = M.Files.size() - M.FirstNotProcessedFile; |
| 356 |
} |
| 357 |
} else { |
| 358 |
VPrintf(V, "MERGE-OUTER: bad control file, will overwrite it\n"); |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
if (!NumAttempts) { |
| 363 |
// The supplied control file is empty or bad, create a fresh one. |
| 364 |
VPrintf(V, "MERGE-OUTER: " |
| 365 |
"%zd files, %zd in the initial corpus, %zd processed earlier\n", |
| 366 |
OldCorpus.size() + NewCorpus.size(), OldCorpus.size(), |
| 367 |
KnownFiles.size()); |
| 368 |
Res = WriteNewControlFile(CFPath, OldCorpus, NewCorpus, KnownFiles, NumAttempts); |
| 369 |
if (Res != 0) |
| 370 |
return Res; |
| 371 |
} |
| 372 |
|
| 373 |
// Execute the inner process until it passes. |
| 374 |
// Every inner process should execute at least one input. |
| 375 |
Command BaseCmd(Args); |
| 376 |
BaseCmd.removeFlag("merge"); |
| 377 |
BaseCmd.removeFlag("fork"); |
| 378 |
BaseCmd.removeFlag("collect_data_flow"); |
| 379 |
for (size_t Attempt = 1; Attempt <= NumAttempts; Attempt++) { |
| 380 |
if (Fuzzer::MaybeExitGracefully()) |
| 381 |
return 0; |
| 382 |
VPrintf(V, "MERGE-OUTER: attempt %zd\n", Attempt); |
| 383 |
Command Cmd(BaseCmd); |
| 384 |
Cmd.addFlag("merge_control_file", CFPath); |
| 385 |
Cmd.addFlag("merge_inner", "1"); |
| 386 |
if (!V) { |
| 387 |
Cmd.setOutputFile(getDevNull()); |
| 388 |
Cmd.combineOutAndErr(); |
| 389 |
} |
| 390 |
auto ExitCode = ExecuteCommand(Cmd); |
| 391 |
if (!ExitCode) { |
| 392 |
VPrintf(V, "MERGE-OUTER: succesfull in %zd attempt(s)\n", Attempt); |
| 393 |
break; |
| 394 |
} |
| 395 |
} |
| 396 |
// Read the control file and do the merge. |
| 397 |
Merger M; |
| 398 |
std::ifstream IF(CFPath); |
| 399 |
IF.seekg(0, IF.end); |
| 400 |
VPrintf(V, "MERGE-OUTER: the control file has %zd bytes\n", |
| 401 |
(size_t)IF.tellg()); |
| 402 |
IF.seekg(0, IF.beg); |
| 403 |
Res = M.ParseOrExit(IF, true); |
| 404 |
if (Res != 0) |
| 405 |
return Res; |
| 406 |
IF.close(); |
| 407 |
VPrintf(V, |
| 408 |
"MERGE-OUTER: consumed %zdMb (%zdMb rss) to parse the control file\n", |
| 409 |
M.ApproximateMemoryConsumption() >> 20, GetPeakRSSMb()); |
| 410 |
|
| 411 |
M.Files.insert(M.Files.end(), KnownFiles.begin(), KnownFiles.end()); |
| 412 |
M.Merge(InitialFeatures, NewFeatures, InitialCov, NewCov, NewFiles); |
| 413 |
VPrintf(V, "MERGE-OUTER: %zd new files with %zd new features added; " |
| 414 |
"%zd new coverage edges\n", |
| 415 |
NewFiles->size(), NewFeatures->size(), NewCov->size()); |
| 416 |
return 0; |
| 417 |
} |
| 418 |
|
| 419 |
} // namespace fuzzer |