Index | Thread | Search

From:
Alex Rønne Petersen <alex@alexrp.com>
Subject:
libc: fix jrand48(3) and mrand48(3) result range
To:
tech@openbsd.org
Date:
Mon, 16 Nov 2026 11:46:47 +0100

Download raw body.

Thread
  • Alex Rønne Petersen:

    libc: fix jrand48(3) and mrand48(3) result range

Hi,

The attached patch fixes OpenBSD's jrand48() and mrand48() functions to
return values in the documented [-2**31, 2**31-1] range. We noticed this
bug while running Zig's libc test suite against OpenBSD 8.0 on amd64. I
don't think the bug occurs on 32-bit architectures, but I don't have a
machine to test that.

Regards,
Alex
Index: lib/libc/stdlib/jrand48.c
===================================================================
RCS file: /cvs/src/lib/libc/stdlib/jrand48.c,v
diff -u -p -r1.3 jrand48.c
--- lib/libc/stdlib/jrand48.c	8 Aug 2005 08:05:36 -0000	1.3
+++ lib/libc/stdlib/jrand48.c	16 Nov 2026 10:34:56 -0000
@@ -18,5 +18,5 @@ long
 jrand48(unsigned short xseed[3])
 {
 	__dorand48(xseed);
-	return ((long) xseed[2] << 16) + (long) xseed[1];
+	return (int) (((unsigned int) xseed[2] << 16) | xseed[1]);
 }
Index: lib/libc/stdlib/mrand48.c
===================================================================
RCS file: /cvs/src/lib/libc/stdlib/mrand48.c,v
diff -u -p -r1.6 mrand48.c
--- lib/libc/stdlib/mrand48.c	27 Aug 2015 04:33:31 -0000	1.6
+++ lib/libc/stdlib/mrand48.c	16 Nov 2026 10:34:56 -0000
@@ -20,5 +20,5 @@ mrand48(void)
 	if (__rand48_deterministic == 0)
 		return (int)arc4random();
 	__dorand48(__rand48_seed);
-	return ((long) __rand48_seed[2] << 16) + (long) __rand48_seed[1];
+	return (int) (((unsigned int) __rand48_seed[2] << 16) | __rand48_seed[1]);
 }