Debian Codegraph @

3rdparty/hidapi/mac/hid.c

raw symbols SCIP
1 /*******************************************************
2 HIDAPI - Multi-Platform library for
3 communication with HID devices.
4
5 Alan Ott
6 Signal 11 Software
7
8 libusb/hidapi Team
9
10 Copyright 2022, All Rights Reserved.
11
12 At the discretion of the user of this library,
13 this software may be licensed under the terms of the
14 GNU General Public License v3, a BSD-Style license, or the
15 original HIDAPI license as outlined in the LICENSE.txt,
16 LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
17 files located at the root of the source distribution.
18 These files may also be found in the public source
19 code repository located at:
20 https://github.com/libusb/hidapi .
21 ********************************************************/
22
23 /* See Apple Technical Note TN2187 for details on IOHidManager. */
24
25 #include <IOKit/hid/IOHIDManager.h>
26 #include <IOKit/hid/IOHIDKeys.h>
27 #include <IOKit/IOKitLib.h>
28 #include <IOKit/usb/USBSpec.h>
29 #include <CoreFoundation/CoreFoundation.h>
30 #include <mach/mach_error.h>
31 #include <stdbool.h>
32 #include <wchar.h>
33 #include <locale.h>
34 #include <pthread.h>
35 #include <sys/time.h>
36 #include <unistd.h>
37 #include <dlfcn.h>
38
39 #include "hidapi_darwin.h"
40
41 /* Barrier implementation because Mac OSX doesn't have pthread_barrier.
42 It also doesn't have clock_gettime(). So much for POSIX and SUSv2.
43 This implementation came from Brent Priddy and was posted on
44 StackOverflow. It is used with his permission. */
45 typedef int pthread_barrierattr_t;
46 typedef struct pthread_barrier {
47 pthread_mutex_t mutex;
48 pthread_cond_t cond;
49 int count;
50 int trip_count;
51 } pthread_barrier_t;
52
53 static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
54 {
55 (void) attr;
56
57 if (count == 0) {
58 errno = EINVAL;
59 return -1;
60 }
61
62 if (pthread_mutex_init(&barrier->mutex, 0) < 0) {
63 return -1;
64 }
65 if (pthread_cond_init(&barrier->cond, 0) < 0) {
66 pthread_mutex_destroy(&barrier->mutex);
67 return -1;
68 }
69 barrier->trip_count = count;
70 barrier->count = 0;
71
72 return 0;
73 }
74
75 static int pthread_barrier_destroy(pthread_barrier_t *barrier)
76 {
77 pthread_cond_destroy(&barrier->cond);
78 pthread_mutex_destroy(&barrier->mutex);
79 return 0;
80 }
81
82 static int pthread_barrier_wait(pthread_barrier_t *barrier)
83 {
84 pthread_mutex_lock(&barrier->mutex);
85 ++(barrier->count);
86 if (barrier->count >= barrier->trip_count) {
87 barrier->count = 0;
88 pthread_mutex_unlock(&barrier->mutex);
89 pthread_cond_broadcast(&barrier->cond);
90 return 1;
91 }
92 else {
93 do {
94 pthread_cond_wait(&barrier->cond, &(barrier->mutex));
95 }
96 while (barrier->count != 0);
97
98 pthread_mutex_unlock(&barrier->mutex);
99 return 0;
100 }
101 }
102
103 static int return_data(hid_device *dev, unsigned char *data, size_t length);
104
105 /* Linked List of input reports received from the device. */
106 struct input_report {
107 uint8_t *data;
108 size_t len;
109 struct input_report *next;
110 };
111
112 static struct hid_api_version api_version = {
113 .major = HID_API_VERSION_MAJOR,
114 .minor = HID_API_VERSION_MINOR,
115 .patch = HID_API_VERSION_PATCH
116 };
117
118 /* - Run context - */
119 static IOHIDManagerRef hid_mgr = 0x0;
120 static int is_macos_10_10_or_greater = 0;
121 static IOOptionBits device_open_options = 0;
122 static wchar_t *last_global_error_str = NULL;
123 /* --- */
124
125 struct hid_device_ {
126 IOHIDDeviceRef device_handle;
127 IOOptionBits open_options;
128 int blocking;
129 int disconnected;
130 CFStringRef run_loop_mode;
131 CFRunLoopRef run_loop;
132 CFRunLoopSourceRef source;
133 uint8_t *input_report_buf;
134 CFIndex max_input_report_len;
135 struct input_report *input_reports;
136 struct hid_device_info* device_info;
137
138 pthread_t thread;
139 pthread_mutex_t mutex; /* Protects input_reports */
140 pthread_cond_t condition;
141 pthread_barrier_t barrier; /* Ensures correct startup sequence */
142 pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */
143 int shutdown_thread;
144 wchar_t *last_error_str;
145 wchar_t *last_read_error_str;
146 };
147
148 static hid_device *new_hid_device(void)
149 {
150 hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
151 if (dev == NULL) {
152 return NULL;
153 }
154
155 dev->device_handle = NULL;
156 dev->open_options = device_open_options;
157 dev->blocking = 1;
158 dev->disconnected = 0;
159 dev->run_loop_mode = NULL;
160 dev->run_loop = NULL;
161 dev->source = NULL;
162 dev->input_report_buf = NULL;
163 dev->input_reports = NULL;
164 dev->device_info = NULL;
165 dev->shutdown_thread = 0;
166 dev->last_error_str = NULL;
167 dev->last_read_error_str = NULL;
168
169 /* Thread objects */
170 pthread_mutex_init(&dev->mutex, NULL);
171 pthread_cond_init(&dev->condition, NULL);
172 pthread_barrier_init(&dev->barrier, NULL, 2);
173 pthread_barrier_init(&dev->shutdown_barrier, NULL, 2);
174
175 return dev;
176 }
177
178 static void free_hid_device(hid_device *dev)
179 {
180 if (!dev)
181 return;
182
183 /* Delete any input reports still left over. */
184 struct input_report *rpt = dev->input_reports;
185 while (rpt) {
186 struct input_report *next = rpt->next;
187 free(rpt->data);
188 free(rpt);
189 rpt = next;
190 }
191
192 /* Free the string and the report buffer. The check for NULL
193 is necessary here as CFRelease() doesn't handle NULL like
194 free() and others do. */
195 if (dev->run_loop_mode)
196 CFRelease(dev->run_loop_mode);
197 if (dev->source)
198 CFRelease(dev->source);
199 free(dev->input_report_buf);
200 free(dev->last_error_str);
201 free(dev->last_read_error_str);
202 hid_free_enumeration(dev->device_info);
203
204 /* Clean up the thread objects */
205 pthread_barrier_destroy(&dev->shutdown_barrier);
206 pthread_barrier_destroy(&dev->barrier);
207 pthread_cond_destroy(&dev->condition);
208 pthread_mutex_destroy(&dev->mutex);
209
210 /* Free the structure itself. */
211 free(dev);
212 }
213
214
215 /* The caller must free the returned string with free(). */
216 static wchar_t *utf8_to_wchar_t(const char *utf8)
217 {
218 wchar_t *ret = NULL;
219
220 if (utf8) {
221 size_t wlen = mbstowcs(NULL, utf8, 0);
222 if ((size_t) -1 == wlen) {
223 return wcsdup(L"");
224 }
225 ret = (wchar_t*) calloc(wlen+1, sizeof(wchar_t));
226 if (ret == NULL) {
227 /* as much as we can do at this point */
228 return NULL;
229 }
230 mbstowcs(ret, utf8, wlen+1);
231 ret[wlen] = 0x0000;
232 }
233
234 return ret;
235 }
236
237
238 /* Makes a copy of the given error message (and decoded according to the
239 * currently locale) into the wide string pointer pointed by error_str.
240 * The last stored error string is freed.
241 * Use register_error_str(NULL) to free the error message completely. */
242 static void register_error_str(wchar_t **error_str, const char *msg)
243 {
244 free(*error_str);
245 *error_str = utf8_to_wchar_t(msg);
246 }
247
248 /* Similar to register_error_str, but allows passing a format string with va_list args into this function. */
249 static void register_error_str_vformat(wchar_t **error_str, const char *format, va_list args)
250 {
251 char msg[1024];
252 vsnprintf(msg, sizeof(msg), format, args);
253
254 register_error_str(error_str, msg);
255 }
256
257 /* Set the last global error to be reported by hid_error(NULL).
258 * The given error message will be copied (and decoded according to the
259 * currently locale, so do not pass in string constants).
260 * The last stored global error message is freed.
261 * Use register_global_error(NULL) to indicate "no error". */
262 static void register_global_error(const char *msg)
263 {
264 register_error_str(&last_global_error_str, msg);
265 }
266
267 /* Similar to register_global_error, but allows passing a format string into this function. */
268 static void register_global_error_format(const char *format, ...)
269 {
270 va_list args;
271 va_start(args, format);
272 register_error_str_vformat(&last_global_error_str, format, args);
273 va_end(args);
274 }
275
276 /* Set the last error for a device to be reported by hid_error(dev).
277 * The given error message will be copied (and decoded according to the
278 * currently locale, so do not pass in string constants).
279 * The last stored device error message is freed.
280 * Use register_device_error(dev, NULL) to indicate "no error". */
281 static void register_device_error(hid_device *dev, const char *msg)
282 {
283 register_error_str(&dev->last_error_str, msg);
284 }
285
286 /* Similar to register_device_error, but you can pass a format string into this function. */
287 static void register_device_error_format(hid_device *dev, const char *format, ...)
288 {
289 va_list args;
290 va_start(args, format);
291 register_error_str_vformat(&dev->last_error_str, format, args);
292 va_end(args);
293 }
294
295
296 static CFArrayRef get_array_property(IOHIDDeviceRef device, CFStringRef key)
297 {
298 CFTypeRef ref = IOHIDDeviceGetProperty(device, key);
299 if (ref != NULL && CFGetTypeID(ref) == CFArrayGetTypeID()) {
300 return (CFArrayRef)ref;
301 } else {
302 return NULL;
303 }
304 }
305
306 static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key)
307 {
308 CFTypeRef ref;
309 int32_t value = 0;
310
311 ref = IOHIDDeviceGetProperty(device, key);
312 if (ref) {
313 if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
314 CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value);
315 return value;
316 }
317 }
318 return 0;
319 }
320
321 static bool try_get_int_property(IOHIDDeviceRef device, CFStringRef key, int32_t *out_val)
322 {
323 bool result = false;
324 CFTypeRef ref;
325
326 ref = IOHIDDeviceGetProperty(device, key);
327 if (ref) {
328 if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
329 result = CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, out_val);
330 }
331 }
332 return result;
333 }
334
335 static bool try_get_ioregistry_int_property(io_service_t service, CFStringRef property, int32_t *out_val)
336 {
337 bool result = false;
338 CFTypeRef ref = IORegistryEntryCreateCFProperty(service, property, kCFAllocatorDefault, 0);
339
340 if (ref) {
341 if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
342 result = CFNumberGetValue(ref, kCFNumberSInt32Type, out_val);
343 }
344
345 CFRelease(ref);
346 }
347
348 return result;
349 }
350
351 static CFArrayRef get_usage_pairs(IOHIDDeviceRef device)
352 {
353 return get_array_property(device, CFSTR(kIOHIDDeviceUsagePairsKey));
354 }
355
356 static unsigned short get_vendor_id(IOHIDDeviceRef device)
357 {
358 return get_int_property(device, CFSTR(kIOHIDVendorIDKey));
359 }
360
361 static unsigned short get_product_id(IOHIDDeviceRef device)
362 {
363 return get_int_property(device, CFSTR(kIOHIDProductIDKey));
364 }
365
366 static int32_t get_max_report_length(IOHIDDeviceRef device)
367 {
368 return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));
369 }
370
371 static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len)
372 {
373 CFStringRef str;
374
375 if (!len)
376 return 0;
377
378 str = (CFStringRef) IOHIDDeviceGetProperty(device, prop);
379
380 buf[0] = 0;
381
382 if (str && CFGetTypeID(str) == CFStringGetTypeID()) {
383 CFIndex str_len = CFStringGetLength(str);
384 CFRange range;
385 CFIndex used_buf_len;
386 CFIndex chars_copied;
387
388 len --;
389
390 range.location = 0;
391 range.length = ((size_t) str_len > len)? len: (size_t) str_len;
392 chars_copied = CFStringGetBytes(str,
393 range,
394 kCFStringEncodingUTF32LE,
395 (char) '?',
396 FALSE,
397 (UInt8*)buf,
398 len * sizeof(wchar_t),
399 &used_buf_len);
400
401 if (chars_copied <= 0)
402 buf[0] = 0;
403 else
404 buf[chars_copied] = 0;
405
406 return 0;
407 }
408 else
409 return -1;
410
411 }
412
413 static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len)
414 {
415 return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len);
416 }
417
418 static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
419 {
420 return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len);
421 }
422
423 static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
424 {
425 return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len);
426 }
427
428
429 /* Implementation of wcsdup() for Mac. */
430 static wchar_t *dup_wcs(const wchar_t *s)
431 {
432 size_t len = wcslen(s);
433 wchar_t *ret = (wchar_t*) malloc((len+1)*sizeof(wchar_t));
434 wcscpy(ret, s);
435
436 return ret;
437 }
438
439 /* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */
440 static int init_hid_manager(void)
441 {
442 /* Initialize all the HID Manager Objects */
443 hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
444 if (hid_mgr) {
445 IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
446 IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
447 return 0;
448 }
449
450 register_global_error("Failed to create IOHIDManager");
451 return -1;
452 }
453
454 HID_API_EXPORT const struct hid_api_version* HID_API_CALL hid_version(void)
455 {
456 return &api_version;
457 }
458
459 HID_API_EXPORT const char* HID_API_CALL hid_version_str(void)
460 {
461 return HID_API_VERSION_STR;
462 }
463
464 /* Initialize the IOHIDManager if necessary. This is the public function, and
465 it is safe to call this function repeatedly. Return 0 for success and -1
466 for failure. */
467 int HID_API_EXPORT hid_init(void)
468 {
469 register_global_error(NULL);
470
471 if (!hid_mgr) {
472 is_macos_10_10_or_greater = (kCFCoreFoundationVersionNumber >= 1151.16); /* kCFCoreFoundationVersionNumber10_10 */
473 hid_darwin_set_open_exclusive(1); /* Backward compatibility */
474 return init_hid_manager();
475 }
476
477 /* Already initialized. */
478 return 0;
479 }
480
481 int HID_API_EXPORT hid_exit(void)
482 {
483 if (hid_mgr) {
484 /* Close the HID manager. */
485 IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone);
486 CFRelease(hid_mgr);
487 hid_mgr = NULL;
488 }
489
490 /* Free global error message */
491 register_global_error(NULL);
492
493 return 0;
494 }
495
496 static void process_pending_events(void) {
497 SInt32 res;
498 do {
499 res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE);
500 } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut);
501 }
502
503 static int read_usb_interface_from_hid_service_parent(io_service_t hid_service)
504 {
505 int32_t result = -1;
506 bool success = false;
507 io_registry_entry_t current = IO_OBJECT_NULL;
508 kern_return_t res;
509 int parent_number = 0;
510
511 res = IORegistryEntryGetParentEntry(hid_service, kIOServicePlane, &current);
512 while (KERN_SUCCESS == res
513 /* Only search up to 3 parent entries.
514 * With the default driver - the parent-of-interest supposed to be the first one,
515 * but lets assume some custom drivers or so, with deeper tree. */
516 && parent_number < 3) {
517 io_registry_entry_t parent = IO_OBJECT_NULL;
518 int32_t interface_number = -1;
519 parent_number++;
520
521 success = try_get_ioregistry_int_property(current, CFSTR(kUSBInterfaceNumber), &interface_number);
522 if (success) {
523 result = interface_number;
524 break;
525 }
526
527 res = IORegistryEntryGetParentEntry(current, kIOServicePlane, &parent);
528 if (parent) {
529 IOObjectRelease(current);
530 current = parent;
531 }
532
533 }
534
535 if (current) {
536 IOObjectRelease(current);
537 current = IO_OBJECT_NULL;
538 }
539
540 return result;
541 }
542
543 static struct hid_device_info *create_device_info_with_usage(IOHIDDeviceRef dev, int32_t usage_page, int32_t usage)
544 {
545 unsigned short dev_vid;
546 unsigned short dev_pid;
547 int BUF_LEN = 256;
548 wchar_t buf[BUF_LEN];
549 CFTypeRef transport_prop;
550
551 struct hid_device_info *cur_dev;
552 io_service_t hid_service;
553 kern_return_t res;
554 uint64_t entry_id = 0;
555
556 if (dev == NULL) {
557 return NULL;
558 }
559
560 cur_dev = (struct hid_device_info *)calloc(1, sizeof(struct hid_device_info));
561 if (cur_dev == NULL) {
562 return NULL;
563 }
564
565 dev_vid = get_vendor_id(dev);
566 dev_pid = get_product_id(dev);
567
568 cur_dev->usage_page = usage_page;
569 cur_dev->usage = usage;
570
571 /* Fill out the record */
572 cur_dev->next = NULL;
573
574 /* Fill in the path (as a unique ID of the service entry) */
575 cur_dev->path = NULL;
576 hid_service = IOHIDDeviceGetService(dev);
577 if (hid_service != MACH_PORT_NULL) {
578 res = IORegistryEntryGetRegistryEntryID(hid_service, &entry_id);
579 }
580 else {
581 res = KERN_INVALID_ARGUMENT;
582 }
583
584 if (res == KERN_SUCCESS) {
585 /* max value of entry_id(uint64_t) is 18446744073709551615 which is 20 characters long,
586 so for (max) "path" string 'DevSrvsID:18446744073709551615' we would need
587 9+1+20+1=31 bytes buffer, but allocate 32 for simple alignment */
588 const size_t path_len = 32;
589 cur_dev->path = calloc(1, path_len);
590 if (cur_dev->path != NULL) {
591 snprintf(cur_dev->path, path_len, "DevSrvsID:%llu", entry_id);
592 }
593 }
594
595 if (cur_dev->path == NULL) {
596 /* for whatever reason, trying to keep it a non-NULL string */
597 cur_dev->path = strdup("");
598 }
599
600 /* Serial Number */
601 get_serial_number(dev, buf, BUF_LEN);
602 cur_dev->serial_number = dup_wcs(buf);
603
604 /* Manufacturer and Product strings */
605 get_manufacturer_string(dev, buf, BUF_LEN);
606 cur_dev->manufacturer_string = dup_wcs(buf);
607 get_product_string(dev, buf, BUF_LEN);
608 cur_dev->product_string = dup_wcs(buf);
609
610 /* VID/PID */
611 cur_dev->vendor_id = dev_vid;
612 cur_dev->product_id = dev_pid;
613
614 /* Release Number */
615 cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));
616
617 /* Interface Number.
618 * We can only retrieve the interface number for USB HID devices.
619 * See below */
620 cur_dev->interface_number = -1;
621
622 /* Bus Type */
623 transport_prop = IOHIDDeviceGetProperty(dev, CFSTR(kIOHIDTransportKey));
624
625 if (transport_prop != NULL && CFGetTypeID(transport_prop) == CFStringGetTypeID()) {
626 if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportUSBValue), 0) == kCFCompareEqualTo) {
627 int32_t interface_number = -1;
628 cur_dev->bus_type = HID_API_BUS_USB;
629
630 /* A IOHIDDeviceRef used to have this simple property,
631 * until macOS 13.3 - we will try to use it. */
632 if (try_get_int_property(dev, CFSTR(kUSBInterfaceNumber), &interface_number)) {
633 cur_dev->interface_number = interface_number;
634 } else {
635 /* Otherwise fallback to io_service_t property.
636 * (of one of the parent services). */
637 cur_dev->interface_number = read_usb_interface_from_hid_service_parent(hid_service);
638
639 /* If the above doesn't work -
640 * no (known) fallback exists at this point. */
641 }
642
643 /* Match "Bluetooth", "BluetoothLowEnergy" and "Bluetooth Low Energy" strings */
644 } else if (CFStringHasPrefix((CFStringRef)transport_prop, CFSTR(kIOHIDTransportBluetoothValue))) {
645 cur_dev->bus_type = HID_API_BUS_BLUETOOTH;
646 } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportI2CValue), 0) == kCFCompareEqualTo) {
647 cur_dev->bus_type = HID_API_BUS_I2C;
648 } else if (CFStringCompare((CFStringRef)transport_prop, CFSTR(kIOHIDTransportSPIValue), 0) == kCFCompareEqualTo) {
649 cur_dev->bus_type = HID_API_BUS_SPI;
650 }
651 }
652
653 return cur_dev;
654 }
655
656 static struct hid_device_info *create_device_info(IOHIDDeviceRef device)
657 {
658 const int32_t primary_usage_page = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey));
659 const int32_t primary_usage = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey));
660
661 /* Primary should always be first, to match previous behavior. */
662 struct hid_device_info *root = create_device_info_with_usage(device, primary_usage_page, primary_usage);
663 struct hid_device_info *cur = root;
664
665 if (!root)
666 return NULL;
667
668 CFArrayRef usage_pairs = get_usage_pairs(device);
669
670 if (usage_pairs != NULL) {
671 struct hid_device_info *next = NULL;
672 for (CFIndex i = 0; i < CFArrayGetCount(usage_pairs); i++) {
673 CFTypeRef dict = CFArrayGetValueAtIndex(usage_pairs, i);
674 if (CFGetTypeID(dict) != CFDictionaryGetTypeID()) {
675 continue;
676 }
677
678 CFTypeRef usage_page_ref, usage_ref;
679 int32_t usage_page, usage;
680
681 if (!CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsagePageKey), &usage_page_ref) ||
682 !CFDictionaryGetValueIfPresent((CFDictionaryRef)dict, CFSTR(kIOHIDDeviceUsageKey), &usage_ref) ||
683 CFGetTypeID(usage_page_ref) != CFNumberGetTypeID() ||
684 CFGetTypeID(usage_ref) != CFNumberGetTypeID() ||
685 !CFNumberGetValue((CFNumberRef)usage_page_ref, kCFNumberSInt32Type, &usage_page) ||
686 !CFNumberGetValue((CFNumberRef)usage_ref, kCFNumberSInt32Type, &usage)) {
687 continue;
688 }
689 if (usage_page == primary_usage_page && usage == primary_usage)
690 continue; /* Already added. */
691
692 next = create_device_info_with_usage(device, usage_page, usage);
693 cur->next = next;
694 if (next != NULL) {
695 cur = next;
696 }
697 }
698 }
699
700 return root;
701 }
702
703 struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
704 {
705 struct hid_device_info *root = NULL; /* return object */
706 struct hid_device_info *cur_dev = NULL;
707 CFIndex num_devices;
708 int i;
709
710 /* Set up the HID Manager if it hasn't been done */
711 if (hid_init() < 0) {
712 return NULL;
713 }
714 /* register_global_error: global error is set/reset by hid_init */
715
716 /* give the IOHIDManager a chance to update itself */
717 process_pending_events();
718
719 /* Get a list of the Devices */
720 CFMutableDictionaryRef matching = NULL;
721 if (vendor_id != 0 || product_id != 0) {
722 matching = CFDictionaryCreateMutable(kCFAllocatorDefault, kIOHIDOptionsTypeNone, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
723
724 if (matching && vendor_id != 0) {
725 CFNumberRef v = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &vendor_id);
726 CFDictionarySetValue(matching, CFSTR(kIOHIDVendorIDKey), v);
727 CFRelease(v);
728 }
729
730 if (matching && product_id != 0) {
731 CFNumberRef p = CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &product_id);
732 CFDictionarySetValue(matching, CFSTR(kIOHIDProductIDKey), p);
733 CFRelease(p);
734 }
735 }
736 IOHIDManagerSetDeviceMatching(hid_mgr, matching);
737 if (matching != NULL) {
738 CFRelease(matching);
739 }
740
741 CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
742
743 IOHIDDeviceRef *device_array = NULL;
744
745 if (device_set != NULL) {
746 /* Convert the list into a C array so we can iterate easily. */
747 num_devices = CFSetGetCount(device_set);
748 device_array = (IOHIDDeviceRef*) calloc(num_devices, sizeof(IOHIDDeviceRef));
749 CFSetGetValues(device_set, (const void **) device_array);
750 } else {
751 num_devices = 0;
752 }
753
754 /* Iterate over each device, making an entry for it. */
755 for (i = 0; i < num_devices; i++) {
756
757 IOHIDDeviceRef dev = device_array[i];
758 if (!dev) {
759 continue;
760 }
761
762 struct hid_device_info *tmp = create_device_info(dev);
763 if (tmp == NULL) {
764 continue;
765 }
766
767 if (cur_dev) {
768 cur_dev->next = tmp;
769 }
770 else {
771 root = tmp;
772 }
773 cur_dev = tmp;
774
775 /* move the pointer to the tail of returned list */
776 while (cur_dev->next != NULL) {
777 cur_dev = cur_dev->next;
778 }
779 }
780
781 free(device_array);
782 if (device_set != NULL)
783 CFRelease(device_set);
784
785 if (root == NULL) {
786 if (vendor_id == 0 && product_id == 0) {
787 register_global_error("No HID devices found in the system.");
788 } else {
789 register_global_error("No HID devices with requested VID/PID found in the system.");
790 }
791 }
792
793 return root;
794 }
795
796 void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
797 {
798 /* This function is identical to the Linux version. Platform independent. */
799 struct hid_device_info *d = devs;
800 while (d) {
801 struct hid_device_info *next = d->next;
802 free(d->path);
803 free(d->serial_number);
804 free(d->manufacturer_string);
805 free(d->product_string);
806 free(d);
807 d = next;
808 }
809 }
810
811 hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
812 {
813 /* This function is identical to the Linux version. Platform independent. */
814
815 struct hid_device_info *devs, *cur_dev;
816 const char *path_to_open = NULL;
817 hid_device * handle = NULL;
818
819 /* register_global_error: global error is reset by hid_enumerate/hid_init */
820 devs = hid_enumerate(vendor_id, product_id);
821 if (devs == NULL) {
822 /* register_global_error: global error is already set by hid_enumerate */
823 return NULL;
824 }
825
826 cur_dev = devs;
827 while (cur_dev) {
828 if (cur_dev->vendor_id == vendor_id &&
829 cur_dev->product_id == product_id) {
830 if (serial_number) {
831 if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
832 path_to_open = cur_dev->path;
833 break;
834 }
835 }
836 else {
837 path_to_open = cur_dev->path;
838 break;
839 }
840 }
841 cur_dev = cur_dev->next;
842 }
843
844 if (path_to_open) {
845 handle = hid_open_path(path_to_open);
846 } else {
847 register_global_error("Device with requested VID/PID/(SerialNumber) not found");
848 }
849
850 hid_free_enumeration(devs);
851
852 return handle;
853 }
854
855 static void hid_device_removal_callback(void *context, IOReturn result,
856 void *sender)
857 {
858 (void) result;
859 (void) sender;
860
861 /* Stop the Run Loop for this device. */
862 hid_device *d = (hid_device*) context;
863
864 d->disconnected = 1;
865 CFRunLoopStop(d->run_loop);
866 }
867
868 /* The Run Loop calls this function for each input report received.
869 This function puts the data into a linked list to be picked up by
870 hid_read(). */
871 static void hid_report_callback(void *context, IOReturn result, void *sender,
872 IOHIDReportType report_type, uint32_t report_id,
873 uint8_t *report, CFIndex report_length)
874 {
875 (void) result;
876 (void) sender;
877 (void) report_type;
878 (void) report_id;
879
880 struct input_report *rpt;
881 hid_device *dev = (hid_device*) context;
882
883 /* Make a new Input Report object */
884 rpt = (struct input_report*) calloc(1, sizeof(struct input_report));
885 rpt->data = (uint8_t*) calloc(1, report_length);
886 memcpy(rpt->data, report, report_length);
887 rpt->len = report_length;
888 rpt->next = NULL;
889
890 /* Lock this section */
891 pthread_mutex_lock(&dev->mutex);
892
893 /* Attach the new report object to the end of the list. */
894 if (dev->input_reports == NULL) {
895 /* The list is empty. Put it at the root. */
896 dev->input_reports = rpt;
897 }
898 else {
899 /* Find the end of the list and attach. */
900 struct input_report *cur = dev->input_reports;
901 int num_queued = 0;
902 while (cur->next != NULL) {
903 cur = cur->next;
904 num_queued++;
905 }
906 cur->next = rpt;
907
908 /* Pop one off if we've reached 30 in the queue. This
909 way we don't grow forever if the user never reads
910 anything from the device. */
911 if (num_queued > 30) {
912 return_data(dev, NULL, 0);
913 }
914 }
915
916 /* Signal a waiting thread that there is data. */
917 pthread_cond_signal(&dev->condition);
918
919 /* Unlock */
920 pthread_mutex_unlock(&dev->mutex);
921
922 }
923
924 /* This gets called when the read_thread's run loop gets signaled by
925 hid_close(), and serves to stop the read_thread's run loop. */
926 static void perform_signal_callback(void *context)
927 {
928 hid_device *dev = (hid_device*) context;
929 CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/
930 }
931
932 static void *read_thread(void *param)
933 {
934 hid_device *dev = (hid_device*) param;
935 SInt32 code;
936
937 /* Move the device's run loop to this thread. */
938 IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode);
939
940 /* Create the RunLoopSource which is used to signal the
941 event loop to stop when hid_close() is called. */
942 CFRunLoopSourceContext ctx;
943 memset(&ctx, 0, sizeof(ctx));
944 ctx.version = 0;
945 ctx.info = dev;
946 ctx.perform = &perform_signal_callback;
947 dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx);
948 CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode);
949
950 /* Store off the Run Loop so it can be stopped from hid_close()
951 and on device disconnection. */
952 dev->run_loop = CFRunLoopGetCurrent();
953
954 /* Notify the main thread that the read thread is up and running. */
955 pthread_barrier_wait(&dev->barrier);
956
957 /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input
958 reports into the hid_report_callback(). */
959 while (!dev->shutdown_thread && !dev->disconnected) {
960 code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE);
961 /* Return if the device has been disconnected */
962 if (code == kCFRunLoopRunFinished || code == kCFRunLoopRunStopped) {
963 dev->disconnected = 1;
964 break;
965 }
966
967
968 /* Break if The Run Loop returns Finished or Stopped. */
969 if (code != kCFRunLoopRunTimedOut &&
970 code != kCFRunLoopRunHandledSource) {
971 /* There was some kind of error. Setting
972 shutdown seems to make sense, but
973 there may be something else more appropriate */
974 dev->shutdown_thread = 1;
975 break;
976 }
977 }
978
979 /* Now that the read thread is stopping, Wake any threads which are
980 waiting on data (in hid_read_timeout()). Do this under a mutex to
981 make sure that a thread which is about to go to sleep waiting on
982 the condition actually will go to sleep before the condition is
983 signaled. */
984 pthread_mutex_lock(&dev->mutex);
985 pthread_cond_broadcast(&dev->condition);
986 pthread_mutex_unlock(&dev->mutex);
987
988 /* Wait here until hid_close() is called and makes it past
989 the call to CFRunLoopWakeUp(). This thread still needs to
990 be valid when that function is called on the other thread. */
991 pthread_barrier_wait(&dev->shutdown_barrier);
992
993 return NULL;
994 }
995
996 /* \p path must be one of:
997 - in format 'DevSrvsID:<RegistryEntryID>' (as returned by hid_enumerate);
998 - a valid path to an IOHIDDevice in the IOService plane (as returned by IORegistryEntryGetPath,
999 e.g.: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver");
1000 Second format is for compatibility with paths accepted by older versions of HIDAPI.
1001 */
1002 static io_registry_entry_t hid_open_service_registry_from_path(const char *path)
1003 {
1004 if (path == NULL)
1005 return MACH_PORT_NULL;
1006
1007 /* Get the IORegistry entry for the given path */
1008 if (strncmp("DevSrvsID:", path, 10) == 0) {
1009 char *endptr;
1010 uint64_t entry_id = strtoull(path + 10, &endptr, 10);
1011 if (*endptr == '\0') {
1012 return IOServiceGetMatchingService((mach_port_t) 0, IORegistryEntryIDMatching(entry_id));
1013 }
1014 }
1015 else {
1016 /* Fallback to older format of the path */
1017 return IORegistryEntryFromPath((mach_port_t) 0, path);
1018 }
1019
1020 return MACH_PORT_NULL;
1021 }
1022
1023 hid_device * HID_API_EXPORT hid_open_path(const char *path)
1024 {
1025 hid_device *dev = NULL;
1026 io_registry_entry_t entry = MACH_PORT_NULL;
1027 IOReturn ret = kIOReturnInvalid;
1028 char str[32];
1029
1030 /* Set up the HID Manager if it hasn't been done */
1031 if (hid_init() < 0) {
1032 return NULL;
1033 }
1034 /* register_global_error: global error is set/reset by hid_init */
1035
1036 dev = new_hid_device();
1037 if (!dev) {
1038 register_global_error("Couldn't allocate memory");
1039 return NULL;
1040 }
1041
1042 /* Get the IORegistry entry for the given path */
1043 entry = hid_open_service_registry_from_path(path);
1044 if (entry == MACH_PORT_NULL) {
1045 /* Path wasn't valid (maybe device was removed?) */
1046 register_global_error("hid_open_path: device mach entry not found with the given path");
1047 goto return_error;
1048 }
1049
1050 /* Create an IOHIDDevice for the entry */
1051 dev->device_handle = IOHIDDeviceCreate(kCFAllocatorDefault, entry);
1052 if (dev->device_handle == NULL) {
1053 /* Error creating the HID device */
1054 register_global_error("hid_open_path: failed to create IOHIDDevice from the mach entry");
1055 goto return_error;
1056 }
1057
1058 /* Open the IOHIDDevice */
1059 ret = IOHIDDeviceOpen(dev->device_handle, dev->open_options);
1060 if (ret != kIOReturnSuccess) {
1061 register_global_error_format("hid_open_path: failed to open IOHIDDevice from mach entry: (0x%08X) %s", ret, mach_error_string(ret));
1062 goto return_error;
1063 }
1064
1065 /* Create the buffers for receiving data */
1066 dev->max_input_report_len = (CFIndex) get_max_report_length(dev->device_handle);
1067 dev->input_report_buf = (uint8_t*) calloc(dev->max_input_report_len, sizeof(uint8_t));
1068
1069 /* Create the Run Loop Mode for this device.
1070 printing the reference seems to work. */
1071 snprintf(str, sizeof(str), "HIDAPI_%p", (void*) dev->device_handle);
1072 dev->run_loop_mode =
1073 CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);
1074
1075 /* Attach the device to a Run Loop */
1076 IOHIDDeviceRegisterInputReportCallback(
1077 dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
1078 &hid_report_callback, dev);
1079 IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev);
1080
1081 /* Start the read thread */
1082 pthread_create(&dev->thread, NULL, read_thread, dev);
1083
1084 /* Wait here for the read thread to be initialized. */
1085 pthread_barrier_wait(&dev->barrier);
1086
1087 IOObjectRelease(entry);
1088 return dev;
1089
1090 return_error:
1091 if (dev->device_handle != NULL)
1092 CFRelease(dev->device_handle);
1093
1094 if (entry != MACH_PORT_NULL)
1095 IOObjectRelease(entry);
1096
1097 free_hid_device(dev);
1098 return NULL;
1099 }
1100
1101 static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length)
1102 {
1103 const unsigned char *data_to_send = data;
1104 CFIndex length_to_send = length;
1105 IOReturn res;
1106 unsigned char report_id;
1107
1108 if (!data || (length == 0)) {
1109 register_device_error(dev, "Zero buffer/length");
1110 return -1;
1111 }
1112
1113 register_device_error(dev, NULL);
1114
1115 report_id = data[0];
1116
1117 if (report_id == 0x0) {
1118 /* Not using numbered Reports.
1119 Don't send the report number. */
1120 data_to_send = data+1;
1121 length_to_send = length-1;
1122 }
1123
1124 /* Avoid crash if the device has been unplugged. */
1125 if (dev->disconnected) {
1126 register_device_error(dev, "Device is disconnected");
1127 return -1;
1128 }
1129
1130 res = IOHIDDeviceSetReport(dev->device_handle,
1131 type,
1132 report_id,
1133 data_to_send, length_to_send);
1134
1135 if (res != kIOReturnSuccess) {
1136 register_device_error_format(dev, "IOHIDDeviceSetReport failed: (0x%08X) %s", res, mach_error_string(res));
1137 return -1;
1138 }
1139
1140 return (int) length;
1141 }
1142
1143 static int get_report(hid_device *dev, IOHIDReportType type, unsigned char *data, size_t length)
1144 {
1145 unsigned char *report = data;
1146 CFIndex report_length = length;
1147 IOReturn res = kIOReturnSuccess;
1148 unsigned char report_id;
1149
1150 if (!data || (length == 0)) {
1151 register_device_error(dev, "Zero buffer/length");
1152 return -1;
1153 }
1154
1155 register_device_error(dev, NULL);
1156
1157 report_id = data[0];
1158
1159 if (report_id == 0x0) {
1160 /* Not using numbered Reports.
1161 Don't send the report number. */
1162 report = data+1;
1163 report_length = length-1;
1164 }
1165
1166 /* Avoid crash if the device has been unplugged. */
1167 if (dev->disconnected) {
1168 register_device_error(dev, "Device is disconnected");
1169 return -1;
1170 }
1171
1172 res = IOHIDDeviceGetReport(dev->device_handle,
1173 type,
1174 report_id,
1175 report, &report_length);
1176
1177 if (res != kIOReturnSuccess) {
1178 register_device_error_format(dev, "IOHIDDeviceGetReport failed: (0x%08X) %s", res, mach_error_string(res));
1179 return -1;
1180 }
1181
1182 if (report_id == 0x0) { /* 0 report number still present at the beginning */
1183 report_length++;
1184 }
1185
1186 return (int) report_length;
1187 }
1188
1189 int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
1190 {
1191 return set_report(dev, kIOHIDReportTypeOutput, data, length);
1192 }
1193
1194 /* Helper function, so that this isn't duplicated in hid_read(). */
1195 static int return_data(hid_device *dev, unsigned char *data, size_t length)
1196 {
1197 /* Copy the data out of the linked list item (rpt) into the
1198 return buffer (data), and delete the liked list item. */
1199 struct input_report *rpt = dev->input_reports;
1200 size_t len = (length < rpt->len)? length: rpt->len;
1201 if (data != NULL) {
1202 memcpy(data, rpt->data, len);
1203 }
1204 dev->input_reports = rpt->next;
1205 free(rpt->data);
1206 free(rpt);
1207 return (int) len;
1208 }
1209
1210 static int cond_wait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex)
1211 {
1212 while (!dev->input_reports) {
1213 int res = pthread_cond_wait(cond, mutex);
1214 if (res != 0)
1215 return res;
1216
1217 /* A res of 0 means we may have been signaled or it may
1218 be a spurious wakeup. Check to see that there's actually
1219 data in the queue before returning, and if not, go back
1220 to sleep. See the pthread_cond_timedwait() man page for
1221 details. */
1222
1223 if (dev->shutdown_thread || dev->disconnected) {
1224 return -1;
1225 }
1226 }
1227
1228 return 0;
1229 }
1230
1231 static int cond_timedwait(hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
1232 {
1233 while (!dev->input_reports) {
1234 int res = pthread_cond_timedwait(cond, mutex, abstime);
1235 if (res != 0)
1236 return res;
1237
1238 /* A res of 0 means we may have been signaled or it may
1239 be a spurious wakeup. Check to see that there's actually
1240 data in the queue before returning, and if not, go back
1241 to sleep. See the pthread_cond_timedwait() man page for
1242 details. */
1243
1244 if (dev->shutdown_thread || dev->disconnected) {
1245 return -1;
1246 }
1247 }
1248
1249 return 0;
1250 }
1251
1252 int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
1253 {
1254 int bytes_read = -1;
1255
1256 if (!data || (length == 0)) {
1257 register_error_str(&dev->last_read_error_str, "Zero buffer/length");
1258 return -1;
1259 }
1260
1261 register_error_str(&dev->last_read_error_str, NULL);
1262
1263 /* Lock the access to the report list. */
1264 pthread_mutex_lock(&dev->mutex);
1265
1266 /* There's an input report queued up. Return it. */
1267 if (dev->input_reports) {
1268 /* Return the first one */
1269 bytes_read = return_data(dev, data, length);
1270 goto ret;
1271 }
1272
1273 /* Return if the device has been disconnected. */
1274 if (dev->disconnected) {
1275 bytes_read = -1;
1276 register_error_str(&dev->last_read_error_str, "hid_read_timeout: device disconnected");
1277 goto ret;
1278 }
1279
1280 if (dev->shutdown_thread) {
1281 /* This means the device has been closed (or there
1282 has been an error. An error code of -1 should
1283 be returned. */
1284 bytes_read = -1;
1285 register_error_str(&dev->last_read_error_str, "hid_read_timeout: thread shutdown");
1286 goto ret;
1287 }
1288
1289 /* There is no data. Go to sleep and wait for data. */
1290
1291 if (milliseconds == -1) {
1292 /* Blocking */
1293 int res;
1294 res = cond_wait(dev, &dev->condition, &dev->mutex);
1295 if (res == 0)
1296 bytes_read = return_data(dev, data, length);
1297 else {
1298 /* There was an error, or a device disconnection. */
1299 register_error_str(&dev->last_read_error_str, "hid_read_timeout: error waiting for more data");
1300 bytes_read = -1;
1301 }
1302 }
1303 else if (milliseconds > 0) {
1304 /* Non-blocking, but called with timeout. */
1305 int res;
1306 struct timespec ts;
1307 struct timeval tv;
1308 gettimeofday(&tv, NULL);
1309 TIMEVAL_TO_TIMESPEC(&tv, &ts);
1310 ts.tv_sec += milliseconds / 1000;
1311 ts.tv_nsec += (milliseconds % 1000) * 1000000;
1312 if (ts.tv_nsec >= 1000000000L) {
1313 ts.tv_sec++;
1314 ts.tv_nsec -= 1000000000L;
1315 }
1316
1317 res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts);
1318 if (res == 0) {
1319 bytes_read = return_data(dev, data, length);
1320 } else if (res == ETIMEDOUT) {
1321 bytes_read = 0;
1322 } else {
1323 register_error_str(&dev->last_read_error_str, "hid_read_timeout: error waiting for more data");
1324 bytes_read = -1;
1325 }
1326 }
1327 else {
1328 /* Purely non-blocking */
1329 bytes_read = 0;
1330 }
1331
1332 ret:
1333 /* Unlock */
1334 pthread_mutex_unlock(&dev->mutex);
1335 return bytes_read;
1336 }
1337
1338 int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
1339 {
1340 return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
1341 }
1342
1343 HID_API_EXPORT const wchar_t * HID_API_CALL hid_read_error(hid_device *dev)
1344 {
1345 if (dev->last_read_error_str == NULL)
1346 return L"Success";
1347 return dev->last_read_error_str;
1348 }
1349
1350 int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
1351 {
1352 /* All Nonblocking operation is handled by the library. */
1353 dev->blocking = !nonblock;
1354
1355 return 0;
1356 }
1357
1358 int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
1359 {
1360 return set_report(dev, kIOHIDReportTypeFeature, data, length);
1361 }
1362
1363 int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
1364 {
1365 return get_report(dev, kIOHIDReportTypeFeature, data, length);
1366 }
1367
1368 int HID_API_EXPORT hid_send_output_report(hid_device *dev, const unsigned char *data, size_t length)
1369 {
1370 return set_report(dev, kIOHIDReportTypeOutput, data, length);
1371 }
1372
1373 int HID_API_EXPORT HID_API_CALL hid_get_input_report(hid_device *dev, unsigned char *data, size_t length)
1374 {
1375 return get_report(dev, kIOHIDReportTypeInput, data, length);
1376 }
1377
1378 void HID_API_EXPORT hid_close(hid_device *dev)
1379 {
1380 if (!dev)
1381 return;
1382
1383 /* Disconnect the report callback before close.
1384 See comment below.
1385 */
1386 if (is_macos_10_10_or_greater || !dev->disconnected) {
1387 IOHIDDeviceRegisterInputReportCallback(
1388 dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
1389 NULL, dev);
1390 IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev);
1391 IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode);
1392 IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
1393 }
1394
1395 /* Cause read_thread() to stop. */
1396 dev->shutdown_thread = 1;
1397
1398 /* Wake up the run thread's event loop so that the thread can exit. */
1399 CFRunLoopSourceSignal(dev->source);
1400 CFRunLoopWakeUp(dev->run_loop);
1401
1402 /* Notify the read thread that it can shut down now. */
1403 pthread_barrier_wait(&dev->shutdown_barrier);
1404
1405 /* Wait for read_thread() to end. */
1406 pthread_join(dev->thread, NULL);
1407
1408 /* Close the OS handle to the device, but only if it's not
1409 been unplugged. If it's been unplugged, then calling
1410 IOHIDDeviceClose() will crash.
1411
1412 UPD: The crash part was true in/until some version of macOS.
1413 Starting with macOS 10.15, there is an opposite effect in some environments:
1414 crash happenes if IOHIDDeviceClose() is not called.
1415 Not leaking a resource in all tested environments.
1416 */
1417 if (is_macos_10_10_or_greater || !dev->disconnected) {
1418 IOHIDDeviceClose(dev->device_handle, dev->open_options);
1419 }
1420
1421 /* Clear out the queue of received reports. */
1422 pthread_mutex_lock(&dev->mutex);
1423 while (dev->input_reports) {
1424 return_data(dev, NULL, 0);
1425 }
1426 pthread_mutex_unlock(&dev->mutex);
1427 CFRelease(dev->device_handle);
1428
1429 free_hid_device(dev);
1430 }
1431
1432 int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
1433 {
1434 if (!string || !maxlen)
1435 {
1436 register_device_error(dev, "Zero buffer/length");
1437 return -1;
1438 }
1439
1440 struct hid_device_info *info = hid_get_device_info(dev);
1441 if (!info)
1442 {
1443 // hid_get_device_info will have set an error already
1444 return -1;
1445 }
1446
1447 wcsncpy(string, info->manufacturer_string, maxlen);
1448 string[maxlen - 1] = L'\0';
1449
1450 return 0;
1451 }
1452
1453 int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
1454 {
1455 if (!string || !maxlen) {
1456 register_device_error(dev, "Zero buffer/length");
1457 return -1;
1458 }
1459
1460 struct hid_device_info *info = hid_get_device_info(dev);
1461 if (!info) {
1462 // hid_get_device_info will have set an error already
1463 return -1;
1464 }
1465
1466 wcsncpy(string, info->product_string, maxlen);
1467 string[maxlen - 1] = L'\0';
1468
1469 return 0;
1470 }
1471
1472 int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
1473 {
1474 if (!string || !maxlen) {
1475 register_device_error(dev, "Zero buffer/length");
1476 return -1;
1477 }
1478
1479 struct hid_device_info *info = hid_get_device_info(dev);
1480 if (!info) {
1481 // hid_get_device_info will have set an error already
1482 return -1;
1483 }
1484
1485 wcsncpy(string, info->serial_number, maxlen);
1486 string[maxlen - 1] = L'\0';
1487
1488 return 0;
1489 }
1490
1491 HID_API_EXPORT struct hid_device_info *HID_API_CALL hid_get_device_info(hid_device *dev) {
1492 if (dev->device_info) {
1493 register_device_error(dev, NULL);
1494 }
1495 else {
1496 dev->device_info = create_device_info(dev->device_handle);
1497 if (!dev->device_info) {
1498 register_device_error(dev, "Failed to create hid_device_info");
1499 }
1500 }
1501
1502 return dev->device_info;
1503 }
1504
1505 int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
1506 {
1507 (void) dev;
1508 (void) string_index;
1509 (void) string;
1510 (void) maxlen;
1511
1512 register_device_error(dev, "hid_get_indexed_string: not available on this platform");
1513 return -1;
1514 }
1515
1516 int HID_API_EXPORT_CALL hid_darwin_get_location_id(hid_device *dev, uint32_t *location_id)
1517 {
1518 if (!location_id) {
1519 register_device_error(dev, "Location ID is NULL");
1520 return -1;
1521 }
1522
1523 register_device_error(dev, NULL);
1524
1525 int res = get_int_property(dev->device_handle, CFSTR(kIOHIDLocationIDKey));
1526 if (res != 0) {
1527 *location_id = (uint32_t) res;
1528 return 0;
1529 } else {
1530 register_device_error(dev, "Failed to get IOHIDLocationID property");
1531 return -1;
1532 }
1533 }
1534
1535 void HID_API_EXPORT_CALL hid_darwin_set_open_exclusive(int open_exclusive)
1536 {
1537 device_open_options = (open_exclusive == 0) ? kIOHIDOptionsTypeNone : kIOHIDOptionsTypeSeizeDevice;
1538 }
1539
1540 int HID_API_EXPORT_CALL hid_darwin_get_open_exclusive(void)
1541 {
1542 return (device_open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0;
1543 }
1544
1545 int HID_API_EXPORT_CALL hid_darwin_is_device_open_exclusive(hid_device *dev)
1546 {
1547 return (dev->open_options == kIOHIDOptionsTypeSeizeDevice) ? 1 : 0;
1548 }
1549
1550 int HID_API_EXPORT_CALL hid_get_report_descriptor(hid_device *dev, unsigned char *buf, size_t buf_size)
1551 {
1552 if (!buf || !buf_size) {
1553 register_device_error(dev, "Zero buffer/length");
1554 return -1;
1555 }
1556
1557 register_device_error(dev, NULL);
1558
1559 CFTypeRef ref = IOHIDDeviceGetProperty(dev->device_handle, CFSTR(kIOHIDReportDescriptorKey));
1560 if (ref != NULL && CFGetTypeID(ref) == CFDataGetTypeID()) {
1561 CFDataRef report_descriptor = (CFDataRef) ref;
1562 const UInt8 *descriptor_buf = CFDataGetBytePtr(report_descriptor);
1563 const CFIndex descriptor_buf_len = CFDataGetLength(report_descriptor);
1564 size_t copy_len = (size_t) descriptor_buf_len;
1565
1566 if (descriptor_buf == NULL || descriptor_buf_len < 0) {
1567 register_device_error(dev, "Zero descriptor from device");
1568 return -1;
1569 }
1570
1571 if (buf_size < copy_len) {
1572 copy_len = buf_size;
1573 }
1574
1575 memcpy(buf, descriptor_buf, copy_len);
1576 return copy_len;
1577 }
1578 else {
1579 register_device_error(dev, "Failed to get kIOHIDReportDescriptorKey property");
1580 return -1;
1581 }
1582 }
1583
1584 HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
1585 {
1586 if (dev) {
1587 if (dev->last_error_str == NULL)
1588 return L"Success";
1589 return dev->last_error_str;
1590 }
1591
1592 if (last_global_error_str == NULL)
1593 return L"Success";
1594 return last_global_error_str;
1595 }