xref: /llvm-project/libc/fuzzing/stdlib/heap_sort_fuzz.cpp (revision a738d81cd2822698539b0482af48d49d91ea5a2e)
14ad2628eSRoseZhang03 //===-- heap_sort_fuzz.cpp ------------------------------------------------===//
24ad2628eSRoseZhang03 //
34ad2628eSRoseZhang03 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
44ad2628eSRoseZhang03 // See https://llvm.org/LICENSE.txt for license information.
54ad2628eSRoseZhang03 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
64ad2628eSRoseZhang03 //
74ad2628eSRoseZhang03 //===----------------------------------------------------------------------===//
84ad2628eSRoseZhang03 ///
94ad2628eSRoseZhang03 /// Fuzzing test for llvm-libc heap_sort implementation.
104ad2628eSRoseZhang03 ///
114ad2628eSRoseZhang03 //===----------------------------------------------------------------------===//
124ad2628eSRoseZhang03 
13*a738d81cSLukas Bergdoll #include "src/stdlib/qsort_util.h"
144ad2628eSRoseZhang03 #include <stdint.h>
154ad2628eSRoseZhang03 
164ad2628eSRoseZhang03 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
174ad2628eSRoseZhang03   const size_t array_size = size / sizeof(int);
184ad2628eSRoseZhang03   if (array_size == 0)
194ad2628eSRoseZhang03     return 0;
204ad2628eSRoseZhang03 
214ad2628eSRoseZhang03   int *array = new int[array_size];
224ad2628eSRoseZhang03   const int *data_as_int = reinterpret_cast<const int *>(data);
234ad2628eSRoseZhang03   for (size_t i = 0; i < array_size; ++i)
244ad2628eSRoseZhang03     array[i] = data_as_int[i];
254ad2628eSRoseZhang03 
26*a738d81cSLukas Bergdoll   const auto is_less = [](const void *a_ptr,
27*a738d81cSLukas Bergdoll                           const void *b_ptr) noexcept -> bool {
28*a738d81cSLukas Bergdoll     const int &a = *static_cast<const int *>(a_ptr);
29*a738d81cSLukas Bergdoll     const int &b = *static_cast<const int *>(b_ptr);
304ad2628eSRoseZhang03 
31*a738d81cSLukas Bergdoll     return a < b;
32*a738d81cSLukas Bergdoll   };
334ad2628eSRoseZhang03 
34*a738d81cSLukas Bergdoll   constexpr bool USE_QUICKSORT = false;
35*a738d81cSLukas Bergdoll   LIBC_NAMESPACE::internal::unstable_sort_impl<USE_QUICKSORT>(
36*a738d81cSLukas Bergdoll       array, array_size, sizeof(int), is_less);
37*a738d81cSLukas Bergdoll 
38*a738d81cSLukas Bergdoll   for (size_t i = 0; i < array_size - 1; ++i) {
394ad2628eSRoseZhang03     if (array[i] > array[i + 1])
404ad2628eSRoseZhang03       __builtin_trap();
41*a738d81cSLukas Bergdoll   }
424ad2628eSRoseZhang03 
434ad2628eSRoseZhang03   delete[] array;
444ad2628eSRoseZhang03   return 0;
454ad2628eSRoseZhang03 }
46