Skip to content

spawn_os sends capturing closures to OS threads with no ScopedSend checking #974

Closed

Description

@eas4ai

Classification

Verified safe-code soundness hole (audit finding THREAD-001). Severity High: data race / use-after-scope / refcount race reachable from safe code.

Source chain

spawn_os(worker: fn() -> i32) (lib/std/thread.w:31) is a safe pub fn that transmutes the worker to fn_ptr+ctx (:32) and hands both to with_thread_spawn, which really spawns an OS thread invoking worker(ctx) (rt/rt_core.w:1295-1313, rt_thread_entry). Per spec §16.6, plain fn values 'may carry closure context' — and they do: a capturing closure with a mutating capture passes with check (probe .audit/probes/readonly_pass_20260903/closure_probe.w). The structured path s.spawn enforces ScopedSend per capture plus mutate-before-join errors (src/SemaCheck.w:22438-22460); this path enforces nothing.

Reachable payloads (all in safe code today)

  • Rc[T]: non-atomic count raced across threads → UAF/double-free;
  • &T borrows: use-after-scope when the parent scope ends first;
  • var captures mutated on both sides: data race.

Wrong rationale on site

The comment (:25-30) declines an effect pin because 'fn() -> i32 is Copy, so an escape_value pin has no ownership consequence' — confusing handle-Copy with pointee-Send. The fat pointer is Copy AND points at shared context.

Repair boundary

unsafe fn, or a ScopedSend bound on the closure context, or removal in favor of s.spawn.

