hidapi: Don't leak device handle in macOS 10.10 or newer

Ported from libusb's hidapi fork. Original patch by Youw (cdc473dfe43f6432dda7ad53d7656b8ae8ff968b).
This commit is contained in:
OatmealDome 2021-08-09 21:24:10 -04:00
parent b24599cf5b
commit 25c85d827a

View File

@ -33,6 +33,9 @@
#include "hidapi.h" #include "hidapi.h"
/* As defined in AppKit.h, but we don't need the entire AppKit for a single constant. */
extern const double NSAppKitVersionNumber;
/* Barrier implementation because Mac OSX doesn't have pthread_barrier. /* Barrier implementation because Mac OSX doesn't have pthread_barrier.
It also doesn't have clock_gettime(). So much for POSIX and SUSv2. It also doesn't have clock_gettime(). So much for POSIX and SUSv2.
This implementation came from Brent Priddy and was posted on This implementation came from Brent Priddy and was posted on
@ -177,6 +180,7 @@ static void free_hid_device(hid_device *dev)
} }
static IOHIDManagerRef hid_mgr = 0x0; static IOHIDManagerRef hid_mgr = 0x0;
static int is_macos_10_10_or_greater = 0;
#if 0 #if 0
@ -390,6 +394,7 @@ static int init_hid_manager(void)
int HID_API_EXPORT hid_init(void) int HID_API_EXPORT hid_init(void)
{ {
if (!hid_mgr) { if (!hid_mgr) {
is_macos_10_10_or_greater = (NSAppKitVersionNumber >= 1343); /* NSAppKitVersionNumber10_10 */
return init_hid_manager(); return init_hid_manager();
} }
@ -989,7 +994,7 @@ void HID_API_EXPORT hid_close(hid_device *dev)
return; return;
/* Disconnect the report callback before close. */ /* Disconnect the report callback before close. */
if (!dev->disconnected) { if (is_macos_10_10_or_greater || !dev->disconnected) {
IOHIDDeviceRegisterInputReportCallback( IOHIDDeviceRegisterInputReportCallback(
dev->device_handle, dev->input_report_buf, dev->max_input_report_len, dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
NULL, dev); NULL, dev);
@ -1013,8 +1018,14 @@ void HID_API_EXPORT hid_close(hid_device *dev)
/* Close the OS handle to the device, but only if it's not /* Close the OS handle to the device, but only if it's not
been unplugged. If it's been unplugged, then calling been unplugged. If it's been unplugged, then calling
IOHIDDeviceClose() will crash. */ IOHIDDeviceClose() will crash.
if (!dev->disconnected) {
UPD: The crash part was true in/until some version of macOS.
Starting with macOS 10.15, there is an opposite effect in some environments:
crash happenes if IOHIDDeviceClose() is not called.
Not leaking a resource in all tested environments.
*/
if (is_macos_10_10_or_greater || !dev->disconnected) {
IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeSeizeDevice); IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeSeizeDevice);
} }