blob: f03a94a54dd9a7b1f5967710af29093933a5a634 [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 Serebryanyf3424592015-05-22 22:35:31 +000012#include <cstring>
13
Aaron Ballmanef116982015-01-29 16:58:29 +000014#include "FuzzerInternal.h"
Aaron Ballmanef116982015-01-29 16:58:29 +000015
16namespace fuzzer {
17
Kostya Serebryanyf3424592015-05-22 22:35:31 +000018// Cross Data1 and Data2, store the result (up to MaxOutSize bytes) in Out.
19size_t CrossOver(const uint8_t *Data1, size_t Size1,
20 const uint8_t *Data2, size_t Size2,
21 uint8_t *Out, size_t MaxOutSize) {
22 MaxOutSize = rand() % MaxOutSize + 1;
23 size_t OutPos = 0;
24 size_t Pos1 = 0;
25 size_t Pos2 = 0;
26 size_t *InPos = &Pos1;
27 size_t InSize = Size1;
28 const uint8_t *Data = Data1;
29 bool CurrentlyUsingFirstData = true;
30 while (OutPos < MaxOutSize && (Pos1 < Size1 || Pos2 < Size2)) {
31 // Merge a part of Data into Out.
32 size_t OutSizeLeft = MaxOutSize - OutPos;
33 if (*InPos < InSize) {
34 size_t InSizeLeft = InSize - *InPos;
35 size_t MaxExtraSize = std::min(OutSizeLeft, InSizeLeft);
Aaron Ballmanef116982015-01-29 16:58:29 +000036 size_t ExtraSize = rand() % MaxExtraSize + 1;
Kostya Serebryanyf3424592015-05-22 22:35:31 +000037 memcpy(Out + OutPos, Data + *InPos, ExtraSize);
38 OutPos += ExtraSize;
39 (*InPos) += ExtraSize;
Aaron Ballmanef116982015-01-29 16:58:29 +000040 }
Kostya Serebryanyf3424592015-05-22 22:35:31 +000041 // Use the other input data on the next iteration.
42 InPos = CurrentlyUsingFirstData ? &Pos2 : &Pos1;
43 InSize = CurrentlyUsingFirstData ? Size2 : Size1;
44 Data = CurrentlyUsingFirstData ? Data2 : Data1;
45 CurrentlyUsingFirstData = !CurrentlyUsingFirstData;
Aaron Ballmanef116982015-01-29 16:58:29 +000046 }
Kostya Serebryanyf3424592015-05-22 22:35:31 +000047 return OutPos;
Aaron Ballmanef116982015-01-29 16:58:29 +000048}
49
50} // namespace fuzzer