fuzzing.cpp 24.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
// -*- C++ -*-
//===------------------------- fuzzing.cpp -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

//  A set of routines to use when fuzzing the algorithms in libc++
//  Each one tests a single algorithm.
//
//  They all have the form of:
//      int `algorithm`(const uint8_t *data, size_t size);
//
//  They perform the operation, and then check to see if the results are correct.
//  If so, they return zero, and non-zero otherwise.
//
//  For example, sort calls std::sort, then checks two things:
//      (1) The resulting vector is sorted
//      (2) The resulting vector contains the same elements as the original data.



#include "fuzzing.h"
#include <vector>
#include <algorithm>
#include <functional>
#include <regex>
#include <random>
#include <cassert>
#include <cmath>

#include <iostream>

#ifdef NDEBUG
#undef NDEBUG
#endif
#include <cassert>
//  If we had C++14, we could use the four iterator version of is_permutation and equal

#ifndef _LIBCPP_VERSION
#error These test should be built with libc++ only.
#endif

namespace fuzzing {

//  This is a struct we can use to test the stable_XXX algorithms.
//  perform the operation on the key, then check the order of the payload.

struct stable_test {
    uint8_t key;
    size_t payload;

    stable_test(uint8_t k) : key(k), payload(0) {}
    stable_test(uint8_t k, size_t p) : key(k), payload(p) {}
    };

void swap(stable_test &lhs, stable_test &rhs)
{
    using std::swap;
    swap(lhs.key,     rhs.key);
    swap(lhs.payload, rhs.payload);
}

struct key_less
{
    bool operator () (const stable_test &lhs, const stable_test &rhs) const
    {
        return lhs.key < rhs.key;
    }
};

struct payload_less
{
    bool operator () (const stable_test &lhs, const stable_test &rhs) const
    {
        return lhs.payload < rhs.payload;
    }
};

struct total_less
{
    bool operator () (const stable_test &lhs, const stable_test &rhs) const
    {
        return lhs.key == rhs.key ? lhs.payload < rhs.payload : lhs.key < rhs.key;
    }
};

bool operator==(const stable_test &lhs, const stable_test &rhs)
{
    return lhs.key == rhs.key && lhs.payload == rhs.payload;
}


template<typename T>
struct is_even
{
    bool operator () (const T &t) const
    {
        return t % 2 == 0;
    }
};


template<>
struct is_even<stable_test>
{
    bool operator () (const stable_test &t) const
    {
        return t.key % 2 == 0;
    }
};

typedef std::vector<uint8_t> Vec;
typedef std::vector<stable_test> StableVec;
typedef StableVec::const_iterator SVIter;

//  Cheap version of is_permutation
//  Builds a set of buckets for each of the key values.
//  Sums all the payloads.
//  Not 100% perfect, but _way_ faster
bool is_permutation(SVIter first1, SVIter last1, SVIter first2)
{
    size_t xBuckets[256]  = {0};
    size_t xPayloads[256] = {0};
    size_t yBuckets[256]  = {0};
    size_t yPayloads[256] = {0};

    for (; first1 != last1; ++first1, ++first2)
    {
        xBuckets [first1->key]++;
        xPayloads[first1->key] += first1->payload;

        yBuckets [first2->key]++;
        yPayloads[first2->key] += first2->payload;
    }

    for (size_t i = 0; i < 256; ++i)
    {
        if (xBuckets[i]  != yBuckets[i])
            return false;
        if (xPayloads[i] != yPayloads[i])
            return false;
    }

    return true;
}

template <typename Iter1, typename Iter2>
bool is_permutation(Iter1 first1, Iter1 last1, Iter2 first2)
{
    static_assert((std::is_same<typename std::iterator_traits<Iter1>::value_type, uint8_t>::value), "");
    static_assert((std::is_same<typename std::iterator_traits<Iter2>::value_type, uint8_t>::value), "");

    size_t xBuckets[256]  = {0};
    size_t yBuckets[256]  = {0};

    for (; first1 != last1; ++first1, ++first2)
    {
        xBuckets [*first1]++;
        yBuckets [*first2]++;
    }

    for (size_t i = 0; i < 256; ++i)
        if (xBuckets[i]  != yBuckets[i])
            return false;

    return true;
}

//  == sort ==
int sort(const uint8_t *data, size_t size)
{
    Vec working(data, data + size);
    std::sort(working.begin(), working.end());

    if (!std::is_sorted(working.begin(), working.end())) return 1;
    if (!fuzzing::is_permutation(data, data + size, working.cbegin())) return 99;
    return 0;
}


//  == stable_sort ==
int stable_sort(const uint8_t *data, size_t size)
{
    StableVec input;
    for (size_t i = 0; i < size; ++i)
        input.push_back(stable_test(data[i], i));
    StableVec working = input;
    std::stable_sort(working.begin(), working.end(), key_less());

    if (!std::is_sorted(working.begin(), working.end(), key_less()))   return 1;
    auto iter = working.begin();
    while (iter != working.end())
    {
        auto range = std::equal_range(iter, working.end(), *iter, key_less());
        if (!std::is_sorted(range.first, range.second, total_less())) return 2;
        iter = range.second;
    }
    if (!fuzzing::is_permutation(input.cbegin(), input.cend(), working.cbegin())) return 99;
    return 0;
}

//  == partition ==
int partition(const uint8_t *data, size_t size)
{
    Vec working(data, data + size);
    auto iter = std::partition(working.begin(), working.end(), is_even<uint8_t>());

    if (!std::all_of (working.begin(), iter, is_even<uint8_t>())) return 1;
    if (!std::none_of(iter,   working.end(), is_even<uint8_t>())) return 2;
    if (!fuzzing::is_permutation(data, data + size, working.cbegin())) return 99;
    return 0;
}


//  == partition_copy ==
int partition_copy(const uint8_t *data, size_t size)
{
    Vec v1, v2;
    auto iter = std::partition_copy(data, data + size,
        std::back_inserter<Vec>(v1), std::back_inserter<Vec>(v2),
        is_even<uint8_t>());
  ((void)iter);
//  The two vectors should add up to the original size
    if (v1.size() + v2.size() != size) return 1;

//  All of the even values should be in the first vector, and none in the second
    if (!std::all_of (v1.begin(), v1.end(), is_even<uint8_t>())) return 2;
    if (!std::none_of(v2.begin(), v2.end(), is_even<uint8_t>())) return 3;

//  Every value in both vectors has to be in the original

//	Make a copy of the input, and sort it
    Vec v0{data, data + size};
    std::sort(v0.begin(), v0.end());

//	Sort each vector and ensure that all of the elements appear in the original input
    std::sort(v1.begin(), v1.end());
    if (!std::includes(v0.begin(), v0.end(), v1.begin(), v1.end())) return 4;

    std::sort(v2.begin(), v2.end());
    if (!std::includes(v0.begin(), v0.end(), v2.begin(), v2.end())) return 5;

//  This, while simple, is really slow - 20 seconds on a 500K element input.
//     for (auto v: v1)
//         if (std::find(data, data + size, v) == data + size) return 4;
//
//     for (auto v: v2)
//         if (std::find(data, data + size, v) == data + size) return 5;

    return 0;
}

//  == stable_partition ==
int stable_partition (const uint8_t *data, size_t size)
{
    StableVec input;
    for (size_t i = 0; i < size; ++i)
        input.push_back(stable_test(data[i], i));
    StableVec working = input;
    auto iter = std::stable_partition(working.begin(), working.end(), is_even<stable_test>());

    if (!std::all_of (working.begin(), iter, is_even<stable_test>())) return 1;
    if (!std::none_of(iter,   working.end(), is_even<stable_test>())) return 2;
    if (!std::is_sorted(working.begin(), iter, payload_less()))   return 3;
    if (!std::is_sorted(iter,   working.end(), payload_less()))   return 4;
    if (!fuzzing::is_permutation(input.cbegin(), input.cend(), working.cbegin())) return 99;
    return 0;
}

//  == nth_element ==
//  use the first element as a position into the data
int nth_element (const uint8_t *data, size_t size)
{
    if (size <= 1) return 0;
    const size_t partition_point = data[0] % size;
    Vec working(data + 1, data + size);
    const auto partition_iter = working.begin() + partition_point;
    std::nth_element(working.begin(), partition_iter, working.end());

//  nth may be the end iterator, in this case nth_element has no effect.
    if (partition_iter == working.end())
    {
        if (!std::equal(data + 1, data + size, working.begin())) return 98;
    }
    else
    {
        const uint8_t nth = *partition_iter;
        if (!std::all_of(working.begin(), partition_iter, [=](uint8_t v) { return v <= nth; }))
            return 1;
        if (!std::all_of(partition_iter, working.end(),   [=](uint8_t v) { return v >= nth; }))
            return 2;
        if (!fuzzing::is_permutation(data + 1, data + size, working.cbegin())) return 99;
        }

    return 0;
}

//  == partial_sort ==
//  use the first element as a position into the data
int partial_sort (const uint8_t *data, size_t size)
{
    if (size <= 1) return 0;
    const size_t sort_point = data[0] % size;
    Vec working(data + 1, data + size);
    const auto sort_iter = working.begin() + sort_point;
    std::partial_sort(working.begin(), sort_iter, working.end());

    if (sort_iter != working.end())
    {
        const uint8_t nth = *std::min_element(sort_iter, working.end());
        if (!std::all_of(working.begin(), sort_iter, [=](uint8_t v) { return v <= nth; }))
            return 1;
        if (!std::all_of(sort_iter, working.end(),   [=](uint8_t v) { return v >= nth; }))
            return 2;
    }
    if (!std::is_sorted(working.begin(), sort_iter)) return 3;
    if (!fuzzing::is_permutation(data + 1, data + size, working.cbegin())) return 99;

    return 0;
}


//  == partial_sort_copy ==
//  use the first element as a count
int partial_sort_copy (const uint8_t *data, size_t size)
{
    if (size <= 1) return 0;
    const size_t num_results = data[0] % size;
    Vec results(num_results);
    (void) std::partial_sort_copy(data + 1, data + size, results.begin(), results.end());

//  The results have to be sorted
    if (!std::is_sorted(results.begin(), results.end())) return 1;
//  All the values in results have to be in the original data
    for (auto v: results)
        if (std::find(data + 1, data + size, v) == data + size) return 2;

//  The things in results have to be the smallest N in the original data
    Vec sorted(data + 1, data + size);
    std::sort(sorted.begin(), sorted.end());
    if (!std::equal(results.begin(), results.end(), sorted.begin())) return 3;
    return 0;
}

//  The second sequence has been "uniqued"
template <typename Iter1, typename Iter2>
static bool compare_unique(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2)
{
    assert(first1 != last1 && first2 != last2);
    if (*first1 != *first2) return false;

    uint8_t last_value = *first1;
    ++first1; ++first2;
    while(first1 != last1 && first2 != last2)
    {
    //  Skip over dups in the first sequence
        while (*first1 == last_value)
            if (++first1 == last1) return false;
        if (*first1 != *first2) return false;
        last_value = *first1;
        ++first1; ++first2;
    }

//  Still stuff left in the 'uniqued' sequence - oops
    if (first1 == last1 && first2 != last2) return false;

//  Still stuff left in the original sequence - better be all the same
    while (first1 != last1)
    {
        if (*first1 != last_value) return false;
        ++first1;
    }
    return true;
}

//  == unique ==
int unique (const uint8_t *data, size_t size)
{
    Vec working(data, data + size);
    std::sort(working.begin(), working.end());
    Vec results = working;
    Vec::iterator new_end = std::unique(results.begin(), results.end());
    Vec::iterator it;   // scratch iterator

//  Check the size of the unique'd sequence.
//  it should only be zero if the input sequence was empty.
    if (results.begin() == new_end)
        return working.size() == 0 ? 0 : 1;

//  'results' is sorted
    if (!std::is_sorted(results.begin(), new_end)) return 2;

//  All the elements in 'results' must be different
    it = results.begin();
    uint8_t prev_value = *it++;
    for (; it != new_end; ++it)
    {
        if (*it == prev_value) return 3;
        prev_value = *it;
    }

//  Every element in 'results' must be in 'working'
    for (it = results.begin(); it != new_end; ++it)
        if (std::find(working.begin(), working.end(), *it) == working.end())
            return 4;

//  Every element in 'working' must be in 'results'
    for (auto v : working)
        if (std::find(results.begin(), new_end, v) == new_end)
            return 5;

    return 0;
}

//  == unique_copy ==
int unique_copy (const uint8_t *data, size_t size)
{
    Vec working(data, data + size);
    std::sort(working.begin(), working.end());
    Vec results;
    (void) std::unique_copy(working.begin(), working.end(),
                            std::back_inserter<Vec>(results));
    Vec::iterator it;   // scratch iterator

//  Check the size of the unique'd sequence.
//  it should only be zero if the input sequence was empty.
    if (results.size() == 0)
        return working.size() == 0 ? 0 : 1;

//  'results' is sorted
    if (!std::is_sorted(results.begin(), results.end())) return 2;

//  All the elements in 'results' must be different
    it = results.begin();
    uint8_t prev_value = *it++;
    for (; it != results.end(); ++it)
    {
        if (*it == prev_value) return 3;
        prev_value = *it;
    }

//  Every element in 'results' must be in 'working'
    for (auto v : results)
        if (std::find(working.begin(), working.end(), v) == working.end())
            return 4;

//  Every element in 'working' must be in 'results'
    for (auto v : working)
        if (std::find(results.begin(), results.end(), v) == results.end())
            return 5;

    return 0;
}


// --   regex fuzzers
static int regex_helper(const uint8_t *data, size_t size, std::regex::flag_type flag)
{
    if (size > 0)
    {
#ifndef _LIBCPP_NO_EXCEPTIONS
        try
        {
            std::string s((const char *)data, size);
            std::regex re(s, flag);
            return std::regex_match(s, re) ? 1 : 0;
        }
        catch (std::regex_error &ex) {}
#else
      ((void)data);
      ((void)size);
      ((void)flag);
#endif
    }
    return 0;
}


int regex_ECMAScript (const uint8_t *data, size_t size)
{
    (void) regex_helper(data, size, std::regex_constants::ECMAScript);
    return 0;
}

int regex_POSIX (const uint8_t *data, size_t size)
{
    (void) regex_helper(data, size, std::regex_constants::basic);
    return 0;
}

int regex_extended (const uint8_t *data, size_t size)
{
    (void) regex_helper(data, size, std::regex_constants::extended);
    return 0;
}

int regex_awk (const uint8_t *data, size_t size)
{
    (void) regex_helper(data, size, std::regex_constants::awk);
    return 0;
}

int regex_grep (const uint8_t *data, size_t size)
{
    (void) regex_helper(data, size, std::regex_constants::grep);
    return 0;
}

int regex_egrep (const uint8_t *data, size_t size)
{
    (void) regex_helper(data, size, std::regex_constants::egrep);
    return 0;
}

// --   heap fuzzers
int make_heap (const uint8_t *data, size_t size)
{
    Vec working(data, data + size);
    std::make_heap(working.begin(), working.end());

    if (!std::is_heap(working.begin(), working.end())) return 1;
    if (!fuzzing::is_permutation(data, data + size, working.cbegin())) return 99;
    return 0;
}

int push_heap (const uint8_t *data, size_t size)
{
    if (size < 2) return 0;

//  Make a heap from the first half of the data
    Vec working(data, data + size);
    auto iter = working.begin() + (size / 2);
    std::make_heap(working.begin(), iter);
    if (!std::is_heap(working.begin(), iter)) return 1;

//  Now push the rest onto the heap, one at a time
    ++iter;
    for (; iter != working.end(); ++iter) {
        std::push_heap(working.begin(), iter);
        if (!std::is_heap(working.begin(), iter)) return 2;
        }

    if (!fuzzing::is_permutation(data, data + size, working.cbegin())) return 99;
    return 0;
}

int pop_heap (const uint8_t *data, size_t size)
{
    if (size < 2) return 0;
    Vec working(data, data + size);
    std::make_heap(working.begin(), working.end());

//  Pop things off, one at a time
    auto iter = --working.end();
    while (iter != working.begin()) {
        std::pop_heap(working.begin(), iter);
        if (!std::is_heap(working.begin(), --iter)) return 2;
        }

    return 0;
}


// --   search fuzzers
int search (const uint8_t *data, size_t size)
{
    if (size < 2) return 0;

    const size_t pat_size = data[0] * (size - 1) / std::numeric_limits<uint8_t>::max();
    assert(pat_size <= size - 1);
    const uint8_t *pat_begin = data + 1;
    const uint8_t *pat_end   = pat_begin + pat_size;
    const uint8_t *data_end  = data + size;
    assert(pat_end <= data_end);
//  std::cerr << "data[0] = " << size_t(data[0]) << " ";
//  std::cerr << "Pattern size = " << pat_size << "; corpus is " << size - 1 << std::endl;
    auto it = std::search(pat_end, data_end, pat_begin, pat_end);
    if (it != data_end) // not found
        if (!std::equal(pat_begin, pat_end, it))
            return 1;
    return 0;
}

template <typename S>
static int search_helper (const uint8_t *data, size_t size)
{
    if (size < 2) return 0;

    const size_t pat_size = data[0] * (size - 1) / std::numeric_limits<uint8_t>::max();
    const uint8_t *pat_begin = data + 1;
    const uint8_t *pat_end   = pat_begin + pat_size;
    const uint8_t *data_end  = data + size;

    auto it = std::search(pat_end, data_end, S(pat_begin, pat_end));
    if (it != data_end) // not found
        if (!std::equal(pat_begin, pat_end, it))
            return 1;
    return 0;
}

//  These are still in std::experimental
// int search_boyer_moore (const uint8_t *data, size_t size)
// {
//  return search_helper<std::boyer_moore_searcher<const uint8_t *>>(data, size);
// }
//
// int search_boyer_moore_horspool (const uint8_t *data, size_t size)
// {
//  return search_helper<std::boyer_moore_horspool_searcher<const uint8_t *>>(data, size);
// }


// --   set operation fuzzers
template <typename S>
static void set_helper (const uint8_t *data, size_t size, Vec &v1, Vec &v2)
{
    assert(size > 1);

    const size_t pat_size = data[0] * (size - 1) / std::numeric_limits<uint8_t>::max();
    const uint8_t *pat_begin = data + 1;
    const uint8_t *pat_end   = pat_begin + pat_size;
    const uint8_t *data_end  = data + size;
    v1.assign(pat_begin, pat_end);
    v2.assign(pat_end, data_end);

    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());
}

