From ab55ec485028599255ec606785508ca83ab1f416 Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Fri, 1 Jan 2021 11:12:41 -0800 Subject: [PATCH] Fix use-after-free SBH corruption due to overlapped ReadFile in hidapi not being canceled for all threads before device close - hidapi already called CancelIo on hid_close but that only cancels pending IO for the current thread. Controller read/writes originate from multiple threads (serialized, but on a different thread nonetheless) but device destruction was always done on the main device thread which left any pending overlapped reads still running after hidapi's internal read buffer is deallocated leading to intermittent free list corruption. --- src/hidapi/windows/hid.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/hidapi/windows/hid.c b/src/hidapi/windows/hid.c index 3965a281b..6534a52ef 100644 --- a/src/hidapi/windows/hid.c +++ b/src/hidapi/windows/hid.c @@ -932,9 +932,13 @@ int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev) { + DWORD bytes_read = 0; + if (!dev) return; - CancelIo(dev->device_handle); + CancelIoEx(dev->device_handle, NULL); + if (dev->read_pending) + GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/); free_hid_device(dev); }