From a982ad089d1962f1b92f4343c910c0be6b6e6280 Mon Sep 17 00:00:00 2001 From: martijneken Date: Mon, 28 Oct 2024 16:36:36 -0400 Subject: [PATCH] fix: Implement getentropy using wasi preview 1 (#178) * fix: Implement getentropy while Emscripten gets patched Issue: https://github.com/emscripten-core/emscripten/issues/22782 Signed-off-by: Martijn Stevenson --- proxy_wasm_intrinsics.cc | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/proxy_wasm_intrinsics.cc b/proxy_wasm_intrinsics.cc index a6e8b8b..93ae120 100644 --- a/proxy_wasm_intrinsics.cc +++ b/proxy_wasm_intrinsics.cc @@ -271,3 +271,25 @@ extern "C" PROXY_WASM_KEEPALIVE void proxy_on_foreign_function(uint32_t context_id, uint32_t foreign_function_id, uint32_t data_size) { getContextBase(context_id)->onForeignFunction(foreign_function_id, data_size); } + +// Patch an Emscripten gap: https://github.com/emscripten-core/emscripten/issues/22782 +// Implement getentropy for RNG support (e.g. for absl::random). + +typedef uint16_t __wasi_errno_t; +typedef size_t __wasi_size_t; + +__wasi_errno_t __wasi_random_get(uint8_t *buf, __wasi_size_t buf_len) + __attribute__((__import_module__("wasi_snapshot_preview1"), __import_name__("random_get"))); + +extern "C" int getentropy(void *buffer, size_t len) { + if (len > 256) { + errno = EIO; + return -1; + } + int r = __wasi_random_get((uint8_t *)buffer, len); + if (r != 0) { + errno = r; + return -1; + } + return 0; +}