Skip to content

Commit

Permalink
core: tweak runtime destruction sequence
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
saghul committed Feb 29, 2024
1 parent edf4329 commit a87f0df
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/vm.c
Original file line number Diff line number Diff line change
Expand Up @@ -228,25 +228,28 @@ TJSRuntime *TJS_NewRuntimeInternal(bool is_worker, TJSRunOptions *options) {
}

void TJS_FreeRuntime(TJSRuntime *qrt) {
JS_FreeValue(qrt->ctx, JS_GetException(qrt->ctx));
JS_FreeContext(qrt->ctx);
qrt->ctx = NULL;
JS_RunGC(qrt->rt);

/* Close all loop handles. */
/* Close all core loop handles. */
uv_close((uv_handle_t *) &qrt->jobs.prepare, NULL);
uv_close((uv_handle_t *) &qrt->jobs.idle, NULL);
uv_close((uv_handle_t *) &qrt->jobs.check, NULL);
uv_close((uv_handle_t *) &qrt->stop, NULL);

JS_FreeContext(qrt->ctx);
JS_FreeRuntime(qrt->rt);

/* Destroy CURLM handle. */
if (qrt->curl_ctx.curlm_h) {
curl_multi_cleanup(qrt->curl_ctx.curlm_h);
uv_close((uv_handle_t *) &qrt->curl_ctx.timer, NULL);
}

/* Destroy WASM runtime. */
m3_FreeEnvironment(qrt->wasm_ctx.env);
qrt->wasm_ctx.env = NULL;

/* Give close handles a chance to run. */
for (int i = 0; i < 5; i++) {
uv_run(&qrt->loop, UV_RUN_NOWAIT);
}

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

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

/* Destroy CURLM handle. */
if (qrt->curl_ctx.curlm_h) {
curl_multi_cleanup(qrt->curl_ctx.curlm_h);
qrt->curl_ctx.curlm_h = NULL;
}

JS_FreeRuntime(qrt->rt);
qrt->rt = NULL;

free(qrt);
}

Expand Down

0 comments on commit a87f0df

Please sign in to comment.