wasi-libc/libc-bottom-half/crt/crt1-command.c
Dan Gohman 21d93b927d
Add a check to command modules to ensure that they're only started once. (#329)
* Add a check to command modules to ensure that they're only started once.

Wasm command modules should only be called once per instance, because
the programming model doesn't leave linear memory in a reusable state
when the program exits. As use cases arise for loading wasm modules in
environments that want to treat them like reactors, add a safety check
to ensure that command modules are used according to their
expectations.
2022-10-13 17:58:14 -07:00

35 lines
1.0 KiB
C

#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.
if (started != 0) {
__builtin_trap();
}
started = 1;
// The linker synthesizes this to call constructors.
__wasm_call_ctors();
// Call `__main_void` which will either be the application's zero-argument
// `__main_void` function or a libc routine which obtains the command-line
// arguments and calls `__main_argv_argc`.
int r = __main_void();
// Call atexit functions, destructors, stdio cleanup, etc.
__wasm_call_dtors();
// If main exited successfully, just return, otherwise call
// `__wasi_proc_exit`.
if (r != 0) {
__wasi_proc_exit(r);
}
}