xref: /llvm-project/libc/fuzzing/stdlib/heap_sort_fuzz.cpp (revision 4ad2628ec9bf492f7c2ad4a9ada835d06b1a55e7)
1 //===-- heap_sort_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 heap_sort implementation.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #include "src/__support/macros/config.h"
14 #include "src/stdlib/heap_sort.h"
15 #include <stdint.h>
16 
17 static int int_compare(const void *l, const void *r) {
18   int li = *reinterpret_cast<const int *>(l);
19   int ri = *reinterpret_cast<const int *>(r);
20   if (li == ri)
21     return 0;
22   if (li > ri)
23     return 1;
24   return -1;
25 }
26 
27 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
28 
29   const size_t array_size = size / sizeof(int);
30   if (array_size == 0)
31     return 0;
32 
33   int *array = new int[array_size];
34   const int *data_as_int = reinterpret_cast<const int *>(data);
35   for (size_t i = 0; i < array_size; ++i)
36     array[i] = data_as_int[i];
37 
38   auto arr = LIBC_NAMESPACE::internal::Array(
39       reinterpret_cast<uint8_t *>(array), array_size, sizeof(int), int_compare);
40 
41   LIBC_NAMESPACE::internal::heap_sort(arr);
42 
43   for (size_t i = 0; i < array_size - 1; ++i)
44     if (array[i] > array[i + 1])
45       __builtin_trap();
46 
47   delete[] array;
48   return 0;
49 }
50