]> git.kaiwu.me - njs.git/commitdiff
QuickJS: fix njs.on() with a foreign receiver
authorDmitry Volyntsev <xeioex@nginx.com>
Thu, 12 Nov 2026 01:33:52 +0000 (17:33 -0800)
committerDmitry Volyntsev <xeioexception@gmail.com>
Thu, 12 Nov 2026 22:29:31 +0000 (14:29 -0800)
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).

src/qjs.c
test/js/njs_on_receiver.t.js [new file with mode: 0644]

index c1c8c1d35c87f65b0773d7c6b1dcccb1e510299a..5220486b227e4feb2a1fd125925c9b64c4464adb 100644 (file)
--- 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 (file)
index 0000000..635afe9
--- /dev/null
@@ -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');
+}