Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions crates/guest-rust/src/rt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,21 @@ pub unsafe fn cabi_realloc(
/// wit-bindgen-rust generates a call to this function at the start of all
/// component export functions. Importantly, it is not called as part of
/// `cabi_realloc`, which is a *core* export func, but should not execute ctors.
/// Constructors already invoked by `_initialize` or `_start` do not need to be
/// run again when an export is called.
#[cfg(target_arch = "wasm32")]
pub fn run_ctors_once() {
static mut RUN: bool = false;

extern "C" fn mark_run() {
unsafe { RUN = true }
}

// Record startup regardless of who calls `__wasm_call_ctors`.
#[used]
#[unsafe(link_section = ".init_array")]
static MARK_RUN: extern "C" fn() = mark_run;

unsafe {
if !RUN {
// This function is synthesized by `wasm-ld` to run all static
Expand Down
14 changes: 14 additions & 0 deletions tests/runtime/rust/ctors-run-once/runner.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
include!(env!("BINDINGS"));

struct Component;

export!(Component);

impl Guest for Component {
fn run() {
// Startup may have run the constructors at instantiation or at the
// first export call. Neither export call should run them again.
assert_eq!(the::test::i::ctor_runs(), 1);
assert_eq!(the::test::i::ctor_runs(), 1);
}
}
23 changes: 23 additions & 0 deletions tests/runtime/rust/ctors-run-once/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
include!(env!("BINDINGS"));

use std::sync::atomic::{AtomicU32, Ordering::Relaxed};

static CTOR_RUNS: AtomicU32 = AtomicU32::new(0);

extern "C" fn ctor() {
CTOR_RUNS.fetch_add(1, Relaxed);
}

#[used]
#[unsafe(link_section = ".init_array")]
static CTOR: extern "C" fn() = ctor;

struct Test;

export!(Test);

impl exports::the::test::i::Guest for Test {
fn ctor_runs() -> u32 {
CTOR_RUNS.load(Relaxed)
}
}
14 changes: 14 additions & 0 deletions tests/runtime/rust/ctors-run-once/test.wit
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package the:test;

interface i {
ctor-runs: func() -> u32;
}

world runner {
import i;
export run: func();
}

world test {
export i;
}
Loading