From 7ffb4d6407d43bbae7c04323fba79d38290c36d0 Mon Sep 17 00:00:00 2001 From: bptato Date: Sat, 9 Sep 2023 13:33:39 +0200 Subject: javascript: fix a GC bug GC_unref may indirectly call nim_finalize_for_js, which could mess up execution of checkDestroy. I haven't encountered it in refc, but it's definitely present in orc. --- src/js/javascript.nim | 27 ++++++++++++++++++++++----- src/js/opaque.nim | 1 + 2 files changed, 23 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/js/javascript.nim b/src/js/javascript.nim index 8031c288..036f4628 100644 --- a/src/js/javascript.nim +++ b/src/js/javascript.nim @@ -1148,7 +1148,11 @@ proc nim_finalize_for_js*(obj: pointer) = fin[](val) JS_SetOpaque(val, nil) rtOpaque.plist.del(obj) - JS_FreeValueRT(rt, val) + if rtOpaque.destroying == obj: + # Allow QJS to collect the JSValue through checkDestroy. + rtOpaque.destroying = nil + else: + JS_FreeValueRT(rt, val) type TabGetSet* = object @@ -1385,11 +1389,24 @@ proc bindCheckDestroy(stmts: NimNode, info: RegistryInfo) = # refcount reaches zero. Then, the JS object's opaque will be set # to nil, and its refcount decreased again, so next time this # function will return true. + # + # Actually, we need another hack to ensure correct + # operation. GC_unref may call the destructor of this object, and + # in this case we cannot ask QJS to keep the JSValue alive. So we set + # the "destroying" pointer to the current opaque, and return true if + # the opaque was collected. + rt.getOpaque().destroying = opaque GC_unref(cast[`t`](opaque)) - # Returning false from this function signals to the QJS GC that it - # should not be collected yet. Accordingly, the JSObject's refcount - # will be set to one again. - return false + if rt.getOpaque().destroying == nil: + # Looks like GC_unref called nim_finalize_for_js for this pointer. + # This means we can allow QJS to collect this JSValue. + return true + else: + rt.getOpaque().destroying = nil + # Returning false from this function signals to the QJS GC that it + # should not be collected yet. Accordingly, the JSObject's refcount + # will be set to one again. + return false else: # This is not a reference, just a pointer with a reference to the # root ancestor object. diff --git a/src/js/opaque.nim b/src/js/opaque.nim index f132db24..f8eb7c77 100644 --- a/src/js/opaque.nim +++ b/src/js/opaque.nim @@ -36,6 +36,7 @@ type flist*: seq[seq[JSCFunctionListEntry]] fins*: Table[JSClassID, proc(val: JSValue)] refmap*: Table[pointer, tuple[cref, cunref: (proc() {.closure.})]] + destroying*: pointer func newJSContextOpaque*(ctx: JSContext): JSContextOpaque = let opaque = JSContextOpaque() -- cgit