libroot: Synchronize random() implementation with upstream FreeBSD.

Specifically, FreeBSD 12 (newer versions refactored this API into
more than just one file.)

Fixes #18346.
This commit is contained in:
Augustin Cavalier
2023-04-08 13:49:03 -04:00
parent 6d3d196648
commit 05a0671dde
+95 -134
View File
@@ -1,4 +1,6 @@
/* /*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 1983, 1993 * Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved. * The Regents of the University of California. All rights reserved.
* *
@@ -10,11 +12,7 @@
* 2. Redistributions in binary form must reproduce the above copyright * 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the * notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. * documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software * 3. Neither the name of the University nor the names of its contributors
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software * may be used to endorse or promote products derived from this software
* without specific prior written permission. * without specific prior written permission.
* *
@@ -29,16 +27,15 @@
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE. * SUCH DAMAGE.
*
* $FreeBSD: src/lib/libc/stdlib/random.c,v 1.13 2000/01/27 23:06:49 jasone Exp $
*
*/ */
#include <stdio.h> #include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
/*
/* An improved random number generation package. In addition to the standard * random.c:
*
* An improved random number generation package. In addition to the standard
* rand()/srand() like interface, this package also has a special state info * rand()/srand() like interface, this package also has a special state info
* interface. The initstate() routine is called with a seed, an array of * interface. The initstate() routine is called with a seed, an array of
* bytes, and a count of how many bytes are being passed in; this array is * bytes, and a count of how many bytes are being passed in; this array is
@@ -51,10 +48,10 @@
* congruential generator. If the amount of state information is less than * congruential generator. If the amount of state information is less than
* 32 bytes, a simple linear congruential R.N.G. is used. * 32 bytes, a simple linear congruential R.N.G. is used.
* *
* Internally, the state information is treated as an array of longs; the * Internally, the state information is treated as an array of uint32_t's; the
* zeroeth element of the array is the type of R.N.G. being used (small * zeroeth element of the array is the type of R.N.G. being used (small
* integer); the remainder of the array is the state information for the * integer); the remainder of the array is the state information for the
* R.N.G. Thus, 32 bytes of state information will give 7 longs worth of * R.N.G. Thus, 32 bytes of state information will give 7 ints worth of
* state information, which will allow a degree seven polynomial. (Note: * state information, which will allow a degree seven polynomial. (Note:
* the zeroeth word of state information also has some other information * the zeroeth word of state information also has some other information
* stored in it -- see setstate() for details). * stored in it -- see setstate() for details).
@@ -70,7 +67,7 @@
* period of the generator is approximately deg*(2**deg - 1); thus doubling * period of the generator is approximately deg*(2**deg - 1); thus doubling
* the amount of state information has a vast influence on the period of the * the amount of state information has a vast influence on the period of the
* generator. Note: the deg*(2**deg - 1) is an approximation only good for * generator. Note: the deg*(2**deg - 1) is an approximation only good for
* large deg, when the period of the shift register is the dominant factor. * large deg, when the period of the shift is the dominant factor.
* With deg equal to seven, the period is actually much longer than the * With deg equal to seven, the period is actually much longer than the
* 7*(2**7 - 1) predicted by this formula. * 7*(2**7 - 1) predicted by this formula.
* *
@@ -132,8 +129,10 @@
*/ */
#define MAX_TYPES 5 /* max number of types above */ #define MAX_TYPES 5 /* max number of types above */
static long degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 }; #define NSHUFF 50 /* to drop some "seed -> 1st value" linearity */
static long seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
static const int degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
static const int seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
/* /*
* Initially, everything is set up as if from: * Initially, everything is set up as if from:
@@ -149,25 +148,14 @@ static long seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
* MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3. * MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
*/ */
static long randtbl[DEG_3 + 1] = { static uint32_t randtbl[DEG_3 + 1] = {
TYPE_3, TYPE_3,
#ifdef USE_WEAK_SEEDING 0x2cf41758, 0x27bb3711, 0x4916d4d1, 0x7b02f59f, 0x9b8e28eb, 0xc0e80269,
/* Historic implementation compatibility */ 0x696f5c16, 0x878f1ff5, 0x52d9c07f, 0x916a06cd, 0xb50b3a20, 0x2776970a,
/* The random sequences do not vary much with the seed */ 0xee4eb2a6, 0xe94640ec, 0xb1d65612, 0x9d1ed968, 0x1043f6b7, 0xa3432a76,
0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5, 0x17eacbb9, 0x3c09e2eb, 0x4f8c2b3, 0x708a1f57, 0xee341814, 0x95d0e4d2,
0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd, 0xb06f216c, 0x8bd2e72e, 0x8f7c38d7, 0xcfc6a8fc, 0x2a59495, 0xa20d2a69,
0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88, 0xe29d12d1
0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
0x27fb47b9,
#else /* !USE_WEAK_SEEDING */
0x991539b1, 0x16a5bce3, 0x6774a4cd, 0x3e01511e, 0x4e508aaa, 0x61048c05,
0xf5500617, 0x846b7115, 0x6a19892c, 0x896a97af, 0xdb48f936, 0x14898454,
0x37ffd106, 0xb58bff9c, 0x59e17104, 0xcf918a49, 0x09378c83, 0x52c7a471,
0x8d293ea9, 0x1f4fc301, 0xc3db71be, 0x39b44e1c, 0xf8a44ef9, 0x4c8b80b1,
0x19edc328, 0x87bf4bdd, 0xc9b240e5, 0xe9ee4b1b, 0x4382aee7, 0x535b6b41,
0xf3bec5da
#endif /* !USE_WEAK_SEEDING */
}; };
/* /*
@@ -184,8 +172,8 @@ static long randtbl[DEG_3 + 1] = {
* in the initialization of randtbl) because the state table pointer is set * in the initialization of randtbl) because the state table pointer is set
* to point to randtbl[1] (as explained below). * to point to randtbl[1] (as explained below).
*/ */
static long *fptr = &randtbl[SEP_3 + 1]; static uint32_t *fptr = &randtbl[SEP_3 + 1];
static long *rptr = &randtbl[1]; static uint32_t *rptr = &randtbl[1];
/* /*
* The following things are the pointer to the state information table, the * The following things are the pointer to the state information table, the
@@ -197,24 +185,15 @@ static long *rptr = &randtbl[1];
* this is more efficient than indexing every time to find the address of * this is more efficient than indexing every time to find the address of
* the last element to see if the front and rear pointers have wrapped. * the last element to see if the front and rear pointers have wrapped.
*/ */
static long *state = &randtbl[1]; static uint32_t *state = &randtbl[1];
static long rand_type = TYPE_3; static int rand_type = TYPE_3;
static long rand_deg = DEG_3; static int rand_deg = DEG_3;
static long rand_sep = SEP_3; static int rand_sep = SEP_3;
static long *end_ptr = &randtbl[DEG_3 + 1]; static uint32_t *end_ptr = &randtbl[DEG_3 + 1];
static inline long good_rand(long); static inline uint32_t
good_rand(uint32_t ctx)
static inline long good_rand(long x)
{ {
#ifdef USE_WEAK_SEEDING
/*
* Historic implementation compatibility.
* The random sequences do not vary much with the seed,
* even with overflowing.
*/
return (1103515245 * x + 12345);
#else /* !USE_WEAK_SEEDING */
/* /*
* Compute x = (7^5 * x) mod (2^31 - 1) * Compute x = (7^5 * x) mod (2^31 - 1)
* wihout overflowing 31 bits: * wihout overflowing 31 bits:
@@ -223,15 +202,17 @@ static inline long good_rand(long x)
* Park and Miller, Communications of the ACM, vol. 31, no. 10, * Park and Miller, Communications of the ACM, vol. 31, no. 10,
* October 1988, p. 1195. * October 1988, p. 1195.
*/ */
register long hi, lo; int32_t hi, lo, x;
/* Transform to [1, 0x7ffffffe] range. */
x = (ctx % 0x7ffffffe) + 1;
hi = x / 127773; hi = x / 127773;
lo = x % 127773; lo = x % 127773;
x = 16807 * lo - 2836 * hi; x = 16807 * lo - 2836 * hi;
if (x <= 0) if (x < 0)
x += 0x7fffffff; x += 0x7fffffff;
return (x); /* Transform to [0, 0x7ffffffd] range. */
#endif /* !USE_WEAK_SEEDING */ return (x - 1);
} }
/* /*
@@ -249,61 +230,56 @@ static inline long good_rand(long x)
void void
srandom(unsigned int x) srandom(unsigned int x)
{ {
long i; int i, lim;
if (rand_type == TYPE_0) { state[0] = (uint32_t)x;
state[0] = x; if (rand_type == TYPE_0)
} else { lim = NSHUFF;
state[0] = x; else {
for (i = 1; i < rand_deg; i++) { for (i = 1; i < rand_deg; i++)
state[i] = good_rand(state[i - 1]); state[i] = good_rand(state[i - 1]);
}
fptr = &state[rand_sep]; fptr = &state[rand_sep];
rptr = &state[0]; rptr = &state[0];
for (i = 0; i < 10 * rand_deg; i++) { lim = 10 * rand_deg;
(void)random();
}
} }
for (i = 0; i < lim; i++)
(void)random();
} }
/* /*
* srandomdev: * srandomdev:
* *
* Many programs choose the seed value in a totally predictable manner. * Many programs choose the seed value in a totally predictable manner.
* This often causes problems. We seed the generator using the much more * This often causes problems. We seed the generator using pseudo-random
* secure urandom(4) interface. Note that this particular seeding * data from the kernel.
* procedure can generate states which are impossible to reproduce by *
* calling srandom() with any value, since the succeeding terms in the * Note that this particular seeding procedure can generate states
* state buffer are no longer derived from the LC algorithm applied to * which are impossible to reproduce by calling srandom() with any
* a fixed seed. * value, since the succeeding terms in the state buffer are no longer
* derived from the LC algorithm applied to a fixed seed.
*/ */
#if 0 #if 0
void void
srandomdev() srandomdev(void)
{ {
int fd, done; int mib[2];
size_t len; size_t expected, len;
if (rand_type == TYPE_0) if (rand_type == TYPE_0)
len = sizeof state[0]; expected = len = sizeof(state[0]);
else else
len = rand_deg * sizeof state[0]; expected = len = rand_deg * sizeof(state[0]);
done = 0; mib[0] = CTL_KERN;
fd = _open("/dev/urandom", O_RDONLY, 0); mib[1] = KERN_ARND;
if (fd >= 0) { if (sysctl(mib, 2, state, &len, NULL, 0) == -1 || len != expected) {
if (_read(fd, (void *) state, len) == (ssize_t) len) /*
done = 1; * The sysctl cannot fail. If it does fail on some FreeBSD
_close(fd); * derivative or after some future change, just abort so that
} * the problem will be found and fixed. abort is not normally
* suitable for a library but makes sense here.
if (!done) { */
struct timeval tv; abort();
unsigned long junk;
gettimeofday(&tv, NULL);
srandom(getpid() ^ tv.tv_sec ^ tv.tv_usec ^ junk);
return;
} }
if (rand_type != TYPE_0) { if (rand_type != TYPE_0) {
@@ -332,25 +308,22 @@ srandomdev()
* *
* Returns a pointer to the old state. * Returns a pointer to the old state.
* *
* Note: The Sparc platform requires that arg_state begin on a long * Note: The Sparc platform requires that arg_state begin on an int
* word boundary; otherwise a bus error will occur. Even so, lint will * word boundary; otherwise a bus error will occur. Even so, lint will
* complain about mis-alignment, but you should disregard these messages. * complain about mis-alignment, but you should disregard these messages.
*/ */
char * char *
initstate(unsigned int seed, char *arg_state, size_t n) initstate(unsigned int seed, char *arg_state, size_t n)
{ {
register char *ostate = (char *)(&state[-1]); char *ostate = (char *)(&state[-1]);
register long *long_arg_state = (long *) arg_state; uint32_t *int_arg_state = (uint32_t *)arg_state;
if (n < BREAK_0)
return (NULL);
if (rand_type == TYPE_0) if (rand_type == TYPE_0)
state[-1] = rand_type; state[-1] = rand_type;
else else
state[-1] = MAX_TYPES * (rptr - state) + rand_type; state[-1] = MAX_TYPES * (rptr - state) + rand_type;
if (n < BREAK_0) {
(void)fprintf(stderr,
"random: not enough state (%ld bytes); ignored.\n", n);
return(0);
}
if (n < BREAK_1) { if (n < BREAK_1) {
rand_type = TYPE_0; rand_type = TYPE_0;
rand_deg = DEG_0; rand_deg = DEG_0;
@@ -372,14 +345,14 @@ initstate(unsigned int seed, char *arg_state, size_t n)
rand_deg = DEG_4; rand_deg = DEG_4;
rand_sep = SEP_4; rand_sep = SEP_4;
} }
state = (long *) (long_arg_state + 1); /* first location */ state = int_arg_state + 1; /* first location */
end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */ end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */
srandom(seed); srandom(seed);
if (rand_type == TYPE_0) if (rand_type == TYPE_0)
long_arg_state[0] = rand_type; int_arg_state[0] = rand_type;
else else
long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type; int_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;
return(ostate); return (ostate);
} }
/* /*
@@ -397,47 +370,36 @@ initstate(unsigned int seed, char *arg_state, size_t n)
* *
* Returns a pointer to the old state information. * Returns a pointer to the old state information.
* *
* Note: The Sparc platform requires that arg_state begin on a long * Note: The Sparc platform requires that arg_state begin on an int
* word boundary; otherwise a bus error will occur. Even so, lint will * word boundary; otherwise a bus error will occur. Even so, lint will
* complain about mis-alignment, but you should disregard these messages. * complain about mis-alignment, but you should disregard these messages.
*/ */
char * char *
setstate(arg_state) setstate(char *arg_state)
char *arg_state; /* pointer to state array */
{ {
register long *new_state = (long *) arg_state; uint32_t *new_state = (uint32_t *)arg_state;
register long type = new_state[0] % MAX_TYPES; uint32_t type = new_state[0] % MAX_TYPES;
register long rear = new_state[0] / MAX_TYPES; uint32_t rear = new_state[0] / MAX_TYPES;
char *ostate = (char *)(&state[-1]); char *ostate = (char *)(&state[-1]);
if (type != TYPE_0 && rear >= degrees[type])
return (NULL);
if (rand_type == TYPE_0) if (rand_type == TYPE_0)
state[-1] = rand_type; state[-1] = rand_type;
else else
state[-1] = MAX_TYPES * (rptr - state) + rand_type; state[-1] = MAX_TYPES * (rptr - state) + rand_type;
switch(type) { rand_type = type;
case TYPE_0: rand_deg = degrees[type];
case TYPE_1: rand_sep = seps[type];
case TYPE_2: state = new_state + 1;
case TYPE_3:
case TYPE_4:
rand_type = type;
rand_deg = degrees[type];
rand_sep = seps[type];
break;
default:
(void)fprintf(stderr,
"random: state info corrupted; not changed.\n");
}
state = (long *) (new_state + 1);
if (rand_type != TYPE_0) { if (rand_type != TYPE_0) {
rptr = &state[rear]; rptr = &state[rear];
fptr = &state[(rear + rand_sep) % rand_deg]; fptr = &state[(rear + rand_sep) % rand_deg];
} }
end_ptr = &state[rand_deg]; /* set end_ptr too */ end_ptr = &state[rand_deg]; /* set end_ptr too */
return(ostate); return (ostate);
} }
/* /*
* random: * random:
* *
@@ -458,20 +420,19 @@ setstate(arg_state)
int int
random(void) random(void)
{ {
long i; uint32_t i;
long *f; uint32_t *f, *r;
long *r;
if (rand_type == TYPE_0) { if (rand_type == TYPE_0) {
i = state[0]; i = state[0];
state[0] = i = (good_rand(i)) & 0x7fffffff; state[0] = i = good_rand(i);
} else { } else {
/* /*
* Use local variables rather than static variables for speed. * Use local variables rather than static variables for speed.
*/ */
f = fptr; r = rptr; f = fptr; r = rptr;
*f += *r; *f += *r;
i = (*f >> 1) & 0x7fffffff; /* chucking least random bit */ i = *f >> 1; /* chucking least random bit */
if (++f >= end_ptr) { if (++f >= end_ptr) {
f = state; f = state;
++r; ++r;
@@ -482,5 +443,5 @@ random(void)
fptr = f; rptr = r; fptr = f; rptr = r;
} }
return(i); return ((long)i);
} }