65 lines · cpp
1//===-- hypot_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 hypot implementation.10///11//===----------------------------------------------------------------------===//12 13#include "src/math/hypot.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 in_x;22 mpfr_t in_y;23 mpfr_t out;24 mpfr_init2(in_x, 53);25 mpfr_init2(in_y, 53);26 mpfr_init2(out, 128);27 28 for (size_t i = 0; i < size / (2 * sizeof(double)); ++i) {29 double x;30 double y;31 32 std::memcpy(&x, data, sizeof(double));33 data += sizeof(double);34 std::memcpy(&y, data, sizeof(double));35 data += sizeof(double);36 37 // remove NaN, inf, and signed zeros38 if (isnan(x) || isinf(x) || (signbit(x) && x == 0.0))39 return 0;40 if (isnan(y) || isinf(y) || (signbit(y) && y == 0.0))41 return 0;42 43 mpfr_set_d(in_x, x, MPFR_RNDN);44 mpfr_set_d(in_y, y, MPFR_RNDN);45 46 int output = mpfr_hypot(out, in_x, in_y, MPFR_RNDN);47 mpfr_subnormalize(out, output, MPFR_RNDN);48 double to_compare = mpfr_get_d(out, MPFR_RNDN);49 50 double result = LIBC_NAMESPACE::hypot(x, y);51 52 if (result != to_compare) {53 std::cout << std::hexfloat << "Failing x: " << x << std::endl;54 std::cout << std::hexfloat << "Failing y: " << y << std::endl;55 std::cout << std::hexfloat << "Failing output: " << result << std::endl;56 std::cout << std::hexfloat << "Expected: " << to_compare << std::endl;57 __builtin_trap();58 }59 }60 mpfr_clear(in_x);61 mpfr_clear(in_y);62 mpfr_clear(out);63 return 0;64}65