summaryrefslogtreecommitdiff
path: root/sys
diff options
context:
space:
mode:
authorMatthew Dempsky <matthew@cvs.openbsd.org>2012-06-24 18:25:13 +0000
committerMatthew Dempsky <matthew@cvs.openbsd.org>2012-06-24 18:25:13 +0000
commit64d28a493b8c2e63b90033ed40026c84b8fb9d9b (patch)
tree0dc540243a2475ffa466075f667b6811ea984d11 /sys
parentcdeeb2dd1f0747245cd979e52a13a30196091eee (diff)
Change arc4random_uniform() to calculate ``2**32 % upper_bound'' as
``-upper_bound % upper_bound''. Simplifies the code and makes it the same on both ILP32 and LP64 architectures, and also slightly faster on LP64 architectures by using a 32-bit remainder instead of a 64-bit remainder. Pointed out by Jorden Verwer on tech@ ok deraadt; no objections from djm or otto
Diffstat (limited to 'sys')
-rw-r--r--sys/dev/rnd.c15
1 files changed, 3 insertions, 12 deletions
diff --git a/sys/dev/rnd.c b/sys/dev/rnd.c
index 9beb232b963..cb7ebe491de 100644
--- a/sys/dev/rnd.c
+++ b/sys/dev/rnd.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: rnd.c,v 1.140 2011/07/06 14:49:30 nicm Exp $ */
+/* $OpenBSD: rnd.c,v 1.141 2012/06/24 18:25:12 matthew Exp $ */
/*
* Copyright (c) 2011 Theo de Raadt.
@@ -594,17 +594,8 @@ arc4random_uniform(u_int32_t upper_bound)
if (upper_bound < 2)
return 0;
-#if (ULONG_MAX > 0xffffffffUL)
- min = 0x100000000UL % upper_bound;
-#else
- /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
- if (upper_bound > 0x80000000)
- min = 1 + ~upper_bound; /* 2**32 - upper_bound */
- else {
- /* (2**32 - x) % x == 2**32 % x when x <= 2**31 */
- min = ((0xffffffff - upper_bound) + 1) % upper_bound;
- }
-#endif
+ /* 2**32 % x == (2**32 - x) % x */
+ min = -upper_bound % upper_bound;
/*
* This could theoretically loop forever but each retry has