mirror of
https://codeberg.org/libreboot/lbmk.git
synced 2026-07-16 13:16:47 +02:00
rand: fix modulo bias in rmalloc
Signed-off-by: Leah Rowe <leah@libreboot.org>
This commit is contained in:
@@ -81,7 +81,7 @@ win_lottery(char **buf) /* are u lucky? */
|
|||||||
char *s1 = rmalloc(&size);
|
char *s1 = rmalloc(&size);
|
||||||
char *s2 = rmalloc(&size);
|
char *s2 = rmalloc(&size);
|
||||||
|
|
||||||
if (scmp(s1, s2, BUFSIZ + 2, &rval) >= 0 &&
|
if (scmp(s1, s2, BUFSIZ + 1, &rval) >= 0 &&
|
||||||
rval == 0)
|
rval == 0)
|
||||||
rval = 1; /* winner! */
|
rval = 1; /* winner! */
|
||||||
else
|
else
|
||||||
@@ -98,10 +98,16 @@ win_lottery(char **buf) /* are u lucky? */
|
|||||||
void *
|
void *
|
||||||
rmalloc(size_t *rval)
|
rmalloc(size_t *rval)
|
||||||
{
|
{
|
||||||
|
/* clamp rand to prevent modulo bias */
|
||||||
|
size_t limit = SIZE_MAX - (SIZE_MAX % BUFSIZ);
|
||||||
|
|
||||||
if (if_err(rval == NULL, EFAULT))
|
if (if_err(rval == NULL, EFAULT))
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
rset(rval, sizeof(*rval));
|
do {
|
||||||
|
rset(rval, sizeof(*rval));
|
||||||
|
} while (*rval >= limit);
|
||||||
|
|
||||||
return mkrstr(*rval %= BUFSIZ);
|
return mkrstr(*rval %= BUFSIZ);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user