aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorbptato <nincsnevem662@gmail.com>2024-06-03 20:28:29 +0200
committerbptato <nincsnevem662@gmail.com>2024-06-03 20:28:29 +0200
commitdfb03387691e72f8832734255765ddfdd38db372 (patch)
tree31f2c489859aa8bd7d7bc2b3b1854f11708b45f2 /lib
parent34b0abd1a5811afa88b16442c0dc327881456d8f (diff)
downloadchawan-dfb03387691e72f8832734255765ddfdd38db372.tar.gz
js: fix runtime cleanup
This is a minefield. Intuitively, you would think that just clearing the opaque and manually freeing registered object should be enough. Unfortunately, this is not true; we do not store whether we are actually holding a reference to registered JS objects, so this approach leads to double frees. Instead, we add a QJS callback that is called right after the final GC cleanup, but before the list_free assertion. This way, we can be sure that any object still in our registry is referenced by us, and can therefore unreference them safely.
Diffstat (limited to 'lib')
-rw-r--r--lib/quickjs/quickjs.c8
-rw-r--r--lib/quickjs/quickjs.h3
2 files changed, 11 insertions, 0 deletions
diff --git a/lib/quickjs/quickjs.c b/lib/quickjs/quickjs.c
index af7ea852..427b36df 100644
--- a/lib/quickjs/quickjs.c
+++ b/lib/quickjs/quickjs.c
@@ -306,6 +306,7 @@ struct JSRuntime {
uint32_t operator_count;
#endif
void *user_opaque;
+ JSRuntimeCleanUpFunc *user_cleanup;
};
struct JSClass {
@@ -1703,6 +1704,11 @@ void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque)
rt->user_opaque = opaque;
}
+void JS_SetRuntimeCleanUpFunc(JSRuntime *rt, JSRuntimeCleanUpFunc cleanup_func)
+{
+ rt->user_cleanup = cleanup_func;
+}
+
/* default memory allocation functions with memory limitation */
static size_t js_def_malloc_usable_size(const void *ptr)
{
@@ -1960,6 +1966,8 @@ void JS_FreeRuntime(JSRuntime *rt)
JS_RunGC(rt);
+ rt->user_cleanup(rt);
+
#ifdef DUMP_LEAKS
/* leaking objects */
{
diff --git a/lib/quickjs/quickjs.h b/lib/quickjs/quickjs.h
index 8c81be47..366f341b 100644
--- a/lib/quickjs/quickjs.h
+++ b/lib/quickjs/quickjs.h
@@ -331,6 +331,8 @@ typedef struct JSMallocFunctions {
typedef struct JSGCObjectHeader JSGCObjectHeader;
+typedef void JSRuntimeCleanUpFunc(JSRuntime *rt);
+
JSRuntime *JS_NewRuntime(void);
/* info lifetime must exceed that of rt */
void JS_SetRuntimeInfo(JSRuntime *rt, const char *info);
@@ -345,6 +347,7 @@ JSRuntime *JS_NewRuntime2(const JSMallocFunctions *mf, void *opaque);
void JS_FreeRuntime(JSRuntime *rt);
void *JS_GetRuntimeOpaque(JSRuntime *rt);
void JS_SetRuntimeOpaque(JSRuntime *rt, void *opaque);
+void JS_SetRuntimeCleanUpFunc(JSRuntime *rt, JSRuntimeCleanUpFunc cleanup_func);
typedef void JS_MarkFunc(JSRuntime *rt, JSGCObjectHeader *gp);
void JS_MarkValue(JSRuntime *rt, JSValueConst val, JS_MarkFunc *mark_func);
void JS_RunGC(JSRuntime *rt);