Skip to content

Commit cfa3387

Browse files
sribee8Sriya Pratipati
authored andcommitted
[libc] cbrt fuzz test (llvm#150063)
Implemented fuzz test for cbrt Co-authored-by: Sriya Pratipati <[email protected]>
1 parent 180d99f commit cfa3387

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

libc/fuzzing/math/CMakeLists.txt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,12 @@ add_libc_fuzzer(
196196
DEPENDS
197197
libc.src.__support.FPUtil.generic.sqrt
198198
)
199+
200+
add_libc_fuzzer(
201+
cbrt_fuzz
202+
NEED_MPFR
203+
SRCS
204+
cbrt_fuzz.cpp
205+
DEPENDS
206+
libc.src.math.cbrt
207+
)

libc/fuzzing/math/cbrt_fuzz.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//===-- cbrt_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 cbrt implementation.
10+
///
11+
//===----------------------------------------------------------------------===//
12+
13+
#include "src/math/cbrt.h"
14+
#include "utils/MPFRWrapper/mpfr_inc.h"
15+
#include <cstdint>
16+
#include <cstring>
17+
#include <iostream>
18+
#include <math.h>
19+
20+
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
21+
mpfr_t input;
22+
mpfr_init2(input, 53);
23+
for (size_t i = 0; i < size / sizeof(double); ++i) {
24+
double x;
25+
std::memcpy(&x, data, sizeof(double));
26+
data += sizeof(double);
27+
// remove NaN and inf
28+
if (isnan(x) || isinf(x))
29+
continue;
30+
// signed zeros already tested in unit tests
31+
if (signbit(x) && x == 0.0)
32+
continue;
33+
34+
mpfr_set_d(input, x, MPFR_RNDN);
35+
int output = mpfr_cbrt(input, input, MPFR_RNDN);
36+
mpfr_subnormalize(input, output, MPFR_RNDN);
37+
double to_compare = mpfr_get_d(input, MPFR_RNDN);
38+
39+
double result = LIBC_NAMESPACE::cbrt(x);
40+
41+
if (result != to_compare) {
42+
std::cout << std::hexfloat << "Failing input: " << x << std::endl;
43+
std::cout << std::hexfloat << "Failing output: " << result << std::endl;
44+
std::cout << std::hexfloat << "Expected: " << to_compare << std::endl;
45+
__builtin_trap();
46+
}
47+
}
48+
mpfr_clear(input);
49+
return 0;
50+
}

0 commit comments

Comments
 (0)