Skip to content

Commit 7955cfd

Browse files
committed
Fix use-after-free of a suspended coroutine reachable only via a closure
A suspended coroutine (async function, generator or async generator) keeps its activation frame in a heap-allocated GC object. When a closure captures one of the coroutine's locals it holds an *open* var_ref that points into that frame. Open var_refs were not GC objects and were not traced by their holders, so the edge closure -> var_ref -> coroutine frame was invisible to the cycle collector: a coroutine reachable only through such a closure was collected while still live, and resuming it (or running the closure) then touched freed memory. Make an open var_ref that captures a coroutine local a GC object holding a counted reference to the owning coroutine (JSStackFrame.cur_gc_obj) and mark it from every var_ref holder, so the collector sees the edge and keeps the suspended coroutine (and the frame the var_ref points into) alive.
1 parent a07a918 commit 7955cfd

4 files changed

Lines changed: 211 additions & 8 deletions

File tree

‎quickjs.c‎

Lines changed: 115 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,12 @@ typedef struct JSStackFrame {
439439
/* only used in generators. Current stack pointer value. NULL if
440440
the function is running. */
441441
JSValue *cur_sp;
442+
/* only set for coroutine frames (async function / generator /
443+
async generator): the GC object owning this heap-allocated frame,
444+
NULL for ordinary C-stack frames. Lets a var_ref capturing one of
445+
the coroutine's locals keep the (suspended) coroutine reachable by
446+
the cycle collector. */
447+
struct JSGCObjectHeader *cur_gc_obj;
442448
} JSStackFrame;
443449

