Skip to content

Fix blockInPlace cancellation UAF by waiting through the event loop - #543

Merged
lalinsky merged 2 commits into
cancel-blocking-fileopsfrom
fix-blockinplace-uaf-539
Jul 5, 2026
Merged

lalinsky merged 2 commits into
cancel-blocking-fileopsfrom
fix-blockinplace-uaf-539

Conversation

@lalinsky

@lalinsky lalinsky commented Jul 5, 2026

Copy link
Copy Markdown
Owner

Stacked on #539 (cancel-blocking-fileops). Fixes the use-after-free behind the common.test.blockInPlace: cancellation interrupts a blocking syscall on the worker segfault seen on powerpc64le/epoll under QEMU in CI (cmpxchgStrong at 0x0).

Root cause

blockInPlace keeps ctx/work/waiter on its own stack and used a custom completion_fn that signaled the waiter directly from the worker thread. The cancel path returned as soon as it observed a done flag that completion_fn set before its trailing waiter.signal():

ctx.done.store(true, .release);   // observed by the cancel loop → return, frame freed
waiter.signal();                  // worker still touching the freed Waiter

The freed Waiter's union tag then decoded as .select, taking the cmpxchgStrong path on a garbage winner pointer → segfault at 0x0. The window is ~2 instructions on the worker, so it needs the resend-backoff timer to fire in exactly that gap — which happens regularly under QEMU/CI load. It reproduces in CI fairly often.

Fix: wait through the event loop

Submit the work through the loop (loop.add) and wait via waitForIo(&work.c). The loop owns completion delivery — it finalizes work.c and signals the waiter on the loop thread as the last step, and waitForIo waits for that before returning. Nothing touches the stack frame after we may return, so the UAF is gone by construction. This deletes the custom completion_fn, the done flag, and the entire manual token/resend loop:

var work = ev.Work.init(Context.workFn, &ctx);
work.cancel_token = &token;
waitForIo(&work.c) catch {};
return ctx.result;

I reproduced the original crash's structural conditions and then ran the pipe-based blockInPlace cancellation test ~10k times under 14-way parallel QEMU load on powerpc64le/epoll with zero failures.

Supporting changes

  • Generalize the loop's SIGURG cancel-resend list (added in Cancelable delegated file ops on kqueue/poll backends #539 for DelegatedWork) to key on any Work.cancel_token. The intrusive link moves from DelegatedWork to Work (resend_next/resend_key). resend_key is the public completion whose finalization drops the entry, so both a plain .work op (key == &work.c) and a delegated file op (key == the owning op completion) are handled uniformly. The generic .work cancel path now registers for resend too. The entry is still removed as the completion finalizes, before its waiter is signaled, so sweepResend never dereferences a token whose frame is about to be freed.

  • ThreadPool.cancel never drops token-bearing work. Its func always runs so the caller-owned result is always valid — a still-queued syscall aborts at begin(), a running one is interrupted via SIGURG. This preserves blockInPlace's "workFn always runs" invariant (so ctx.result is never undefined) and matches the delegated ops, which report Canceled from the op func whether the syscall was dropped or run-then-aborted (handleFileOpen sets the completion error directly).

Behavior note

A canceled blockInPlace now re-arms the task's pending cancellation (via waitForIo's recancel), so the task stays canceled afterward — consistent with the rest of the std.Io cancellation semantics. The previous code consumed the cancel.

Testing

  • zig build test -Dtarget=powerpc64le-linux -Dbackend=epoll -Dtest-filter=cancel — 51/51 pass under QEMU (incl. the original failing test and the delegated Dir: canceling a blocking open test that exercises the ThreadPool.cancel change).
  • Native -Dtest-filter=blockInPlace passes.
  • ~10k-iteration parallel stress of the cancellation test on ppc64le/epoll: clean.

Supersedes #542 (a self-contained fix on main that kept the custom completion path).

blockInPlace kept ctx/work/waiter on its own stack and used a custom
completion_fn that signaled the waiter directly from the worker thread.
The cancel path returned as soon as it observed a `done` flag that
completion_fn set *before* its trailing waiter.signal(), so the task
could return and reclaim the frame while the worker was still inside
signal() — a use-after-free that read the freed Waiter (its union tag
decoded as .select, taking cmpxchgStrong on a garbage pointer and
segfaulting at 0x0). It reproduced regularly on powerpc64le under QEMU
in CI, where the resend-backoff timer reliably fired in the tiny window
between the store and the signal.

Fix: submit the work through the event loop and wait via waitForIo, so
the loop owns completion delivery — it finalizes work.c and signals the
waiter on the loop thread as the last step, and waitForIo waits for that
before returning. Nothing touches the stack frame after we may return,
so the UAF window is gone by construction. This deletes the custom
completion_fn, the `done` flag, and the whole manual token/resend loop.

To make this correct and cover the first-signal-lost case generically:

- Generalize the loop's SIGURG cancel-resend list to key on any
  Work.cancel_token, not just DelegatedWork. The intrusive link moves
  from DelegatedWork to Work (resend_next/resend_key); resend_key is the
  public completion whose finalization drops the entry, so both a plain
  .work op (key == &work.c) and a delegated file op (key == the owning
  op completion) are handled uniformly. The generic .work cancel path
  now registers for resend too.

- ThreadPool.cancel never drops token-bearing work: its func always runs
  so the result is always valid (a still-queued syscall aborts at
  begin(), a running one is interrupted via SIGURG). This preserves
  blockInPlace's "workFn always runs" invariant and matches the delegated
  ops (which report Canceled from the op func either way).

A canceled blockInPlace now also re-arms the task's pending cancellation
(via waitForIo's recancel), so the task stays canceled afterward.
@coderabbitai

coderabbitai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: db0f241e-3828-4914-a344-1612f428d778

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-blockinplace-uaf-539

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.

waitForIo only returns error.Canceled when the completion carries a
Canceled result, which only happens on the drop path where workFn never
runs and ctx.result is undefined. Token-bearing work is never dropped, so
that is unreachable here; assert it with `catch unreachable` rather than
swallowing it, so a broken invariant crashes loudly instead of returning
uninitialized ctx.result.
@lalinsky
lalinsky merged commit b41e854 into cancel-blocking-fileops Jul 5, 2026
26 of 27 checks passed
@lalinsky
lalinsky deleted the fix-blockinplace-uaf-539 branch July 5, 2026 10:33
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