From 2a5375b1e7fc78372b3cc29a0538acffc3e10a92 Mon Sep 17 00:00:00 2001
From: Cory McWilliams <cory@unprompted.com>
Date: Sun, 20 Apr 2025 18:26:44 -0400
Subject: [PATCH] core: Don't start new tasks as we're shutting down. #108

---
 src/task.c        | 8 ++++++++
 src/task.h        | 7 +++++++
 src/taskstub.js.c | 5 +++++
 3 files changed, 20 insertions(+)

diff --git a/src/task.c b/src/task.c
index 14e05edf..5b70a11b 100644
--- a/src/task.c
+++ b/src/task.c
@@ -119,6 +119,7 @@ typedef struct _tf_task_t
 	bool _trusted;
 	bool _one_proc;
 	bool _killed;
+	bool _shutting_down;
 	char _scriptName[256];
 	int _global_exception_count;
 
@@ -1818,6 +1819,8 @@ JSValue tf_taskstub_kill(tf_taskstub_t* stub);
 
 void tf_task_destroy(tf_task_t* task)
 {
+	task->_shutting_down = true;
+
 	while (task->_children)
 	{
 		for (task_child_node_t* node = task->_children; node; node = node->next)
@@ -2162,6 +2165,11 @@ void tf_task_set_android_service_callbacks(tf_android_start_service_t* start_ser
 	s_android_stop_service = stop_service;
 }
 
+bool tf_task_is_shutting_down(tf_task_t* task)
+{
+	return task && task->_shutting_down;
+}
+
 tf_android_start_service_t* tf_task_get_android_start_service()
 {
 	return s_android_start_service;
diff --git a/src/task.h b/src/task.h
index 3623f8e7..f0b225b9 100644
--- a/src/task.h
+++ b/src/task.h
@@ -364,4 +364,11 @@ tf_android_stop_service_t* tf_task_get_android_stop_service();
 */
 void tf_task_check_jobs(tf_task_t* task);
 
+/**
+** Check whether tf_task_destroy has been called already.
+** @param task The task.
+** @return true if the task is in the process of shutting down.
+*/
+bool tf_task_is_shutting_down(tf_task_t* task);
+
 /** @} */
diff --git a/src/taskstub.js.c b/src/taskstub.js.c
index 5df8a8ff..ab199c81 100644
--- a/src/taskstub.js.c
+++ b/src/taskstub.js.c
@@ -125,6 +125,11 @@ static void _tf_taskstub_packetstream_close(void* user_data)
 static JSValue _taskstub_create(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
 {
 	tf_task_t* parent = tf_task_get(context);
+	if (parent && tf_task_is_shutting_down(parent))
+	{
+		return JS_UNDEFINED;
+	}
+
 	tf_taskstub_t* stub = tf_malloc(sizeof(tf_taskstub_t));
 	memset(stub, 0, sizeof(*stub));
 	stub->_stream = tf_packetstream_create();