You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
spawn_os sends capturing closures to OS threads with no ScopedSend checking #974
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.
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.
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``
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:
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.
The spec's §14.16 example must fail with check with that diagnostic.
The d4_len.w shape above must be rejected at check time; the join-inside control must still compile.
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.
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 () => ...`
Activity
eas4ai commentedon Sep 3, 2026
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 aspawn_osARGUMENT passes unchecked. The analysis covers return position but not param position, andspawn_osis exactly the param-position case where the value crosses threads. A ScopedSend-style check on the parameter's closure context (orunsafe fn) would close the gap symmetric with the return-position rule.ehartford commentedon Sep 15, 2026
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-Copylocal by place (spec §12, "Closure captures are by place") can be handed tospawn_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) passeswith checktoday. Two peripheral claims are refuted:spawn_osdoes not "enforce nothing" (aSendcapture check and the escaping-ephemeral check both fire), and theRcpayload is not reachable from safe code becauseRccaptures are rejected as non-Send.Tested revision and compiler
main@ 5809ac1 (2026-09-14);lib/std/thread.wunchanged since the reported 450733ewith buildof 5809ac1 in a detached worktree, self-reportswith v0.15.2.1Probe matrix
with checkRc.new(5)captured,r.clone()in workerthread.spawn_os captures non-Send value \r``let r = &localthenspawn_os(() => peek(r))escaping closure cannot capture ephemeral referencesstrcaptured, then used in mainuse of moved valuelet local = "hello"; spawn_os(() => peek(&local))(spec §14.16's ERROR example)local, not as a borrow of the framevar x = 0, both threads do 1,000,000x = x + 1x=1000000after 2,000,000 incrementsstart()buildsVec[i32], spawns a worker that reads it after a delay, returns the handle;mainjoins laterinteger overflowreading garbage, rc 134joininsidestart()(control)joined=10Repro for the use-after-scope row:
Root cause (observed in MIR, not inferred)
with check d4_len.w --dump-mirforstart:--trace-ownership start:_1confirms_1goesInit -> drop at bb2.stmt4; the closure creation records no move out of_1. So the frame ownsv, the closure holds a by-place view of it, andspawn_oslets that view escape the frame. The checks that do run on the argument aresrc/SemaCheck.w:15530-15535(check_callable_captures_thread_traitwith theSendtrait) and the ephemeral-escape rule; neither treats "by-place capture of an owned local" as a borrow, so aSend-typedVecpasses. The comment atlib/std/thread.w:25-30reasons about the Copy-ness of the fn value, which is the handle, not the captured place; the report is right about that.Spec / decisions
thread.spawn_os(() => use_ref(&local)) // ERROR: &local is not Send. The compiler accepts this spelling.&Tbindings, not for by-place captures of owned locals.docs/decisions.md(line 1455) records that theescape_valuepin onspawn_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.wor the spawn_os branch ofSemaCheck.w.Would I champion a fix? Yes; this is a memory-safety hole in safe code.
Acceptance criteria:
spawn_os(and any other escaping sink) must own its captures: either requiremove ||at the call site with a fix-it, or reject any by-place capture of a non-Copy local with the existingescaping closure cannot capture ...diagnostic.with checkwith that diagnostic.d4_len.wshape above must be rejected at check time; the join-inside control must still compile.varcaptures written on both sides: decide by ruling whether a by-placeCopycapture 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
lldbbacktrace 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-allocwould have made this a one-command proof. Linux and Windows not executed.Sema/Codegen: every capture of a non-move closure is by place, Copy o…
Sema/Codegen: every capture of a non-move closure is by place, Copy o…
Sema/Codegen: every capture of a non-move closure is by place, Copy o…
Sema/Codegen: every capture of a non-move closure is by place, Copy o…
ehartford commentedon Oct 25, 2026
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).