SDL: Fixed crash if joystick functions are passed a NULL joystick

From 0dfdf1f3f2a1f62e579527ef3abe63543af7e6da Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Wed, 27 Dec 2023 11:25:54 -0800
Subject: [PATCH] Fixed crash if joystick functions are passed a NULL joystick

---
 src/joystick/SDL_joystick.c | 46 +++++++++++++++++++++++--------------
 1 file changed, 29 insertions(+), 17 deletions(-)

diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c
index 1948c3a94228..5e21dd95d8dd 100644
--- a/src/joystick/SDL_joystick.c
+++ b/src/joystick/SDL_joystick.c
@@ -1521,13 +1521,17 @@ const char *SDL_GetJoystickName(SDL_Joystick *joystick)
     const SDL_SteamVirtualGamepadInfo *info;
 
     SDL_LockJoysticks();
-    info = SDL_GetJoystickInstanceVirtualGamepadInfo(joystick->instance_id);
-    if (info) {
-        retval = info->name;
-    } else {
+    {
         CHECK_JOYSTICK_MAGIC(joystick, NULL);
 
-        retval = joystick->name;
+        info = SDL_GetJoystickInstanceVirtualGamepadInfo(joystick->instance_id);
+        if (info) {
+            retval = info->name;
+        } else {
+            CHECK_JOYSTICK_MAGIC(joystick, NULL);
+
+            retval = joystick->name;
+        }
     }
     SDL_UnlockJoysticks();
 
@@ -3247,13 +3251,17 @@ Uint16 SDL_GetJoystickVendor(SDL_Joystick *joystick)
     const SDL_SteamVirtualGamepadInfo *info;
 
     SDL_LockJoysticks();
-    info = SDL_GetJoystickInstanceVirtualGamepadInfo(joystick->instance_id);
-    if (info) {
-        vendor = info->vendor_id;
-    } else {
-        SDL_JoystickGUID guid = SDL_GetJoystickGUID(joystick);
+    {
+        CHECK_JOYSTICK_MAGIC(joystick, 0);
 
-        SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL, NULL);
+        info = SDL_GetJoystickInstanceVirtualGamepadInfo(joystick->instance_id);
+        if (info) {
+            vendor = info->vendor_id;
+        } else {
+            SDL_JoystickGUID guid = SDL_GetJoystickGUID(joystick);
+
+            SDL_GetJoystickGUIDInfo(guid, &vendor, NULL, NULL, NULL);
+        }
     }
     SDL_UnlockJoysticks();
 
@@ -3266,13 +3274,17 @@ Uint16 SDL_GetJoystickProduct(SDL_Joystick *joystick)
     const SDL_SteamVirtualGamepadInfo *info;
 
     SDL_LockJoysticks();
-    info = SDL_GetJoystickInstanceVirtualGamepadInfo(joystick->instance_id);
-    if (info) {
-        product = info->product_id;
-    } else {
-        SDL_JoystickGUID guid = SDL_GetJoystickGUID(joystick);
+    {
+        CHECK_JOYSTICK_MAGIC(joystick, 0);
 
-        SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL, NULL);
+        info = SDL_GetJoystickInstanceVirtualGamepadInfo(joystick->instance_id);
+        if (info) {
+            product = info->product_id;
+        } else {
+            SDL_JoystickGUID guid = SDL_GetJoystickGUID(joystick);
+
+            SDL_GetJoystickGUIDInfo(guid, NULL, &product, NULL, NULL);
+        }
     }
     SDL_UnlockJoysticks();