enum class ParamKind {
  OneValue,
  TwoValues,
  PointerRange
};

template <class IntT>
std::vector<IntT> GetValues(const uint8_t *data, size_t size) {
  std::vector<IntT> result;
  while (size >= sizeof(IntT)) {
    IntT tmp;
    memcpy(&tmp, data, sizeof(IntT));
    size -= sizeof(IntT);
    data += sizeof(IntT);
    result.push_back(tmp);
  }
  return result;
}

enum InitKind {
  Default,
  DoubleOnly,
  VectorDouble,
  VectorResultType
};



template <class Dist>
struct ParamTypeHelper {
  using ParamT = typename Dist::param_type;
  using ResultT = typename Dist::result_type;
  static_assert(std::is_same<ResultT, typename ParamT::distribution_type::result_type>::value, "");
  static  ParamT Create(const uint8_t* data, size_t size, bool &OK) {

    constexpr bool select_vector_result = std::is_constructible<ParamT, ResultT*, ResultT*, ResultT*>::value;
    constexpr bool select_vector_double = std::is_constructible<ParamT, double*, double*>::value;
    constexpr int selector = select_vector_result ? 0 : (select_vector_double ? 1 : 2);
    return DispatchAndCreate(std::integral_constant<int, selector>{}, data, size, OK);

  }

