From 8fe039156b427bb212e3885d688e362e56e4fdb6 Mon Sep 17 00:00:00 2001 From: Laurent Demailly Date: Sat, 20 Jul 2024 15:29:52 -0700 Subject: [PATCH] fix: Avoid total failure on wasm finalizer call --- targets/wasm_exec.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/targets/wasm_exec.js b/targets/wasm_exec.js index defc73ba8..e30f3256f 100644 --- a/targets/wasm_exec.js +++ b/targets/wasm_exec.js @@ -303,9 +303,22 @@ // func finalizeRef(v ref) "syscall/js.finalizeRef": (v_ref) => { - // Note: TinyGo does not support finalizers so this should never be - // called. - console.error('syscall/js.finalizeRef not implemented'); + // Note: TinyGo does not support finalizers so this is only called + // for one specific case, by js.go:jsString. and can/might leak memory. + const id = mem().getUint32(unboxValue(v_ref), true); + // Note that this if is so far seemingly never true. Someone should investigate why. + if (this._goRefCounts?.[id] !== undefined) { + this._goRefCounts[id]--; + if (this._goRefCounts[id] === 0) { + const v = this._values[id]; + this._values[id] = null; + this._ids.delete(v); + this._idPool.push(id); + } + } else { + // Log as a hint and reminder that something is probably off. + console.log("syscall/js.finalizeRef: unknown id", id); + } }, // func stringVal(value string) ref