|
| 1 | +// openkal.random on this system --- getentropy(2). |
| 2 | +// |
| 3 | +// ⭐ THE NUMBER CAME FROM THE MACHINE, NOT FROM MEMORY. `.github/workflows/ |
| 4 | +// numbers.yml` reads every number this implementation uses out of the SDK's own |
| 5 | +// `sys/syscall.h`, on both runners this repository targets, and both answered |
| 6 | +// `SYS_getentropy 500`. That workflow exists because a number recalled rather |
| 7 | +// than read is a number that is right until the day it is not. |
| 8 | +// |
| 9 | +// ⚠️ AND NOT `arc4random_buf`, WHICH IS WHAT libc++ WOULD REACH FOR HERE. |
| 10 | +// That name is in libSystem, and reaching into libSystem is what this backend |
| 11 | +// exists to avoid: it issues this kernel's calls directly, as the note in |
| 12 | +// `sys.h` records. `getentropy` is the call underneath. |
| 13 | +// |
| 14 | +// ⚠️ THE KERNEL CAPS A CALL AT 256 BYTES. That is this system's limit and not |
| 15 | +// this interface's, so the loop below turns it into the all-or-nothing |
| 16 | +// `kal_random_fill` promises. |
| 17 | +#include "sys.h" |
| 18 | +#include <openkal/random.h> |
| 19 | + |
| 20 | +extern "C" int kal_random_fill(void* out, kal_uintptr len) { |
| 21 | + if (len == 0) return kal_ok; |
| 22 | + if (out == nullptr) return kal_err_invalid; |
| 23 | + |
| 24 | + auto* p = static_cast<unsigned char*>(out); |
| 25 | + kal_uintptr filled = 0; |
| 26 | + while (filled < len) { |
| 27 | + const kal_uintptr chunk = (len - filled) > 256 ? 256 : (len - filled); |
| 28 | + const okm_long r = okm::sys(okm::nr_getentropy, |
| 29 | + reinterpret_cast<okm_long>(p + filled), |
| 30 | + static_cast<okm_long>(chunk), 0, 0); |
| 31 | + if (r < 0) { |
| 32 | + // ⚠️ The buffer is not restored, and the contract says it need not |
| 33 | + // be: a failed fill leaves it unspecified rather than unchanged. |
| 34 | + if (r == -4 /* EINTR */) continue; |
| 35 | + return kal_err_io; |
| 36 | + } |
| 37 | + filled += chunk; |
| 38 | + } |
| 39 | + return kal_ok; |
| 40 | +} |
| 41 | + |
| 42 | +// Neither blocking nor hardware. This kernel's generator is seeded before a |
| 43 | +// process runs, so there is no wait to report; and whether the seed came from a |
| 44 | +// hardware source is not something this backend can observe. |
| 45 | +extern "C" const kal_uintptr kal_random_props = 0; |
0 commit comments