  static ParamT DispatchAndCreate(std::integral_constant<int, 0>, const uint8_t *data, size_t size, bool &OK) {
    return CreateVectorResult(data, size, OK);
  }
  static ParamT DispatchAndCreate(std::integral_constant<int, 1>, const uint8_t *data, size_t size, bool &OK) {
    return CreateVectorDouble(data, size, OK);
  }
  static ParamT DispatchAndCreate(std::integral_constant<int, 2>, const uint8_t *data, size_t size, bool &OK) {
    return CreateDefault(data, size, OK);
  }

static ParamT
CreateVectorResult(const uint8_t *data, size_t size, bool &OK) {
  auto Input = GetValues<ResultT>(data, size);
  OK = false;
  if (Input.size() < 10)
    return ParamT{};
  OK = true;
  auto Beg = Input.begin();
  auto End = Input.end();
  auto Mid = Beg + ((End - Beg) / 2);

  assert(Mid - Beg <= (End  -  Mid));
  ParamT p(Beg, Mid, Mid);
  return p;
}

  static ParamT
  CreateVectorDouble(const uint8_t *data, size_t size, bool &OK) {
    auto Input = GetValues<double>(data, size);

    OK = true;
    auto Beg = Input.begin();
    auto End = Input.end();

    ParamT p(Beg, End);
    return p;
  }


