From: Dmitry Volyntsev Date: Thu, 12 Nov 2026 01:33:52 +0000 (-0800) Subject: QuickJS: fix njs.on() with a foreign receiver X-Git-Url: https://git.kaiwu.me/ngx_http_auth_basic_module.html?a=commitdiff_plain;h=9f7e874b66856ccd5d0ccadf1450a9198ded821d;p=njs.git QuickJS: fix njs.on() with a foreign receiver Previously, njs.on() allocated the hooks state lazily and attached it to its receiver with JS_SetOpaque() if the receiver was not an njs object. Called with another receiver, for example njs.on.call(f, ...), it overwrote the internal opaque pointer of an arbitrary object, which resulted in memory corruption. Now the hooks state is allocated with the njs object, and njs.on() called with another receiver throws TypeError. The issue was introduced in 04f6dfb9 (0.9.2). --- diff --git a/src/qjs.c b/src/qjs.c index c1c8c1d3..5220486b 100644 --- a/src/qjs.c +++ b/src/qjs.c @@ -394,7 +394,8 @@ done: static int qjs_add_intrinsic_njs(JSContext *cx, JSValueConst global) { - JSValue obj, proto; + JSValue obj, proto; + qjs_njs_t *njs; if (JS_NewClass(JS_GetRuntime(cx), QJS_CORE_CLASS_ID_NJS, &qjs_njs_class) < 0) @@ -417,6 +418,16 @@ qjs_add_intrinsic_njs(JSContext *cx, JSValueConst global) return -1; } + njs = js_mallocz(cx, sizeof(qjs_njs_t)); + if (njs == NULL) { + JS_FreeValue(cx, obj); + return -1; + } + + njs->hooks[QJS_NJS_HOOK_EXIT] = JS_UNDEFINED; + + JS_SetOpaque(obj, njs); + if (JS_SetPropertyStr(cx, global, "njs", obj) < 0) { return -1; } @@ -469,14 +480,9 @@ qjs_njs_on(JSContext *ctx, JSValueConst this_val, int argc, njs_str("exit"), }; - njs = JS_GetOpaque(this_val, QJS_CORE_CLASS_ID_NJS); + njs = JS_GetOpaque2(ctx, this_val, QJS_CORE_CLASS_ID_NJS); if (njs == NULL) { - njs = js_mallocz(ctx, sizeof(qjs_njs_t)); - if (njs == NULL) { - return JS_ThrowOutOfMemory(ctx); - } - - JS_SetOpaque(this_val, njs); + return JS_EXCEPTION; } name.start = (u_char *) JS_ToCStringLen(ctx, &name.length, argv[0]); diff --git a/test/js/njs_on_receiver.t.js b/test/js/njs_on_receiver.t.js new file mode 100644 index 00000000..635afe94 --- /dev/null +++ b/test/js/njs_on_receiver.t.js @@ -0,0 +1,12 @@ +/*--- +includes: [] +flags: [] +---*/ + +if (typeof njs == 'object' && njs.engine == 'QuickJS') { + function f() { return 'f'; } + + assert.throws(TypeError, () => njs.on.call(f, 'exit', () => {})); + assert.throws(TypeError, () => njs.on.call({}, 'exit', () => {})); + assert.sameValue(f(), 'f'); +}