blob: 8b0fd7d529a81205034f364985501bf1fac311b4 [file] [log] [blame]
Aaron Ballmanef116982015-01-29 16:58:29 +00001//===- FuzzerCrossOver.cpp - Cross over two test inputs -------------------===//
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// Cross over test inputs.
10//===----------------------------------------------------------------------===//
11
Kostya Serebryany556894f2016-09-21 02:05:39 +000012#include "FuzzerDefs.h"
Kostya Serebryany6f5a8042016-09-21 01:50:50 +000013#include "FuzzerMutate.h"
14#include "FuzzerRandom.h"
Marcos Pividori178fe582016-12-13 17:46:11 +000015#include <cstring>
Aaron Ballmanef116982015-01-29 16:58:29 +000016
17namespace fuzzer {
18
Kostya Serebryanyf3424592015-05-22 22:35:31 +000019// Cross Data1 and Data2, store the result (up to MaxOutSize bytes) in Out.
Kostya Serebryanyec2dcb12015-09-03 21:24:19 +000020size_t MutationDispatcher::CrossOver(const uint8_t *Data1, size_t Size1,
21 const uint8_t *Data2, size_t Size2,
22 uint8_t *Out, size_t MaxOutSize) {
Kostya Serebryanyc8228dd2015-05-26 19:29:33 +000023 assert(Size1 || Size2);
Kostya Serebryany404c69f2015-07-24 01:06:40 +000024 MaxOutSize = Rand(MaxOutSize) + 1;
Kostya Serebryanyf3424592015-05-22 22:35:31 +000025 size_t OutPos = 0;
26 size_t Pos1 = 0;
27 size_t Pos2 = 0;
28 size_t *InPos = &Pos1;
29 size_t InSize = Size1;
30 const uint8_t *Data = Data1;
31 bool CurrentlyUsingFirstData = true;
32 while (OutPos < MaxOutSize && (Pos1 < Size1 || Pos2 < Size2)) {
33 // Merge a part of Data into Out.
34 size_t OutSizeLeft = MaxOutSize - OutPos;
35 if (*InPos < InSize) {
36 size_t InSizeLeft = InSize - *InPos;
37 size_t MaxExtraSize = std::min(OutSizeLeft, InSizeLeft);
Kostya Serebryany404c69f2015-07-24 01:06:40 +000038 size_t ExtraSize = Rand(MaxExtraSize) + 1;
Kostya Serebryanyf3424592015-05-22 22:35:31 +000039 memcpy(Out + OutPos, Data + *InPos, ExtraSize);
40 OutPos += ExtraSize;
41 (*InPos) += ExtraSize;
Aaron Ballmanef116982015-01-29 16:58:29 +000042 }
Kostya Serebryanyf3424592015-05-22 22:35:31 +000043 // Use the other input data on the next iteration.
44 InPos = CurrentlyUsingFirstData ? &Pos2 : &Pos1;
45 InSize = CurrentlyUsingFirstData ? Size2 : Size1;
46 Data = CurrentlyUsingFirstData ? Data2 : Data1;
47 CurrentlyUsingFirstData = !CurrentlyUsingFirstData;
Aaron Ballmanef116982015-01-29 16:58:29 +000048 }
Kostya Serebryanyf3424592015-05-22 22:35:31 +000049 return OutPos;
Aaron Ballmanef116982015-01-29 16:58:29 +000050}
51
52} // namespace fuzzer