  static ParamT
  CreateDefault(const uint8_t *data, size_t size, bool &OK) {
    OK = false;
    if (size < sizeof(ParamT))
      return ParamT{};
    OK = true;
    ParamT input;
    memcpy(&input, data, sizeof(ParamT));
    return input;
  }

};




template <class IntT>
struct ParamTypeHelper<std::poisson_distribution<IntT>> {
    using Dist = std::poisson_distribution<IntT>;
      using ParamT = typename Dist::param_type;
    using ResultT = typename Dist::result_type;

     static ParamT Create(const uint8_t *data, size_t size, bool& OK) {
        OK = false;
        auto vals = GetValues<double>(data, size);
        if (vals.empty() || std::isnan(vals[0]) || std::isnan(std::abs(vals[0])) || vals[0] < 0 )
          return ParamT{};
        OK = true;
        //std::cerr << "Value: " << vals[0] << std::endl;
        return ParamT{vals[0]};
     }
};


template <class IntT>
struct ParamTypeHelper<std::geometric_distribution<IntT>> {
    using Dist = std::geometric_distribution<IntT>;
      using ParamT = typename Dist::param_type;
    using ResultT = typename Dist::result_type;

     static ParamT Create(const uint8_t *data, size_t size, bool& OK) {
        OK = false;
        auto vals = GetValues<double>(data, size);
        if (vals.empty() || std::isnan(vals[0]) || vals[0] < 0 )
          return ParamT{};
        OK = true;
       // std::cerr << "Value: " << vals[0] << std::endl;
        return ParamT{vals[0]};
     }
};


