Skip to content

quickjs-libc: fix use-after-free of the message port in handle_posted_message - #627

Closed
Perennos wants to merge 1 commit into
bellard:masterfrom
Perennos:fix-worker-port-uaf
Closed

Perennos wants to merge 1 commit into
bellard:masterfrom
Perennos:fix-worker-port-uaf

Conversation

@Perennos

Copy link
Copy Markdown

Fixes #527

Problem

handle_posted_message() reads port->on_message_func after calling JS_ReadObject() and JS_NewObject(), either of which can trigger the cycle GC. If the owning Worker is only reachable through a self-cycle (for example, w.self_ref = w; w = null;), the GC finalizes it and js_worker_finalizer() frees port, causing a heap-use-after-free on the subsequent read. ASan reports the read at quickjs-libc.c:2460, with the free in js_free_port via gc_free_cycles and js_trigger_gc.

Fix

Duplicate the handler reference (JS_DupValue(ctx, port->on_message_func)) before any allocation and release it at the end of the function. port is not dereferenced after that point. The duplicated reference still protects the handler call if func frees the handler, and the existing comment about func freeing the handler is merged into the new comment.

Testing

  • Added tests/test_worker_gc.js, a reduced reproducer from the issue that runs as part of make test.
  • Before the change, on an ASan build (make CONFIG_ASAN=y), the new test and the issue's PoC fail with heap-use-after-free in handle_posted_message.
  • After the change, the PoC and the new test pass (run 6 times), and make CONFIG_ASAN=y test exits 0, including tests/test_worker.js.

AI-assisted: drafted with an AI coding assistant; reproduced and tested locally before submitting.

…_message

The cycle GC can run during JS_ReadObject() or JS_NewObject() and finalize a
Worker that is only reachable through a self-cycle, which frees its message
handler. handle_posted_message() then read port->on_message_func from freed
memory. Take the reference to the handler function before any allocation and
do not touch port afterwards.

Add tests/test_worker_gc.js as a regression test.

Fixes bellard#527

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@bellard

bellard commented Nov 28, 2026

Copy link
Copy Markdown
Owner

applied

@bellard bellard closed this Nov 28, 2026
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.

heap-use-after-free in handle_posted_message

2 participants