1 /* 2 * Copyright (c) 2008, Damien Miller <djm (at) openbsd.org> 3 * 4 * Permission to use, copy, modify, and distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 #include <stdint.h> 18 #include <stdlib.h> 19 20 /* We need to include config.h so we pickup either the system arc4random 21 * or our compat one. */ 22 #include "../config.h" 23 24 /* 25 * Calculate a uniformly distributed random number less than upper_bound 26 * avoiding "modulo bias". 27 * 28 * Uniformity is achieved by generating new random numbers until the one 29 * returned is outside the range [0, 2**32 % upper_bound). This 30 * guarantees the selected random number will be inside 31 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound) 32 * after reduction modulo upper_bound. 33 */ 34 uint32_t 35 arc4random_uniform(uint32_t upper_bound) 36 { 37 uint32_t r, min; 38 39 if (upper_bound < 2) 40 return 0; 41 42 /* 2**32 % x == (2**32 - x) % x */ 43 min = -upper_bound % upper_bound; 44 45 /* 46 * This could theoretically loop forever but each retry has 47 * p > 0.5 (worst case, usually far better) of selecting a 48 * number inside the range we need, so it should rarely need 49 * to re-roll. 50 */ 51 do 52 r = arc4random(); 53 while (r < min); 54 55 return r % upper_bound; 56 } 57