template <class IntT>
struct ParamTypeHelper<std::lognormal_distribution<IntT>> {
    using Dist = std::lognormal_distribution<IntT>;
      using ParamT = typename Dist::param_type;
    using ResultT = typename Dist::result_type;

     static ParamT Create(const uint8_t *data, size_t size, bool& OK) {
        OK = false;
        auto vals = GetValues<ResultT>(data, size);
        if (vals.size() < 2 )
          return ParamT{};
        OK = true;
        return ParamT{vals[0], vals[1]};
     }
};


template <>
struct ParamTypeHelper<std::bernoulli_distribution> {
    using Dist = std::bernoulli_distribution;
      using ParamT = typename Dist::param_type;
    using ResultT = typename Dist::result_type;

     static ParamT Create(const uint8_t *data, size_t size, bool& OK) {
        OK = false;
        auto vals = GetValues<double>(data, size);
        if (vals.empty())
          return ParamT{};
        OK = true;
        return ParamT{vals[0]};
     }
};

template <class Distribution>
int random_distribution_helper(const uint8_t *data, size_t size) {

  std::mt19937 engine;
  using ParamT = typename Distribution::param_type;
  bool OK;
  ParamT p = ParamTypeHelper<Distribution>::Create(data, size, OK);
  if (!OK)
    return 0;
  Distribution d(p);
  volatile auto res = d(engine);
  if (std::isnan(res)) {
    // FIXME(llvm.org/PR44289):
    // Investigate why these distributions are returning NaN and decide
    // if that's what we want them to be doing.
    //
    // Make this assert false (or return non-zero).
    return 0;
  }
  return 0;
}

