Debian Codegraph @

libc-top-half/sources/arc4random.c

raw
1 #include <assert.h>
2 #include <stdint.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <wasi/api.h>
7 #include <wasi/libc.h>
8
9 void arc4random_buf(void* buffer, size_t len)
10 {
11 // Always call `__wasi_random_get` rather than doing a guest PRNG, because
12 // Wasm engines may snapshot or even clone Wasm state, which we don't have
13 // any visibility into.
14 //
15 // We therefore effectively expect that `__wasi_random_get` is "fast",
16 // presumably using a PRNG-style implementation rather than a slower
17 // raw-entropy-style implementation.
18 #if defined(__wasip1__)
19 int r = __wasi_random_get(buffer, len);
20 #elif defined(__wasip2__) || defined(__wasip3__)
21 int r = __wasilibc_random(buffer, len);
22 #else
23 # error "Unknown WASI version"
24 #endif
25
26 // `__wasi_random_get` should always succeed.
27 if (r != 0) {
28 __builtin_trap();
29 }
30 }
31
32 uint32_t arc4random(void)
33 {
34 uint32_t v;
35
36 arc4random_buf(&v, sizeof v);
37
38 return v;
39 }
40
41 uint32_t arc4random_uniform(const uint32_t upper_bound)
42 {
43 uint32_t min;
44 uint32_t r;
45
46 if (upper_bound < 2U) {
47 return 0;
48 }
49 min = (1U + ~upper_bound) % upper_bound; // = 2**32 mod upper_bound
50 do {
51 r = arc4random();
52 } while (r < min);
53
54 // r is now clamped to a set whose size mod upper_bound == 0.
55 // The worst case (2**31+1) requires 2 attempts on average.
56
57 return r % upper_bound;
58 }