444450
typedef enum {
@@ -465,6 +471,20 @@ typedef struct JSVarRef {
465471
uint8_t is_detached;
466472
uint8_t is_lexical; /* only used with global variables */
467473
uint8_t is_const; /* only used with global variables */
474+
/* Set at creation for an open var_ref that captures a local of a
475+
coroutine (async function / generator / async generator): such a
476+
var_ref holds a counted reference to that coroutine's GC object and
477+
is itself a GC object, so the cycle collector can see the closure ->
478+
var_ref -> coroutine edge and keep the suspended coroutine (hence the
479+
captured variable it points into) alive. The coroutine is recovered
480+
as stack_frame->cur_gc_obj (valid while open). This is a *snapshot* of
481+
cur_gc_obj != NULL taken at creation, NOT rederived at read time:
482+
cur_gc_obj transitions NULL -> owner (it is set only after a
483+
generator's initial resume), so var_refs created during the prologue
484+
(e.g. mapped `arguments`) must stay non-coro even though cur_gc_obj is
485+
later set. Cleared when the var_ref is detached; the ref is released on
486+
detach/free. */
487+
uint8_t is_coro;
468488
JSValue *pvalue; /* pointer to the value, either on the stack or
469489
to 'value' */
470490
union {
@@ -1456,6 +1476,8 @@ static JSValue js_import_meta(JSContext *ctx);
14561476
static JSValue js_dynamic_import(JSContext *ctx, JSValueConst specifier,
14571477
JSValueConst options);
14581478
static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref);
1479+
static void js_async_function_free(JSRuntime *rt, JSAsyncFunctionData *s);
1480+
static void js_release_coro(JSRuntime *rt, JSGCObjectHeader *coro);
14591481
static JSValue js_new_promise_capability(JSContext *ctx,
14601482
JSValue *resolving_funcs,
14611483
JSValueConst ctor);
@@ -6872,6 +6894,23 @@ static inline JSShapeProperty *find_own_property(JSProperty **ppr,
68726894
return NULL;
68736895
}
68746896

6897+
/* Release a counted reference an open var_ref held on the coroutine
6898+
(async function / generator / async generator) owning the frame it
6899+
points into. */
6900+
static void js_release_coro(JSRuntime *rt, JSGCObjectHeader *coro)
6901+
{
6902+
switch (JS_GC_TYPE(coro)) {
6903+
case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:
6904+
js_async_function_free(rt, (JSAsyncFunctionData *)coro);
6905+
break;
6906+
case JS_GC_OBJ_TYPE_JS_OBJECT: /* generator / async generator */
6907+
JS_FreeValueRT(rt, JS_MKPTR(JS_TAG_OBJECT, (JSObject *)coro));
6908+
break;
6909+
default:
6910+
abort();
6911+
}
6912+
}
6913+
68756914
static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref)
68766915
{
68776916
if (var_ref) {
@@ -6884,6 +6923,12 @@ static void free_var_ref(JSRuntime *rt, JSVarRef *var_ref)
68846923
JSStackFrame *sf = var_ref->stack_frame;
68856924
assert(sf->var_refs[var_ref->var_ref_idx] == var_ref);
68866925
sf->var_refs[var_ref->var_ref_idx] = NULL;
6926+
/* an open coroutine var_ref is itself a GC object and holds
6927+
a counted ref to its coroutine (sf->cur_gc_obj) */
6928+
if (var_ref->is_coro) {
6929+
js_release_coro(rt, sf->cur_gc_obj);
6930+
remove_gc_object(&var_ref->header);
6931+
}
68876932
}
68886933
js_free_rt(rt, var_ref);
68896934
}
@@ -6982,7 +7027,10 @@ static void js_bytecode_function_mark(JSRuntime *rt, JSValueConst val,
69827027
if (var_refs) {
69837028
for(i = 0; i < b->closure_var_count; i++) {
69847029
JSVarRef *var_ref = var_refs[i];
6985-
if (var_ref && var_ref->is_detached) {
7030+
/* Detached var_refs are GC objects; open var_refs are GC
7031+
objects only when they capture a coroutine local (see
7032+
get_var_ref). Only those may be marked. */
7033+
if (var_ref && (var_ref->is_detached || var_ref->is_coro)) {
69867034
mark_func(rt, &var_ref->header);
69877035
}
69887036
}
@@ -7265,7 +7313,8 @@ static void mark_children(JSRuntime *rt, JSGCObjectHeader *gp,
72657313
if (pr->u.getset.setter)
72667314
mark_func(rt, &pr->u.getset.setter->header);
72677315
} else if ((prs->flags & JS_PROP_TMASK) == JS_PROP_VARREF) {
7268-
if (pr->u.var_ref->is_detached) {
7316+
if (pr->u.var_ref->is_detached ||
7317+
pr->u.var_ref->is_coro) {
72697318
/* Note: the tag does not matter
72707319
provided it is a GC object */
72717320
mark_func(rt, &pr->u.var_ref->header);
@@ -7307,9 +7356,17 @@ static void mark_children(JSRuntime *rt, JSGCObjectHeader *gp,
73077356
case JS_GC_OBJ_TYPE_VAR_REF:
73087357
{
73097358
JSVarRef *var_ref = (JSVarRef *)gp;
7310-
/* only detached variable referenced are taken into account */
7311-
assert(var_ref->is_detached);
7312-
JS_MarkValue(rt, *var_ref->pvalue, mark_func);
7359+
if (var_ref->is_detached) {
7360+
/* the var_ref owns its value */
7361+
JS_MarkValue(rt, *var_ref->pvalue, mark_func);
7362+
} else {
7363+
/* open var_ref: the value lives in the coroutine's frame
7364+
and is marked by the coroutine itself; only keep that
7365+
coroutine reachable. (Open var_refs are GC objects only
7366+
when they capture a coroutine local.) */
7367+
assert(var_ref->is_coro);
7368+
mark_func(rt, var_ref->stack_frame->cur_gc_obj);
7369+
}
73137370
}
73147371
break;
73157372
case JS_GC_OBJ_TYPE_ASYNC_FUNCTION:
@@ -16663,8 +16720,12 @@ static void js_mapped_arguments_mark(JSRuntime *rt, JSValueConst val,
1666316720
int i;
1666416721
if (var_refs) {
1666516722
for(i = 0; i < p->u.array.count; i++) {
16666-
if (var_refs[i] && var_refs[i]->is_detached)
16667-
mark_func(rt, &var_refs[i]->header);
16723+
/* mapped arguments hold a counted ref to each var_ref; the
16724+
ones that are GC objects (detached, or open capturing a
16725+
coroutine local) must be marked, like the other holders */
16726+
JSVarRef *vr = var_refs[i];
16727+
if (vr && (vr->is_detached || vr->is_coro))
16728+
mark_func(rt, &vr->header);
1666816729
}
1666916730
}
1667016731
}
@@ -17462,6 +17523,7 @@ static JSVarRef *js_create_var_ref(JSContext *ctx, bool is_gc_object)
1746217523
return NULL;
1746317524
JS_REF_COUNT(var_ref) = 1;
1746417525
var_ref->is_detached = true;
17526+
var_ref->is_coro = false;
1746517527
var_ref->value = JS_UNDEFINED;
1746617528
var_ref->pvalue = &var_ref->value;
1746717529
if (is_gc_object)
@@ -17512,6 +17574,19 @@ static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx,
1751217574
var_ref->stack_frame = sf;
1751317575
sf->var_refs[var_ref_idx] = var_ref;
1751417576
var_ref->pvalue = pvalue;
17577+
/* If this local belongs to a coroutine (async function, generator or
17578+
async generator), keep the coroutine reachable for as long as a
17579+
closure references the variable: make the open var_ref a GC object
17580+
holding a counted reference to the coroutine (sf->cur_gc_obj).
17581+
Otherwise (ordinary C-stack frame, cur_gc_obj == NULL) the running
17582+
function is a GC root and no extra bookkeeping is needed. Snapshot
17583+
the decision in is_coro now (cur_gc_obj may become non-NULL later);
17584+
the coroutine itself is recovered via stack_frame->cur_gc_obj. */
17585+
var_ref->is_coro = (sf->cur_gc_obj != NULL);
17586+
if (sf->cur_gc_obj) {
17587+
JS_REF_COUNT(sf->cur_gc_obj)++;
17588+
add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
17589+
}
1751517590
return var_ref;
1751617591
} else {
1751717592
/* Variable is not captured (e.g., from eval closures on uncaptured vars).
@@ -17521,6 +17596,7 @@ static JSVarRef *get_var_ref(JSContext *ctx, JSStackFrame *sf, int var_idx,
1752117596
return NULL;
1752217597
JS_REF_COUNT(var_ref) = 1;
1752317598
var_ref->is_detached = true;
17599+
var_ref->is_coro = false;
1752417600
var_ref->value = js_dup(*pvalue);
1752517601
var_ref->pvalue = &var_ref->value;
1752617602
add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
@@ -17756,11 +17832,27 @@ static int js_op_define_class(JSContext *ctx, JSValue *sp,
1775617832

1775717833
static void close_var_ref(JSRuntime *rt, JSVarRef *var_ref)
1775817834
{
17835+
JSGCObjectHeader *coro;
17836+
/* Already closed. This can happen during reentrant coroutine teardown:
17837+
closing one var_ref can drop the coroutine's refcount to zero and
17838+
re-enter close_var_refs on the same frame. Once detached, the union
17839+
holds 'value' rather than stack_frame, so we must not touch it. */
17840+
if (var_ref->is_detached)
17841+
return;
17842+
/* Read the coroutine (if any) before js_dup() overwrites the union
17843+
member that aliases stack_frame with 'value'. */
17844+
coro = var_ref->is_coro ? var_ref->stack_frame->cur_gc_obj : NULL;
1775917845
var_ref->value = js_dup(*var_ref->pvalue);
1776017846
var_ref->pvalue = &var_ref->value;
1776117847
/* the reference is no longer to a local variable */
1776217848
var_ref->is_detached = true;
17763-
add_gc_object(rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
17849+
var_ref->is_coro = false;
17850+
/* an open coroutine var_ref is already a GC object and holds a
17851+
reference to its coroutine; drop it now that it is detached. */
17852+
if (coro)
17853+
js_release_coro(rt, coro);
17854+
else
17855+
add_gc_object(rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
1776417856
}
1776517857

1776617858
static void close_var_refs(JSRuntime *rt, JSStackFrame *sf)
@@ -18106,6 +18198,8 @@ static JSValue JS_CallInternal(JSContext *caller_ctx, JSValueConst func_obj,
1810618198
sf->var_ref_count = b->var_ref_count;
1810718199
for(i = 0; i < b->var_ref_count; i++)
1810818200
sf->var_refs[i] = NULL;
18201+
/* ordinary C-stack frame: not owned by a coroutine GC object */
18202+
sf->cur_gc_obj = NULL;
1810918203
sp = stack_buf;
1811018204
pc = b->byte_code_buf;
1811118205
/* sf->cur_pc must we set to pc before any recursive calls to JS_CallInternal. */
@@ -21101,6 +21195,8 @@ static __exception int async_func_init(JSContext *ctx, JSAsyncFunctionState *s,
2110121195
sf->arg_count = arg_buf_len;
2110221196
sf->var_buf = sf->arg_buf + arg_buf_len;
2110321197
sf->cur_sp = sf->var_buf + b->var_count;
21198+
/* set by the caller once the owning coroutine GC object exists */
21199+
sf->cur_gc_obj = NULL;
2110421200
sf->var_refs = (JSVarRef **)(sf->cur_sp + b->stack_size);
2110521201
sf->var_ref_count = b->var_ref_count;
2110621202
for(i = 0; i < b->var_ref_count; i++)
@@ -21338,6 +21434,10 @@ static JSValue js_call_generator_function(JSContext *ctx, JSValueConst func_obj,
2133821434
if (JS_IsException(obj))
2133921435
goto fail;
2134021436
JS_SetOpaqueInternal(obj, s);
21437+
/* the body only starts running on the first next(); root captured
21438+
locals against the generator object from now on (the initial resume
21439+
above only reaches OP_initial_yield, before any user code) */
21440+
s->func_state.frame.cur_gc_obj = &JS_VALUE_GET_OBJ(obj)->header;
2134121441
return obj;
2134221442
fail:
2134321443
free_generator_stack_rt(ctx->rt, s);
@@ -21537,6 +21637,9 @@ static JSValue js_async_function_call(JSContext *ctx, JSValueConst func_obj,
2153721637
return JS_EXCEPTION;
2153821638
}
2153921639
s->is_active = true;
21640+
/* the body runs immediately (up to the first await), so the frame must
21641+
already know its owning coroutine to root captured locals */
21642+
s->func_state.frame.cur_gc_obj = &s->header;
2154021643

2154121644
if (!js_async_function_resume(ctx, s))
2154221645
goto fail;
@@ -21983,6 +22086,9 @@ static JSValue js_async_generator_function_call(JSContext *ctx,
2198322086
if (JS_IsException(obj))
2198422087
goto fail;
2198522088
s->generator = JS_VALUE_GET_OBJ(obj);
22089+
/* root captured locals against the async generator object (the initial
22090+
resume above only reaches OP_initial_yield, before any user code) */
22091+
s->func_state.frame.cur_gc_obj = &s->generator->header;
2198622092
JS_SetOpaqueInternal(obj, s);
2198722093
return obj;
2198822094
fail:
@@ -31297,6 +31403,7 @@ static JSVarRef *js_create_module_var(JSContext *ctx, bool is_lexical)
3129731403
var_ref->value = JS_UNDEFINED;
3129831404
var_ref->pvalue = &var_ref->value;
3129931405
var_ref->is_detached = true;
31406+
var_ref->is_coro = false;
3130031407
add_gc_object(ctx->rt, &var_ref->header, JS_GC_OBJ_TYPE_VAR_REF);
3130131408
return var_ref;
3130231409
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import * as std from "qjs:std";
2+
import { assert } from "./assert.js";
3+
4+
// Regression test: a suspended coroutine reachable only through a closure that
5+
// captured one of its locals must not be collected while it is still live.
6+
//
7+
// A closure capturing a coroutine local holds an *open* var_ref into the
8+
// coroutine's frame. Open var_refs are not GC objects and are not marked by
9+
// the closure, so the edge closure -> open var_ref -> value is invisible to
10+
// the cycle collector. An ordinary function's frame is a live C-stack root, but
11+
// a suspended coroutine's frame is a heap GC object, so if the only thing
12+
// keeping it reachable is such an escaped closure, the whole still-live
13+
// coroutine used to be collected -- and resuming it, or running the closure,
14+
// then touched freed memory.
15+
//
16+
// The async function below suspends at `await d.promise`; that promise is never
17+
// resolved, so nothing keeps the coroutine reachable except `leaked`'s capture
18+
// of the frame local `d`. Forcing a GC while it is suspended used to free it.
19+
20+
globalThis.leaked = null;
21+
22+
(function () {
23+
async function step() {
24+
const d = Promise.withResolvers();
25+
globalThis.leaked = () => d; // escapes, capturing the coroutine local `d`
26+
await d.promise; // suspend: reachable only via leaked -> d
27+
}
28+
step();
29+
})();
30+
31+
std.gc();
32+
33+
// If the suspended coroutine's frame was wrongly collected, `d` is freed memory.
34+
const d = leaked();
35+
assert(typeof d.resolve, "function");
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import * as std from "qjs:std";
2+
import { assert } from "./assert.js";
3+
4+
// Regression test: a suspended coroutine kept reachable only through its mapped
5+
// `arguments` object must not be collected.
6+
//
7+
// A sloppy function with a simple parameter list that uses `arguments` gets a
8+
// *mapped* arguments object whose entries are open var_refs pointing into the
9+
// function's frame. That object is a third var_ref holder (besides closures and
10+
// object var_ref properties) and must be traced the same way; otherwise a
11+
// suspended coroutine reachable only via an escaped `arguments` is either freed
12+
// while still live (use-after-free) or wrongly retained (a leak that trips the
13+
// gc_obj_list check at runtime teardown).
14+
15+
globalThis.leaked = null;
16+
17+
const AsyncFunction = (async function () {}).constructor;
18+
const step = AsyncFunction("a", `
19+
globalThis.leaked = () => arguments; // escapes, capturing the frame
20+
const d = Promise.withResolvers();
21+
await d.promise; // suspend; never resolved
22+
`);
23+
step(123);
24+
25+
std.gc();
26+
27+
// If the frame was wrongly collected this reads freed memory.
28+
assert(leaked()[0], 123);
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import * as std from "qjs:std";
2+
import { assert } from "./assert.js";
3+
4+
// Regression test: a suspended generator kept reachable only through a closure
5+
// that captured one of its locals must not be collected.
6+
//
7+
// This is the sync-generator counterpart of suspended-coroutine-closure-gc.js:
8+
// there is no promise involved. The generator object is held in a cycle through
9+
// a captured local, and the escaped closure is the only external anchor. The
10+
// closure holds an open var_ref into the generator's (heap) frame; if that edge
11+
// is invisible to the cycle collector the generator and its frame are freed
12+
// while the closure still points into them.
13+
14+
globalThis.leaked = null;
15+
16+
(function () {
17+
let g;
18+
function* gen() {
19+
const o = {};
20+
o.g = g; // frame local -> generator object (a cycle)
21+
globalThis.leaked = () => o; // escapes, capturing the frame local `o`
22+
yield; // suspend
23+
}
24+
g = gen();
25+
g.next(); // run to the yield
26+
g = null; // now reachable only via the cycle + leaked
27+
})();
28+
29+
std.gc();
30+
31+
const o = leaked();
32+
assert(o.g !== null && o.g !== undefined); // the generator object is still alive
33+
o.g.next(); // resume it: touches its frame

0 commit comments

Comments
 (0)