From ede49d7153ed628078bcbc2473f898904b5250ea Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Thu, 28 Apr 2011 01:18:53 -0700 Subject: [PATCH] * sysdep.c (get_random): Don't assume EMACS_INT is no wider than long. Also, don't assume VALBITS / RAND_BITS is less than 5, and don't rely on undefined behavior when shifting a 1 left into the sign bit. * lisp.h (get_random): Change signature to match. --- src/ChangeLog | 6 ++++++ src/lisp.h | 2 +- src/sysdep.c | 21 ++++++--------------- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/ChangeLog b/src/ChangeLog index 2bda5ffa46f..40fb601e061 100644 --- a/src/ChangeLog +++ b/src/ChangeLog @@ -1,5 +1,11 @@ 2011-04-28 Paul Eggert + * sysdep.c (get_random): Don't assume EMACS_INT is no wider than long. + Also, don't assume VALBITS / RAND_BITS is less than 5, + and don't rely on undefined behavior when shifting a 1 left into + the sign bit. + * lisp.h (get_random): Change signature to match. + * lread.c (hash_string): Use size_t, not int, for hash computation. Normally we prefer signed values; but hashing is special, because it's better to use unsigned division on hash table sizes so that diff --git a/src/lisp.h b/src/lisp.h index 625027769cf..dca3b4d9a32 100644 --- a/src/lisp.h +++ b/src/lisp.h @@ -3353,7 +3353,7 @@ extern void flush_pending_output (int); extern void child_setup_tty (int); extern void setup_pty (int); extern int set_window_size (int, int, int); -extern long get_random (void); +extern EMACS_INT get_random (void); extern void seed_random (long); extern int emacs_open (const char *, int, int); extern int emacs_close (int); diff --git a/src/sysdep.c b/src/sysdep.c index ca7de4f54bb..43f50cdb0a9 100644 --- a/src/sysdep.c +++ b/src/sysdep.c @@ -1760,23 +1760,14 @@ seed_random (long int arg) * Build a full Emacs-sized word out of whatever we've got. * This suffices even for a 64-bit architecture with a 15-bit rand. */ -long +EMACS_INT get_random (void) { - long val = random (); -#if VALBITS > RAND_BITS - val = (val << RAND_BITS) ^ random (); -#if VALBITS > 2*RAND_BITS - val = (val << RAND_BITS) ^ random (); -#if VALBITS > 3*RAND_BITS - val = (val << RAND_BITS) ^ random (); -#if VALBITS > 4*RAND_BITS - val = (val << RAND_BITS) ^ random (); -#endif /* need at least 5 */ -#endif /* need at least 4 */ -#endif /* need at least 3 */ -#endif /* need at least 2 */ - return val & ((1L << VALBITS) - 1); + EMACS_UINT val = 0; + int i; + for (i = 0; i < (VALBITS + RAND_BITS - 1) / RAND_BITS; i++) + val = (val << RAND_BITS) ^ random (); + return val & (((EMACS_INT) 1 << VALBITS) - 1); } #ifndef HAVE_STRERROR -- 2.39.2