Permalink
Browse files

1) POSIX requires rand(3) return values to be in the [0, RAND_MAX]

range, but ACM formula we use have internal state (and return value) in
the [1, 0x7ffffffe] range, so our RAND_MAX (0x7fffffff) is never reached
because it is off by one, zero is not reached too.

Correct both RAND_MAX and rand(3) return value, shifting last one
to the 0 by 1 subtracted, resulting POSIXed [0, 0x7ffffffd(=new
RAND_MAX)] range.

2) Add a checks for not overflowing on too big seeds. It may happens on
the machines, where sizeof(unsigned int) > 32 bits.

This change is binary compatible because range is reduced, not expanded,
so no bump is needed.

Reviewed by:    bde
Approved by:    re (glebius)
  • Loading branch information...
1 parent 20f5323 commit f04b0e35393fe03b4f6d9b64ca80156139312f58 ache committed Jul 24, 2013
Showing with 34 additions and 9 deletions.
  1. +1 −1 include/stdlib.h
  2. +33 −8 lib/libc/stdlib/rand.c
View
@@ -69,7 +69,7 @@ typedef struct {
#define EXIT_FAILURE 1
#define EXIT_SUCCESS 0
-#define RAND_MAX 0x7fffffff
+#define RAND_MAX 0x7ffffffd
__BEGIN_DECLS
#ifdef _XLOCALE_H_
@@ -67,31 +67,48 @@ do_rand(unsigned long *ctx)
*/
long hi, lo, x;
- /* Can't be initialized with 0, so use another value. */
- if (*ctx == 0)
- *ctx = 123459876;
+ /* Must be in [1, 0x7ffffffe] range at this point. */
hi = *ctx / 127773;
lo = *ctx % 127773;
x = 16807 * lo - 2836 * hi;
if (x < 0)
x += 0x7fffffff;
- return ((*ctx = x) % ((u_long)RAND_MAX + 1));
+ *ctx = x;
+ /* Transform to [0, 0x7ffffffd] range. */
+ return (x - 1);
#endif /* !USE_WEAK_SEEDING */
}
int
rand_r(unsigned int *ctx)
{
- u_long val = (u_long) *ctx;
- int r = do_rand(&val);
+ u_long val;
+ int r;
- *ctx = (unsigned int) val;
+#ifdef USE_WEAK_SEEDING
+ val = *ctx;
+#else
+ /* Transform to [1, 0x7ffffffe] range. */
+ val = (*ctx % 0x7ffffffe) + 1;
+#endif
+ r = do_rand(&val);
+
+#ifdef USE_WEAK_SEEDING
+ *ctx = (unsigned int)val;
+#else
+ *ctx = (unsigned int)(val - 1);
+#endif
return (r);
}
-static u_long next = 1;
+static u_long next =
+#ifdef USE_WEAK_SEEDING
+ 1;
+#else
+ 2;
+#endif
int
rand()
@@ -104,6 +121,10 @@ srand(seed)
u_int seed;
{
next = seed;
+#ifndef USE_WEAK_SEEDING
+ /* Transform to [1, 0x7ffffffe] range. */
+ next = (next % 0x7ffffffe) + 1;
+#endif
}
@@ -125,6 +146,10 @@ sranddev()
mib[0] = CTL_KERN;
mib[1] = KERN_ARND;
sysctl(mib, 2, (void *)&next, &len, NULL, 0);
+#ifndef USE_WEAK_SEEDING
+ /* Transform to [1, 0x7ffffffe] range. */
+ next = (next % 0x7ffffffe) + 1;
+#endif
}

0 comments on commit f04b0e3

Please sign in to comment.