71 lines · cpp
1//===-- sincos_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-exception6//7//===----------------------------------------------------------------------===//8///9/// Fuzzing test for llvm-libc sincos implementation.10///11//===----------------------------------------------------------------------===//12 13#include "src/math/sincos.h"14#include "utils/MPFRWrapper/mpfr_inc.h"15#include <cstdint>16#include <cstring>17#include <iostream>18#include <math.h>19 20extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {21 mpfr_t input;22 mpfr_t sin_x;23 mpfr_t cos_x;24 25 mpfr_init2(input, 53);26 mpfr_init2(sin_x, 53);27 mpfr_init2(cos_x, 53);28 for (size_t i = 0; i < size / sizeof(double); ++i) {29 double x;30 std::memcpy(&x, data, sizeof(double));31 data += sizeof(double);32 33 // remove NaN and inf as preconditions34 if (isnan(x) || isinf(x))35 continue;36 37 // signed zeros already tested in unit tests38 if (signbit(x) && x == 0.0)39 continue;40 41 mpfr_set_d(input, x, MPFR_RNDN);42 int output = mpfr_sin_cos(sin_x, cos_x, input, MPFR_RNDN);43 mpfr_subnormalize(sin_x, output, MPFR_RNDN);44 mpfr_subnormalize(cos_x, output, MPFR_RNDN);45 46 double to_compare_sin = mpfr_get_d(sin_x, MPFR_RNDN);47 double to_compare_cos = mpfr_get_d(cos_x, MPFR_RNDN);48 49 double sin_res, cos_res;50 LIBC_NAMESPACE::sincos(x, &sin_res, &cos_res);51 52 if (sin_res != to_compare_sin || cos_res != to_compare_cos) {53 std::cout << std::hexfloat << "Failing input: " << x << std::endl;54 std::cout << std::hexfloat << "Failing sin output: " << sin_res55 << std::endl;56 std::cout << std::hexfloat << "Expected sin: " << to_compare_sin57 << std::endl;58 std::cout << std::hexfloat << "Failing cos output: " << cos_res59 << std::endl;60 std::cout << std::hexfloat << "Expected cos: " << to_compare_cos61 << std::endl;62 __builtin_trap();63 }64 }65 66 mpfr_clear(input);67 mpfr_clear(sin_x);68 mpfr_clear(cos_x);69 return 0;70}71