Skip to content

ev/kqueue: fix completion-lifecycle use-after-free under concurrent cancellation - #443

Merged
lalinsky merged 1 commit into
lalinsky:mainfrom
GrapeBaBa:fix/kqueue-completion-uaf
May 31, 2026
Merged

lalinsky merged 1 commit into
lalinsky:mainfrom
GrapeBaBa:fix/kqueue-completion-uaf

Conversation

@GrapeBaBa

@GrapeBaBa GrapeBaBa commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The kqueue backend stores a raw *Completion in the kevent udata and recovers it via @ptrFromInt in poll(). Because a Completion is freed when its fiber unwinds, completing event[i] in a poll batch can resume a fiber that cancels a sibling and frees that sibling's completion, while a stale event[j] in the same batch still points at it — poll() then dereferences freed memory (EXC_BAD_ACCESS reading completion.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_queue keyed 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:

  • Key each knote by (ident, filter) in a loop-owned poll_queue (AutoHashMapUnmanaged); udata is no longer used for routing. poll() re-derives the completion(s) via poll_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.
  • Knotes stay persistent level-triggered (no EV_ONESHOT), and the changelist is still batched into poll()'s kevent() as before — so a registration error still comes back as an EV_ERROR event handled by checkCompletion (preserves the existing pipe/socket error semantics).
  • EV.DELETE changes carry a sentinel udata, so their EV_ERROR receipts (e.g. ENOENT when the knote was already gone — common after poll+write on one fd) are skipped instead of being mis-routed to a completion that recycled the same (ident, filter).
  • The (ident, filter) key is packed wide enough for NetBSD's i32 kevent.filter (it is i16 on Darwin/FreeBSD).

No public API change. checkCompletion / handleKqueueError (the per-op I/O logic) are untouched.

Testing

  • New src/io.zig test (io: concurrent cross-executor cancel of N blocked recvmsg fibers is UAF-free): 8 fibers blocked in receiveMany, cancelled concurrently on a 2-executor runtime. On main this crashes; with the fix it passes 25–30/30 under stress on macOS arm64.
  • Full zig build test green on macOS arm64 (the only failure is the pre-existing, network-dependent dns: lookup www.github.com follows CNAME). Cross-compiles clean for x86_64-freebsd / x86_64-netbsd.

zig 0.16.0.

Fixes #442

@coderabbitai

coderabbitai Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Replace 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.

Changes

kqueue persistent knote refactor

Layer / File(s) Summary
Poll queue data structure and lifecycle
src/ev/backends/kqueue.zig
Introduce delete-marker sentinel, PollEntry, poll_queue map keyed by packed (ident, filter), makeKey(), and update init()/deinit() to provision poll_queue capacity.
Persistent knote helpers and filter extensions
src/ev/backends/kqueue.zig
Add getFflags() for .process_wait, extend getFilter() for .process_wait/.mach_port, refactor reserveChange() flush behavior, and add addToPollQueue()/removeFromPollQueue() that arm/delete persistent knotes using delete-marker udata.
Submit path refactored for poll_queue enqueue
src/ev/backends/kqueue.zig
Consolidate submit() async branches so .net_connect would-block/pending, network, pipe, .mach_port, and .process_wait enqueue into poll_queue via addToPollQueue() instead of per-op one-shot registrations.
Cancellation removes completion from poll_queue
src/ev/backends/kqueue.zig
cancel() removes the target completion from poll_queue prior to completing with error.Canceled, removing stale unregister bookkeeping.
Poll event resolution via poll_queue lookup
src/ev/backends/kqueue.zig
poll() calls kevent() with change_buffer.items, clears the buffer, treats INTR as zero events, ignores EVFILT_USER wake and delete-marker udata, looks up the waiter list by (ident, filter), and completes/removes only completions whose checkCompletion() returns completed (others are requeued).

Concurrent cancellation regression test

