Skip to content

Commit 4ad2628

Browse files
authored
[libc] fuzz test for heap_sort (#100826)
Made a fuzz test for heap_sort based off of qsort_fuzz implementation
1 parent 245e607 commit 4ad2628

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

libc/fuzzing/stdlib/CMakeLists.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@ add_libc_fuzzer(
66
libc.src.stdlib.qsort
77
)
88

9+
add_libc_fuzzer(
10+
heap_sort_fuzz
11+
SRCS
12+
heap_sort_fuzz.cpp
13+
DEPENDS
14+
libc.src.stdlib.qsort_util
15+
)
16+
917
add_libc_fuzzer(
1018
atof_differential_fuzz
1119
SRCS
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
}

0 commit comments

Comments
 (0)