FuzzerCorpus.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. //===- FuzzerCorpus.h - Internal header for the Fuzzer ----------*- C++ -* ===//
  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. // fuzzer::InputCorpus
  9. //===----------------------------------------------------------------------===//
  10. #ifndef LLVM_FUZZER_CORPUS
  11. #define LLVM_FUZZER_CORPUS
  12. #include "FuzzerDataFlowTrace.h"
  13. #include "FuzzerDefs.h"
  14. #include "FuzzerIO.h"
  15. #include "FuzzerRandom.h"
  16. #include "FuzzerSHA1.h"
  17. #include "FuzzerTracePC.h"
  18. #include <algorithm>
  19. #include <chrono>
  20. #include <numeric>
  21. #include <random>
  22. #include <unordered_set>
  23. namespace fuzzer {
  24. struct InputInfo {
  25. Unit U; // The actual input data.
  26. std::chrono::microseconds TimeOfUnit;
  27. uint8_t Sha1[kSHA1NumBytes]; // Checksum.
  28. // Number of features that this input has and no smaller input has.
  29. size_t NumFeatures = 0;
  30. size_t Tmp = 0; // Used by ValidateFeatureSet.
  31. // Stats.
  32. size_t NumExecutedMutations = 0;
  33. size_t NumSuccessfullMutations = 0;
  34. bool NeverReduce = false;
  35. bool MayDeleteFile = false;
  36. bool Reduced = false;
  37. bool HasFocusFunction = false;
  38. std::vector<uint32_t> UniqFeatureSet;
  39. std::vector<uint8_t> DataFlowTraceForFocusFunction;
  40. // Power schedule.
  41. bool NeedsEnergyUpdate = false;
  42. double Energy = 0.0;
  43. double SumIncidence = 0.0;
  44. std::vector<std::pair<uint32_t, uint16_t>> FeatureFreqs;
  45. // Delete feature Idx and its frequency from FeatureFreqs.
  46. bool DeleteFeatureFreq(uint32_t Idx) {
  47. if (FeatureFreqs.empty())
  48. return false;
  49. // Binary search over local feature frequencies sorted by index.
  50. auto Lower = std::lower_bound(FeatureFreqs.begin(), FeatureFreqs.end(),
  51. std::pair<uint32_t, uint16_t>(Idx, 0));
  52. if (Lower != FeatureFreqs.end() && Lower->first == Idx) {
  53. FeatureFreqs.erase(Lower);
  54. return true;
  55. }
  56. return false;
  57. }
  58. // Assign more energy to a high-entropy seed, i.e., that reveals more
  59. // information about the globally rare features in the neighborhood of the
  60. // seed. Since we do not know the entropy of a seed that has never been
  61. // executed we assign fresh seeds maximum entropy and let II->Energy approach
  62. // the true entropy from above. If ScalePerExecTime is true, the computed
  63. // entropy is scaled based on how fast this input executes compared to the
  64. // average execution time of inputs. The faster an input executes, the more
  65. // energy gets assigned to the input.
  66. void UpdateEnergy(size_t GlobalNumberOfFeatures, bool ScalePerExecTime,
  67. std::chrono::microseconds AverageUnitExecutionTime) {
  68. Energy = 0.0;
  69. SumIncidence = 0.0;
  70. // Apply add-one smoothing to locally discovered features.
  71. for (auto F : FeatureFreqs) {
  72. double LocalIncidence = F.second + 1;
  73. Energy -= LocalIncidence * log(LocalIncidence);
  74. SumIncidence += LocalIncidence;
  75. }
  76. // Apply add-one smoothing to locally undiscovered features.
  77. // PreciseEnergy -= 0; // since log(1.0) == 0)
  78. SumIncidence +=
  79. static_cast<double>(GlobalNumberOfFeatures - FeatureFreqs.size());
  80. // Add a single locally abundant feature apply add-one smoothing.
  81. double AbdIncidence = static_cast<double>(NumExecutedMutations + 1);
  82. Energy -= AbdIncidence * log(AbdIncidence);
  83. SumIncidence += AbdIncidence;
  84. // Normalize.
  85. if (SumIncidence != 0)
  86. Energy = Energy / SumIncidence + log(SumIncidence);
  87. if (ScalePerExecTime) {
  88. // Scaling to favor inputs with lower execution time.
  89. uint32_t PerfScore = 100;
  90. if (TimeOfUnit.count() > AverageUnitExecutionTime.count() * 10)
  91. PerfScore = 10;
  92. else if (TimeOfUnit.count() > AverageUnitExecutionTime.count() * 4)
  93. PerfScore = 25;
  94. else if (TimeOfUnit.count() > AverageUnitExecutionTime.count() * 2)
  95. PerfScore = 50;
  96. else if (TimeOfUnit.count() * 3 > AverageUnitExecutionTime.count() * 4)
  97. PerfScore = 75;
  98. else if (TimeOfUnit.count() * 4 < AverageUnitExecutionTime.count())
  99. PerfScore = 300;
  100. else if (TimeOfUnit.count() * 3 < AverageUnitExecutionTime.count())
  101. PerfScore = 200;
  102. else if (TimeOfUnit.count() * 2 < AverageUnitExecutionTime.count())
  103. PerfScore = 150;
  104. Energy *= PerfScore;
  105. }
  106. }
  107. // Increment the frequency of the feature Idx.
  108. void UpdateFeatureFrequency(uint32_t Idx) {
  109. NeedsEnergyUpdate = true;
  110. // The local feature frequencies is an ordered vector of pairs.
  111. // If there are no local feature frequencies, push_back preserves order.
  112. // Set the feature frequency for feature Idx32 to 1.
  113. if (FeatureFreqs.empty()) {
  114. FeatureFreqs.push_back(std::pair<uint32_t, uint16_t>(Idx, 1));
  115. return;
  116. }
  117. // Binary search over local feature frequencies sorted by index.
  118. auto Lower = std::lower_bound(FeatureFreqs.begin(), FeatureFreqs.end(),
  119. std::pair<uint32_t, uint16_t>(Idx, 0));
  120. // If feature Idx32 already exists, increment its frequency.
  121. // Otherwise, insert a new pair right after the next lower index.
  122. if (Lower != FeatureFreqs.end() && Lower->first == Idx) {
  123. Lower->second++;
  124. } else {
  125. FeatureFreqs.insert(Lower, std::pair<uint32_t, uint16_t>(Idx, 1));
  126. }
  127. }
  128. };
  129. struct EntropicOptions {
  130. bool Enabled;
  131. size_t NumberOfRarestFeatures;
  132. size_t FeatureFrequencyThreshold;
  133. bool ScalePerExecTime;
  134. };
  135. class InputCorpus {
  136. static const uint32_t kFeatureSetSize = 1 << 21;
  137. static const uint8_t kMaxMutationFactor = 20;
  138. static const size_t kSparseEnergyUpdates = 100;
  139. size_t NumExecutedMutations = 0;
  140. EntropicOptions Entropic;
  141. public:
  142. InputCorpus(const std::string &OutputCorpus, EntropicOptions Entropic)
  143. : Entropic(Entropic), OutputCorpus(OutputCorpus) {
  144. memset(InputSizesPerFeature, 0, sizeof(InputSizesPerFeature));
  145. memset(SmallestElementPerFeature, 0, sizeof(SmallestElementPerFeature));
  146. }
  147. ~InputCorpus() {
  148. for (auto II : Inputs)
  149. delete II;
  150. }
  151. size_t size() const { return Inputs.size(); }
  152. size_t SizeInBytes() const {
  153. size_t Res = 0;
  154. for (auto II : Inputs)
  155. Res += II->U.size();
  156. return Res;
  157. }
  158. size_t NumActiveUnits() const {
  159. size_t Res = 0;
  160. for (auto II : Inputs)
  161. Res += !II->U.empty();
  162. return Res;
  163. }
  164. size_t MaxInputSize() const {
  165. size_t Res = 0;
  166. for (auto II : Inputs)
  167. Res = std::max(Res, II->U.size());
  168. return Res;
  169. }
  170. void IncrementNumExecutedMutations() { NumExecutedMutations++; }
  171. size_t NumInputsThatTouchFocusFunction() {
  172. return std::count_if(Inputs.begin(), Inputs.end(), [](const InputInfo *II) {
  173. return II->HasFocusFunction;
  174. });
  175. }
  176. size_t NumInputsWithDataFlowTrace() {
  177. return std::count_if(Inputs.begin(), Inputs.end(), [](const InputInfo *II) {
  178. return !II->DataFlowTraceForFocusFunction.empty();
  179. });
  180. }
  181. bool empty() const { return Inputs.empty(); }
  182. const Unit &operator[] (size_t Idx) const { return Inputs[Idx]->U; }
  183. InputInfo *AddToCorpus(const Unit &U, size_t NumFeatures, bool MayDeleteFile,
  184. bool HasFocusFunction, bool NeverReduce,
  185. std::chrono::microseconds TimeOfUnit,
  186. const std::vector<uint32_t> &FeatureSet,
  187. const DataFlowTrace &DFT, const InputInfo *BaseII) {
  188. assert(!U.empty());
  189. if (FeatureDebug)
  190. Printf("ADD_TO_CORPUS %zd NF %zd\n", Inputs.size(), NumFeatures);
  191. // Inputs.size() is cast to uint32_t below.
  192. assert(Inputs.size() < std::numeric_limits<uint32_t>::max());
  193. Inputs.push_back(new InputInfo());
  194. InputInfo &II = *Inputs.back();
  195. II.U = U;
  196. II.NumFeatures = NumFeatures;
  197. II.NeverReduce = NeverReduce;
  198. II.TimeOfUnit = TimeOfUnit;
  199. II.MayDeleteFile = MayDeleteFile;
  200. II.UniqFeatureSet = FeatureSet;
  201. II.HasFocusFunction = HasFocusFunction;
  202. // Assign maximal energy to the new seed.
  203. II.Energy = RareFeatures.empty() ? 1.0 : log(RareFeatures.size());
  204. II.SumIncidence = static_cast<double>(RareFeatures.size());
  205. II.NeedsEnergyUpdate = false;
  206. std::sort(II.UniqFeatureSet.begin(), II.UniqFeatureSet.end());
  207. ComputeSHA1(U.data(), U.size(), II.Sha1);
  208. auto Sha1Str = Sha1ToString(II.Sha1);
  209. Hashes.insert(Sha1Str);
  210. if (HasFocusFunction)
  211. if (auto V = DFT.Get(Sha1Str))
  212. II.DataFlowTraceForFocusFunction = *V;
  213. // This is a gross heuristic.
  214. // Ideally, when we add an element to a corpus we need to know its DFT.
  215. // But if we don't, we'll use the DFT of its base input.
  216. if (II.DataFlowTraceForFocusFunction.empty() && BaseII)
  217. II.DataFlowTraceForFocusFunction = BaseII->DataFlowTraceForFocusFunction;
  218. DistributionNeedsUpdate = true;
  219. PrintCorpus();
  220. // ValidateFeatureSet();
  221. return &II;
  222. }
  223. // Debug-only
  224. void PrintUnit(const Unit &U) {
  225. if (!FeatureDebug) return;
  226. for (uint8_t C : U) {
  227. if (C != 'F' && C != 'U' && C != 'Z')
  228. C = '.';
  229. Printf("%c", C);
  230. }
  231. }
  232. // Debug-only
  233. void PrintFeatureSet(const std::vector<uint32_t> &FeatureSet) {
  234. if (!FeatureDebug) return;
  235. Printf("{");
  236. for (uint32_t Feature: FeatureSet)
  237. Printf("%u,", Feature);
  238. Printf("}");
  239. }
  240. // Debug-only
  241. void PrintCorpus() {
  242. if (!FeatureDebug) return;
  243. Printf("======= CORPUS:\n");
  244. int i = 0;
  245. for (auto II : Inputs) {
  246. if (std::find(II->U.begin(), II->U.end(), 'F') != II->U.end()) {
  247. Printf("[%2d] ", i);
  248. Printf("%s sz=%zd ", Sha1ToString(II->Sha1).c_str(), II->U.size());
  249. PrintUnit(II->U);
  250. Printf(" ");
  251. PrintFeatureSet(II->UniqFeatureSet);
  252. Printf("\n");
  253. }
  254. i++;
  255. }
  256. }
  257. void Replace(InputInfo *II, const Unit &U,
  258. std::chrono::microseconds TimeOfUnit) {
  259. assert(II->U.size() > U.size());
  260. Hashes.erase(Sha1ToString(II->Sha1));
  261. DeleteFile(*II);
  262. ComputeSHA1(U.data(), U.size(), II->Sha1);
  263. Hashes.insert(Sha1ToString(II->Sha1));
  264. II->U = U;
  265. II->Reduced = true;
  266. II->TimeOfUnit = TimeOfUnit;
  267. DistributionNeedsUpdate = true;
  268. }
  269. bool HasUnit(const Unit &U) { return Hashes.count(Hash(U)); }
  270. bool HasUnit(const std::string &H) { return Hashes.count(H); }
  271. InputInfo &ChooseUnitToMutate(Random &Rand) {
  272. InputInfo &II = *Inputs[ChooseUnitIdxToMutate(Rand)];
  273. assert(!II.U.empty());
  274. return II;
  275. }
  276. InputInfo &ChooseUnitToCrossOverWith(Random &Rand, bool UniformDist) {
  277. if (!UniformDist) {
  278. return ChooseUnitToMutate(Rand);
  279. }
  280. InputInfo &II = *Inputs[Rand(Inputs.size())];
  281. assert(!II.U.empty());
  282. return II;
  283. }
  284. // Returns an index of random unit from the corpus to mutate.
  285. size_t ChooseUnitIdxToMutate(Random &Rand) {
  286. UpdateCorpusDistribution(Rand);
  287. size_t Idx = static_cast<size_t>(CorpusDistribution(Rand));
  288. assert(Idx < Inputs.size());
  289. return Idx;
  290. }
  291. void PrintStats() {
  292. for (size_t i = 0; i < Inputs.size(); i++) {
  293. const auto &II = *Inputs[i];
  294. Printf(" [% 3zd %s] sz: % 5zd runs: % 5zd succ: % 5zd focus: %d\n", i,
  295. Sha1ToString(II.Sha1).c_str(), II.U.size(),
  296. II.NumExecutedMutations, II.NumSuccessfullMutations,
  297. II.HasFocusFunction);
  298. }
  299. }
  300. void PrintFeatureSet() {
  301. for (size_t i = 0; i < kFeatureSetSize; i++) {
  302. if(size_t Sz = GetFeature(i))
  303. Printf("[%zd: id %zd sz%zd] ", i, SmallestElementPerFeature[i], Sz);
  304. }
  305. Printf("\n\t");
  306. for (size_t i = 0; i < Inputs.size(); i++)
  307. if (size_t N = Inputs[i]->NumFeatures)
  308. Printf(" %zd=>%zd ", i, N);
  309. Printf("\n");
  310. }
  311. void DeleteFile(const InputInfo &II) {
  312. if (!OutputCorpus.empty() && II.MayDeleteFile)
  313. RemoveFile(DirPlusFile(OutputCorpus, Sha1ToString(II.Sha1)));
  314. }
  315. void DeleteInput(size_t Idx) {
  316. InputInfo &II = *Inputs[Idx];
  317. DeleteFile(II);
  318. Unit().swap(II.U);
  319. II.Energy = 0.0;
  320. II.NeedsEnergyUpdate = false;
  321. DistributionNeedsUpdate = true;
  322. if (FeatureDebug)
  323. Printf("EVICTED %zd\n", Idx);
  324. }
  325. void AddRareFeature(uint32_t Idx) {
  326. // Maintain *at least* TopXRarestFeatures many rare features
  327. // and all features with a frequency below ConsideredRare.
  328. // Remove all other features.
  329. while (RareFeatures.size() > Entropic.NumberOfRarestFeatures &&
  330. FreqOfMostAbundantRareFeature > Entropic.FeatureFrequencyThreshold) {
  331. // Find most and second most abbundant feature.
  332. uint32_t MostAbundantRareFeatureIndices[2] = {RareFeatures[0],
  333. RareFeatures[0]};
  334. size_t Delete = 0;
  335. for (size_t i = 0; i < RareFeatures.size(); i++) {
  336. uint32_t Idx2 = RareFeatures[i];
  337. if (GlobalFeatureFreqs[Idx2] >=
  338. GlobalFeatureFreqs[MostAbundantRareFeatureIndices[0]]) {
  339. MostAbundantRareFeatureIndices[1] = MostAbundantRareFeatureIndices[0];
  340. MostAbundantRareFeatureIndices[0] = Idx2;
  341. Delete = i;
  342. }
  343. }
  344. // Remove most abundant rare feature.
  345. RareFeatures[Delete] = RareFeatures.back();
  346. RareFeatures.pop_back();
  347. for (auto II : Inputs) {
  348. if (II->DeleteFeatureFreq(MostAbundantRareFeatureIndices[0]))
  349. II->NeedsEnergyUpdate = true;
  350. }
  351. // Set 2nd most abundant as the new most abundant feature count.
  352. FreqOfMostAbundantRareFeature =
  353. GlobalFeatureFreqs[MostAbundantRareFeatureIndices[1]];
  354. }
  355. // Add rare feature, handle collisions, and update energy.
  356. RareFeatures.push_back(Idx);
  357. GlobalFeatureFreqs[Idx] = 0;
  358. for (auto II : Inputs) {
  359. II->DeleteFeatureFreq(Idx);
  360. // Apply add-one smoothing to this locally undiscovered feature.
  361. // Zero energy seeds will never be fuzzed and remain zero energy.
  362. if (II->Energy > 0.0) {
  363. II->SumIncidence += 1;
  364. II->Energy += log(II->SumIncidence) / II->SumIncidence;
  365. }
  366. }
  367. DistributionNeedsUpdate = true;
  368. }
  369. bool AddFeature(size_t Idx, uint32_t NewSize, bool Shrink) {
  370. assert(NewSize);
  371. Idx = Idx % kFeatureSetSize;
  372. uint32_t OldSize = GetFeature(Idx);
  373. if (OldSize == 0 || (Shrink && OldSize > NewSize)) {
  374. if (OldSize > 0) {
  375. size_t OldIdx = SmallestElementPerFeature[Idx];
  376. InputInfo &II = *Inputs[OldIdx];
  377. assert(II.NumFeatures > 0);
  378. II.NumFeatures--;
  379. if (II.NumFeatures == 0)
  380. DeleteInput(OldIdx);
  381. } else {
  382. NumAddedFeatures++;
  383. if (Entropic.Enabled)
  384. AddRareFeature((uint32_t)Idx);
  385. }
  386. NumUpdatedFeatures++;
  387. if (FeatureDebug)
  388. Printf("ADD FEATURE %zd sz %d\n", Idx, NewSize);
  389. // Inputs.size() is guaranteed to be less than UINT32_MAX by AddToCorpus.
  390. SmallestElementPerFeature[Idx] = static_cast<uint32_t>(Inputs.size());
  391. InputSizesPerFeature[Idx] = NewSize;
  392. return true;
  393. }
  394. return false;
  395. }
  396. // Increment frequency of feature Idx globally and locally.
  397. void UpdateFeatureFrequency(InputInfo *II, size_t Idx) {
  398. uint32_t Idx32 = Idx % kFeatureSetSize;
  399. // Saturated increment.
  400. if (GlobalFeatureFreqs[Idx32] == 0xFFFF)
  401. return;
  402. uint16_t Freq = GlobalFeatureFreqs[Idx32]++;
  403. // Skip if abundant.
  404. if (Freq > FreqOfMostAbundantRareFeature ||
  405. std::find(RareFeatures.begin(), RareFeatures.end(), Idx32) ==
  406. RareFeatures.end())
  407. return;
  408. // Update global frequencies.
  409. if (Freq == FreqOfMostAbundantRareFeature)
  410. FreqOfMostAbundantRareFeature++;
  411. // Update local frequencies.
  412. if (II)
  413. II->UpdateFeatureFrequency(Idx32);
  414. }
  415. size_t NumFeatures() const { return NumAddedFeatures; }
  416. size_t NumFeatureUpdates() const { return NumUpdatedFeatures; }
  417. private:
  418. static const bool FeatureDebug = false;
  419. uint32_t GetFeature(size_t Idx) const { return InputSizesPerFeature[Idx]; }
  420. void ValidateFeatureSet() {
  421. if (FeatureDebug)
  422. PrintFeatureSet();
  423. for (size_t Idx = 0; Idx < kFeatureSetSize; Idx++)
  424. if (GetFeature(Idx))
  425. Inputs[SmallestElementPerFeature[Idx]]->Tmp++;
  426. for (auto II: Inputs) {
  427. if (II->Tmp != II->NumFeatures)
  428. Printf("ZZZ %zd %zd\n", II->Tmp, II->NumFeatures);
  429. assert(II->Tmp == II->NumFeatures);
  430. II->Tmp = 0;
  431. }
  432. }
  433. // Updates the probability distribution for the units in the corpus.
  434. // Must be called whenever the corpus or unit weights are changed.
  435. //
  436. // Hypothesis: inputs that maximize information about globally rare features
  437. // are interesting.
  438. void UpdateCorpusDistribution(Random &Rand) {
  439. // Skip update if no seeds or rare features were added/deleted.
  440. // Sparse updates for local change of feature frequencies,
  441. // i.e., randomly do not skip.
  442. if (!DistributionNeedsUpdate &&
  443. (!Entropic.Enabled || Rand(kSparseEnergyUpdates)))
  444. return;
  445. DistributionNeedsUpdate = false;
  446. size_t N = Inputs.size();
  447. assert(N);
  448. Intervals.resize(N + 1);
  449. Weights.resize(N);
  450. std::iota(Intervals.begin(), Intervals.end(), 0);
  451. std::chrono::microseconds AverageUnitExecutionTime(0);
  452. for (auto II : Inputs) {
  453. AverageUnitExecutionTime += II->TimeOfUnit;
  454. }
  455. AverageUnitExecutionTime /= N;
  456. bool VanillaSchedule = true;
  457. if (Entropic.Enabled) {
  458. for (auto II : Inputs) {
  459. if (II->NeedsEnergyUpdate && II->Energy != 0.0) {
  460. II->NeedsEnergyUpdate = false;
  461. II->UpdateEnergy(RareFeatures.size(), Entropic.ScalePerExecTime,
  462. AverageUnitExecutionTime);
  463. }
  464. }
  465. for (size_t i = 0; i < N; i++) {
  466. if (Inputs[i]->NumFeatures == 0) {
  467. // If the seed doesn't represent any features, assign zero energy.
  468. Weights[i] = 0.;
  469. } else if (Inputs[i]->NumExecutedMutations / kMaxMutationFactor >
  470. NumExecutedMutations / Inputs.size()) {
  471. // If the seed was fuzzed a lot more than average, assign zero energy.
  472. Weights[i] = 0.;
  473. } else {
  474. // Otherwise, simply assign the computed energy.
  475. Weights[i] = Inputs[i]->Energy;
  476. }
  477. // If energy for all seeds is zero, fall back to vanilla schedule.
  478. if (Weights[i] > 0.0)
  479. VanillaSchedule = false;
  480. }
  481. }
  482. if (VanillaSchedule) {
  483. for (size_t i = 0; i < N; i++)
  484. Weights[i] =
  485. Inputs[i]->NumFeatures
  486. ? static_cast<double>((i + 1) *
  487. (Inputs[i]->HasFocusFunction ? 1000 : 1))
  488. : 0.;
  489. }
  490. if (FeatureDebug) {
  491. for (size_t i = 0; i < N; i++)
  492. Printf("%zd ", Inputs[i]->NumFeatures);
  493. Printf("SCORE\n");
  494. for (size_t i = 0; i < N; i++)
  495. Printf("%f ", Weights[i]);
  496. Printf("Weights\n");
  497. }
  498. CorpusDistribution = std::piecewise_constant_distribution<double>(
  499. Intervals.begin(), Intervals.end(), Weights.begin());
  500. }
  501. std::piecewise_constant_distribution<double> CorpusDistribution;
  502. std::vector<double> Intervals;
  503. std::vector<double> Weights;
  504. std::unordered_set<std::string> Hashes;
  505. std::vector<InputInfo *> Inputs;
  506. size_t NumAddedFeatures = 0;
  507. size_t NumUpdatedFeatures = 0;
  508. uint32_t InputSizesPerFeature[kFeatureSetSize];
  509. uint32_t SmallestElementPerFeature[kFeatureSetSize];
  510. bool DistributionNeedsUpdate = true;
  511. uint16_t FreqOfMostAbundantRareFeature = 0;
  512. uint16_t GlobalFeatureFreqs[kFeatureSetSize] = {};
  513. std::vector<uint32_t> RareFeatures;
  514. std::string OutputCorpus;
  515. };
  516. } // namespace fuzzer
  517. #endif // LLVM_FUZZER_CORPUS