1/* mpfr_check -- Check if a floating-point number has not been corrupted. 2 3Copyright 2003-2004, 2006-2023 Free Software Foundation, Inc. 4Contributed by the AriC and Caramba projects, INRIA. 5 6This file is part of the GNU MPFR Library. 7 8The GNU MPFR Library is free software; you can redistribute it and/or modify 9it under the terms of the GNU Lesser General Public License as published by 10the Free Software Foundation; either version 3 of the License, or (at your 11option) any later version. 12 13The GNU MPFR Library is distributed in the hope that it will be useful, but 14WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 15or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 16License for more details. 17 18You should have received a copy of the GNU Lesser General Public License 19along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see 20https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., 2151 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ 22 23#include "mpfr-impl.h" 24 25/* 26 * Check if x is a valid mpfr_t initialized by mpfr_init 27 * Returns 0 if isn't valid 28 * 29 * Note: Due to the MPFR_GET_ALLOC_SIZE test, this function must not 30 * be called on statically allocated numbers (only used inside MPFR). 31 * Anyway, this test should not be useful on such numbers. 32 */ 33int 34mpfr_check (mpfr_srcptr x) 35{ 36 mp_size_t s, i; 37 mp_limb_t tmp; 38 volatile mp_limb_t *xm; 39 mpfr_prec_t prec; 40 int rw; 41 42 /* Check sign */ 43 if (MPFR_SIGN(x) != MPFR_SIGN_POS && 44 MPFR_SIGN(x) != MPFR_SIGN_NEG) 45 return 0; 46 /* Check precision */ 47 prec = MPFR_PREC(x); 48 if (! MPFR_PREC_COND (prec)) 49 return 0; 50 /* Check mantissa */ 51 xm = MPFR_MANT(x); 52 if (xm == NULL) 53 return 0; 54 /* Check size of mantissa */ 55 s = MPFR_GET_ALLOC_SIZE(x); 56 if (s <= 0 || s > MP_SIZE_T_MAX || 57 prec > (mpfr_prec_t) s * GMP_NUMB_BITS) 58 return 0; 59 /* Access all the mp_limb of the mantissa: may do a seg fault */ 60 for (i = 0 ; i < s ; i++) 61 tmp = xm[i]; 62 /* Check singular numbers (do not use MPFR_IS_PURE_FP() in order to avoid 63 any assertion checking, as this function mpfr_check() does something 64 similar by returning a Boolean instead of doing an abort if the format 65 is incorrect). */ 66 if (MPFR_IS_SINGULAR (x)) 67 return MPFR_IS_ZERO(x) || MPFR_IS_NAN(x) || MPFR_IS_INF(x); 68 /* Check the most significant limb (its MSB must be 1) */ 69 if (! MPFR_IS_NORMALIZED (x)) 70 return 0; 71 /* Check the least significant limb (the trailing bits must be 0) */ 72 rw = prec % GMP_NUMB_BITS; 73 if (rw != 0) 74 { 75 tmp = MPFR_LIMB_MASK (GMP_NUMB_BITS - rw); 76 if ((xm[0] & tmp) != 0) 77 return 0; 78 } 79 /* Check exponent range */ 80 return MPFR_EXP_IN_RANGE (MPFR_EXP (x)); 81} 82