SDL: main: Call SDL_AppQuit() if SDL_EVENT_TERMINATING fires.

https://github.com/libsdl-org/SDL/commit/b4c0634fefe59c5264e9c567e63eb9f3c55ad3a3

From b4c0634fefe59c5264e9c567e63eb9f3c55ad3a3 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Wed, 7 Oct 2026 16:12:03 -0400
Subject: [PATCH] main: Call SDL_AppQuit() if SDL_EVENT_TERMINATING fires.

We had logic to do this, but due to the nature of iOS, we never actually
called it because the process terminated before we could. This was likely
true on Android, HarmonyOS, and Emscripten, too, so this adds a new interface
that various platforms can use as appropriate when the event fires.

The generic implementation just attempts to set apprc to success, which will
result in normal process termination, including calling SDL_AppQuit(), which
matched current behavior, but to be fair, all the platforms that use the
generic backend shouldn't ever fire this event.

When calling SDL_AppQuit() due to SDL_EVENT_TERMINATING, the other backends
leave the SDL_AppResult as SDL_APP_CONTINUE (assuming SDL_AppEvent() didn't
respond to SDL_EVENT_TERMINATING by returning a terminating result), so that
SDL_AppQuit() has a signal that they have arrived at termination in an unusual
way, instead of the app explicitly requesting it.

Fixes #16457.
---
 include/SDL3/SDL_main.h                      | 12 ++++++--
 src/core/openharmony/SDL_openharmony.c       |  2 ++
 src/main/SDL_main_callbacks.c                |  2 +-
 src/main/SDL_main_callbacks.h                |  3 ++
 src/main/emscripten/SDL_sysmain_callbacks.c  |  8 ++++++
 src/main/generic/SDL_sysmain_callbacks.c     |  6 ++++
 src/main/ios/SDL_sysmain_callbacks.m         | 29 +++++++++++++++-----
 src/main/ngage/SDL_sysmain_callbacks.c       |  7 +++++
 src/main/openharmony/SDL_sysmain_callbacks.c |  7 +++++
 src/video/android/SDL_androidevents.c        |  2 +-
 src/video/emscripten/SDL_emscriptenevents.c  |  4 +--
 11 files changed, 69 insertions(+), 13 deletions(-)

