SDL: Make sure we don't allocate a TLS ID clobbering an application defined one (add17)

From add176e5381b9d9fd5c2a8bf9ba0c86df0ef963a Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Wed, 29 Oct 2025 14:04:52 -0700
Subject: [PATCH] Make sure we don't allocate a TLS ID clobbering an
 application defined one

Fixes https://github.com/libsdl-org/SDL/issues/14359

(cherry picked from commit d9ca0457b5c9f819c3af5f156880219c8d41da40)
---
 src/thread/SDL_thread.c | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/src/thread/SDL_thread.c b/src/thread/SDL_thread.c
index d9180f5267b4d..f31e670b9d475 100644
--- a/src/thread/SDL_thread.c
+++ b/src/thread/SDL_thread.c
@@ -80,6 +80,15 @@ bool SDL_SetTLS(SDL_TLSID *id, const void *value, SDL_TLSDestructorCallback dest
          * will have the same storage index for this id.
          */
         storage_index = SDL_GetAtomicInt(id) - 1;
+    } else {
+        // Make sure we don't allocate an ID clobbering this one
+        int tls_id = SDL_GetAtomicInt(&SDL_tls_id);
+        while (storage_index >= tls_id) {
+            if (SDL_CompareAndSwapAtomicInt(&SDL_tls_id, tls_id, storage_index + 1)) {
+                break;
+            }
+            tls_id = SDL_GetAtomicInt(&SDL_tls_id);
+        }
     }
 
     // Get the storage for the current thread