FuzzerCrossOver.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //===- FuzzerCrossOver.cpp - Cross over two test inputs -------------------===//
  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. // Cross over test inputs.
  9. //===----------------------------------------------------------------------===//
  10. #include "FuzzerDefs.h"
  11. #include "FuzzerMutate.h"
  12. #include "FuzzerRandom.h"
  13. #include <cstring>
  14. namespace fuzzer {
  15. // Cross Data1 and Data2, store the result (up to MaxOutSize bytes) in Out.
  16. size_t MutationDispatcher::CrossOver(const uint8_t *Data1, size_t Size1,
  17. const uint8_t *Data2, size_t Size2,
  18. uint8_t *Out, size_t MaxOutSize) {
  19. assert(Size1 || Size2);
  20. MaxOutSize = Rand(MaxOutSize) + 1;
  21. size_t OutPos = 0;
  22. size_t Pos1 = 0;
  23. size_t Pos2 = 0;
  24. size_t *InPos = &Pos1;
  25. size_t InSize = Size1;
  26. const uint8_t *Data = Data1;
  27. bool CurrentlyUsingFirstData = true;
  28. while (OutPos < MaxOutSize && (Pos1 < Size1 || Pos2 < Size2)) {
  29. // Merge a part of Data into Out.
  30. size_t OutSizeLeft = MaxOutSize - OutPos;
  31. if (*InPos < InSize) {
  32. size_t InSizeLeft = InSize - *InPos;
  33. size_t MaxExtraSize = std::min(OutSizeLeft, InSizeLeft);
  34. size_t ExtraSize = Rand(MaxExtraSize) + 1;
  35. memcpy(Out + OutPos, Data + *InPos, ExtraSize);
  36. OutPos += ExtraSize;
  37. (*InPos) += ExtraSize;
  38. }
  39. // Use the other input data on the next iteration.
  40. InPos = CurrentlyUsingFirstData ? &Pos2 : &Pos1;
  41. InSize = CurrentlyUsingFirstData ? Size2 : Size1;
  42. Data = CurrentlyUsingFirstData ? Data2 : Data1;
  43. CurrentlyUsingFirstData = !CurrentlyUsingFirstData;
  44. }
  45. return OutPos;
  46. }
  47. } // namespace fuzzer