From c378eb43889f3b9555b34bda8edf1519d79e1d97 Mon Sep 17 00:00:00 2001 From: Adhemerval Zanella Date: Tue, 22 Apr 2025 14:06:33 -0300 Subject: [PATCH] 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. --- stdlib/erand48_r.c | 3 ++- stdlib/jrand48_r.c | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/stdlib/erand48_r.c b/stdlib/erand48_r.c index ae68a5b5a0..6d540cb2c0 100644 --- a/stdlib/erand48_r.c +++ b/stdlib/erand48_r.c @@ -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; diff --git a/stdlib/jrand48_r.c b/stdlib/jrand48_r.c index 6fe2863bef..aa9d7de316 100644 --- a/stdlib/jrand48_r.c +++ b/stdlib/jrand48_r.c @@ -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; } -- 2.47.2