X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=src%2Flib%2Frandom.c;h=a4761b6b52c14d3202a783d1e7eb1ab64baba767;hb=53a7f5d0952a4595f252247f5ee3d017468eb57e;hp=c9973d07b3102bca4f4f0f1a1e8a8c7d2086e717;hpb=5e8c072fc51af0d3e6c3501c6f697b01c9c607b7;p=pintos-anon diff --git a/src/lib/random.c b/src/lib/random.c index c9973d0..a4761b6 100644 --- a/src/lib/random.c +++ b/src/lib/random.c @@ -1,12 +1,26 @@ #include "random.h" #include #include +#include "debug.h" -/* RC4-based pseudo-random state. */ -static uint8_t s[256]; -static uint8_t s_i, s_j; -static bool inited; +/* RC4-based pseudo-random number generator (PRNG). + RC4 is a stream cipher. We're not using it here for its + cryptographic properties, but because it is easy to implement + and its output is plenty random for non-cryptographic + purposes. + + See http://en.wikipedia.org/wiki/RC4_(cipher) for information + on RC4.*/ + +/* RC4 state. */ +static uint8_t s[256]; /* S[]. */ +static uint8_t s_i, s_j; /* i, j. */ + +/* Already initialized? */ +static bool inited; + +/* Swaps the bytes pointed to by A and B. */ static inline void swap_byte (uint8_t *a, uint8_t *b) { @@ -15,6 +29,7 @@ swap_byte (uint8_t *a, uint8_t *b) *b = t; } +/* Initializes or reinitializes the PRNG with the given SEED. */ void random_init (unsigned seed) { @@ -22,9 +37,6 @@ random_init (unsigned seed) int i; uint8_t j; - if (inited) - return; - for (i = 0; i < 256; i++) s[i] = i; for (i = j = 0; i < 256; i++) @@ -37,12 +49,15 @@ random_init (unsigned seed) inited = true; } +/* Writes SIZE random bytes into BUF. */ void random_bytes (void *buf_, size_t size) { uint8_t *buf; - ASSERT (inited); + if (!inited) + random_init (0); + for (buf = buf_; size-- > 0; buf++) { uint8_t s_k; @@ -56,7 +71,9 @@ random_bytes (void *buf_, size_t size) } } -/* Returns a pseudo-random unsigned long. */ +/* Returns a pseudo-random unsigned long. + Use random_ulong() % n to obtain a random number in the range + 0...n (exclusive). */ unsigned long random_ulong (void) {