diff options
Diffstat (limited to 'util/libreboot-utils/lib')
| -rw-r--r-- | util/libreboot-utils/lib/rand.c | 48 |
1 files changed, 14 insertions, 34 deletions
diff --git a/util/libreboot-utils/lib/rand.c b/util/libreboot-utils/lib/rand.c index 06d5f49e..3155eec3 100644 --- a/util/libreboot-utils/lib/rand.c +++ b/util/libreboot-utils/lib/rand.c @@ -72,43 +72,20 @@ * or your program dies. */ -int -win_lottery(char **buf) /* are u lucky? */ -{ - size_t size = 0; - int rval; - - char *s1 = rmalloc(&size); - char *s2 = rmalloc(&size); - - if (scmp(s1, s2, BUFSIZ + 1, &rval) >= 0 && - rval == 0) - rval = 1; /* winner! */ - else - rval = 0; - - (void) scat(s1, s2, BUFSIZ << 1, buf); - - free_if_null(&s1); - free_if_null(&s2); - - return rval; -} - void * rmalloc(size_t *rval) { - /* clamp rand to prevent modulo bias */ - size_t limit = SIZE_MAX - (SIZE_MAX % BUFSIZ); - - if (if_err(rval == NULL, EFAULT)) - return NULL; + return if_err(rval == NULL, EFAULT) ? + NULL : mkrstr(*rval = rsize(BUFSIZ)); +} - do { - rset(rval, sizeof(*rval)); - } while (*rval >= limit); +size_t +rsize(size_t n) +{ + size_t rval = SIZE_MAX; + for (; rval >= SIZE_MAX - (SIZE_MAX % n); rset(&rval, sizeof(rval))); - return mkrstr(*rval %= BUFSIZ); + return rval % n; } char * @@ -120,7 +97,7 @@ mkrstr(size_t n) /* emulates spkmodem-decode */ if (n == 0) err_no_cleanup(0, EPERM, "mkrbuf: zero-byte request"); - if (n == SIZE_MAX) + if (n >= SIZE_MAX - 1) err_no_cleanup(0, EOVERFLOW, "mkrbuf: overflow"); if (if_err((s = mkrbuf(n + 1)) == NULL, EFAULT)) @@ -138,11 +115,14 @@ mkrstr(size_t n) /* emulates spkmodem-decode */ void * mkrbuf(size_t n) { - void *buf; + void *buf = ""; if (n == 0) err_no_cleanup(0, EPERM, "mkrbuf: zero-byte request"); + if (n >= SIZE_MAX - 1) + err_no_cleanup(0, EOVERFLOW, "integer overflow in mkrbuf"); + if ((buf = malloc(n)) == NULL) err_no_cleanup(0, ENOMEM, "mkrbuf: malloc"); |
