Repository navigation
ev/kqueue: fix completion-lifecycle use-after-free under concurrent cancellation - #443
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughReplace per-completion one-shot kevents with persistent knotes keyed by (ident, filter) in a loop-owned poll_queue; submit/cancel/poll now enqueue/remove completions in that map and resolve events by lookup. Add a regression test that cancels many parked UDP receivers concurrently on a 2-executor runtime. Changeskqueue persistent knote refactor
Concurrent cancellation regression test
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
57f3de9 to
acc3ebc
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/ev/backends/kqueue.zig`:
- Around line 418-436: The loop currently snapshots completion.next into iter
before calling state.markCompletedFromBackend(completion), which may resume
fibers and free sibling waiters, causing iter to point to freed memory; fix by
changing iteration to only read completion.next when you intend to follow it in
the .requeue path, and after handling a .completed (or .dead) outcome call
self.poll_queue.get(makeKey(event.ident, event.filter)) to reload the live entry
and restart iteration from entry.completions.head (rather than using the
previously captured iter pointer); update the loop around checkCompletion,
removeFromPollQueue, and state.markCompletedFromBackend to reflect this restart
behaviour so you never carry a raw next pointer across a possible resume in
markCompletedFromBackend.
In `@src/io.zig`:
- Around line 3783-3820: The test can false-pass because the fixed sleep doesn't
ensure all cancelUafBareRecv fibers are parked in receiveManyTimeout and the
results of fut.cancel/io group await are ignored; add a synchronization
barrier/ready counter that each cancelUafBareRecv increments (or awaits) after
entering receiveManyTimeout so the test only issues cancellations once all N
fibers report ready, then modify cancelUafCancelOne (or the group invocation) to
capture and assert that fut.cancel(io) returns error.Canceled for each
CancelUafFut and ensure group.await(io) errors are checked (propagated or
asserted) rather than discarded to guarantee the cancellation path was
exercised.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 8da08736-03f7-4e1e-bb92-900ab9598831
📒 Files selected for processing (2)
src/ev/backends/kqueue.zigsrc/io.zig
|
Hm, I'll have to think about this, because canceling a task should always cancel the operation, and actually wait for it to get canceled. I think the problem is that we call |
acc3ebc to
518682a
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/ev/backends/kqueue.zig (1)
407-421:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winDon't carry
completion.nextacrossmarkCompletedFromBackend().Line 409 snapshots
completion.nextbefore Line 419 can resume a fiber and free sibling waiters on the same(ident, filter). The next loop turn can then walk freed memory again. After any.completedpath, reload the live waiter list frompoll_queue; only follownexton skip/requeue paths.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/ev/backends/kqueue.zig` around lines 407 - 421, The loop currently snapshots completion.next into iter before calling checkCompletion and then, on the .completed path, calls state.markCompletedFromBackend(completion) which can resume a fiber and free sibling waiters; to fix, do not carry a pre-read completion.next across the completed path—only advance via completion.next when you took a skip or requeue branch; after handling the .completed branch (after calling self.removeFromPollQueue and state.markCompletedFromBackend) reload the live waiter list from entry.completions.head or poll_queue and continue from there so you never dereference freed memory; keep the existing behavior for skip/requeue where you set iter = completion.next.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@src/ev/backends/kqueue.zig`:
- Around line 209-214: reserveChange() currently ignores std.c.kevent()’s return
value and always calls change_buffer.clearRetainingCapacity(), which can desync
kernel knotes on failure, and poll() caches completion.next before invoking
state.markCompletedFromBackend(completion) so callbacks that cancel siblings can
mutate the intrusive list mid-iteration; fix reserveChange() to check kevent()’s
return value and only clear the change_buffer (or propagate/return an error)
when kevent() succeeds (handle and propagate errors from kevent() instead of
dropping them), and update poll() iteration to avoid carrying a raw next pointer
across the callback boundary (e.g., determine the next element after the
callback or use a safe iteration pattern) so that state.markCompletedFromBackend
and completion callbacks cannot corrupt the traversal of the completion list.
---
Duplicate comments:
In `@src/ev/backends/kqueue.zig`:
- Around line 407-421: The loop currently snapshots completion.next into iter
before calling checkCompletion and then, on the .completed path, calls
state.markCompletedFromBackend(completion) which can resume a fiber and free
sibling waiters; to fix, do not carry a pre-read completion.next across the
completed path—only advance via completion.next when you took a skip or requeue
branch; after handling the .completed branch (after calling
self.removeFromPollQueue and state.markCompletedFromBackend) reload the live
waiter list from entry.completions.head or poll_queue and continue from there so
you never dereference freed memory; keep the existing behavior for skip/requeue
where you set iter = completion.next.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 79627de3-7a73-4543-ba58-a421b851b2ca
📒 Files selected for processing (2)
src/ev/backends/kqueue.zigsrc/io.zig
🚧 Files skipped from review as they are similar to previous changes (1)
- src/io.zig
a091023 to
f2e9669
Compare
…ancellation The kqueue backend stored a raw *Completion in the kevent udata and recovered it via @ptrFromInt in poll(). A Completion is freed when its fiber unwinds, so completing event[i] in a poll batch can resume a fiber that cancels a sibling and frees its Completion, while a stale event[j] in the same batch still carries the pointer -- poll() then dereferences freed memory (EXC_BAD_ACCESS reading completion.state). It surfaces under concurrent cross-executor cancellation (listener/endpoint teardown). Mirror the epoll backend: key each knote by (ident, filter) in a loop-owned poll_queue and re-derive the Completion from that table in poll() rather than trusting the kevent cookie (udata is no longer used for routing). A stale event resolves to a removed entry or a live Completion, never freed memory. poll() reloads the live entry from poll_queue after each completion instead of carrying a completion.next across markCompletedFromBackend, which can resume a fiber that frees a sibling waiter on the same (ident, filter). Knotes stay persistent level-triggered (no EV_ONESHOT) and the changelist is still batched into poll()'s kevent(). EV.DELETE changes carry a sentinel udata so their EV_ERROR receipts (e.g. ENOENT on an already-removed knote) are skipped rather than mis-routed to a recycled (ident, filter). The key is packed wide enough for NetBSD's i32 kevent.filter. No public API change; checkCompletion/handleKqueueError are untouched. Adds a regression test in src/io.zig.
f2e9669 to
3697b56
Compare
|
Ok, given that I wanted to do #262 eventually, the map is fine. I was experimenting with an alternative fix for this, but if we want to support multiple reads per fd, we would still need the map. |
) Point the zio dependency at the PR commit GrapeBaBa/zio@3697b565 instead of the vendored v0.12.0 + local kqueue patch. The PR fixes the kqueue completion-lifecycle use-after-free under concurrent cancellation by keying knotes in a loop-owned (ident, filter) table and re-deriving completions from it rather than from a raw udata pointer. This also upgrades zio v0.12.0 -> v0.13.0 (the PR is based on zio main); verified clean: full `zig build test` 75/82 pass + 7 skip, no QUIC API breaks. NOTE: this pins a fork commit (immutable by SHA) until lalinsky/zio#443 merges; re-point at the merged commit / a zio release afterward.
Problem
The kqueue backend stores a raw
*Completionin the keventudataand recovers it via@ptrFromIntinpoll(). Because aCompletionis freed when its fiber unwinds, completingevent[i]in a poll batch can resume a fiber that cancels a sibling and frees that sibling's completion, while a staleevent[j]in the same batch still points at it —poll()then dereferences freed memory (EXC_BAD_ACCESSreadingcompletion.state). It surfaces under concurrent cross-executor cancellation (listener / endpoint teardown).Neither sibling backend has this: epoll re-derives the completion from a loop-owned
poll_queuekeyed by fd (the cookie is the fd, not a pointer); io_uring frees only on the op's own CQE.Fix
Mirror the epoll backend:
(ident, filter)in a loop-ownedpoll_queue(AutoHashMapUnmanaged);udatais no longer used for routing.poll()re-derives the completion(s) viapoll_queue.get(...), never from the event cookie — a stale event resolves to a removed entry (skip) or a live completion (a real I/O retry), never freed memory.EV_ONESHOT), and the changelist is still batched intopoll()'skevent()as before — so a registration error still comes back as anEV_ERRORevent handled bycheckCompletion(preserves the existing pipe/socket error semantics).EV.DELETEchanges carry a sentineludata, so theirEV_ERRORreceipts (e.g.ENOENTwhen the knote was already gone — common afterpoll+writeon one fd) are skipped instead of being mis-routed to a completion that recycled the same(ident, filter).(ident, filter)key is packed wide enough for NetBSD'si32kevent.filter(it isi16on Darwin/FreeBSD).No public API change.
checkCompletion/handleKqueueError(the per-op I/O logic) are untouched.Testing
src/io.zigtest (io: concurrent cross-executor cancel of N blocked recvmsg fibers is UAF-free): 8 fibers blocked inreceiveMany, cancelled concurrently on a 2-executor runtime. Onmainthis crashes; with the fix it passes 25–30/30 under stress on macOS arm64.zig build testgreen on macOS arm64 (the only failure is the pre-existing, network-dependentdns: lookup www.github.com follows CNAME). Cross-compiles clean forx86_64-freebsd/x86_64-netbsd.zig 0.16.0.
Fixes #442