From 56b0b3315243742e61df8528dbd593db0281960a Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Wed, 28 Oct 2026 14:50:51 -0700
Subject: [PATCH] Use CM_Register_Notification() for SDL_hidapi device
notifications on Windows
This removes our dependence on the Windows message loop for HIDAPI device notifications, which has bitten us before.
Partial fix for https://github.com/libsdl-org/SDL/issues/5543
---
src/core/windows/SDL_hid.c | 123 ++++++++++++++++++++++++------
src/core/windows/SDL_windows.h | 7 ++
src/hidapi/SDL_hidapi.c | 135 +++++++--------------------------
src/hidapi/libusb/hid.c | 4 +-
4 files changed, 134 insertions(+), 135 deletions(-)
diff --git a/src/core/windows/SDL_hid.c b/src/core/windows/SDL_hid.c
index 1f629d58d2174..0623e7d4e2586 100644
--- a/src/core/windows/SDL_hid.c
+++ b/src/core/windows/SDL_hid.c
@@ -167,18 +167,39 @@ typedef DWORD (CALLBACK *PCM_NOTIFY_CALLBACK)(HCMNOTIFICATION hNotify, PVOID Con
typedef DWORD (WINAPI *CM_Register_NotificationFunc)(PCM_NOTIFY_FILTER pFilter, PVOID pContext, PCM_NOTIFY_CALLBACK pCallback, PHCMNOTIFICATION pNotifyContext);
typedef DWORD (WINAPI *CM_Unregister_NotificationFunc)(HCMNOTIFICATION NotifyContext);
+#define CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES 0x00000001
+
static GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2L, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } };
+static SDL_InitState SDL_cfgmgr32_init;
+static CM_Register_NotificationFunc SDL_CM_Register_Notification;
+static CM_Unregister_NotificationFunc SDL_CM_Unregister_Notification;
+
static int s_DeviceNotificationsRequested;
-static HMODULE cfgmgr32_lib_handle;
-static CM_Register_NotificationFunc CM_Register_Notification;
-static CM_Unregister_NotificationFunc CM_Unregister_Notification;
static HCMNOTIFICATION s_DeviceNotificationFuncHandle;
static Uint64 s_LastDeviceNotification = 1;
static HANDLE s_HotplugEvent = INVALID_HANDLE_VALUE;
static SDL_AtomicInt s_HotplugRunning;
static SDL_Thread *s_HotplugThread;
+static bool WIN_LoadCfgMgr32(void)
+{
+ if (SDL_ShouldInit(&SDL_cfgmgr32_init)) {
+ // We'll keep this loaded for future use
+ HMODULE cfgmgr32 = LoadLibraryA("cfgmgr32.dll");
+ if (cfgmgr32) {
+ SDL_CM_Register_Notification = (CM_Register_NotificationFunc)GetProcAddress(cfgmgr32, "CM_Register_Notification");
+ SDL_CM_Unregister_Notification = (CM_Unregister_NotificationFunc)GetProcAddress(cfgmgr32, "CM_Unregister_Notification");
+ }
+ SDL_SetInitialized(&SDL_cfgmgr32_init, true);
+ }
+
+ if (!SDL_CM_Register_Notification || !SDL_CM_Unregister_Notification) {
+ return false;
+ }
+ return true;
+}
+
#ifdef SDL_VIDEO_DRIVER_WINDOWS
// Defined in SDL_windowsevents.c
extern void WIN_CheckKeyboardAndMouseHotplug(bool hid_loaded);
@@ -224,20 +245,15 @@ void WIN_InitDeviceNotification(void)
s_HotplugEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
s_HotplugThread = SDL_CreateThread(DeviceHotplugThread, "DeviceHotplugThread", NULL);
- cfgmgr32_lib_handle = LoadLibraryA("cfgmgr32.dll");
- if (cfgmgr32_lib_handle) {
- CM_Register_Notification = (CM_Register_NotificationFunc)GetProcAddress(cfgmgr32_lib_handle, "CM_Register_Notification");
- CM_Unregister_Notification = (CM_Unregister_NotificationFunc)GetProcAddress(cfgmgr32_lib_handle, "CM_Unregister_Notification");
- if (CM_Register_Notification && CM_Unregister_Notification) {
- CM_NOTIFY_FILTER notify_filter;
-
- SDL_zero(notify_filter);
- notify_filter.cbSize = sizeof(notify_filter);
- notify_filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE;
- notify_filter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_HID;
- if (CM_Register_Notification(¬ify_filter, NULL, SDL_DeviceNotificationFunc, &s_DeviceNotificationFuncHandle) == CR_SUCCESS) {
- return;
- }
+ if (WIN_LoadCfgMgr32()) {
+ CM_NOTIFY_FILTER notify_filter;
+
+ SDL_zero(notify_filter);
+ notify_filter.cbSize = sizeof(notify_filter);
+ notify_filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE;
+ notify_filter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_HID;
+ if (SDL_CM_Register_Notification(¬ify_filter, NULL, SDL_DeviceNotificationFunc, &s_DeviceNotificationFuncHandle) == CR_SUCCESS) {
+ return;
}
}
@@ -249,6 +265,59 @@ Uint64 WIN_GetLastDeviceNotification(void)
return s_LastDeviceNotification;
}
+struct WIN_DeviceInterfaceNotification
+{
+ HCMNOTIFICATION handle;
+ WIN_DeviceInterfaceCallback callback;
+ void *userdata;
+};
+
+static DWORD CALLBACK WIN_DeviceInterfaceNotificationFunc(HCMNOTIFICATION hNotify, PVOID context, CM_NOTIFY_ACTION action, PCM_NOTIFY_EVENT_DATA eventData, DWORD event_data_size)
+{
+ WIN_DeviceInterfaceNotification *notification = (WIN_DeviceInterfaceNotification *)context;
+
+ if (action == CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL ||
+ action == CM_NOTIFY_ACTION_DEVICEINTERFACEREMOVAL) {
+ notification->callback(notification->userdata);
+ }
+ return ERROR_SUCCESS;
+}
+
+WIN_DeviceInterfaceNotification *WIN_RegisterDeviceInterfaceNotification(WIN_DeviceInterfaceCallback callback, void *userdata)
+{
+ WIN_DeviceInterfaceNotification *notification;
+ CM_NOTIFY_FILTER notify_filter;
+
+ if (!WIN_LoadCfgMgr32()) {
+ return NULL;
+ }
+
+ notification = (WIN_DeviceInterfaceNotification *)SDL_calloc(1, sizeof(*notification));
+ if (!notification) {
+ return NULL;
+ }
+ notification->callback = callback;
+ notification->userdata = userdata;
+
+ SDL_zero(notify_filter);
+ notify_filter.cbSize = sizeof(notify_filter);
+ notify_filter.Flags = CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES;
+ notify_filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE;
+ if (SDL_CM_Register_Notification(¬ify_filter, notification, WIN_DeviceInterfaceNotificationFunc, ¬ification->handle) != CR_SUCCESS) {
+ SDL_free(notification);
+ return NULL;
+ }
+ return notification;
+}
+
+void WIN_UnregisterDeviceInterfaceNotification(WIN_DeviceInterfaceNotification *notification)
+{
+ if (notification) {
+ SDL_CM_Unregister_Notification(notification->handle);
+ SDL_free(notification);
+ }
+}
+
void WIN_QuitDeviceNotification(void)
{
if (--s_DeviceNotificationsRequested > 0) {
@@ -263,14 +332,9 @@ void WIN_QuitDeviceNotification(void)
SDL_WaitThread(s_HotplugThread, NULL);
s_HotplugThread = NULL;
- if (cfgmgr32_lib_handle) {
- if (s_DeviceNotificationFuncHandle && CM_Unregister_Notification) {
- CM_Unregister_Notification(s_DeviceNotificationFuncHandle);
- s_DeviceNotificationFuncHandle = NULL;
- }
-
- FreeLibrary(cfgmgr32_lib_handle);
- cfgmgr32_lib_handle = NULL;
+ if (s_DeviceNotificationFuncHandle) {
+ SDL_CM_Unregister_Notification(s_DeviceNotificationFuncHandle);
+ s_DeviceNotificationFuncHandle = NULL;
}
}
@@ -289,4 +353,13 @@ void WIN_QuitDeviceNotification(void)
{
}
+WIN_DeviceInterfaceNotification *WIN_RegisterDeviceInterfaceNotification(WIN_DeviceInterfaceCallback callback, void *userdata)
+{
+ return NULL;
+}
+
+void WIN_UnregisterDeviceInterfaceNotification(WIN_DeviceInterfaceNotification *notification)
+{
+}
+
#endif // !SDL_PLATFORM_XBOXONE && !SDL_PLATFORM_XBOXSERIES
diff --git a/src/core/windows/SDL_windows.h b/src/core/windows/SDL_windows.h
index f5006393a8ab8..50c91f0263a35 100644
--- a/src/core/windows/SDL_windows.h
+++ b/src/core/windows/SDL_windows.h
@@ -234,6 +234,13 @@ extern char *WIN_GetModulePath(HMODULE handle);
// Return true if this system has a broken EZFRD64.DLL installed
extern bool WIN_HasBrokenEZFRD64DLL(void);
+// Register for device interface arrival and removal notifications for all interface classes.
+// The callback is called on a system thread. Returns NULL if notifications aren't available.
+typedef struct WIN_DeviceInterfaceNotification WIN_DeviceInterfaceNotification;
+typedef void (*WIN_DeviceInterfaceCallback)(void *userdata);
+extern WIN_DeviceInterfaceNotification *WIN_RegisterDeviceInterfaceNotification(WIN_DeviceInterfaceCallback callback, void *userdata);
+extern void WIN_UnregisterDeviceInterfaceNotification(WIN_DeviceInterfaceNotification *notification);
+
// Ends C function definitions when using C++
#ifdef __cplusplus
}
diff --git a/src/hidapi/SDL_hidapi.c b/src/hidapi/SDL_hidapi.c
index d00c06a924aae..b7ff159720b46 100644
--- a/src/hidapi/SDL_hidapi.c
+++ b/src/hidapi/SDL_hidapi.c
@@ -106,16 +106,12 @@ static const SDL_UDEV_Symbols *usyms = NULL;
static struct
{
bool m_bInitialized;
- Uint32 m_unDeviceChangeCounter;
+ SDL_AtomicU32 m_unDeviceChangeCounter;
bool m_bCanGetNotifications;
Uint64 m_unLastDetect;
#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
- SDL_ThreadID m_nThreadID;
- WNDCLASSEXA m_wndClass;
- HWND m_hwndMsg;
- HDEVNOTIFY m_hNotify;
- double m_flLastWin32MessageCheck;
+ WIN_DeviceInterfaceNotification *m_pNotification;
#endif
#ifdef SDL_PLATFORM_MACOS
@@ -130,51 +126,17 @@ static struct
#endif
} SDL_HIDAPI_discovery;
-#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
-struct _DEV_BROADCAST_HDR
-{
- DWORD dbch_size;
- DWORD dbch_devicetype;
- DWORD dbch_reserved;
-};
-
-typedef struct _DEV_BROADCAST_DEVICEINTERFACE_A
+static void HIDAPI_DeviceChanged(void)
{
- DWORD dbcc_size;
- DWORD dbcc_devicetype;
- DWORD dbcc_reserved;
- GUID dbcc_classguid;
- char dbcc_name[1];
-} DEV_BROADCAST_DEVICEINTERFACE_A, *PDEV_BROADCAST_DEVICEINTERFACE_A;
-
-typedef struct _DEV_BROADCAST_HDR DEV_BROADCAST_HDR;
-#define DBT_DEVICEARRIVAL 0x8000 // system detected a new device
-#define DBT_DEVICEREMOVECOMPLETE 0x8004 // device was removed from the system
-#define DBT_DEVTYP_DEVICEINTERFACE 0x00000005 // device interface class
-#define DBT_DEVNODES_CHANGED 0x0007
-#define DBT_CONFIGCHANGED 0x0018
-#define DBT_DEVICETYPESPECIFIC 0x8005 // type specific event
-#define DBT_DEVINSTSTARTED 0x8008 // device installed and started
+ SDL_AddAtomicU32(&SDL_HIDAPI_discovery.m_unDeviceChangeCounter, 1);
+}
+#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
#include <initguid.h>
-DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED);
-static LRESULT CALLBACK ControllerWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
+static void HIDAPI_DeviceInterfaceChanged(void *userdata)
{
- switch (message) {
- case WM_DEVICECHANGE:
- switch (wParam) {
- case DBT_DEVICEARRIVAL:
- case DBT_DEVICEREMOVECOMPLETE:
- if (((DEV_BROADCAST_HDR *)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
- }
- break;
- }
- return TRUE;
- }
-
- return DefWindowProc(hwnd, message, wParam, lParam);
+ HIDAPI_DeviceChanged();
}
#endif // defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
@@ -185,7 +147,7 @@ static void CallbackIOServiceFunc(void *context, io_iterator_t portIterator)
io_object_t entry;
while ((entry = IOIteratorNext(portIterator)) != 0) {
IOObjectRelease(entry);
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
+ HIDAPI_DeviceChanged();
}
}
#endif // SDL_PLATFORM_MACOS
@@ -235,37 +197,19 @@ static int StrIsInteger(const char *string)
static void HIDAPI_InitializeDiscovery(void)
{
SDL_HIDAPI_discovery.m_bInitialized = true;
- SDL_HIDAPI_discovery.m_unDeviceChangeCounter = 1;
SDL_HIDAPI_discovery.m_bCanGetNotifications = false;
SDL_HIDAPI_discovery.m_unLastDetect = 0;
#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
- SDL_HIDAPI_discovery.m_nThreadID = SDL_GetCurrentThreadID();
-
- SDL_zero(SDL_HIDAPI_discovery.m_wndClass);
- SDL_HIDAPI_discovery.m_wndClass.hInstance = GetModuleHandle(NULL);
- SDL_HIDAPI_discovery.m_wndClass.lpszClassName = "SDL_HIDAPI_DEVICE_DETECTION";
- SDL_HIDAPI_discovery.m_wndClass.lpfnWndProc = ControllerWndProc; // This function is called by windows
- SDL_HIDAPI_discovery.m_wndClass.cbSize = sizeof(WNDCLASSEX);
-
- RegisterClassExA(&SDL_HIDAPI_discovery.m_wndClass);
- SDL_HIDAPI_discovery.m_hwndMsg = CreateWindowExA(0, "SDL_HIDAPI_DEVICE_DETECTION", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
-
- {
- DEV_BROADCAST_DEVICEINTERFACE_A devBroadcast;
-
- SDL_zero(devBroadcast);
- devBroadcast.dbcc_size = sizeof(devBroadcast);
- devBroadcast.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
- devBroadcast.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
-
- /* DEVICE_NOTIFY_ALL_INTERFACE_CLASSES is important, makes GUID_DEVINTERFACE_USB_DEVICE ignored,
- * but that seems to be necessary to get a notice after each individual usb input device actually
- * installs, rather than just as the composite device is seen.
- */
- SDL_HIDAPI_discovery.m_hNotify = RegisterDeviceNotification(SDL_HIDAPI_discovery.m_hwndMsg, &devBroadcast, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
- SDL_HIDAPI_discovery.m_bCanGetNotifications = (SDL_HIDAPI_discovery.m_hNotify != 0);
- }
+ /* We want notifications for all interface classes, not just HID, so we get a notice after
+ * each individual USB input device actually installs, rather than just as the composite
+ * device is seen, and so WinUSB devices used through libusb are noticed too.
+ *
+ * The callback is called on a system thread, so this doesn't depend on which thread
+ * initialized hidapi or pumps messages.
+ */
+ SDL_HIDAPI_discovery.m_pNotification = WIN_RegisterDeviceInterfaceNotification(HIDAPI_DeviceInterfaceChanged, NULL);
+ SDL_HIDAPI_discovery.m_bCanGetNotifications = (SDL_HIDAPI_discovery.m_pNotification != NULL);
#endif // defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
#ifdef SDL_PLATFORM_MACOS
@@ -381,29 +325,12 @@ static void HIDAPI_UpdateDiscovery(void)
const Uint32 SDL_HIDAPI_DETECT_INTERVAL_MS = 3000; // Update every 3 seconds
Uint64 now = SDL_GetTicks();
if (!SDL_HIDAPI_discovery.m_unLastDetect || now >= (SDL_HIDAPI_discovery.m_unLastDetect + SDL_HIDAPI_DETECT_INTERVAL_MS)) {
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
+ HIDAPI_DeviceChanged();
SDL_HIDAPI_discovery.m_unLastDetect = now;
}
return;
}
-#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
- if (SDL_IsVideoThread()) {
- // just let the usual SDL_PumpEvents loop dispatch these, fixing bug 2998. --ryan.
- } else {
- // We'll only get messages on the same thread that created the window
- if (SDL_GetCurrentThreadID() == SDL_HIDAPI_discovery.m_nThreadID) {
- MSG msg;
- while (PeekMessage(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0, PM_NOREMOVE)) {
- if (GetMessageA(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0) != 0) {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- }
- }
- }
-#endif // defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
-
#ifdef SDL_PLATFORM_MACOS
if (SDL_HIDAPI_discovery.m_notificationPort) {
struct
@@ -440,7 +367,7 @@ static void HIDAPI_UpdateDiscovery(void)
const char *action = NULL;
action = usyms->udev_device_get_action(pUdevDevice);
if (action == NULL || SDL_strcmp(action, "add") == 0 || SDL_strcmp(action, "remove") == 0) {
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
+ HIDAPI_DeviceChanged();
}
usyms->udev_device_unref(pUdevDevice);
}
@@ -471,7 +398,7 @@ static void HIDAPI_UpdateDiscovery(void)
if (buf.event.len > 0) {
if (StrHasPrefix(buf.event.name, "hidraw") &&
StrIsInteger(buf.event.name + SDL_strlen("hidraw"))) {
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
+ HIDAPI_DeviceChanged();
/* We found an hidraw change. We still continue to
* drain the inotify fd to avoid leaving old
* notifications in the queue. */
@@ -497,15 +424,8 @@ static void HIDAPI_ShutdownDiscovery(void)
}
#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK)
- if (SDL_HIDAPI_discovery.m_hNotify) {
- UnregisterDeviceNotification(SDL_HIDAPI_discovery.m_hNotify);
- }
-
- if (SDL_HIDAPI_discovery.m_hwndMsg) {
- DestroyWindow(SDL_HIDAPI_discovery.m_hwndMsg);
- }
-
- UnregisterClassA(SDL_HIDAPI_discovery.m_wndClass.lpszClassName, SDL_HIDAPI_discovery.m_wndClass.hInstance);
+ WIN_UnregisterDeviceInterfaceNotification(SDL_HIDAPI_discovery.m_pNotification);
+ SDL_HIDAPI_discovery.m_pNotification = NULL;
#endif
#ifdef SDL_PLATFORM_MACOS
@@ -1327,11 +1247,10 @@ Uint32 SDL_hid_device_change_count(void)
HIDAPI_UpdateDiscovery();
- if (SDL_HIDAPI_discovery.m_unDeviceChangeCounter == 0) {
- // Counter wrapped!
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
- }
- counter = SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
+ // Bump the counter if it's freshly initialized or wrapped
+ SDL_CompareAndSwapAtomicU32(&SDL_HIDAPI_discovery.m_unDeviceChangeCounter, 0, 1);
+
+ counter = SDL_GetAtomicU32(&SDL_HIDAPI_discovery.m_unDeviceChangeCounter);
#endif // !SDL_HIDAPI_DISABLED
diff --git a/src/hidapi/libusb/hid.c b/src/hidapi/libusb/hid.c
index 5a4c7cabe69a2..84d3d78a1d195 100644
--- a/src/hidapi/libusb/hid.c
+++ b/src/hidapi/libusb/hid.c
@@ -657,10 +657,10 @@ static int LIBUSB_CALL hotplug_callback(struct libusb_context *ctx, struct libus
{
switch (event) {
case LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED:
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
+ HIDAPI_DeviceChanged();
break;
case LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT:
- ++SDL_HIDAPI_discovery.m_unDeviceChangeCounter;
+ HIDAPI_DeviceChanged();
break;
default:
break;