SDL: Lock joysticks when they are connected/disconnected on emscripten

From 028107124358a3d256c8c3acf4e4db6f20e4c348 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Wed, 1 Jan 2025 13:51:47 -0800
Subject: [PATCH] Lock joysticks when they are connected/disconnected on
 emscripten

Fixes https://github.com/libsdl-org/SDL/issues/11499
---
 src/joystick/emscripten/SDL_sysjoystick.c | 22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)

diff --git a/src/joystick/emscripten/SDL_sysjoystick.c b/src/joystick/emscripten/SDL_sysjoystick.c
index 12081e751dc01..b481d5da7304c 100644
--- a/src/joystick/emscripten/SDL_sysjoystick.c
+++ b/src/joystick/emscripten/SDL_sysjoystick.c
@@ -36,17 +36,18 @@ static int numjoysticks = 0;
 
 static EM_BOOL Emscripten_JoyStickConnected(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData)
 {
+    SDL_joylist_item *item;
     int i;
 
-    SDL_joylist_item *item;
+    SDL_LockJoysticks();
 
     if (JoystickByIndex(gamepadEvent->index) != NULL) {
-        return 1;
+        goto done;
     }
 
     item = (SDL_joylist_item *)SDL_malloc(sizeof(SDL_joylist_item));
     if (!item) {
-        return 1;
+        goto done;
     }
 
     SDL_zerop(item);
@@ -55,14 +56,14 @@ static EM_BOOL Emscripten_JoyStickConnected(int eventType, const EmscriptenGamep
     item->name = SDL_CreateJoystickName(0, 0, NULL, gamepadEvent->id);
     if (!item->name) {
         SDL_free(item);
-        return 1;
+        goto done;
     }
 
     item->mapping = SDL_strdup(gamepadEvent->mapping);
     if (!item->mapping) {
         SDL_free(item->name);
         SDL_free(item);
-        return 1;
+        goto done;
     }
 
     item->naxes = gamepadEvent->numAxes;
@@ -98,6 +99,9 @@ static EM_BOOL Emscripten_JoyStickConnected(int eventType, const EmscriptenGamep
     SDL_Log("Added joystick with index %d", item->index);
 #endif
 
+done:
+    SDL_UnlockJoysticks();
+
     return 1;
 }
 
@@ -106,6 +110,8 @@ static EM_BOOL Emscripten_JoyStickDisconnected(int eventType, const EmscriptenGa
     SDL_joylist_item *item = SDL_joylist;
     SDL_joylist_item *prev = NULL;
 
+    SDL_LockJoysticks();
+
     while (item) {
         if (item->index == gamepadEvent->index) {
             break;
@@ -115,7 +121,7 @@ static EM_BOOL Emscripten_JoyStickDisconnected(int eventType, const EmscriptenGa
     }
 
     if (!item) {
-        return 1;
+        goto done;
     }
 
     if (item->joystick) {
@@ -143,6 +149,10 @@ static EM_BOOL Emscripten_JoyStickDisconnected(int eventType, const EmscriptenGa
     SDL_free(item->name);
     SDL_free(item->mapping);
     SDL_free(item);
+
+done:
+    SDL_UnlockJoysticks();
+
     return 1;
 }