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