94af6d547edcb7c58b6476c7710d7273dbfd7555
[oota-llvm.git] / lib / Fuzzer / FuzzerCrossOver.cpp
1 //===- 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
12 #include "FuzzerInternal.h"
13 #include <algorithm>
14
15 namespace fuzzer {
16
17 // Cross A and B, store the result (ap to MaxLen bytes) in U.
18 void CrossOver(const Unit &A, const Unit &B, Unit *U, size_t MaxLen) {
19   size_t Size = rand() % MaxLen + 1;
20   U->clear();
21   const Unit *V = &A;
22   size_t PosA = 0;
23   size_t PosB = 0;
24   size_t *Pos = &PosA;
25   while (U->size() < Size && (PosA < A.size() || PosB < B.size())) {
26     // Merge a part of V into U.
27     size_t SizeLeftU = Size - U->size();
28     if (*Pos < V->size()) {
29       size_t SizeLeftV = V->size() - *Pos;
30       size_t MaxExtraSize = std::min(SizeLeftU, SizeLeftV);
31       size_t ExtraSize = rand() % MaxExtraSize + 1;
32       U->insert(U->end(), V->begin() + *Pos, V->begin() + *Pos + ExtraSize);
33       (*Pos) += ExtraSize;
34     }
35
36     // Use the other Unit on the next iteration.
37     if (Pos == &PosA) {
38       Pos = &PosB;
39       V = &B;
40     } else {
41       Pos = &PosA;
42       V = &A;
43     }
44   }
45 }
46
47 }  // namespace fuzzer