SDL: Make HIDAPI_JoystickOpen() more robust against internal logic errors

From 9ff498e78e4d83d3ef45260db3c753d033666f0c Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Wed, 10 Aug 2022 06:00:30 -0700
Subject: [PATCH] Make HIDAPI_JoystickOpen() more robust against internal logic
 errors

Fixes https://github.com/libsdl-org/SDL/issues/6030
---
 src/joystick/hidapi/SDL_hidapijoystick.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/joystick/hidapi/SDL_hidapijoystick.c b/src/joystick/hidapi/SDL_hidapijoystick.c
index 69e848802ea..3d596c8a777 100644
--- a/src/joystick/hidapi/SDL_hidapijoystick.c
+++ b/src/joystick/hidapi/SDL_hidapijoystick.c
@@ -1100,10 +1100,15 @@ HIDAPI_JoystickGetDeviceInstanceID(int device_index)
 static int
 HIDAPI_JoystickOpen(SDL_Joystick *joystick, int device_index)
 {
-    SDL_JoystickID joystickID;
+    SDL_JoystickID joystickID = -1;
     SDL_HIDAPI_Device *device = HIDAPI_GetDeviceByIndex(device_index, &joystickID);
     struct joystick_hwdata *hwdata;
 
+    if (!device || !device->driver) {
+        /* This should never happen - validated before being called */
+        return SDL_SetError("Couldn't find HIDAPI device at index %d\n", device_index);
+    }
+
     hwdata = (struct joystick_hwdata *)SDL_calloc(1, sizeof(*hwdata));
     if (!hwdata) {
         return SDL_OutOfMemory();