| 1 | #include <errno.h> |
| 2 | #include <unistd.h> |
| 3 | #ifdef __wasilibc_use_wasip2 |
| 4 | #include <wasi/wasip2.h> |
| 5 | #include <sysexits.h> |
| 6 | |
| 7 | int __wasilibc_random(void *buffer, size_t len) { |
| 8 | |
| 9 | // Set up a WASI byte list to receive the results |
| 10 | wasip2_list_u8_t wasi_list; |
| 11 | |
| 12 | // Get random bytes |
| 13 | random_get_random_bytes(len, &wasi_list); |
| 14 | |
| 15 | // The spec for get-random-bytes specifies that wasi_list.len |
| 16 | // will be equal to len. |
| 17 | if (wasi_list.len != len) |
| 18 | _Exit(EX_OSERR); |
| 19 | else { |
| 20 | // Copy the result |
| 21 | memcpy(buffer, wasi_list.ptr, len); |
| 22 | } |
| 23 | |
| 24 | // Free the WASI byte list |
| 25 | wasip2_list_u8_free(&wasi_list); |
| 26 | |
| 27 | return 0; |
| 28 | } |
| 29 | #endif |