aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2023-09-09 13:33:39 +0200
committerbptato <nincsnevem662@gmail.com>2023-09-09 13:37:11 +0200
commit7ffb4d6407d43bbae7c04323fba79d38290c36d0 (patch)
treee7853779750a8dbad1858a93f64cf125bd35ad85 /src
parenta4ae0ae16f8f3fbe706e9a4ac23557a4fe790c4b (diff)
downloadchawan-7ffb4d6407d43bbae7c04323fba79d38290c36d0.tar.gz
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.
Diffstat (limited to 'src')
-rw-r--r--src/js/javascript.nim27
-rw-r--r--src/js/opaque.nim1
2 files changed, 23 insertions, 5 deletions
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()