sdl2-compat: Prevent sending gamepad buttons that are out of range for SDL2

From d702f0e25e2808c2e353132a0d5cf3b7fe8c2fc4 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Fri, 12 Jun 2026 14:53:37 -0700
Subject: [PATCH] Prevent sending gamepad buttons that are out of range for
 SDL2

Fixes https://github.com/libsdl-org/sdl2-compat/issues/602
---
 src/sdl2_compat.c |  8 ++++++++
 src/sdl2_compat.h | 27 +++++++++++++++++++++++++++
 2 files changed, 35 insertions(+)

diff --git a/src/sdl2_compat.c b/src/sdl2_compat.c
index 533bf688..c1cc5bcc 100644
--- a/src/sdl2_compat.c
+++ b/src/sdl2_compat.c
@@ -2802,6 +2802,14 @@ EventFilter3to2(void *userdata, SDL_Event *event3)
         case SDL_EVENT_CAMERA_DEVICE_DENIED:
         case SDL_EVENT_RENDER_DEVICE_LOST:
             return false;
+        case SDL_EVENT_GAMEPAD_BUTTON_DOWN:
+        case SDL_EVENT_GAMEPAD_BUTTON_UP:
+            if (event3->gbutton.button >= SDL_CONTROLLER_BUTTON_MAX) {
+                return false;
+            }
+            break;
+        default:
+            break;
     }
 
     GestureProcessEvent(event3);  /* this might need to generate new gesture events from touch input. */
diff --git a/src/sdl2_compat.h b/src/sdl2_compat.h
index b6647b36..2f75f5d1 100644
--- a/src/sdl2_compat.h
+++ b/src/sdl2_compat.h
@@ -179,6 +179,33 @@ typedef enum
     SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_PAIR
 } SDL_GameControllerType;
 
+typedef enum SDL2_GameControllerButton
+{
+    SDL_CONTROLLER_BUTTON_INVALID = -1,
+    SDL_CONTROLLER_BUTTON_A,
+    SDL_CONTROLLER_BUTTON_B,
+    SDL_CONTROLLER_BUTTON_X,
+    SDL_CONTROLLER_BUTTON_Y,
+    SDL_CONTROLLER_BUTTON_BACK,
+    SDL_CONTROLLER_BUTTON_GUIDE,
+    SDL_CONTROLLER_BUTTON_START,
+    SDL_CONTROLLER_BUTTON_LEFTSTICK,
+    SDL_CONTROLLER_BUTTON_RIGHTSTICK,
+    SDL_CONTROLLER_BUTTON_LEFTSHOULDER,
+    SDL_CONTROLLER_BUTTON_RIGHTSHOULDER,
+    SDL_CONTROLLER_BUTTON_DPAD_UP,
+    SDL_CONTROLLER_BUTTON_DPAD_DOWN,
+    SDL_CONTROLLER_BUTTON_DPAD_LEFT,
+    SDL_CONTROLLER_BUTTON_DPAD_RIGHT,
+    SDL_CONTROLLER_BUTTON_MISC1,    /* Xbox Series X share button, PS5 microphone button, Nintendo Switch Pro capture button, Amazon Luna microphone button */
+    SDL_CONTROLLER_BUTTON_PADDLE1,  /* Xbox Elite paddle P1 (upper left, facing the back) */
+    SDL_CONTROLLER_BUTTON_PADDLE2,  /* Xbox Elite paddle P3 (upper right, facing the back) */
+    SDL_CONTROLLER_BUTTON_PADDLE3,  /* Xbox Elite paddle P2 (lower left, facing the back) */
+    SDL_CONTROLLER_BUTTON_PADDLE4,  /* Xbox Elite paddle P4 (lower right, facing the back) */
+    SDL_CONTROLLER_BUTTON_TOUCHPAD, /* PS4/PS5 touchpad button */
+    SDL_CONTROLLER_BUTTON_MAX
+} SDL2_GameControllerButton;
+
 typedef SDL_Gamepad SDL_GameController;  /* since they're opaque types, for simplicity we just typedef it here and use the old types in sdl3_syms.h */
 typedef SDL_GamepadAxis SDL_GameControllerAxis;
 typedef SDL_GamepadButton SDL_GameControllerButton;