From affce7f65229a617c816d6674c1f347effaab920 Mon Sep 17 00:00:00 2001
From: "Rob Swindell (on Windows 11)" <rob@synchro.net>
Date: Fri, 8 Dec 2023 17:32:56 -0800
Subject: [PATCH] Only create/use a single run-time for use in JSexec, even
 when re-runnning

The '-l' (loop) option would cause the JS runtime to be destroyed and
recreated for each new execution of the script, which resulted in memory
leaks in Windows builds (see issue #672 for details). So instead, just
use a single JS runtime here when the -l option is used to prevent that
from happening, though truth be told, that's likely not a normal/common
occurrence. Other apparent JS-related memory leaks (e.g. in the web
server) appear to be of a common concern.

Likely upgrading to a modern libmozjs would also fix this issue, but
we're far short of being able to do that right now.
---
 src/sbbs3/jsexec.c | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/src/sbbs3/jsexec.c b/src/sbbs3/jsexec.c
index 00087df6e0..8153b89773 100644
--- a/src/sbbs3/jsexec.c
+++ b/src/sbbs3/jsexec.c
@@ -844,14 +844,6 @@ static BOOL js_init(char** env)
 	memset(&startup,0,sizeof(startup));
 	SAFECOPY(startup.load_path, load_path_list);
 
-	fprintf(statfp,"%s\n",(char *)JS_GetImplementationVersion());
-
-	fprintf(statfp,"JavaScript: Creating runtime: %lu bytes\n"
-		,js_max_bytes);
-
-	if((js_runtime = jsrt_GetNew(js_max_bytes, 5000, __FILE__, __LINE__))==NULL)
-		return(FALSE);
-
     if((js_cx = JS_NewContext(js_runtime, JAVASCRIPT_CONTEXT_STACK))==NULL)
 		return(FALSE);
 	JS_SetOptions(js_cx, js_opts);
@@ -1520,6 +1512,15 @@ int main(int argc, char **argv, char** env)
 
 	setup_debugger();
 
+	fprintf(statfp,"%s\n",(char *)JS_GetImplementationVersion());
+
+	fprintf(statfp,"JavaScript: Creating runtime: %lu bytes\n"
+		,js_max_bytes);
+
+	if((js_runtime = jsrt_GetNew(js_max_bytes, 5000, __FILE__, __LINE__)) == NULL) {
+		lprintf(LOG_ERR,"!JavaScript runtime creation failure");
+		return do_bail(1);
+	}
 	do {
 
 		if(exec_count++)
@@ -1544,11 +1545,12 @@ int main(int argc, char **argv, char** env)
 		fprintf(statfp,"\n");
 		fprintf(statfp,"JavaScript: Destroying context\n");
 		JS_DestroyContext(js_cx);
-		fprintf(statfp,"JavaScript: Destroying runtime\n");
-		jsrt_Release(js_runtime);
 
 	} while((recycled || loop) && !terminated);
 
+	fprintf(statfp,"JavaScript: Destroying runtime\n");
+	jsrt_Release(js_runtime);
+
 	iniFreeStringList(ini);
 	return(do_bail(result));
 }
-- 
GitLab