Skip to content

Commit

Permalink
Support threads in the new crt1-command.c ctor check. (#339)
Browse files Browse the repository at this point in the history
Use an atomic compare-and-swap for checking whether constructors have
been run, when threads are enabled.
  • Loading branch information
sunfishcode authored Nov 8, 2022
1 parent a7af7c0 commit b99173e
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions libc-bottom-half/crt/crt1-command.c
Original file line number Diff line number Diff line change
@@ -1,19 +1,33 @@
#ifdef _REENTRANT
#include <stdatomic.h>
#endif
#include <wasi/api.h>
extern void __wasm_call_ctors(void);
extern int __main_void(void);
extern void __wasm_call_dtors(void);

// Commands should only be called once per instance. This simple check ensures
// that the `_start` function isn't started more than once.
static volatile int started = 0;

__attribute__((export_name("_start")))
void _start(void) {
// Don't allow the program to be called multiple times.
// Commands should only be called once per instance. This simple check
// ensures that the `_start` function isn't started more than once.
//
// We use `volatile` here to prevent the store to `started` from being
// sunk past any subsequent code, and to prevent any compiler from
// optimizing based on the knowledge that `_start` is the program
// entrypoint.
#ifdef _REENTRANT
static volatile _Atomic int started = 0;
int expected = 0;
if (!atomic_compare_exchange_strong(&started, &expected, 1)) {
__builtin_trap();
}
#else
static volatile int started = 0;
if (started != 0) {
__builtin_trap();
}
started = 1;
#endif

// The linker synthesizes this to call constructors.
__wasm_call_ctors();
Expand Down

0 comments on commit b99173e

Please sign in to comment.