#define DEFINE_RANDOM_TEST(name, ...) \
int name(const uint8_t *data, size_t size) { \
  return random_distribution_helper< std::name __VA_ARGS__ >(data, size); \
}
DEFINE_RANDOM_TEST(uniform_int_distribution,<std::int16_t>)
DEFINE_RANDOM_TEST(uniform_real_distribution,<float>)
DEFINE_RANDOM_TEST(bernoulli_distribution)
DEFINE_RANDOM_TEST(poisson_distribution,<std::int16_t>)
DEFINE_RANDOM_TEST(geometric_distribution,<std::int16_t>)
DEFINE_RANDOM_TEST(binomial_distribution, <std::int16_t>)
DEFINE_RANDOM_TEST(negative_binomial_distribution, <std::int16_t>)
DEFINE_RANDOM_TEST(exponential_distribution, <float>)
DEFINE_RANDOM_TEST(gamma_distribution, <float>)
DEFINE_RANDOM_TEST(weibull_distribution, <float>)
DEFINE_RANDOM_TEST(extreme_value_distribution, <float>)
DEFINE_RANDOM_TEST(normal_distribution, <float>)
DEFINE_RANDOM_TEST(lognormal_distribution, <float>)
DEFINE_RANDOM_TEST(chi_squared_distribution, <float>)
DEFINE_RANDOM_TEST(cauchy_distribution, <float>)
DEFINE_RANDOM_TEST(fisher_f_distribution, <float>)
DEFINE_RANDOM_TEST(student_t_distribution, <float>)
DEFINE_RANDOM_TEST(discrete_distribution, <std::int16_t>)
DEFINE_RANDOM_TEST(piecewise_constant_distribution, <float>)
DEFINE_RANDOM_TEST(piecewise_linear_distribution, <float>)

} // namespace fuzzing