Skip to content

Fix use-after-free in blockInPlace cancellation - #542

Closed
lalinsky wants to merge 1 commit into
mainfrom
fix-blockinplace-cancel-uaf
Closed

lalinsky wants to merge 1 commit into
mainfrom
fix-blockinplace-cancel-uaf

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 5, 2026

Copy link
Copy Markdown
Owner

Problem

The common.test.blockInPlace: cancellation interrupts a blocking syscall on the worker test segfaults on powerpc64le/epoll under QEMU in CI (reported crash: cmpxchgStrong at address 0x0, under the completion_fn call in thread_pool.runTasks). It reproduces fairly regularly in CI.

Root cause

blockInPlace keeps everything on its own stack — ctx, waiter, token, work. The invariant that keeps this safe is: the task must not return (and reclaim that stack) until the worker's completionFn has completely finished touching those objects.

The cancel handler broke that invariant. completionFn publishes done before its trailing waiter.signal():

ctx.done.store(true, .release);   // (1)
waiter.signal();                  // (2) still reads our stack-allocated waiter

The cancel loop returned as soon as it observed done:

while (!ctx.done.load(.acquire)) { ... }
return ctx.result;   // frame reclaimed here

So the sequence was:

  1. Worker sets ctx.done = true.
  2. The canceled task (parked in the resend-backoff timedWait) is woken by the backoff timer, sees done == true, and returns from blockInPlace — reclaiming its stack.
  3. Worker executes waiter.signal() against the now-freed waiter. The reused stack memory makes the tagged-union mode read as .select, which takes the cmpxchgStrong path (common.zig, Waiter.signal) on a garbage winner pointer → segfault at 0x0.

The window between (1) and (2) is only a couple of instructions on the worker, so the crash requires the backoff timer to fire in exactly that gap. That is rare on fast native hardware but happens regularly under QEMU emulation and CI load. Nothing here is architecture-specific — it's a pure timing window.

The fast (non-canceled) path was never affected: it returns only after signal(), which is completionFn's last action there.

Fix

Keep resending SIGURG with backoff until the work finishes (done), but drive the backoff sleeps on a separate waiter, leaving blockInPlace's waiter to be signaled only by completionFn. After the loop, do one final waiter.wait(1, .no_cancel) to synchronize with completionFn's trailing signal() — the worker's last access to the stack frame — before returning.

completionFn and the fast path are unchanged.

When a task blocked in blockInPlace is canceled, the cancel handler
waited for the worker only via the `done` flag. But completionFn sets
`done` *before* its trailing waiter.signal():

    ctx.done.store(true, .release);
    waiter.signal();               // still touches our stack frame

Since ctx/work/waiter all live on blockInPlace's stack, observing `done`
let blockInPlace return and reclaim that frame while the worker was still
inside signal(). The worker then read the freed Waiter: its union tag was
interpreted as .select, taking the cmpxchgStrong path on a garbage winner
pointer and segfaulting at address 0x0.

The window is only a couple of instructions on the worker (between the
store and the signal), so it needs the resend-backoff timer to fire in
exactly that gap - which happens regularly under load, e.g. on
powerpc64le under QEMU in CI.

Fix: keep resending SIGURG with backoff until the work finishes (`done`),
but drive the backoff sleeps on a *separate* waiter so our `waiter` is
signaled only by completionFn. Then do one final waiter.wait(1) to
synchronize with completionFn's trailing signal() - the worker's last
access to our stack frame - before returning. The fast (non-canceled)
path is unchanged: it already returns only after signal(), which is
completionFn's last action there.
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 015d3c14-dd52-4dda-8500-cc3721f60d5c

📥 Commits

Reviewing files that changed from the base of the PR and between 2a8bcf5 and de74137.

📒 Files selected for processing (1)
  • src/common.zig

📝 Walkthrough

Walkthrough

Reworked the cancellation handling in blockInPlace's wait/resend logic within src/common.zig. Added clarifying comments about Context.done semantics and replaced the counter-driven waiter.timedWait loop with a sleeper-based exponential backoff resend loop followed by a final no_cancel wait on the main waiter.

Changes

Cancellation Wait/Resend Rework

Layer / File(s) Summary
Done-flag docs and resend loop rework
src/common.zig
Adds comments clarifying that Context.done alone isn't safe-to-return, and replaces the old wait_count-driven waiter.timedWait loop with a fresh sleeper waiter for backoff resends of the cancel token, followed by a final waiter.wait(..., .no_cancel) to sync with completionFn's trailing signal.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Poem

A waiter waits, a sleeper sleeps,
the cancel token quietly creeps,
backoff doubles, done stays false,
till completionFn calls the final waltz.
One last wait, no cancel allowed — 🐇💤

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the main fix: a use-after-free in blockInPlace cancellation.
Description check ✅ Passed The description directly explains the bug, root cause, and fix, and matches the code changes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-blockinplace-cancel-uaf

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@lalinsky

lalinsky commented Jul 5, 2026

Copy link
Copy Markdown
Owner Author

not the right fix

@lalinsky

lalinsky commented Jul 5, 2026

Copy link
Copy Markdown
Owner Author

Superseded by #543, which fixes the same UAF more cleanly by waiting for the work through the event loop (loop-owned completion delivery) instead of the custom completion callback + manual resend loop. #543 is stacked on #539.

@lalinsky
lalinsky deleted the fix-blockinplace-cancel-uaf branch August 24, 2026 11:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant