Skip to content

wasi_thread_start() writes into wrong stack when optimize = Debug #22803

@chung-leong

Description

@chung-leong

Zig Version

0.14.0-dev.3050+d72f3d353

Steps to Reproduce and Observed Behavior

When optimize = Debug, a bunch of writes to stack would happen prior to __set_stack_pointer(). To avoid that, wasi_thread_start() needs to be a naked function:

    comptime {
        if (!builtin.single_threaded) {
            @export(&wasi_thread_start, .{ .name = "wasi_thread_start" });
            @export(&wasi_thread_start_impl, .{ .name = "wasi_thread_start_impl", .visibility = .hidden });
        }
    }

    /// Called by the host environment after thread creation.
    fn wasi_thread_start(_: i32, arg: *Instance) callconv(.naked) void {
        comptime assert(!builtin.single_threaded);
        __set_stack_pointer(arg.thread.memory.ptr + arg.stack_offset);
        asm volatile (
            \\ local.get 0
            \\ local.get 1
            \\ call wasi_thread_start_impl
            \\ return
        );
    }

    fn wasi_thread_start_impl(tid: i32, arg: *Instance) callconv(.c) void {
        __wasm_init_tls(arg.thread.memory.ptr + arg.tls_offset);
        @atomicStore(u32, &WasiThreadImpl.tls_thread_id, @intCast(tid), .seq_cst);

Expected Behavior

No stack operations prior to __set_stack_pointer().

Metadata

Metadata

Assignees

No one assigned

    Labels

    arch-wasm32-bit and 64-bit WebAssemblybugObserved behavior contradicts documented or intended behavioros-wasiWebAssembly System Interfacestandard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions