Skip to content

Commit 90065da

Browse files
authored
[libc] created fuzz test for sin function (#101411)
Verifies that sin function output is correct by comparing with MPFR output. NaN and inf are not tested (as our output will vary compared to MPFR), and signed zeroes are already tested in unit tests.
1 parent bc747c3 commit 90065da

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

libc/fuzzing/CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ add_custom_target(libc-fuzzer)
33

44
add_subdirectory(__support)
55
# TODO(#85680): Re-enable math fuzzing after headers are sorted out
6-
# add_subdirectory(math)
6+
add_subdirectory(math)
77
add_subdirectory(stdlib)
88
add_subdirectory(stdio)
99
add_subdirectory(string)

libc/fuzzing/math/CMakeLists.txt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,12 @@ add_libc_fuzzer(
6161
libc.src.math.nextafterf
6262
libc.src.math.nextafterl
6363
)
64+
65+
add_libc_fuzzer(
66+
sin_fuzz
67+
NEED_MPFR
68+
SRCS
69+
sin_fuzz.cpp
70+
DEPENDS
71+
libc.src.math.sin
72+
)

libc/fuzzing/math/sin_fuzz.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//===-- sin_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 sin implementation.
10+
///
11+
//===----------------------------------------------------------------------===//
12+
13+
#include "src/math/sin.h"
14+
#include <cmath>
15+
#include <mpfr.h>
16+
17+
extern "C" int LLVMFuzzerTestOneInput(const double x) {
18+
// remove NaN and inf as preconditions
19+
if (std::isnan(x))
20+
return 0;
21+
if (std::isinf(x))
22+
return 0;
23+
// signed zeros already tested in unit tests
24+
if (std::signbit(x) && x == 0.0)
25+
return 0;
26+
mpfr_t input;
27+
mpfr_init2(input, 53);
28+
mpfr_set_d(input, x, MPFR_RNDN);
29+
int output = mpfr_sin(input, input, MPFR_RNDN);
30+
mpfr_subnormalize(input, output, MPFR_RNDN);
31+
double to_compare = mpfr_get_d(input, MPFR_RNDN);
32+
33+
double result = LIBC_NAMESPACE::sin(x);
34+
35+
if (result != to_compare)
36+
__builtin_trap();
37+
38+
mpfr_clear(input);
39+
return 0;
40+
}

0 commit comments

Comments
 (0)