diff --git a/include/SDL3/SDL_main.h b/include/SDL3/SDL_main.h
index baccece0e8d2f..46fae84559ef1 100644
--- a/include/SDL3/SDL_main.h
+++ b/include/SDL3/SDL_main.h
@@ -478,8 +478,9 @@ extern SDLMAIN_DECLSPEC SDL_AppResult SDLCALL SDL_AppEvent(void *appstate, SDL_E
  *
  * This function is called once by SDL before terminating the program.
  *
- * This function will be called in all cases, even if SDL_AppInit requests
- * termination at startup.
+ * This function will be called in all normal cases, even if SDL_AppInit
+ * requests termination at startup. This function will not be called for
+ * abnormal process termination, such as a segfault or other crash.
  *
  * This function should not go into an infinite mainloop; it should
  * deinitialize any resources necessary, perform whatever shutdown activities,
@@ -496,6 +497,13 @@ extern SDLMAIN_DECLSPEC SDL_AppResult SDLCALL SDL_AppEvent(void *appstate, SDL_E
  *
  * This function is called by SDL on the main thread.
  *
+ * Note that as of SDL 3.6.0, on mobile platforms, this function will be
+ * called if the system is terminating the app mid-run. In this case, `result`
+ * will be set to SDL_APP_CONTINUE to signify that this was not the app
+ * requesting termination due to either a successful or failed run. This
+ * operates as an alternative to registering an event watcher to monitor for
+ * SDL_EVENT_TERMINATING, if the app is using the main callbacks anyway.
+ *
  * \param appstate an optional pointer, provided by the app in SDL_AppInit.
  * \param result the result code that terminated the app (success or failure).
  *
diff --git a/src/core/openharmony/SDL_openharmony.c b/src/core/openharmony/SDL_openharmony.c
index a8b6872c45d97..40b965986d1bf 100644
--- a/src/core/openharmony/SDL_openharmony.c
+++ b/src/core/openharmony/SDL_openharmony.c
@@ -936,6 +936,8 @@ static napi_value SDL_JS_UIAbility_OnDestroy(napi_env env, napi_callback_info in
     SDL_SendQuit();
     SDL_OnApplicationWillTerminate();
 
+    // !!! FIXME: clean this stuff up elsewhere (and maybe clean up more of it).
+    // !!! FIXME: alternately: Clean up _none_ of it because the process is about to go away anyhow.
     if (commonevent_subscriber) {
         OH_CommonEvent_UnSubscribe(commonevent_subscriber);
         OH_CommonEvent_DestroySubscriber(commonevent_subscriber);
diff --git a/src/main/SDL_main_callbacks.c b/src/main/SDL_main_callbacks.c
index 3b4a20683145b..b35da269cdcc1 100644
--- a/src/main/SDL_main_callbacks.c
+++ b/src/main/SDL_main_callbacks.c
@@ -78,7 +78,7 @@ static bool SDLCALL SDL_MainCallbackEventWatcher(void *userdata, SDL_Event *even
 
         // Make sure that we quit if we get a terminating event
         if (event->type == SDL_EVENT_TERMINATING) {
-            SDL_CompareAndSwapAtomicInt(&apprc, SDL_APP_CONTINUE, SDL_APP_SUCCESS);
+            SDL_MainCallbacksSawEventTerminating(&apprc);
         }
     } else {
         // We'll process this event later from the main event queue
diff --git a/src/main/SDL_main_callbacks.h b/src/main/SDL_main_callbacks.h
index 3a8c30acb75fc..7ce497d4e4b9f 100644
--- a/src/main/SDL_main_callbacks.h
+++ b/src/main/SDL_main_callbacks.h
@@ -27,6 +27,9 @@ SDL_AppResult SDL_InitMainCallbacks(int argc, char *argv[], SDL_AppInit_func app
 SDL_AppResult SDL_IterateMainCallbacks(bool pump_events);
 void SDL_QuitMainCallbacks(SDL_AppResult result);
 
+// This lets some platforms do platform-specific magic in response to SDL_EVENT_TERMINATING. Can change current AppResult if necessary, or maybe terminate the process without returning.
+void SDL_MainCallbacksSawEventTerminating(SDL_AtomicInt *apprc);
+
 // Check args and call the main function
 extern int SDL_CallMainFunction(int argc, char *argv[], SDL_main_func mainFunction);
 
diff --git a/src/main/emscripten/SDL_sysmain_callbacks.c b/src/main/emscripten/SDL_sysmain_callbacks.c
index 138c6ed6d1f84..6a00d41476d51 100644
--- a/src/main/emscripten/SDL_sysmain_callbacks.c
+++ b/src/main/emscripten/SDL_sysmain_callbacks.c
@@ -24,6 +24,14 @@
 
 #include <emscripten.h>
 
+void SDL_MainCallbacksSawEventTerminating(SDL_AtomicInt *apprc)
+{
+    // We leave `result` alone, so if SDL_AppEvent didn't set something else, SDL_APP_CONTINUE will signify the app is terminating in an unexpected way during SDL_AppQuit.
+    const SDL_AppResult result = (SDL_AppResult) SDL_GetAtomicInt(apprc);
+    SDL_QuitMainCallbacks(result);  // we need to call this directly because we won't be returning to where this would be called later.
+}
+
+
 // For Emscripten, we let you use SDL_HINT_MAIN_CALLBACK_RATE, because it might be useful to drop it super-low for
 //  things like loopwave that don't really do much but wait on the audio device, but be warned that browser timers
 //  are super-unreliable in modern times, so you likely won't hit your desired callback rate with good precision.
diff --git a/src/main/generic/SDL_sysmain_callbacks.c b/src/main/generic/SDL_sysmain_callbacks.c
index 3ac645411de12..292450c55675f 100644
--- a/src/main/generic/SDL_sysmain_callbacks.c
+++ b/src/main/generic/SDL_sysmain_callbacks.c
@@ -46,6 +46,12 @@ static void SDLCALL MainCallbackRateHintChanged(void *userdata, const char *name
     }
 }
 
+void SDL_MainCallbacksSawEventTerminating(SDL_AtomicInt *apprc)
+{
+    // if the app hasn't explicit set a termination result, call it a success and be done with it.
+    SDL_CompareAndSwapAtomicInt(apprc, SDL_APP_CONTINUE, SDL_APP_SUCCESS);
+}
+
 static SDL_AppResult GenericIterateMainCallbacks(void)
 {
     bool should_wait = iterate_after_waitevent;
diff --git a/src/main/ios/SDL_sysmain_callbacks.m b/src/main/ios/SDL_sysmain_callbacks.m
index 544f0d6d09767..a9a0ad0ab0bff 100644
--- a/src/main/ios/SDL_sysmain_callbacks.m
+++ b/src/main/ios/SDL_sysmain_callbacks.m
@@ -28,6 +28,7 @@
 
 #include "../../video/uikit/SDL_uikitevents.h"  // For SDL_UpdateLifecycleObserver()
 
+static void CleanupApp(SDL_AppResult result);
 
 @interface SDLIosMainCallbacksDisplayLink : NSObject
 @property(nonatomic, retain) CADisplayLink *displayLink;
@@ -61,18 +62,32 @@ - (instancetype)init:(SDL_AppIterate_func)_appiter quitfunc:(SDL_AppQuit_func)_a
 
 - (void)appIteration:(CADisplayLink *)sender
 {
-    const SDL_AppResult rc = SDL_IterateMainCallbacks(true);
-    if (rc != SDL_APP_CONTINUE) {
-        [self.displayLink invalidate];
-        self.displayLink = nil;
-        globalDisplayLink = nil;
-        SDL_QuitMainCallbacks(rc);
+    const SDL_AppResult result = SDL_IterateMainCallbacks(true);
+    if (result != SDL_APP_CONTINUE) {
+        CleanupApp(result);
         SDL_UpdateLifecycleObserver();
-        exit((rc == SDL_APP_FAILURE) ? 1 : 0);
+        exit((result == SDL_APP_FAILURE) ? 1 : 0);
     }
 }
 @end
 
+static void CleanupApp(SDL_AppResult result)
+{
+    if (globalDisplayLink != nil) {
+        [globalDisplayLink.displayLink invalidate];
+        globalDisplayLink.displayLink = nil;
+        globalDisplayLink = nil;
+    }
+    SDL_QuitMainCallbacks(result);  // we need to call this directly because we won't be returning from here.
+}
+
+void SDL_MainCallbacksSawEventTerminating(SDL_AtomicInt *apprc)
+{
+    // We leave `result` alone, so if SDL_AppEvent didn't set something else, SDL_APP_CONTINUE will signify the app is terminating in an unexpected way during SDL_AppQuit.
+    const SDL_AppResult result = (SDL_AppResult) SDL_GetAtomicInt(apprc);
+    CleanupApp(result);
+}
+
 // SDL_RunApp will land in UIApplicationMain, which calls SDL_main from postFinishLaunch, which calls this.
 // When we return from here, we're living in the RunLoop, and a CADisplayLink is firing regularly for us.
 int SDL_EnterAppMainCallbacks(int argc, char *argv[], SDL_AppInit_func appinit, SDL_AppIterate_func appiter, SDL_AppEvent_func appevent, SDL_AppQuit_func appquit)
diff --git a/src/main/ngage/SDL_sysmain_callbacks.c b/src/main/ngage/SDL_sysmain_callbacks.c
index be17256ab4406..314e9f6fdb3c6 100644
--- a/src/main/ngage/SDL_sysmain_callbacks.c
+++ b/src/main/ngage/SDL_sysmain_callbacks.c
@@ -22,6 +22,13 @@
 
 #ifdef SDL_PLATFORM_NGAGE
 
+void SDL_MainCallbacksSawEventTerminating(SDL_AtomicInt *apprc)
+{
+    // (this does the same thing as the generic implementation because ngage has its own EnterAppMainCallbacks. But ngage doesn't send SDL_EVENT_TERMINATING afaik.)
+    // if the app hasn't explicit set a termination result, call it a success and be done with it.
+    SDL_CompareAndSwapAtomicInt(apprc, SDL_APP_CONTINUE, SDL_APP_SUCCESS);
+}
+
 int SDL_EnterAppMainCallbacks(int argc, char *argv[], SDL_AppInit_func appinit, SDL_AppIterate_func appiter, SDL_AppEvent_func appevent, SDL_AppQuit_func appquit)
 {
     // Intentionally does nothing; Callbacks are called using the RunL() method.
diff --git a/src/main/openharmony/SDL_sysmain_callbacks.c b/src/main/openharmony/SDL_sysmain_callbacks.c
index 520ab5143f06d..422bdb5f99afa 100644
--- a/src/main/openharmony/SDL_sysmain_callbacks.c
+++ b/src/main/openharmony/SDL_sysmain_callbacks.c
@@ -25,6 +25,13 @@
 
 #include "../SDL_main_callbacks.h"
 
+void SDL_MainCallbacksSawEventTerminating(SDL_AtomicInt *apprc)
+{
+    // We leave `result` alone, so if SDL_AppEvent didn't set something else, SDL_APP_CONTINUE will signify the app is terminating in an unexpected way during SDL_AppQuit.
+    const SDL_AppResult result = (SDL_AppResult) SDL_GetAtomicInt(apprc);
+    SDL_QuitMainCallbacks(result);  // we need to call this directly because we won't be returning from here.
+}
+
 void SDL_OpenHarmonyOnFrameCallback(void)   // src/core/openharmony calls this when our XComponent is ready for a new frame, and we call SDL_AppIterate here
 {
     if (SDL_HasMainCallbacks()) {  // ignore this if we're using SDL_main().
diff --git a/src/video/android/SDL_androidevents.c b/src/video/android/SDL_androidevents.c
index f65d7cad11680..8918d3b4072f8 100644
--- a/src/video/android/SDL_androidevents.c
+++ b/src/video/android/SDL_androidevents.c
@@ -171,7 +171,7 @@ static void Android_OnDestroy(void)
      * events other than SDL_EVENT_QUIT and SDL_EVENT_TERMINATING should fire */
     SDL_FlushEvents(SDL_EVENT_FIRST, SDL_EVENT_LAST);
     SDL_SendQuit();
-    SDL_SendAppEvent(SDL_EVENT_TERMINATING);
+    SDL_OnApplicationWillTerminate();
 
     Android_Destroyed = true;
 }
diff --git a/src/video/emscripten/SDL_emscriptenevents.c b/src/video/emscripten/SDL_emscriptenevents.c
index 2c2d920424884..1d1f910e7ee2c 100644
--- a/src/video/emscripten/SDL_emscriptenevents.c
+++ b/src/video/emscripten/SDL_emscriptenevents.c
@@ -604,8 +604,8 @@ static const char *Emscripten_HandleBeforeUnload(int eventType, const void *rese
 {
     /* This event will need to be handled synchronously, e.g. using
        SDL_AddEventWatch, as the page is being closed *now*. */
-    // No need to send a SDL_EVENT_QUIT, the app won't get control again.
-    SDL_SendAppEvent(SDL_EVENT_TERMINATING);
+    SDL_SendQuit();  // the app might see this if they installed an event watcher.
+    SDL_OnApplicationWillTerminate();  // calls SDL_AppQuit if appropriate, etc.
     return ""; // don't trigger confirmation dialog
 }