1 //===-- qsort_fuzz.cpp ----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// Fuzzing test for llvm-libc qsort implementation.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #include "src/stdlib/qsort.h"
14 #include <stdint.h>
15 
16 static int int_compare(const void *l, const void *r) {
17   int li = *reinterpret_cast<const int *>(l);
18   int ri = *reinterpret_cast<const int *>(r);
19   if (li == ri)
20     return 0;
21   else if (li > ri)
22     return 1;
23   else
24     return -1;
25 }
26 
27 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
28   const size_t array_size = size / sizeof(int);
29   if (array_size == 0)
30     return 0;
31 
32   int *array = new int[array_size];
33   const int *data_as_int = reinterpret_cast<const int *>(data);
34   for (size_t i = 0; i < array_size; ++i)
35     array[i] = data_as_int[i];
36 
37   __llvm_libc::qsort(array, array_size, sizeof(int), int_compare);
38 
39   for (size_t i = 0; i < array_size - 1; ++i) {
40     if (array[i] > array[i + 1])
41       __builtin_trap();
42   }
43 
44   delete[] array;
45   return 0;
46 }
47