Skip to content

Commit b09d031

Browse files
committed
core: tweak runtime destruction sequence
Objects might need to be freed after the JS context is gone, so delay destroying the runtime until the very end. This is tricky, however, since it means bindings need to make sure not to use js_free but rather do js_free_rt when releasing resources late.
1 parent 8fbd438 commit b09d031

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

src/vm.c

+19-7
Original file line numberDiff line numberDiff line change
@@ -228,25 +228,28 @@ TJSRuntime *TJS_NewRuntimeInternal(bool is_worker, TJSRunOptions *options) {
228228
}
229229

230230
void TJS_FreeRuntime(TJSRuntime *qrt) {
231+
JS_FreeValue(qrt->ctx, JS_GetException(qrt->ctx));
232+
JS_FreeContext(qrt->ctx);
233+
qrt->ctx = NULL;
231234
JS_RunGC(qrt->rt);
232235

233-
/* Close all loop handles. */
236+
/* Close all core loop handles. */
234237
uv_close((uv_handle_t *) &qrt->jobs.prepare, NULL);
235238
uv_close((uv_handle_t *) &qrt->jobs.idle, NULL);
236239
uv_close((uv_handle_t *) &qrt->jobs.check, NULL);
237240
uv_close((uv_handle_t *) &qrt->stop, NULL);
238-
239-
JS_FreeContext(qrt->ctx);
240-
JS_FreeRuntime(qrt->rt);
241-
242-
/* Destroy CURLM handle. */
243241
if (qrt->curl_ctx.curlm_h) {
244-
curl_multi_cleanup(qrt->curl_ctx.curlm_h);
245242
uv_close((uv_handle_t *) &qrt->curl_ctx.timer, NULL);
246243
}
247244

248245
/* Destroy WASM runtime. */
249246
m3_FreeEnvironment(qrt->wasm_ctx.env);
247+
qrt->wasm_ctx.env = NULL;
248+
249+
/* Give close handles a chance to run. */
250+
for (int i = 0; i < 5; i++) {
251+
uv_run(&qrt->loop, UV_RUN_NOWAIT);
252+
}
250253

251254
uv_walk(&qrt->loop, uv__walk, NULL);
252255

@@ -267,6 +270,15 @@ void TJS_FreeRuntime(TJSRuntime *qrt) {
267270
(void)closed;
268271
#endif
269272

273+
/* Destroy CURLM handle. */
274+
if (qrt->curl_ctx.curlm_h) {
275+
curl_multi_cleanup(qrt->curl_ctx.curlm_h);
276+
qrt->curl_ctx.curlm_h = NULL;
277+
}
278+
279+
JS_FreeRuntime(qrt->rt);
280+
qrt->rt = NULL;
281+
270282
free(qrt);
271283
}
272284

0 commit comments

Comments
 (0)