From 9bec2d3aff198770e98544cb6f13add60e1f5fe6 Mon Sep 17 00:00:00 2001 From: Cheng Shao Date: Mon, 30 Jan 2023 13:30:02 +0100 Subject: [PATCH] Add a check to reactor modules to ensure _initialize is only called once (#388) Calling _initialize multiple times is undefined behavior, since the ctors are not guaranteed to be idempotent. We should have this safety check which is similar to #329. --- libc-bottom-half/crt/crt1-reactor.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/libc-bottom-half/crt/crt1-reactor.c b/libc-bottom-half/crt/crt1-reactor.c index f507c9e..ea4a84f 100644 --- a/libc-bottom-half/crt/crt1-reactor.c +++ b/libc-bottom-half/crt/crt1-reactor.c @@ -1,7 +1,27 @@ +#if defined(_REENTRANT) +#include +extern void __wasi_init_tp(void); +#endif extern void __wasm_call_ctors(void); __attribute__((export_name("_initialize"))) void _initialize(void) { +#if defined(_REENTRANT) + static volatile atomic_int initialized = 0; + int expected = 0; + if (!atomic_compare_exchange_strong(&initialized, &expected, 1)) { + __builtin_trap(); + } + + __wasi_init_tp(); +#else + static volatile int initialized = 0; + if (initialized != 0) { + __builtin_trap(); + } + initialized = 1; +#endif + // The linker synthesizes this to call constructors. __wasm_call_ctors(); }