Skip to content

Retain job realms and trace module lifetimes - #1751

Open
undy-aeon wants to merge 2 commits into
quickjs-ng:masterfrom
tzfm:fix-job-module-lifetimes
Open

undy-aeon wants to merge 2 commits into
quickjs-ng:masterfrom
tzfm:fix-job-module-lifetimes

Conversation

@undy-aeon

Copy link
Copy Markdown

Queued jobs keep their arguments alive, but currently do not retain their realm. If the last external context reference is released while a job is pending, executing that job can access a freed context. Top-level-await state can likewise keep a module reachable after its context's loaded-module list is destroyed, causing a use-after-free during runtime teardown.

This ports and adapts bellard/quickjs@458c34d:

  • retain a job's realm until execution or runtime teardown
  • make module definitions GC-traced objects so asynchronous module state can outlive its context safely
  • add regressions for a queued job after external context release and for repeated dynamic imports through a pending top-level-await dependency

This is the focused lifetime item still listed in #1166.

Validation:

  • ASan and warnings-as-errors build and API tests
  • ASan GC-stress API tests
  • UBSan and warnings-as-errors build and API tests
  • make ctest cxxtest with both NaN-boxing modes
  • test262 configuration: 0/117 errors, 9 excluded

@flora131

Copy link
Copy Markdown

Thanks for working on this. I tested a backport of this PR onto quickjs-ng 0.15.1 in rquickjs 0.12.2, and this PR on the 0.16.2-derived engine in rquickjs 0.14.0. Both fix a cyclic top-level-await module use-after-free, once the embedding also releases its owned compile/read module values.

The minimal teardown cases below produced this before/after result under AddressSanitizer on both versions:

Engine / embedding Plain pending TLA Cyclic pending TLA Anonymous cyclic pending TLA
Unpatched Pass heap-use-after-free heap-use-after-free
This PR, without owned-module-value release gc_obj_list assertion gc_obj_list assertion gc_obj_list assertion
This PR + owned-module-value release Pass Pass Pass

A queued native job whose context owner was dropped before GC also stopped reporting use-after-free with this PR.

Minimal Rust reproduction

Use rquickjs with the loader feature. This test only creates a runtime/context, evaluates a pending module, drains available jobs, and releases the runtime:

fn release_pending_module(source: &str) {
    let runtime = rquickjs::Runtime::new().unwrap();
    let context = rquickjs::Context::full(&runtime).unwrap();
    context.with(|ctx| {
        let (module, promise) = rquickjs::Module::declare(ctx.clone(), "pending.mjs", source)
            .unwrap()
            .eval()
            .unwrap();
        ctx.globals().set("evaluation", promise).unwrap();
        // Accessing an uninitialized export is expected to fail while TLA is pending.
        assert!(module.get::<_, i32>("result").is_err());
    });
    while runtime.execute_pending_job().unwrap() {}
    drop(context);
    drop(runtime);
}

#[test]
fn pending_module_teardown() {
    release_pending_module("await new Promise(() => {}); export const result = 1;");
    release_pending_module(
        "const p = new Promise(() => {}); p.self = p; await p; export const result = 1;",
    );
    release_pending_module(
        "await (() => { const p = new Promise(() => {}); p.self = p; return p; })(); \
         export const result = 1;",
    );
}

ASan settings for the original before/after experiment: nightly Rust, RUSTFLAGS=-Zsanitizer=address, CFLAGS='-fsanitize=address -fno-omit-frame-pointer -g', ASAN_OPTIONS=detect_leaks=0:abort_on_error=1, and --target x86_64-unknown-linux-gnu. Those runs establish the UAF result, not leak absence. A subsequent independent ASan+LSan/UBSan check on the 0.15.1 backport also passed all three paired-fix pending-module cases with leak detection enabled. As a quick native sanity check of the exact test above on macOS, unpatched rquickjs 0.12.2 aborts with SIGABRT, and the 0.15.1 backport plus the owned-module-value release passes.

Embedding integration detail

JS_Eval(..., JS_EVAL_FLAG_COMPILE_ONLY) and JS_ReadObject return owned module values. An embedder that extracts the JSModuleDef * but never frees the returned value retains an extra module reference once modules become GC objects. The context's loaded-module list already retains the module. In rquickjs, adding JS_FreeValue after extracting the pointer in Module::declare and Module::load fixes that integration abort, following quickjs-libc's loader pattern.

Advisory: partly-built module on JS_ReadModule failure

An ownership review found that if reading fails after obj = JS_NewModuleValue, the partly-built module stays registered in ctx->loaded_modules and is retained by that list. In the 0.15.1 backport these are the creation and failure paths at quickjs.c:39155 and 39248–39251; the previous code removed and freed the module there. The corresponding code is also present in this PR and bellard's master.

This is an advisory, not a blocker or a demonstrated leak/double-free: the list still owns the module. It may be worth unlinking it on the error path or documenting that it remains registered until a later sweep/teardown.

This branch has not been deployed

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

2 participants