stdlib: Fix UB on erand48/jrand48

With glibc built with ubsan it triggers:

UBSAN: Undefined behaviour in jrand48_r.c:29:34 left shift of 41612 by 16 cannot be represented in type 'int'
UBSAN: Undefined behaviour in erand48_r.c:39:45 left shift of 3972 by 20 cannot be represented in type 'int'

Fix by casting to uint32_t for the shift operation.
This commit is contained in:
Adhemerval Zanella 2025-04-22 14:06:33 -03:00
parent ea81e7d8c6
commit c378eb4388
2 changed files with 3 additions and 2 deletions

View File

@ -36,7 +36,8 @@ __erand48_r (unsigned short int xsubi[3], struct drand48_data *buffer,
temp.ieee.negative = 0;
temp.ieee.exponent = IEEE754_DOUBLE_BIAS;
temp.ieee.mantissa0 = (xsubi[2] << 4) | (xsubi[1] >> 12);
temp.ieee.mantissa1 = ((xsubi[1] & 0xfff) << 20) | (xsubi[0] << 4);
temp.ieee.mantissa1 = (((uint32_t)xsubi[1] & 0xfff) << 20)
| ((uint32_t)xsubi[0] << 4);
/* Please note the lower 4 bits of mantissa1 are always 0. */
*result = temp.d - 1.0;

View File

@ -26,7 +26,7 @@ __jrand48_r (unsigned short int xsubi[3], struct drand48_data *buffer,
return -1;
/* Store the result. */
*result = (int32_t) ((xsubi[2] << 16) | xsubi[1]);
*result = (int32_t) (((uint32_t)xsubi[2] << 16) | (uint32_t)xsubi[1]);
return 0;
}