Layer / File(s) Summary
Concurrent cancellation test and helpers
src/io.zig
Add CancelUafFut alias and cancel helper, cancelUafBareRecv UDP receive helper that maps cancellation to error.Canceled, and a regression test that spawns N parked receivers on a 2-executor runtime then cancels them concurrently via Io.Group.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • lalinsky/zio#219: Overlapping kqueue cancellation/complete handling and poll protections.
  • lalinsky/zio#50: Prior kqueue change-submission/teardown adjustments relevant to delete-marker handling.
  • lalinsky/zio#205: kqueue wake/EVFILT_USER handling overlap.

Poem

A knote that waits by (ident, filter) tight,
poll_queue keeps lists so kevents don't bite.
Add, remove, and kevent dance in the loop,
cancelled fibers unlinked before they troop.
Executors sleep; the crash is fixed tonight.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main fix: addressing a use-after-free bug in kqueue's completion handling under concurrent cancellation, which is the core of the changeset.
Description check ✅ Passed The description clearly explains the problem (raw pointers in kevent.udata), the root cause (freed completions), and the solution (poll_queue keyed by ident/filter), all of which are directly implemented in the code changes.
Linked Issues check ✅ Passed The PR directly addresses issue #442 by implementing the core fix: replacing raw completion pointers with a loop-owned poll_queue keyed by (ident, filter), preventing stale pointer dereferences in poll() during concurrent cancellation.
Out of Scope Changes check ✅ Passed The kqueue.zig changes focus squarely on the use-after-free fix (poll_queue mechanics, persistent knotes, sentinel udata). The io.zig additions are a regression test for concurrent cancellation, directly supporting the PR's testing objective.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@GrapeBaBa
GrapeBaBa force-pushed the fix/kqueue-completion-uaf branch from 57f3de9 to acc3ebc Compare May 31, 2026 08:19

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between c0382d0 and 57f3de9.

📒 Files selected for processing (2)
  • src/ev/backends/kqueue.zig
  • src/io.zig

Comment thread src/ev/backends/kqueue.zig Resolved
Comment thread src/io.zig Resolved
@lalinsky

lalinsky commented May 31, 2026 •

Copy link
Copy Markdown
Owner

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 EV_DELETE, which cancels it immediately, but kqueue already has the completion events queued up for delivery, so they still arrive later. Maybe the correct approach would be to drain the queue first. Or maybe the map is indeed the best option. Or maybe the map should contains completion pointers to ignore in the next event drain. I'm not sure yet.

@GrapeBaBa
GrapeBaBa force-pushed the fix/kqueue-completion-uaf branch from acc3ebc to 518682a Compare May 31, 2026 09:23

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/ev/backends/kqueue.zig (1)

407-421: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Don't carry completion.next across markCompletedFromBackend().

Line 409 snapshots completion.next before 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 .completed path, reload the live waiter list from poll_queue; only follow next on 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

📥 Commits

Reviewing files that changed from the base of the PR and between acc3ebc and 518682a.

📒 Files selected for processing (2)
  • src/ev/backends/kqueue.zig
  • src/io.zig
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/io.zig

Comment thread src/ev/backends/kqueue.zig Resolved
@GrapeBaBa
GrapeBaBa force-pushed the fix/kqueue-completion-uaf branch 3 times, most recently from a091023 to f2e9669 Compare May 31, 2026 10:52
…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.
@GrapeBaBa
GrapeBaBa force-pushed the fix/kqueue-completion-uaf branch from f2e9669 to 3697b56 Compare May 31, 2026 11:37
@lalinsky

Copy link
Copy Markdown
Owner

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.

@lalinsky
lalinsky merged commit 78d48fa into lalinsky:main May 31, 2026
26 checks passed
GrapeBaBa added a commit to zen-eth/eth-p2p-z that referenced this pull request Jun 2, 2026
)

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.
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.

kqueue backend: use-after-free under concurrent cancellation

2 participants