|
| 1 | +// openkal.random on Linux --- getrandom(2). |
| 2 | +// |
| 3 | +// ⭐ THE KERNEL'S OWN CALL AND NOT `/dev/urandom`. The device would need a |
| 4 | +// descriptor, which needs a path, which a capability-oriented filesystem |
| 5 | +// deliberately does not hand out; and a program early enough in its life not to |
| 6 | +// have a filesystem yet still has this call. `getrandom` is the interface the |
| 7 | +// kernel offers for exactly this question. |
| 8 | +#include "sys.h" |
| 9 | +#include <openkal/random.h> |
| 10 | + |
| 11 | +namespace { |
| 12 | + |
| 13 | +// ⚠️ `GRND_NONBLOCK` IS NOT SET, AND THAT IS WHAT `BLOCKING` REPORTS. |
| 14 | +// |
| 15 | +// Without it the call waits until the pool has been initialised, which on a |
| 16 | +// machine seconds into its first boot can be a real wait. Setting it instead |
| 17 | +// would turn that wait into a short read — a partial success this interface |
| 18 | +// does not have — so the wait is kept and named in the capability word. |
| 19 | +constexpr okl_long flags_blocking = 0; |
| 20 | + |
| 21 | +} // namespace |
| 22 | + |
| 23 | +extern "C" int kal_random_fill(void* out, kal_uintptr len) { |
| 24 | + if (len == 0) return kal_ok; |
| 25 | + if (out == nullptr) return kal_err_invalid; |
| 26 | + |
| 27 | + auto* p = static_cast<unsigned char*>(out); |
| 28 | + kal_uintptr filled = 0; |
| 29 | + while (filled < len) { |
| 30 | + const okl_long r = okl::sys(okl::nr_getrandom, |
| 31 | + reinterpret_cast<okl_long>(p + filled), |
| 32 | + static_cast<okl_long>(len - filled), |
| 33 | + flags_blocking); |
| 34 | + if (r < 0) { |
| 35 | + // ⚠️ THE BUFFER IS NOT RESTORED, AND THE CONTRACT SAYS IT NEED NOT |
| 36 | + // BE: a failed fill leaves the buffer unspecified rather than |
| 37 | + // unchanged. Restoring it would oblige this function to keep a copy |
| 38 | + // of what it was handed, which is a cost every successful call |
| 39 | + // would pay for the benefit of the failing one. |
| 40 | + if (r == -4 /* EINTR */) continue; |
| 41 | + if (r == -11 /* EAGAIN */) return kal_err_again; |
| 42 | + return kal_err_io; |
| 43 | + } |
| 44 | + // A short return is the kernel's, not this interface's: `getrandom` |
| 45 | + // caps a single call at 32 MiB. Looping is what turns it into the |
| 46 | + // all-or-nothing this interface promises. |
| 47 | + filled += static_cast<kal_uintptr>(r); |
| 48 | + } |
| 49 | + return kal_ok; |
| 50 | +} |
| 51 | + |
| 52 | +// Blocking, because GRND_NONBLOCK is not set above. Not hardware: the kernel's |
| 53 | +// pool is what this reads, and whether the pool was seeded from a hardware |
| 54 | +// source is not something this backend can observe. |
| 55 | +extern "C" const kal_uintptr kal_random_props = KAL_RANDOM_PROP_BLOCKING; |
0 commit comments