Activity

  1. eas4ai commented on Sep 3, 2026

    @eas4ai
    ContributorAuthor

    Sharp contrast strengthening this finding: returning a borrow-capturing closure is REJECTED ('escaping closure cannot capture ephemeral references', verified with .audit/probes/readonly_pass_20260903/closesc_probe.w) — the escape analysis exists for closure RETURNS. But passing the identical closure as a spawn_os ARGUMENT passes unchecked. The analysis covers return position but not param position, and spawn_os is exactly the param-position case where the value crosses threads. A ScopedSend-style check on the parameter's closure context (or unsafe fn) would close the gap symmetric with the return-position rule.

  2. ehartford commented on Sep 15, 2026

    @ehartford
    Contributor

    Review: reproduced, with limits on the title and one payload

    Verdict. The central soundness hole is real on current main: a closure that captures a non-Copy local by place (spec §12, "Closure captures are by place") can be handed to spawn_os, the spawning frame then drops that local at its own scope exit while the OS thread is still running, and the thread reads freed memory. The spec's own §14.16 example (thread.spawn_os(() => use_ref(&local)) // ERROR) passes with check today. Two peripheral claims are refuted: spawn_os does not "enforce nothing" (a Send capture check and the escaping-ephemeral check both fire), and the Rc payload is not reachable from safe code because Rc captures are rejected as non-Send.

    Tested revision and compiler

    item value
    source main @ 5809ac1 (2026-09-14); lib/std/thread.w unchanged since the reported 450733e
    compiler with build of 5809ac1 in a detached worktree, self-reports with v0.15.2.1
    platform macOS Darwin 25.6.0, arm64

    Probe matrix

    probe with check run verdict
    Rc.new(5) captured, r.clone() in worker rejected: thread.spawn_os captures non-Send value \r`` n/a refutes the Rc payload
    let r = &local then spawn_os(() => peek(r)) rejected: escaping closure cannot capture ephemeral references n/a escape check exists in param position too
    heap str captured, then used in main rejected: use of moved value n/a the move checker treats the capture as consuming
    let local = "hello"; spawn_os(() => peek(&local)) (spec §14.16's ERROR example) ok prints 5 spec non-conformance: the capture is checked by the type of local, not as a borrow of the frame
    var x = 0, both threads do 1,000,000 x = x + 1 ok x=1000000 after 2,000,000 increments unsynchronised writes to one place accepted
    start() builds Vec[i32], spawns a worker that reads it after a delay, returns the handle; main joins later ok worker panics integer overflow reading garbage, rc 134 use-after-scope
    same, but join inside start() (control) ok joined=10 correct when the frame outlives the thread

    Repro for the use-after-scope row:

    use std.thread
    fn start():
        let v: Vec[i32] = [1, 2, 3, 4]
        spawn_os(() => {
            var k = 0
            while k < 30000000:
                k = k + 1
            var s = 0
            for i in 0..v.len() as i32: s = s + v[i]
            s
        })
    fn clobber(n: i32) -> i32:
        var arr = [n; 256]
        var s = 0
        for i in 0..256: s = s + arr[i]
        s
    fn main:
        let h = start()
        var t = 0
        for i in 0..2000: t = t + clobber(7)
        print(f"joined={join(&h)} t={t}")
    

    Root cause (observed in MIR, not inferred)

    with check d4_len.w --dump-mir for start:

    bb1: _1 = move _2;                       // v
         _3 = const closure(node7474);       // captures _1 by place
         call sym739(copy _3) -> [return: _4]  // spawn_os(worker)
    bb2: drop(_1) @ drop#4 scope-exit _1;    // v freed here, thread still running
         _0 = move _4; return;
    

    --trace-ownership start:_1 confirms _1 goes Init -> drop at bb2.stmt4; the closure creation records no move out of _1. So the frame owns v, the closure holds a by-place view of it, and spawn_os lets that view escape the frame. The checks that do run on the argument are src/SemaCheck.w:15530-15535 (check_callable_captures_thread_trait with the Send trait) and the ephemeral-escape rule; neither treats "by-place capture of an owned local" as a borrow, so a Send-typed Vec passes. The comment at lib/std/thread.w:25-30 reasons about the Copy-ness of the fn value, which is the handle, not the captured place; the report is right about that.

    Spec / decisions

    • §12 (spec line 5713): "For non-Copy values, default capture is by place: the closure observes or mutates the original place." Escaping such a closure to a thread is therefore a frame borrow crossing threads.
    • §14.16 (line 7763): thread.spawn_os(() => use_ref(&local)) // ERROR: &local is not Send. The compiler accepts this spelling.
    • §22.1 rule 9: "Escaping closure captures ephemeral value: Reject." Enforced for explicit &T bindings, not for by-place captures of owned locals.
    • docs/decisions.md (line 1455) records that the escape_value pin on spawn_os "caught exactly this during implementation"; the pin was later removed per the thread.w comment (D30 R2b).

    Related PRs

    42a540d (2026-06-15) "Enforce Send and Sync semantics" added the capture check that refutes the "enforces nothing" claim. No merged or open PR since 450733e touches lib/std/thread.w or the spawn_os branch of SemaCheck.w.

    Would I champion a fix? Yes; this is a memory-safety hole in safe code.

    Acceptance criteria:

    1. A closure passed to spawn_os (and any other escaping sink) must own its captures: either require move || at the call site with a fix-it, or reject any by-place capture of a non-Copy local with the existing escaping closure cannot capture ... diagnostic.
    2. The spec's §14.16 example must fail with check with that diagnostic.
    3. The d4_len.w shape above must be rejected at check time; the join-inside control must still compile.
    4. var captures written on both sides: decide by ruling whether a by-place Copy capture is copied (spec says Copy values are copied, which makes the 1,000,000 result correct) and add a test pinning it.

    Untested / tool gap

    I did not get an lldb backtrace at the worker's panic (the panic path for OS threads does not go through the fiber panic symbols I broke on). The debug allocator did not flag the read of freed memory because it traps frees, not reads; a read-after-free trap for --debug-alloc would have made this a one-command proof. Linux and Windows not executed.

  3. ehartford commented on Oct 25, 2026

    @ehartford
    Contributor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): does not reproduce. Every program the review accepted is now refused at check, by the by-place capture rule from D63 / §12.4 (4932b8b, #1620).

    $ with check main.w      # the use-after-scope repro from the review
    error: closure argument holds `v` by place — a view of this frame — and `spawn_os` stores or returns its parameter (§12.4); pass an owning closure: `move () => ...`
    $ with check spec1416.w  # let local = "hello"; spawn_os(() => peek(&local))
    error: closure argument holds `local` by place — … pass an owning closure: `move () => ...`
    $ with check race.w      # var x mutated by both threads
    error: closure argument holds `x` by place — … pass an owning closure: `move () => ...`
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions