Skip to content

Commit eacb34c

Browse files
committed
refactor: wasi init as a reactor module instead of command module
1 parent fed4449 commit eacb34c

File tree

4 files changed

+14
-8
lines changed

4 files changed

+14
-8
lines changed

packages/tcpip/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
CC ?= clang
22
TARGET = wasm32-wasi
33
CFLAGS = -Oz -Wall -std=c11
4-
LDFLAGS = -Wl,--gc-sections,--strip-all,--export=malloc,--export=free,--allow-undefined
4+
LDFLAGS = -Wl,--gc-sections,--strip-all,--export=malloc,--export=free,--allow-undefined -mexec-model=reactor
55

66
SRC_DIR = wasm
77
OUTPUT = tcpip.wasm

packages/tcpip/src/stack.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -181,11 +181,9 @@ export class VirtualNetworkStack implements NetworkStack {
181181
this.#tcpBindings.register(wasmInstance.exports);
182182
this.#udpBindings.register(wasmInstance.exports);
183183

184-
const result = wasi.start(wasmInstance);
185-
186-
if (result !== 0) {
187-
throw new Error(`wasi start failed with code ${result}`);
188-
}
184+
// Our WASM binary is a WASI reactor module (ie. a lib),
185+
// so we call `initialize()` instead of `start()`.
186+
wasi.initialize(wasmInstance);
189187

190188
// Call lwIP's main loop regularly (required in NO_SYS mode)
191189
// Used to process queued packets (eg. loopback) and expired timeouts

packages/tcpip/src/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export type Pointer = UniquePointer | 0;
1717

1818
export type WasiExports = {
1919
memory: WebAssembly.Memory;
20-
_start(): unknown;
20+
_initialize(): unknown;
2121
};
2222

2323
export type SysExports = {

packages/tcpip/wasm/stack.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ void process_timeouts() {
1919
sys_check_timeouts();
2020
}
2121

22-
int main() {
22+
// Initialize the lwIP stack
23+
//
24+
// We compile as a WASI reactor module (ie. a lib) which has no main() function
25+
// Instead we set up a constructor function which is called when the module is loaded
26+
//
27+
// Under the hood, reactor modules call _initialize() as the entry point which
28+
// wasi-libc implements, and in turn calls __wasm_call_ctors() to run constructors
29+
// See https://github.com/WebAssembly/wasi-libc/blob/main/libc-bottom-half/crt/crt1-reactor.c
30+
__attribute__((constructor)) void initialize() {
2331
lwip_init();
2432
}

0 commit comments

Comments
 (0)