Debian Codegraph @

libusb/os/darwin_usb.c

raw
1 /* -*- Mode: C; indent-tabs-mode:nil -*- */
2 /*
3 * darwin backend for libusb 1.0
4 * Copyright © 2008-2023 Nathan Hjelm <[email protected]>
5 * Copyright © 2019-2023 Google LLC. All rights reserved.
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include <config.h>
23 #include <assert.h>
24 #include <time.h>
25 #include <ctype.h>
26 #include <pthread.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <sys/sysctl.h>
34
35 #include <mach/mach_time.h>
36
37 /* Suppress warnings about the use of the deprecated objc_registerThreadWithCollector
38 * function. Its use is also conditionalized to only older deployment targets. */
39 #define OBJC_SILENCE_GC_DEPRECATIONS 1
40
41 /* Default timeout to 10s for reenumerate. This is needed because USBDeviceReEnumerate
42 * does not return error status on macOS. */
43 #define DARWIN_REENUMERATE_TIMEOUT_US (10ULL * USEC_PER_SEC)
44
45 #include <AvailabilityMacros.h>
46 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
47 #include <objc/objc-auto.h>
48 #endif
49
50 #include "darwin_usb.h"
51
52 /* Both kIOMasterPortDefault or kIOMainPortDefault are synonyms for 0. */
53 static const mach_port_t darwin_default_master_port = 0;
54
55 /* async event thread */
56 /* if both this mutex and darwin_cached_devices_mutex are to be acquired then
57 darwin_cached_devices_mutex must be acquired first. */
58 static usbi_mutex_static_t libusb_darwin_at_mutex = USBI_MUTEX_INITIALIZER;
59 static usbi_cond_t libusb_darwin_at_cond = USBI_COND_INITIALIZER;
60
61 #define LIBUSB_DARWIN_STARTUP_FAILURE ((CFRunLoopRef) -1)
62
63 static CFRunLoopRef libusb_darwin_acfl = NULL; /* event cf loop */
64 static CFRunLoopSourceRef libusb_darwin_acfls = NULL; /* shutdown signal for event cf loop */
65
66 static usbi_mutex_t darwin_cached_devices_mutex = USBI_MUTEX_INITIALIZER;
67 static struct list_head darwin_cached_devices;
68 static int init_count;
69
70 static const char *darwin_device_class = "IOUSBDevice";
71
72 uint32_t libusb_testonly_fake_running_version __attribute__ ((visibility ("hidden")));
73 uint32_t libusb_testonly_using_running_interface_version __attribute__ ((visibility ("hidden")));
74 uint32_t libusb_testonly_using_running_device_version __attribute__ ((visibility ("hidden")));
75 bool libusb_testonly_clear_running_version_cache __attribute__ ((visibility ("hidden")));
76
77 #define DARWIN_CACHED_DEVICE(a) (((struct darwin_device_priv *)usbi_get_device_priv((a)))->dev)
78
79 /* async event thread */
80 static pthread_t libusb_darwin_at;
81
82 /* protected by libusb_darwin_at_mutex */
83 static bool libusb_darwin_at_started;
84
85 static void darwin_exit(struct libusb_context *ctx);
86 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len);
87 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
88 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface);
89 static int darwin_reenumerate_device(struct libusb_device_handle *dev_handle, bool capture);
90 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint);
91 static int darwin_reset_device(struct libusb_device_handle *dev_handle);
92 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface);
93 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0);
94
95 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx);
96 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
97 UInt64 old_session_id);
98
99 static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service, struct darwin_cached_device **cached_out,
100 UInt64 *old_session_id);
101
102 struct darwin_iokit_interface {
103 uint32_t min_os_version;
104 uint32_t version;
105 CFUUIDRef interface_id;
106 };
107
108 static const struct darwin_iokit_interface *get_interface_interface(void) {
109 const struct darwin_iokit_interface interfaces[] = {
110 #if defined(kIOUSBInterfaceInterfaceID800)
111 {
112 .min_os_version = 101200,
113 .version = 800,
114 .interface_id = kIOUSBInterfaceInterfaceID800,
115 },
116 #endif
117 #if defined(kIOUSBInterfaceInterfaceID700)
118 {
119 .min_os_version = 101000,
120 .version = 700,
121 .interface_id = kIOUSBInterfaceInterfaceID700,
122 },
123 #endif
124 #if defined(kIOUSBInterfaceInterfaceID650)
125 {
126 .min_os_version = 100900,
127 .version = 650,
128 .interface_id = kIOUSBInterfaceInterfaceID650
129 },
130 #endif
131 #if defined(kIOUSBInterfaceInterfaceID550)
132 {
133 .min_os_version = 100803,
134 .version = 550,
135 .interface_id = kIOUSBInterfaceInterfaceID550,
136 },
137 #endif
138 #if defined(kIOUSBInterfaceInterfaceID245)
139 {
140 .min_os_version = 100407,
141 .version = 245,
142 .interface_id = kIOUSBInterfaceInterfaceID245,
143 },
144 #endif
145 {
146 .min_os_version = 100000,
147 .version = 220,
148 .interface_id = kIOUSBInterfaceInterfaceID220,
149 },
150 {
151 .version = 0,
152 },
153 };
154 static struct darwin_iokit_interface cached_interface = {.version = 0};
155 if (libusb_testonly_clear_running_version_cache) {
156 memset (&cached_interface, 0, sizeof (cached_interface));
157 }
158 if (0 == cached_interface.version) {
159 uint32_t os_version = get_running_version();
160 for (int i = 0 ; interfaces[i].version > 0 ; ++i) {
161 if (os_version >= interfaces[i].min_os_version && cached_interface.min_os_version < interfaces[i].min_os_version) {
162 cached_interface = interfaces[i];
163 }
164 }
165
166 libusb_testonly_using_running_interface_version = cached_interface.version;
167 }
168
169 return &cached_interface;
170 }
171
172 static CFUUIDRef get_interface_interface_id(void) {
173 return get_interface_interface()->interface_id;
174 }
175
176 static uint32_t get_interface_interface_version(void) {
177 return get_interface_interface()->version;
178 }
179
180 static const struct darwin_iokit_interface *get_device_interface(void) {
181 struct darwin_iokit_interface interfaces[] = {
182 #if defined(kIOUSBDeviceInterfaceID650)
183 {
184 .min_os_version = 100900,
185 .version = 650,
186 .interface_id = kIOUSBDeviceInterfaceID650,
187 },
188 #endif
189 #if defined(kIOUSBDeviceInterfaceID500)
190 {
191 .min_os_version = 100703,
192 .version = 500,
193 .interface_id = kIOUSBDeviceInterfaceID500,
194 },
195 #endif
196 #if defined(kIOUSBDeviceInterfaceID320)
197 {
198 .min_os_version = 100504,
199 .version = 320,
200 .interface_id = kIOUSBDeviceInterfaceID320,
201 },
202 #endif
203 #if defined(kIOUSBDeviceInterfaceID300)
204 {
205 .min_os_version = 100500,
206 .version = 300,
207 .interface_id = kIOUSBDeviceInterfaceID300,
208 },
209 #endif
210 #if defined(kIOUSBDeviceInterfaceID245)
211 {
212 .min_os_version = 100407,
213 .version = 245,
214 .interface_id = kIOUSBDeviceInterfaceID245,
215 },
216 #endif
217 {
218 .min_os_version = 100000,
219 .version = 197,
220 .interface_id = kIOUSBDeviceInterfaceID197,
221 },
222 {
223 .version = 0,
224 },
225 };
226 static struct darwin_iokit_interface cached_interface = {.version = 0};
227 if (libusb_testonly_clear_running_version_cache) {
228 memset (&cached_interface, 0, sizeof (cached_interface));
229 }
230 if (0 == cached_interface.version) {
231 uint32_t os_version = get_running_version();
232 for (int i = 0 ; interfaces[i].version > 0 ; ++i) {
233 if (os_version >= interfaces[i].min_os_version && cached_interface.min_os_version < interfaces[i].min_os_version) {
234 cached_interface = interfaces[i];
235 }
236 }
237 libusb_testonly_using_running_device_version = cached_interface.version;
238 }
239
240 return &cached_interface;
241 }
242
243 static CFUUIDRef get_device_interface_id(void) {
244 return get_device_interface()->interface_id;
245 }
246
247 static uint32_t get_device_interface_version(void) {
248 return get_device_interface()->version;
249 }
250
251 struct darwin_pipe_properties {
252 uint8_t number;
253 uint8_t direction;
254 uint8_t transfer_type;
255 uint16_t max_packet_size; // without multipliers, not "full"
256 uint8_t interval;
257 };
258 typedef struct darwin_pipe_properties darwin_pipe_properties_t;
259
260 static IOReturn darwin_get_pipe_properties(struct darwin_interface *cInterface, uint8_t pipe, darwin_pipe_properties_t *out) {
261 IOReturn kresult;
262
263 #if (MAX_INTERFACE_VERSION >= 550)
264 if (get_interface_interface_version() >= 550) {
265 // GetPipePropertiesV3 returns a "cooked" wMaxPacketSize (premultiplied by burst and mul). This not what we want.
266 // We only call GetPipePropertiesV3 to fill the fields needed to call GetEndpointPropertiesV3.
267 IOUSBEndpointProperties pipe_properties = {.bVersion = kUSBEndpointPropertiesVersion3};
268 kresult = (*IOINTERFACE_V(cInterface, 550))->GetPipePropertiesV3 (IOINTERFACE(cInterface), pipe, &pipe_properties);
269 if (kIOReturnSuccess != kresult) {
270 return kresult;
271 }
272
273 // GetEndpointPropertiesV3 returns the wMaxPacketSize without burst and mul multipliers.
274 kresult = (*IOINTERFACE_V(cInterface, 550))->GetEndpointPropertiesV3 (IOINTERFACE(cInterface), &pipe_properties);
275 if (kIOReturnSuccess == kresult) {
276 out->number = pipe_properties.bEndpointNumber;
277 out->direction = pipe_properties.bDirection;
278 out->transfer_type = pipe_properties.bTransferType;
279 out->max_packet_size = pipe_properties.wMaxPacketSize;
280 out->interval = pipe_properties.bInterval;
281 }
282 return kresult;
283 }
284 #endif
285 // GetPipeProperties returns a "cooked" version of max_packet_size which includes burst and mul. What we want is the
286 // original maxPacketSize so we can send zero-length packet when requested by users.
287 // We only call GetPipeProperties to retrieve the parameters needed to call GetEndpointProperties.
288 kresult = (*IOINTERFACE(cInterface))->GetPipeProperties(IOINTERFACE(cInterface), pipe, &out->direction,
289 &out->number, &out->transfer_type, &out->max_packet_size,
290 &out->interval);
291 if (kIOReturnSuccess != kresult) {
292 return kresult;
293 }
294
295 // To call GetEndpointProperties we also need altSetting
296 UInt8 altSetting;
297 kresult = (*IOINTERFACE(cInterface))->GetAlternateSetting(IOINTERFACE(cInterface), &altSetting);
298 if (kIOReturnSuccess != kresult) {
299 return kresult;
300 }
301 // Retrieve "uncooked" version of maxPacketSize
302 return (*IOINTERFACE(cInterface))->GetEndpointProperties(IOINTERFACE(cInterface), altSetting, out->number,
303 out->direction, &out->transfer_type, &out->max_packet_size,
304 &out->interval);
305 }
306
307 #if defined(ENABLE_LOGGING)
308 static const char *darwin_error_str (IOReturn result) {
309 static char string_buffer[50];
310 switch (result) {
311 case kIOReturnSuccess:
312 return "no error";
313 case kIOReturnNotOpen:
314 return "device not opened for exclusive access";
315 case kIOReturnNoDevice:
316 return "no connection to an IOService";
317 case kIOUSBNoAsyncPortErr:
318 return "no async port has been opened for interface";
319 case kIOReturnExclusiveAccess:
320 return "another process has device opened for exclusive access";
321 case kIOUSBPipeStalled:
322 #if defined(kUSBHostReturnPipeStalled)
323 case kUSBHostReturnPipeStalled:
324 #endif
325 return "pipe is stalled";
326 case kIOReturnError:
327 return "could not establish a connection to the Darwin kernel";
328 case kIOUSBTransactionTimeout:
329 return "transaction timed out";
330 case kIOReturnBadArgument:
331 return "invalid argument";
332 case kIOReturnAborted:
333 return "transaction aborted";
334 case kIOReturnNotResponding:
335 return "device not responding";
336 case kIOReturnOverrun:
337 return "data overrun";
338 case kIOReturnCannotWire:
339 return "physical memory can not be wired down";
340 case kIOReturnNoResources:
341 return "out of resources";
342 case kIOUSBHighSpeedSplitError:
343 return "high speed split error";
344 case kIOUSBUnknownPipeErr:
345 return "pipe ref not recognized";
346 default:
347 snprintf(string_buffer, sizeof(string_buffer), "unknown error (0x%x)", result);
348 return string_buffer;
349 }
350 }
351 #endif
352
353 static enum libusb_error darwin_to_libusb (IOReturn result) {
354 switch (result) {
355 case kIOReturnUnderrun:
356 case kIOReturnSuccess:
357 return LIBUSB_SUCCESS;
358 case kIOReturnNotOpen:
359 case kIOReturnNoDevice:
360 return LIBUSB_ERROR_NO_DEVICE;
361 case kIOReturnExclusiveAccess:
362 return LIBUSB_ERROR_ACCESS;
363 case kIOUSBPipeStalled:
364 #if defined(kUSBHostReturnPipeStalled)
365 case kUSBHostReturnPipeStalled:
366 #endif
367 return LIBUSB_ERROR_PIPE;
368 case kIOReturnBadArgument:
369 return LIBUSB_ERROR_INVALID_PARAM;
370 case kIOUSBTransactionTimeout:
371 return LIBUSB_ERROR_TIMEOUT;
372 case kIOUSBUnknownPipeErr:
373 return LIBUSB_ERROR_NOT_FOUND;
374 case kIOReturnNotResponding:
375 case kIOReturnAborted:
376 case kIOReturnError:
377 case kIOUSBNoAsyncPortErr:
378 default:
379 return LIBUSB_ERROR_OTHER;
380 }
381 }
382
383 uint32_t get_running_version(void) {
384 if (libusb_testonly_fake_running_version > 0) {
385 return libusb_testonly_fake_running_version;
386 }
387
388 int ret;
389 #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
390 char os_version_string[64] = {'\0'};;
391 size_t os_version_string_len = sizeof(os_version_string) - 1;
392
393 /* newer versions of macOS provide a sysctl for the OS version but this is not useful for iOS without
394 * code detecting this is iOS and a mapping from iOS -> macOS version. it is still useful to have since
395 * it provides the exact macOS version instead of the approximate version (as below). */
396 ret = sysctlbyname("kern.osproductversion", os_version_string, &os_version_string_len, NULL, 0);
397 if (ret == 0) {
398 unsigned int major = 10, minor = 0, patch = 0;
399 ret = sscanf(os_version_string, "%u.%u.%u", &major, &minor, &patch);
400 if (ret < 2) {
401 usbi_err (NULL, "could not determine the running OS version, assuming 10.0, kern.osproductversion=%s", os_version_string);
402 return 10 * 10000;
403 }
404 return (major * 10000) + (minor * 100) + patch;
405 }
406 #endif
407
408 char os_release_string[64] = {'\0'};
409 size_t os_release_string_len = sizeof(os_release_string) - 1;
410 /* if the version can not be detected libusb assumes 10.0 so ignore any error here */
411 ret = sysctlbyname("kern.osrelease", os_release_string, &os_release_string_len, NULL, 0);
412 if (ret != 0) {
413 usbi_err (NULL, "could not read kern.osrelease, errno=", errno);
414 return 10 * 10000;
415 }
416
417 unsigned int darwin_major = 1, darwin_minor = 0;
418 ret = sscanf(os_release_string, "%u.%u", &darwin_major, &darwin_minor);
419 if (ret < 1) {
420 usbi_err (NULL, "could not determine the running Darwin version, assuming 1.3 (OS X 10.0), kern.osrelease=%s", os_release_string);
421 return 10 * 10000;
422 }
423
424 unsigned int major = 10, minor = 0, patch = 0;
425
426 if (1 == darwin_major && darwin_minor < 4) {
427 /* 10.0.x */
428 } else if (darwin_major < 6) {
429 /* assume 10.1 for anything in this range */
430 minor = 1;
431 } else if (darwin_major < 20) {
432 /* from macOS 10.2 through 10.15 the minor version can be calculated from the darwin_major by subtracting 4 and
433 * the patch level almost always matches darwin_minor. when the darwin_minor does not match the OS X patch level
434 * it is usually because Apple did not change it in a particular point release. when darwin_minor is changed it
435 * always matches the OS X/macOS patch level. */
436 minor = darwin_major - 4;
437 patch = darwin_minor;
438 } else {
439 /* unlikely to be used as kern.osproductversion is available from 10.10 on */
440 major = darwin_major - 9;
441 minor = darwin_minor;
442 /* ignore the patch level in this range */
443 }
444
445 return (major * 10000) + (minor * 100) + patch;
446 }
447
448 /* this function must be called with the darwin_cached_devices_mutex held */
449 static void darwin_deref_cached_device(struct darwin_cached_device *cached_dev) {
450 cached_dev->refcount--;
451 /* free the device and remove it from the cache */
452 if (0 == cached_dev->refcount) {
453 list_del(&cached_dev->list);
454
455 if (cached_dev->device) {
456 (*cached_dev->device)->Release(cached_dev->device);
457 cached_dev->device = NULL;
458 }
459 IOObjectRelease (cached_dev->service);
460 free (cached_dev);
461 }
462 }
463
464 static void darwin_ref_cached_device(struct darwin_cached_device *cached_dev) {
465 cached_dev->refcount++;
466 }
467
468 static int ep_to_pipeRef(struct libusb_device_handle *dev_handle, uint8_t ep, uint8_t *pipep, uint8_t *ifcp, struct darwin_interface **interface_out) {
469 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
470
471 /* current interface */
472 struct darwin_interface *cInterface;
473
474 uint8_t i, iface;
475
476 struct libusb_context *ctx = HANDLE_CTX(dev_handle);
477
478 usbi_dbg (ctx, "converting ep address 0x%02x to pipeRef and interface", ep);
479
480 usbi_mutex_lock(&dev_handle->lock);
481 for (iface = 0 ; iface < USB_MAXINTERFACES ; iface++) {
482 cInterface = &priv->interfaces[iface];
483
484 if (dev_handle->claimed_interfaces & (1U << iface)) {
485 for (i = 0 ; i < cInterface->num_endpoints ; i++) {
486 if (cInterface->endpoint_addrs[i] == ep) {
487 *pipep = i + 1;
488
489 if (ifcp)
490 *ifcp = iface;
491
492 if (interface_out)
493 *interface_out = cInterface;
494
495 usbi_dbg (ctx, "pipe %d on interface %d matches", *pipep, iface);
496 usbi_mutex_unlock(&dev_handle->lock);
497 return LIBUSB_SUCCESS;
498 }
499 }
500 }
501 }
502
503 /* No pipe found with the correct endpoint address */
504 usbi_warn (HANDLE_CTX(dev_handle), "no pipeRef found with endpoint address 0x%02x.", ep);
505
506 usbi_mutex_unlock(&dev_handle->lock);
507
508 return LIBUSB_ERROR_NOT_FOUND;
509 }
510
511 static IOReturn usb_setup_device_iterator (io_iterator_t *deviceIterator, UInt32 location) {
512 CFMutableDictionaryRef matchingDict = IOServiceMatching(darwin_device_class);
513
514 if (!matchingDict)
515 return kIOReturnError;
516
517 if (location) {
518 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
519 &kCFTypeDictionaryKeyCallBacks,
520 &kCFTypeDictionaryValueCallBacks);
521
522 /* there are no unsigned CFNumber types so treat the value as signed. the OS seems to do this
523 internally (CFNumberType of locationID is kCFNumberSInt32Type) */
524 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
525
526 if (propertyMatchDict && locationCF) {
527 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
528 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
529 }
530 /* else we can still proceed as long as the caller accounts for the possibility of other devices in the iterator */
531
532 /* release our references as per the Create Rule */
533 if (propertyMatchDict)
534 CFRelease (propertyMatchDict);
535 if (locationCF)
536 CFRelease (locationCF);
537 }
538
539 return IOServiceGetMatchingServices(darwin_default_master_port, matchingDict, deviceIterator);
540 }
541
542 /* Returns 1 on success, 0 on failure. */
543 static bool get_ioregistry_value_number (io_service_t service, CFStringRef property, CFNumberType type, void *p) {
544 CFTypeRef cfNumber = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
545 Boolean success = 0;
546
547 if (cfNumber) {
548 if (CFGetTypeID(cfNumber) == CFNumberGetTypeID()) {
549 success = CFNumberGetValue(cfNumber, type, p);
550 }
551
552 CFRelease (cfNumber);
553 }
554
555 return (success != 0);
556 }
557
558 /* Returns 1 on success, 0 on failure. */
559 static bool get_ioregistry_value_data (io_service_t service, CFStringRef property, ssize_t size, void *p) {
560 CFTypeRef cfData = IORegistryEntryCreateCFProperty (service, property, kCFAllocatorDefault, 0);
561 bool success = false;
562
563 if (cfData) {
564 if (CFGetTypeID (cfData) == CFDataGetTypeID ()) {
565 CFIndex length = CFDataGetLength (cfData);
566 if (length < size) {
567 size = length;
568 }
569
570 CFDataGetBytes (cfData, CFRangeMake(0, size), p);
571 success = true;
572 }
573
574 CFRelease (cfData);
575 }
576
577 return success;
578 }
579
580 static int darwin_device_from_service (struct libusb_context *ctx, io_service_t service, usb_device_t* device)
581 {
582 io_cf_plugin_ref_t *plugInInterface = NULL;
583 IOReturn kresult;
584 SInt32 score;
585
586 const int max_retries = 5;
587
588 /* The IOCreatePlugInInterfaceForService function might consistently return
589 an "out of resources" error with certain USB devices the first time we run
590 it. The reason is still unclear, but retrying fixes the problem */
591 for (int count = 0; count < max_retries; count++) {
592 kresult = IOCreatePlugInInterfaceForService(service, kIOUSBDeviceUserClientTypeID,
593 kIOCFPlugInInterfaceID, &plugInInterface,
594 &score);
595 if (kIOReturnSuccess == kresult && plugInInterface) {
596 break;
597 }
598
599 usbi_dbg (ctx, "set up plugin for service retry: %s", darwin_error_str (kresult));
600
601 /* sleep for a little while before trying again */
602 const struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
603 nanosleep(&delay, NULL);
604 }
605
606 if (kIOReturnSuccess != kresult) {
607 usbi_dbg (ctx, "could not set up plugin for service: %s", darwin_error_str (kresult));
608 return darwin_to_libusb(kresult);
609 }
610 if (!plugInInterface) {
611 usbi_dbg (ctx, "could not set up plugin for service");
612 return LIBUSB_ERROR_OTHER;
613 }
614
615 (void)(*plugInInterface)->QueryInterface(plugInInterface, CFUUIDGetUUIDBytes(get_device_interface_id()),
616 (LPVOID *)device);
617 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
618 (*plugInInterface)->Release (plugInInterface);
619
620 return LIBUSB_SUCCESS;
621 }
622
623 static void darwin_devices_attached (void *ptr, io_iterator_t add_devices) {
624 UNUSED(ptr);
625 struct darwin_cached_device *cached_device;
626 UInt64 old_session_id;
627 struct libusb_context *ctx;
628 io_service_t service;
629 int ret;
630
631 usbi_mutex_lock(&active_contexts_lock);
632
633 while ((service = IOIteratorNext(add_devices))) {
634 ret = darwin_get_cached_device (NULL, service, &cached_device, &old_session_id);
635 if (ret < 0 || !cached_device->can_enumerate) {
636 continue;
637 }
638
639 /* add this device to each active context's device list */
640 for_each_context(ctx) {
641 process_new_device (ctx, cached_device, old_session_id);
642 }
643
644 if (atomic_exchange(&cached_device->in_reenumerate, false)) {
645 usbi_dbg (NULL, "cached device in reset state. reset complete...");
646 }
647
648 IOObjectRelease(service);
649 }
650
651 usbi_mutex_unlock(&active_contexts_lock);
652 }
653
654 static void darwin_devices_detached (void *ptr, io_iterator_t rem_devices) {
655 UNUSED(ptr);
656 struct libusb_device *dev = NULL;
657 struct libusb_context *ctx;
658 struct darwin_cached_device *old_device;
659
660 io_service_t device;
661
662 usbi_mutex_lock(&active_contexts_lock);
663
664 while ((device = IOIteratorNext (rem_devices)) != 0) {
665 bool is_reenumerating = false;
666
667 /* get the location from the i/o registry */
668 UInt64 session = 0;
669 bool ret = get_ioregistry_value_number (device, CFSTR("sessionID"), kCFNumberSInt64Type, &session);
670 UInt32 locationID = 0;
671 (void) get_ioregistry_value_number (device, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
672 IOObjectRelease (device);
673 if (!ret)
674 continue;
675
676 /* we need to match darwin_ref_cached_device call made in darwin_get_cached_device function
677 otherwise no cached device will ever get freed */
678 usbi_mutex_lock(&darwin_cached_devices_mutex);
679 list_for_each_entry(old_device, &darwin_cached_devices, list, struct darwin_cached_device) {
680 if (old_device->session == session) {
681 if (atomic_load(&old_device->in_reenumerate)) {
682 /* device is re-enumerating. do not dereference the device at this time. libusb_reset_device()
683 * will deref if needed. */
684 usbi_dbg (NULL, "detected device detached due to re-enumeration. sessionID: 0x%" PRIx64
685 ", locationID: 0x%" PRIx32, session, locationID);
686
687 /* the device object is no longer usable so go ahead and release it */
688 if (old_device->device) {
689 (*old_device->device)->Release(old_device->device);
690 old_device->device = NULL;
691 }
692
693 is_reenumerating = true;
694 } else {
695 darwin_deref_cached_device (old_device);
696 }
697
698 break;
699 }
700 }
701
702 usbi_mutex_unlock(&darwin_cached_devices_mutex);
703 if (is_reenumerating) {
704 continue;
705 }
706
707 for_each_context(ctx) {
708 usbi_dbg (ctx, "notifying context %p of device disconnect", ctx);
709
710 dev = usbi_get_device_by_session_id(ctx, (unsigned long) session);
711 if (dev) {
712 /* signal the core that this device has been disconnected. the core will tear down this device
713 when the reference count reaches 0 */
714 usbi_disconnect_device(dev);
715 libusb_unref_device(dev);
716 }
717 }
718 }
719
720 usbi_mutex_unlock(&active_contexts_lock);
721 }
722
723 static void darwin_hotplug_poll (void)
724 {
725 /* not sure if 1 ms will be too long/short but it should work ok */
726 mach_timespec_t timeout = {.tv_sec = 0, .tv_nsec = 1000000UL};
727
728 /* since a kernel thread may notify the IOIterators used for
729 * hotplug notification we can't just clear the iterators.
730 * instead just wait until all IOService providers are quiet */
731 (void) IOKitWaitQuiet (darwin_default_master_port, &timeout);
732 }
733
734 static void darwin_clear_iterator (io_iterator_t iter) {
735 io_service_t device;
736
737 while ((device = IOIteratorNext (iter)) != 0)
738 IOObjectRelease (device);
739 }
740
741 static void darwin_fail_startup(void) {
742 usbi_mutex_lock (&libusb_darwin_at_mutex);
743 libusb_darwin_acfl = LIBUSB_DARWIN_STARTUP_FAILURE;
744 usbi_cond_signal (&libusb_darwin_at_cond);
745 usbi_mutex_unlock (&libusb_darwin_at_mutex);
746 pthread_exit (NULL);
747 }
748
749 static void *darwin_event_thread_main (void *arg0) {
750 UNUSED(arg0);
751 IOReturn kresult;
752 CFRunLoopRef runloop;
753 CFRunLoopSourceRef libusb_shutdown_cfsource;
754 CFRunLoopSourceContext libusb_shutdown_cfsourcectx;
755
756 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
757 /* Set this thread's name, so it can be seen in the debugger
758 and crash reports. */
759 pthread_setname_np ("org.libusb.device-hotplug");
760 #endif
761
762 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 && MAC_OS_X_VERSION_MIN_REQUIRED < 101200
763 /* Tell the Objective-C garbage collector about this thread.
764 This is required because, unlike NSThreads, pthreads are
765 not automatically registered. Although we don't use
766 Objective-C, we use CoreFoundation, which does.
767 Garbage collection support was entirely removed in 10.12,
768 so don't bother there. */
769 objc_registerThreadWithCollector();
770 #endif
771
772 /* hotplug (device arrival/removal) sources */
773 CFRunLoopSourceRef libusb_notification_cfsource;
774 io_notification_port_t libusb_notification_port;
775 io_iterator_t libusb_rem_device_iterator;
776 io_iterator_t libusb_add_device_iterator;
777
778 /* ctx must only be used for logging during thread startup */
779 usbi_dbg (NULL, "creating hotplug event source");
780
781 runloop = CFRunLoopGetCurrent ();
782 CFRetain (runloop);
783
784 /* add the shutdown cfsource to the run loop */
785 memset(&libusb_shutdown_cfsourcectx, 0, sizeof(libusb_shutdown_cfsourcectx));
786 libusb_shutdown_cfsourcectx.info = runloop;
787 libusb_shutdown_cfsourcectx.perform = (void (*)(void *))CFRunLoopStop;
788 libusb_shutdown_cfsource = CFRunLoopSourceCreate(NULL, 0, &libusb_shutdown_cfsourcectx);
789 CFRunLoopAddSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
790
791 /* add the notification port to the run loop */
792 libusb_notification_port = IONotificationPortCreate (darwin_default_master_port);
793 libusb_notification_cfsource = IONotificationPortGetRunLoopSource (libusb_notification_port);
794 CFRunLoopAddSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
795
796 /* create notifications for removed devices */
797 kresult = IOServiceAddMatchingNotification (libusb_notification_port, kIOTerminatedNotification,
798 IOServiceMatching(darwin_device_class),
799 darwin_devices_detached,
800 NULL, &libusb_rem_device_iterator);
801
802 if (kresult != kIOReturnSuccess) {
803 usbi_err (NULL, "could not add hotplug event source: %s", darwin_error_str (kresult));
804 CFRelease (libusb_shutdown_cfsource);
805 CFRelease (runloop);
806 darwin_fail_startup ();
807 }
808
809 /* create notifications for attached devices */
810 kresult = IOServiceAddMatchingNotification(libusb_notification_port, kIOFirstMatchNotification,
811 IOServiceMatching(darwin_device_class),
812 darwin_devices_attached,
813 NULL, &libusb_add_device_iterator);
814
815 if (kresult != kIOReturnSuccess) {
816 usbi_err (NULL, "could not add hotplug event source: %s", darwin_error_str (kresult));
817 CFRelease (libusb_shutdown_cfsource);
818 CFRelease (runloop);
819 darwin_fail_startup ();
820 }
821
822 /* arm notifiers */
823 darwin_clear_iterator (libusb_rem_device_iterator);
824 darwin_clear_iterator (libusb_add_device_iterator);
825
826 usbi_dbg (NULL, "darwin event thread ready to receive events");
827
828 /* signal the main thread that the hotplug runloop has been created. */
829 usbi_mutex_lock (&libusb_darwin_at_mutex);
830 libusb_darwin_acfl = runloop;
831 libusb_darwin_acfls = libusb_shutdown_cfsource;
832 usbi_cond_signal (&libusb_darwin_at_cond);
833 usbi_mutex_unlock (&libusb_darwin_at_mutex);
834
835 /* run the runloop */
836 CFRunLoopRun();
837
838 usbi_dbg (NULL, "darwin event thread exiting");
839
840 /* signal the main thread that the hotplug runloop has finished. */
841 usbi_mutex_lock (&libusb_darwin_at_mutex);
842 libusb_darwin_acfls = NULL;
843 libusb_darwin_acfl = NULL;
844 usbi_cond_signal (&libusb_darwin_at_cond);
845 usbi_mutex_unlock (&libusb_darwin_at_mutex);
846
847 /* remove the notification cfsource */
848 CFRunLoopRemoveSource(runloop, libusb_notification_cfsource, kCFRunLoopDefaultMode);
849
850 /* remove the shutdown cfsource */
851 CFRunLoopRemoveSource(runloop, libusb_shutdown_cfsource, kCFRunLoopDefaultMode);
852
853 /* delete notification port */
854 IONotificationPortDestroy (libusb_notification_port);
855
856 /* delete iterators */
857 IOObjectRelease (libusb_rem_device_iterator);
858 IOObjectRelease (libusb_add_device_iterator);
859
860 CFRelease (libusb_shutdown_cfsource);
861 CFRelease (runloop);
862
863 pthread_exit (NULL);
864 }
865
866 /* cleanup function to destroy cached devices. must be called with a lock on darwin_cached_devices_mutex */
867 static void darwin_cleanup_devices(void) {
868 struct darwin_cached_device *dev, *next;
869
870 list_for_each_entry_safe(dev, next, &darwin_cached_devices, list, struct darwin_cached_device) {
871 if (dev->refcount > 1) {
872 usbi_err(NULL, "device still referenced at libusb_exit");
873 }
874 darwin_deref_cached_device(dev);
875 }
876 }
877
878 /* must be called with a lock on darwin_cached_devices_mutex */
879 static int darwin_first_time_init(void) {
880 if (NULL == darwin_cached_devices.next) {
881 list_init (&darwin_cached_devices);
882 }
883
884 /* cache the interface versions that will be used. as a sanity check verify
885 * that the interface versions are non-zero. */
886 const struct darwin_iokit_interface *interface_interface = get_interface_interface();
887 const struct darwin_iokit_interface *device_interface = get_device_interface();
888 if (0 == interface_interface->version || 0 == device_interface->version) {
889 usbi_err(NULL, "could not determine the device or interface interface to use with this version "
890 "of macOS (or MacOS X), current_running_version = %" PRIu32, get_running_version());
891 return LIBUSB_ERROR_OTHER;
892 }
893
894 if (!list_empty(&darwin_cached_devices)) {
895 usbi_err(NULL, "libusb_device reference not released on last exit. will not continue");
896 return LIBUSB_ERROR_OTHER;
897 }
898
899 int rc = pthread_create (&libusb_darwin_at, NULL, darwin_event_thread_main, NULL);
900 if (0 != rc) {
901 usbi_err (NULL, "could not create event thread, error %d", rc);
902 return LIBUSB_ERROR_OTHER;
903 }
904
905 usbi_mutex_lock (&libusb_darwin_at_mutex);
906 libusb_darwin_at_started = true;
907 while (NULL == libusb_darwin_acfl) {
908 usbi_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
909 }
910
911 if (libusb_darwin_acfl == LIBUSB_DARWIN_STARTUP_FAILURE) {
912 libusb_darwin_acfl = NULL;
913 rc = LIBUSB_ERROR_OTHER;
914 }
915 usbi_mutex_unlock (&libusb_darwin_at_mutex);
916
917 return rc;
918 }
919
920 static int darwin_init_context(struct libusb_context *ctx) {
921 usbi_mutex_lock(&darwin_cached_devices_mutex);
922
923 bool first_init = (1 == ++init_count);
924
925 if (first_init) {
926 int rc = darwin_first_time_init();
927 if (LIBUSB_SUCCESS != rc) {
928 usbi_mutex_unlock(&darwin_cached_devices_mutex);
929 return rc;
930 }
931 }
932 usbi_mutex_unlock(&darwin_cached_devices_mutex);
933
934 return darwin_scan_devices (ctx);
935 }
936
937 static int darwin_init(struct libusb_context *ctx) {
938 int rc = darwin_init_context(ctx);
939 if (LIBUSB_SUCCESS != rc) {
940 /* clean up any allocated resources */
941 darwin_exit(ctx);
942 }
943
944 return rc;
945 }
946
947 static void darwin_exit (struct libusb_context *ctx) {
948 UNUSED(ctx);
949
950 usbi_mutex_lock(&darwin_cached_devices_mutex);
951 if (0 == --init_count) {
952 /* stop the event runloop and wait for the thread to terminate. */
953 usbi_mutex_lock (&libusb_darwin_at_mutex);
954 if (NULL != libusb_darwin_acfls) {
955 CFRunLoopSourceSignal (libusb_darwin_acfls);
956 CFRunLoopWakeUp (libusb_darwin_acfl);
957 while (libusb_darwin_acfl)
958 usbi_cond_wait (&libusb_darwin_at_cond, &libusb_darwin_at_mutex);
959 }
960
961 if (libusb_darwin_at_started) {
962 pthread_join (libusb_darwin_at, NULL);
963 libusb_darwin_at_started = false;
964 }
965 usbi_mutex_unlock (&libusb_darwin_at_mutex);
966
967 darwin_cleanup_devices ();
968 }
969 usbi_mutex_unlock(&darwin_cached_devices_mutex);
970 }
971
972 static int darwin_get_device_string(struct libusb_device *dev,
973 enum libusb_device_string_type string_type, char *buffer, int length) {
974
975 if (length <= 0)
976 return LIBUSB_ERROR_INVALID_PARAM;
977
978 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
979 io_iterator_t deviceIterator;
980 io_service_t service;
981 kern_return_t kresult;
982 CFStringRef cf;
983
984 kresult = usb_setup_device_iterator (&deviceIterator, priv->location);
985 if (kresult != kIOReturnSuccess)
986 return darwin_to_libusb (kresult);
987
988 service = IOIteratorNext (deviceIterator);
989 IOObjectRelease(deviceIterator);
990 if (service == IO_OBJECT_NULL)
991 return LIBUSB_ERROR_NOT_FOUND;
992
993 switch (string_type) {
994 case LIBUSB_DEVICE_STRING_MANUFACTURER:
995 cf = IORegistryEntryCreateCFProperty(service, CFSTR(kUSBVendorString), kCFAllocatorDefault, 0);
996 break;
997 case LIBUSB_DEVICE_STRING_PRODUCT:
998 cf = IORegistryEntryCreateCFProperty(service, CFSTR(kUSBProductString), kCFAllocatorDefault, 0);
999 break;
1000 case LIBUSB_DEVICE_STRING_SERIAL_NUMBER:
1001 cf = IORegistryEntryCreateCFProperty(service, CFSTR(kUSBSerialNumberString), kCFAllocatorDefault, 0);
1002 break;
1003 case LIBUSB_DEVICE_STRING_COUNT: /* intentional fall-through, avoid -Wswitch-enum */
1004 default:
1005 IOObjectRelease(service);
1006 return LIBUSB_ERROR_INVALID_PARAM;
1007 }
1008
1009 IOObjectRelease(service);
1010 if (cf == NULL)
1011 return LIBUSB_ERROR_NOT_FOUND;
1012
1013 long cfUsedIndex = 0;
1014 CFStringGetBytes(cf, CFRangeMake(0, CFStringGetLength(cf)), kCFStringEncodingUTF8, '?', false,
1015 (uint8_t *) buffer, length - 1, &cfUsedIndex);
1016 CFRelease(cf);
1017
1018 if (cfUsedIndex <= 0)
1019 return LIBUSB_ERROR_NOT_FOUND;
1020
1021 buffer[cfUsedIndex] = '\0';
1022 return (int) cfUsedIndex + 1;
1023 }
1024
1025 static int get_configuration_index (struct libusb_device *dev, UInt8 config_value) {
1026 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
1027 UInt8 i, numConfig;
1028 IOUSBConfigurationDescriptorPtr desc;
1029 IOReturn kresult;
1030
1031 /* is there a simpler way to determine the index? */
1032 kresult = (*priv->device)->GetNumberOfConfigurations (priv->device, &numConfig);
1033 if (kresult != kIOReturnSuccess)
1034 return darwin_to_libusb (kresult);
1035
1036 for (i = 0 ; i < numConfig ; i++) {
1037 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, i, &desc);
1038
1039 if (kresult == kIOReturnSuccess && desc->bConfigurationValue == config_value)
1040 return i;
1041 }
1042
1043 /* configuration not found */
1044 return LIBUSB_ERROR_NOT_FOUND;
1045 }
1046
1047 static int darwin_get_active_config_descriptor(struct libusb_device *dev, void *buffer, size_t len) {
1048 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
1049 int config_index;
1050
1051 if (0 == priv->active_config)
1052 return LIBUSB_ERROR_NOT_FOUND;
1053
1054 config_index = get_configuration_index (dev, priv->active_config);
1055 if (config_index < 0)
1056 return config_index;
1057
1058 assert(config_index >= 0 && config_index <= UINT8_MAX);
1059 return darwin_get_config_descriptor (dev, (UInt8)config_index, buffer, len);
1060 }
1061
1062 static int darwin_get_config_descriptor(struct libusb_device *dev, uint8_t config_index, void *buffer, size_t len) {
1063 struct darwin_cached_device *priv = DARWIN_CACHED_DEVICE(dev);
1064 IOUSBConfigurationDescriptorPtr desc;
1065 IOReturn kresult;
1066 int ret;
1067
1068 if (!priv || !priv->device)
1069 return LIBUSB_ERROR_OTHER;
1070
1071 kresult = (*priv->device)->GetConfigurationDescriptorPtr (priv->device, config_index, &desc);
1072 if (kresult == kIOReturnSuccess) {
1073 /* copy descriptor */
1074 if (libusb_le16_to_cpu(desc->wTotalLength) < len)
1075 len = libusb_le16_to_cpu(desc->wTotalLength);
1076
1077 memmove (buffer, desc, len);
1078 }
1079
1080 ret = darwin_to_libusb (kresult);
1081 if (ret != LIBUSB_SUCCESS)
1082 return ret;
1083
1084 return (int) len;
1085 }
1086
1087 /* check whether the os has configured the device */
1088 static enum libusb_error darwin_check_configuration (struct libusb_context *ctx, struct darwin_cached_device *dev) {
1089 usb_device_t darwin_device = dev->device;
1090
1091 IOUSBConfigurationDescriptorPtr configDesc;
1092 IOUSBFindInterfaceRequest request;
1093 IOReturn kresult;
1094 io_iterator_t interface_iterator;
1095 io_service_t firstInterface;
1096
1097 if (dev->dev_descriptor.bNumConfigurations < 1) {
1098 usbi_err (ctx, "device has no configurations");
1099 return LIBUSB_ERROR_OTHER; /* no configurations at this speed so we can't use it */
1100 }
1101
1102 /* checking the configuration of a root hub simulation takes ~1 s in 10.11. the device is
1103 not usable anyway */
1104 if (0x05ac == libusb_le16_to_cpu (dev->dev_descriptor.idVendor) &&
1105 0x8005 == libusb_le16_to_cpu (dev->dev_descriptor.idProduct)) {
1106 usbi_dbg (ctx, "ignoring configuration on root hub simulation");
1107 dev->active_config = 0;
1108 return LIBUSB_SUCCESS;
1109 }
1110
1111 /* find the first configuration */
1112 kresult = (*darwin_device)->GetConfigurationDescriptorPtr (darwin_device, 0, &configDesc);
1113 dev->first_config = (kIOReturnSuccess == kresult) ? configDesc->bConfigurationValue : 1;
1114
1115 /* check if the device is already configured. there is probably a better way than iterating over the
1116 to accomplish this (the trick is we need to avoid a call to GetConfigurations since buggy devices
1117 might lock up on the device request) */
1118
1119 /* Setup the Interface Request */
1120 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1121 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1122 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1123 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1124
1125 kresult = (*darwin_device)->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1126 if (kresult != kIOReturnSuccess)
1127 return darwin_to_libusb (kresult);
1128
1129 /* iterate once */
1130 firstInterface = IOIteratorNext(interface_iterator);
1131
1132 /* done with the interface iterator */
1133 IOObjectRelease(interface_iterator);
1134
1135 if (firstInterface) {
1136 IOObjectRelease (firstInterface);
1137
1138 /* device is configured */
1139 if (dev->dev_descriptor.bNumConfigurations == 1)
1140 /* to avoid problems with some devices get the configurations value from the configuration descriptor */
1141 dev->active_config = dev->first_config;
1142 else
1143 /* devices with more than one configuration should work with GetConfiguration */
1144 (*darwin_device)->GetConfiguration (darwin_device, &dev->active_config);
1145 } else
1146 /* not configured */
1147 dev->active_config = 0;
1148
1149 usbi_dbg (ctx, "active config: %u, first config: %u", dev->active_config, dev->first_config);
1150
1151 return LIBUSB_SUCCESS;
1152 }
1153
1154 static IOReturn darwin_request_descriptor (usb_device_t device, UInt8 desc, UInt8 desc_index, void *buffer, size_t buffer_size) {
1155 IOUSBDevRequestTO req;
1156
1157 assert(buffer_size <= UINT16_MAX);
1158
1159 memset (buffer, 0, buffer_size);
1160
1161 /* Set up request for descriptor/ */
1162 req.bmRequestType = USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
1163 req.bRequest = kUSBRqGetDescriptor;
1164 req.wValue = (UInt16)(desc << 8);
1165 req.wIndex = desc_index;
1166 req.wLength = (UInt16)buffer_size;
1167 req.pData = buffer;
1168 req.noDataTimeout = 20;
1169 req.completionTimeout = 100;
1170
1171 return (*device)->DeviceRequestTO (device, &req);
1172 }
1173
1174 static enum libusb_error darwin_cache_device_descriptor (struct libusb_context *ctx, struct darwin_cached_device *dev) {
1175 usb_device_t device = dev->device;
1176 int retries = 1;
1177 long delay = 30000; /* microseconds */
1178 int unsuspended = 0, try_unsuspend = 1, try_reconfigure = 1;
1179 int is_open = 0;
1180 IOReturn ret = 0, ret2;
1181 UInt8 bDeviceClass;
1182 UInt16 idProduct, idVendor;
1183
1184 dev->can_enumerate = 0;
1185
1186 (*device)->GetDeviceClass (device, &bDeviceClass);
1187 (*device)->GetDeviceProduct (device, &idProduct);
1188 (*device)->GetDeviceVendor (device, &idVendor);
1189
1190 /* According to Apple's documentation the device must be open for DeviceRequest but we may not be able to open some
1191 * devices and Apple's USB Prober doesn't bother to open the device before issuing a descriptor request. Still,
1192 * to follow the spec as closely as possible, try opening the device */
1193 is_open = ((*device)->USBDeviceOpenSeize(device) == kIOReturnSuccess);
1194
1195 do {
1196 /**** retrieve device descriptor ****/
1197 ret = darwin_request_descriptor (device, kUSBDeviceDesc, 0, &dev->dev_descriptor, sizeof(dev->dev_descriptor));
1198
1199 if (kIOReturnOverrun == ret && kUSBDeviceDesc == dev->dev_descriptor.bDescriptorType)
1200 /* received an overrun error but we still received a device descriptor */
1201 ret = kIOReturnSuccess;
1202
1203 if (kIOUSBVendorIDAppleComputer == idVendor) {
1204 /* NTH: don't bother retrying or unsuspending Apple devices */
1205 break;
1206 }
1207
1208 if (kIOReturnSuccess == ret && (0 == dev->dev_descriptor.bNumConfigurations ||
1209 0 == dev->dev_descriptor.bcdUSB)) {
1210 /* work around for incorrectly configured devices */
1211 if (try_reconfigure && is_open) {
1212 usbi_dbg(ctx, "descriptor appears to be invalid. resetting configuration before trying again...");
1213
1214 /* set the first configuration */
1215 (*device)->SetConfiguration(device, 1);
1216
1217 /* don't try to reconfigure again */
1218 try_reconfigure = 0;
1219 }
1220
1221 ret = kIOUSBPipeStalled;
1222 }
1223
1224 if (kIOReturnSuccess != ret && is_open && try_unsuspend) {
1225 /* device may be suspended. unsuspend it and try again */
1226 #if MAX_DEVICE_VERSION >= 320
1227 if (get_device_interface_version() >= 320) {
1228 UInt32 info = 0;
1229
1230 /* IOUSBFamily 320+ provides a way to detect device suspension but earlier versions do not */
1231 (void)(*IODEVICE_V(device, 320))->GetUSBDeviceInformation (device, &info);
1232
1233 /* note that the device was suspended */
1234 if (info & (1U << kUSBInformationDeviceIsSuspendedBit) || 0 == info)
1235 try_unsuspend = 1;
1236 }
1237 #endif
1238
1239 if (try_unsuspend) {
1240 /* try to unsuspend the device */
1241 ret2 = (*device)->USBDeviceSuspend (device, 0);
1242 if (kIOReturnSuccess != ret2) {
1243 /* prevent log spew from poorly behaving devices. this indicates the
1244 os actually had trouble communicating with the device */
1245 usbi_dbg(ctx, "could not retrieve device descriptor. failed to unsuspend: %s",darwin_error_str(ret2));
1246 } else
1247 unsuspended = 1;
1248
1249 try_unsuspend = 0;
1250 }
1251 }
1252
1253 if (kIOReturnSuccess != ret) {
1254 usbi_dbg(ctx, "kernel responded with code: 0x%08x. sleeping for %ld ms before trying again", ret, delay/1000);
1255 /* sleep for a little while before trying again */
1256 struct timespec full_delay = {delay / 1000000, (delay * 1000) % 1000000000};
1257 nanosleep(&full_delay, NULL);
1258 }
1259 } while (kIOReturnSuccess != ret && retries--);
1260
1261 if (unsuspended)
1262 /* resuspend the device */
1263 (void)(*device)->USBDeviceSuspend (device, 1);
1264
1265 if (is_open)
1266 (void) (*device)->USBDeviceClose (device);
1267
1268 if (ret != kIOReturnSuccess) {
1269 /* a debug message was already printed out for this error */
1270 if (LIBUSB_CLASS_HUB == bDeviceClass)
1271 usbi_dbg (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
1272 idVendor, idProduct, darwin_error_str (ret), ret);
1273 else
1274 usbi_warn (ctx, "could not retrieve device descriptor %.4x:%.4x: %s (%x). skipping device",
1275 idVendor, idProduct, darwin_error_str (ret), ret);
1276 return darwin_to_libusb (ret);
1277 }
1278
1279 /* catch buggy hubs (which appear to be virtual). Apple's own USB prober has problems with these devices. */
1280 if (libusb_le16_to_cpu (dev->dev_descriptor.idProduct) != idProduct) {
1281 /* not a valid device */
1282 usbi_warn (NULL, "idProduct from iokit (%04x) does not match idProduct in descriptor (%04x). skipping device",
1283 idProduct, libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
1284 return LIBUSB_ERROR_NO_DEVICE;
1285 }
1286
1287 usbi_dbg (ctx, "cached device descriptor:");
1288 usbi_dbg (ctx, " bDescriptorType: 0x%02x", dev->dev_descriptor.bDescriptorType);
1289 usbi_dbg (ctx, " bcdUSB: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdUSB));
1290 usbi_dbg (ctx, " bDeviceClass: 0x%02x", dev->dev_descriptor.bDeviceClass);
1291 usbi_dbg (ctx, " bDeviceSubClass: 0x%02x", dev->dev_descriptor.bDeviceSubClass);
1292 usbi_dbg (ctx, " bDeviceProtocol: 0x%02x", dev->dev_descriptor.bDeviceProtocol);
1293 usbi_dbg (ctx, " bMaxPacketSize0: 0x%02x", dev->dev_descriptor.bMaxPacketSize0);
1294 usbi_dbg (ctx, " idVendor: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idVendor));
1295 usbi_dbg (ctx, " idProduct: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.idProduct));
1296 usbi_dbg (ctx, " bcdDevice: 0x%04x", libusb_le16_to_cpu (dev->dev_descriptor.bcdDevice));
1297 usbi_dbg (ctx, " iManufacturer: 0x%02x", dev->dev_descriptor.iManufacturer);
1298 usbi_dbg (ctx, " iProduct: 0x%02x", dev->dev_descriptor.iProduct);
1299 usbi_dbg (ctx, " iSerialNumber: 0x%02x", dev->dev_descriptor.iSerialNumber);
1300 usbi_dbg (ctx, " bNumConfigurations: 0x%02x", dev->dev_descriptor.bNumConfigurations);
1301
1302 dev->can_enumerate = 1;
1303
1304 return LIBUSB_SUCCESS;
1305 }
1306
1307 /* Returns 1 on success, 0 on failure. */
1308 static bool get_device_port (io_service_t service, UInt8 *port) {
1309 IOReturn kresult;
1310 io_service_t parent;
1311 bool ret = false;
1312
1313 if (get_ioregistry_value_number (service, CFSTR("PortNum"), kCFNumberSInt8Type, port)) {
1314 return true;
1315 }
1316
1317 kresult = IORegistryEntryGetParentEntry (service, kIOServicePlane, &parent);
1318 if (kIOReturnSuccess == kresult) {
1319 /*
1320 macOS 10 to 15 always had port number property as "port".
1321 macOS 26 has changed it to "usb-port-number".
1322 For the same binaries to run correctly on both macOS 15 and macOS 26+,
1323 we have to detect os version at runtime and use correct port name property.
1324 */
1325 uint32_t os_version = get_running_version();
1326 CFStringRef cfstrPort = os_version < 260000 ? CFSTR("port") : CFSTR("usb-port-number");
1327 ret = get_ioregistry_value_data (parent, cfstrPort, 1, port);
1328 IOObjectRelease (parent);
1329 }
1330
1331 return ret;
1332 }
1333
1334 /* Returns 1 on success, 0 on failure. */
1335 static bool get_device_parent_sessionID(io_service_t service, UInt64 *parent_sessionID) {
1336 /* Walk up the tree in the IOService plane until we find a parent that has a sessionID */
1337 io_service_t parent = service;
1338 do {
1339 IOReturn kresult = IORegistryEntryGetParentEntry (parent, kIOUSBPlane, &parent);
1340 if (kresult != kIOReturnSuccess) {
1341 break;
1342 }
1343 if (get_ioregistry_value_number (parent, CFSTR("sessionID"), kCFNumberSInt64Type, parent_sessionID)) {
1344 /* Success */
1345 return true;
1346 }
1347 } while (true);
1348
1349 /* We ran out of parents */
1350 return false;
1351 }
1352
1353 static enum libusb_error darwin_get_cached_device(struct libusb_context *ctx, io_service_t service, struct darwin_cached_device **cached_out,
1354 UInt64 *old_session_id) {
1355 struct darwin_cached_device *new_device;
1356 UInt64 sessionID = 0, parent_sessionID = 0;
1357 UInt32 locationID = 0;
1358 enum libusb_error ret = LIBUSB_SUCCESS;
1359 usb_device_t device;
1360 UInt8 port = 0;
1361
1362 /* assuming sessionID != 0 normally (never seen it be 0) */
1363 *old_session_id = 0;
1364 *cached_out = NULL;
1365
1366 /* get some info from the io registry */
1367 (void) get_ioregistry_value_number (service, CFSTR("sessionID"), kCFNumberSInt64Type, &sessionID);
1368 (void) get_ioregistry_value_number (service, CFSTR("locationID"), kCFNumberSInt32Type, &locationID);
1369 if (!get_device_port (service, &port)) {
1370 usbi_dbg(ctx, "could not get connected port number");
1371 }
1372
1373 usbi_dbg(ctx, "finding cached device for sessionID 0x%" PRIx64, sessionID);
1374
1375 if (get_device_parent_sessionID(service, &parent_sessionID)) {
1376 usbi_dbg(ctx, "parent sessionID: 0x%" PRIx64, parent_sessionID);
1377 }
1378
1379 usbi_mutex_lock(&darwin_cached_devices_mutex);
1380 do {
1381 list_for_each_entry(new_device, &darwin_cached_devices, list, struct darwin_cached_device) {
1382 usbi_dbg(ctx, "matching sessionID/locationID 0x%" PRIx64 "/0x%" PRIx32 " against cached device with sessionID/locationID 0x%" PRIx64 "/0x%" PRIx32,
1383 sessionID, locationID, new_device->session, new_device->location);
1384 if (new_device->location == locationID && atomic_load(&new_device->in_reenumerate)) {
1385 usbi_dbg (ctx, "found cached device with matching location that is being re-enumerated");
1386 *old_session_id = new_device->session;
1387 break;
1388 }
1389
1390 if (new_device->session == sessionID) {
1391 usbi_dbg(ctx, "using cached device for device");
1392 *cached_out = new_device;
1393 break;
1394 }
1395 }
1396
1397 if (*cached_out)
1398 break;
1399
1400 usbi_dbg(ctx, "caching new device with sessionID 0x%" PRIx64, sessionID);
1401
1402 ret = darwin_device_from_service (ctx, service, &device);
1403 if (LIBUSB_SUCCESS != ret) {
1404 break;
1405 }
1406
1407 if (!(*old_session_id)) {
1408 new_device = calloc (1, sizeof (*new_device));
1409 if (!new_device) {
1410 ret = LIBUSB_ERROR_NO_MEM;
1411 break;
1412 }
1413
1414 /* add this device to the cached device list */
1415 list_add(&new_device->list, &darwin_cached_devices);
1416
1417 (*device)->GetDeviceAddress (device, (USBDeviceAddress *)&new_device->address);
1418
1419 /* keep a reference to this device */
1420 darwin_ref_cached_device(new_device);
1421
1422 (*device)->GetLocationID (device, &new_device->location);
1423 new_device->port = port;
1424 new_device->parent_session = parent_sessionID;
1425 } else {
1426 /* release the ref to old device's service */
1427 IOObjectRelease (new_device->service);
1428 }
1429
1430 /* keep track of devices regardless of if we successfully enumerate them to
1431 prevent them from being enumerated multiple times */
1432 *cached_out = new_device;
1433
1434 new_device->session = sessionID;
1435 new_device->device = device;
1436 new_device->service = service;
1437
1438 /* retain the service */
1439 IOObjectRetain (service);
1440
1441 /* cache the device descriptor */
1442 ret = darwin_cache_device_descriptor(ctx, new_device);
1443 if (ret)
1444 break;
1445
1446 if (new_device->can_enumerate) {
1447 snprintf(new_device->sys_path, 20, "%03i-%04x-%04x-%02x-%02x", new_device->address,
1448 libusb_le16_to_cpu (new_device->dev_descriptor.idVendor),
1449 libusb_le16_to_cpu (new_device->dev_descriptor.idProduct),
1450 new_device->dev_descriptor.bDeviceClass, new_device->dev_descriptor.bDeviceSubClass);
1451 }
1452 } while (0);
1453
1454 usbi_mutex_unlock(&darwin_cached_devices_mutex);
1455
1456 assert((ret == LIBUSB_SUCCESS) ? (*cached_out != NULL) : true);
1457
1458 return ret;
1459 }
1460
1461 static enum libusb_error process_new_device (struct libusb_context *ctx, struct darwin_cached_device *cached_device,
1462 UInt64 old_session_id) {
1463 struct darwin_device_priv *priv;
1464 struct libusb_device *dev = NULL;
1465 UInt8 devSpeed;
1466 enum libusb_error ret = LIBUSB_SUCCESS;
1467
1468 do {
1469 /* check current active configuration (and cache the first configuration value--
1470 which may be used by claim_interface) */
1471 ret = darwin_check_configuration (ctx, cached_device);
1472 if (ret)
1473 break;
1474
1475 if (0 != old_session_id) {
1476 usbi_dbg (ctx, "re-using existing device from context %p for with session 0x%" PRIx64 " new session 0x%" PRIx64,
1477 ctx, old_session_id, cached_device->session);
1478 /* save the libusb device before the session id is updated */
1479 dev = usbi_get_device_by_session_id (ctx, (unsigned long) old_session_id);
1480 }
1481
1482 if (!dev) {
1483 usbi_dbg (ctx, "allocating new device in context %p for with session 0x%" PRIx64,
1484 ctx, cached_device->session);
1485
1486 dev = usbi_alloc_device(ctx, (unsigned long) cached_device->session);
1487 if (!dev) {
1488 return LIBUSB_ERROR_NO_MEM;
1489 }
1490
1491 priv = usbi_get_device_priv(dev);
1492
1493 priv->dev = cached_device;
1494 darwin_ref_cached_device (priv->dev);
1495 dev->port_number = cached_device->port;
1496 /* the location ID encodes the path to the device. the top byte of the location ID contains the bus number
1497 (numbered from 0). the remaining bytes can be used to construct the device tree for that bus. */
1498 dev->bus_number = cached_device->location >> 24;
1499 assert(cached_device->address <= UINT8_MAX);
1500 dev->device_address = (uint8_t)cached_device->address;
1501 } else {
1502 priv = usbi_get_device_priv(dev);
1503 }
1504
1505 static_assert(sizeof(dev->device_descriptor) == sizeof(cached_device->dev_descriptor),
1506 "mismatch between libusb and IOKit device descriptor sizes");
1507 memcpy(&dev->device_descriptor, &cached_device->dev_descriptor, LIBUSB_DT_DEVICE_SIZE);
1508 usbi_localize_device_descriptor(&dev->device_descriptor);
1509 dev->session_data = cached_device->session;
1510
1511 if (NULL != dev->parent_dev) {
1512 libusb_unref_device(dev->parent_dev);
1513 dev->parent_dev = NULL;
1514 }
1515
1516 if (cached_device->parent_session > 0) {
1517 dev->parent_dev = usbi_get_device_by_session_id (ctx, (unsigned long) cached_device->parent_session);
1518 }
1519
1520 (*priv->dev->device)->GetDeviceSpeed (priv->dev->device, &devSpeed);
1521
1522 switch (devSpeed) {
1523 case kUSBDeviceSpeedLow: dev->speed = LIBUSB_SPEED_LOW; break;
1524 case kUSBDeviceSpeedFull: dev->speed = LIBUSB_SPEED_FULL; break;
1525 case kUSBDeviceSpeedHigh: dev->speed = LIBUSB_SPEED_HIGH; break;
1526 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
1527 case kUSBDeviceSpeedSuper: dev->speed = LIBUSB_SPEED_SUPER; break;
1528 #endif
1529 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
1530 case kUSBDeviceSpeedSuperPlus: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
1531 #endif
1532 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101500
1533 case kUSBDeviceSpeedSuperPlusBy2: dev->speed = LIBUSB_SPEED_SUPER_PLUS_X2; break;
1534 #endif
1535 default:
1536 usbi_warn (ctx, "Got unknown device speed %d", devSpeed);
1537 }
1538
1539 ret = usbi_sanitize_device (dev);
1540 if (ret < 0)
1541 break;
1542
1543 usbi_dbg (ctx, "found device with address %d port = %d parent = %p at %p", dev->device_address,
1544 dev->port_number, (void *) dev->parent_dev, priv->dev->sys_path);
1545
1546 } while (0);
1547
1548 if (!atomic_load(&cached_device->in_reenumerate) && 0 == ret) {
1549 usbi_connect_device (dev);
1550 } else {
1551 libusb_unref_device (dev);
1552 }
1553
1554 return ret;
1555 }
1556
1557 static enum libusb_error darwin_scan_devices(struct libusb_context *ctx) {
1558 struct darwin_cached_device *cached_device;
1559 UInt64 old_session_id;
1560 io_iterator_t deviceIterator;
1561 io_service_t service;
1562 IOReturn kresult;
1563 int ret;
1564
1565 kresult = usb_setup_device_iterator (&deviceIterator, 0);
1566 if (kresult != kIOReturnSuccess)
1567 return darwin_to_libusb (kresult);
1568
1569 while ((service = IOIteratorNext (deviceIterator))) {
1570 ret = darwin_get_cached_device (ctx, service, &cached_device, &old_session_id);
1571 assert((ret >= 0) ? (cached_device != NULL) : true);
1572 if (ret < 0 || !cached_device->can_enumerate) {
1573 continue;
1574 }
1575
1576 (void) process_new_device (ctx, cached_device, old_session_id);
1577
1578 IOObjectRelease(service);
1579 }
1580
1581 IOObjectRelease(deviceIterator);
1582
1583 return LIBUSB_SUCCESS;
1584 }
1585
1586 static int darwin_open (struct libusb_device_handle *dev_handle) {
1587 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1588 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1589 IOReturn kresult;
1590
1591 if (0 == dpriv->open_count) {
1592 if (!dpriv->device) {
1593 usbi_err(HANDLE_CTX(dev_handle), "device interface is NULL, cannot open");
1594 return LIBUSB_ERROR_NO_DEVICE;
1595 }
1596 /* try to open the device */
1597 kresult = (*dpriv->device)->USBDeviceOpenSeize (dpriv->device);
1598 if (kresult != kIOReturnSuccess) {
1599 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceOpen: %s", darwin_error_str(kresult));
1600
1601 if (kIOReturnExclusiveAccess != kresult) {
1602 return darwin_to_libusb (kresult);
1603 }
1604
1605 /* it is possible to perform some actions on a device that is not open so do not return an error */
1606 priv->is_open = false;
1607 } else {
1608 priv->is_open = true;
1609 }
1610
1611 /* create async event source */
1612 kresult = (*dpriv->device)->CreateDeviceAsyncEventSource (dpriv->device,
1613 &priv->cfSource);
1614 if (kresult != kIOReturnSuccess) {
1615 usbi_err (HANDLE_CTX (dev_handle), "CreateDeviceAsyncEventSource: %s", darwin_error_str(kresult));
1616
1617 if (priv->is_open) {
1618 (*dpriv->device)->USBDeviceClose (dpriv->device);
1619 }
1620
1621 priv->is_open = false;
1622
1623 return darwin_to_libusb (kresult);
1624 }
1625
1626 CFRetain (libusb_darwin_acfl);
1627
1628 /* add the cfSource to the async run loop */
1629 CFRunLoopAddSource(libusb_darwin_acfl, priv->cfSource, kCFRunLoopCommonModes);
1630 }
1631
1632 /* device opened successfully */
1633 dpriv->open_count++;
1634
1635 usbi_dbg (HANDLE_CTX(dev_handle), "device open for access");
1636
1637 return 0;
1638 }
1639
1640 static void darwin_close (struct libusb_device_handle *dev_handle) {
1641 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1642 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1643 IOReturn kresult;
1644 int i;
1645
1646 if (dpriv->open_count == 0) {
1647 /* something is probably very wrong if this is the case */
1648 usbi_err (HANDLE_CTX (dev_handle), "Close called on a device that was not open!");
1649 return;
1650 }
1651
1652 dpriv->open_count--;
1653 if (NULL == dpriv->device) {
1654 usbi_warn (HANDLE_CTX (dev_handle), "darwin_close device missing IOService");
1655 return;
1656 }
1657
1658 /* make sure all interfaces are released */
1659 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1660 if (dev_handle->claimed_interfaces & (1U << i))
1661 libusb_release_interface (dev_handle, i);
1662
1663 if (0 == dpriv->open_count) {
1664 /* delete the device's async event source */
1665 if (priv->cfSource) {
1666 CFRunLoopRemoveSource (libusb_darwin_acfl, priv->cfSource, kCFRunLoopDefaultMode);
1667 CFRelease (priv->cfSource);
1668 priv->cfSource = NULL;
1669 CFRelease (libusb_darwin_acfl);
1670 }
1671
1672 if (priv->is_open) {
1673 /* close the device */
1674 kresult = (*dpriv->device)->USBDeviceClose(dpriv->device);
1675 if (kresult != kIOReturnSuccess) {
1676 /* Log the fact that we had a problem closing the file, however failing a
1677 * close isn't really an error, so return success anyway */
1678 usbi_warn (HANDLE_CTX (dev_handle), "USBDeviceClose: %s", darwin_error_str(kresult));
1679 }
1680 }
1681 }
1682 }
1683
1684 static int darwin_get_configuration(struct libusb_device_handle *dev_handle, uint8_t *config) {
1685 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1686
1687 *config = dpriv->active_config;
1688
1689 return LIBUSB_SUCCESS;
1690 }
1691
1692 static enum libusb_error darwin_set_configuration(struct libusb_device_handle *dev_handle, int config) {
1693 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1694 IOReturn kresult;
1695 uint8_t i;
1696
1697 if (config == -1)
1698 config = 0;
1699
1700 /* Setting configuration will invalidate the interface, so we need
1701 to reclaim it. First, dispose of existing interfaces, if any. */
1702 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1703 if (dev_handle->claimed_interfaces & (1U << i))
1704 darwin_release_interface (dev_handle, i);
1705
1706 kresult = (*dpriv->device)->SetConfiguration (dpriv->device, (UInt8)config);
1707 if (kresult != kIOReturnSuccess)
1708 return darwin_to_libusb (kresult);
1709
1710 /* Reclaim any interfaces. */
1711 for (i = 0 ; i < USB_MAXINTERFACES ; i++)
1712 if (dev_handle->claimed_interfaces & (1U << i))
1713 darwin_claim_interface (dev_handle, i);
1714
1715 dpriv->active_config = (UInt8)config;
1716
1717 return LIBUSB_SUCCESS;
1718 }
1719
1720 static IOReturn darwin_get_interface (usb_device_t darwin_device, uint8_t ifc, io_service_t *usbInterfacep) {
1721 IOUSBFindInterfaceRequest request;
1722 IOReturn kresult;
1723 io_iterator_t interface_iterator;
1724 UInt8 bInterfaceNumber;
1725 bool ret;
1726
1727 *usbInterfacep = IO_OBJECT_NULL;
1728
1729 /* Setup the Interface Request */
1730 request.bInterfaceClass = kIOUSBFindInterfaceDontCare;
1731 request.bInterfaceSubClass = kIOUSBFindInterfaceDontCare;
1732 request.bInterfaceProtocol = kIOUSBFindInterfaceDontCare;
1733 request.bAlternateSetting = kIOUSBFindInterfaceDontCare;
1734
1735 kresult = (*darwin_device)->CreateInterfaceIterator(darwin_device, &request, &interface_iterator);
1736 if (kresult != kIOReturnSuccess)
1737 return kresult;
1738
1739 while ((*usbInterfacep = IOIteratorNext(interface_iterator))) {
1740 /* find the interface number */
1741 ret = get_ioregistry_value_number (*usbInterfacep, CFSTR("bInterfaceNumber"), kCFNumberSInt8Type,
1742 &bInterfaceNumber);
1743
1744 if (ret && bInterfaceNumber == ifc) {
1745 break;
1746 }
1747
1748 (void) IOObjectRelease (*usbInterfacep);
1749 }
1750
1751 /* done with the interface iterator */
1752 IOObjectRelease(interface_iterator);
1753
1754 return kIOReturnSuccess;
1755 }
1756
1757 static const struct libusb_interface_descriptor *get_interface_descriptor_by_number(struct libusb_device_handle *dev_handle, struct libusb_config_descriptor *conf_desc, int iface, uint8_t altsetting)
1758 {
1759 int i;
1760
1761 for (i = 0; i < conf_desc->bNumInterfaces; i++) {
1762 if (altsetting < conf_desc->interface[i].num_altsetting && conf_desc->interface[i].altsetting[altsetting].bInterfaceNumber == iface) {
1763 return &conf_desc->interface[i].altsetting[altsetting];
1764 }
1765 }
1766
1767 usbi_err(HANDLE_CTX(dev_handle), "interface %d with altsetting %d not found for device", iface, (int)altsetting);
1768 return NULL;
1769 }
1770
1771 static enum libusb_error get_endpoints (struct libusb_device_handle *dev_handle, uint8_t iface) {
1772 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1773
1774 /* current interface */
1775 struct darwin_interface *cInterface = &priv->interfaces[iface];
1776 IOReturn kresult;
1777 uint8_t numep;
1778 int rc;
1779 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
1780
1781 usbi_dbg (ctx, "building table of endpoints.");
1782
1783 /* retrieve the total number of endpoints on this interface */
1784 kresult = (*IOINTERFACE(cInterface))->GetNumEndpoints(IOINTERFACE(cInterface), &numep);
1785 if (kresult != kIOReturnSuccess) {
1786 usbi_err (ctx, "can't get number of endpoints for interface: %s", darwin_error_str(kresult));
1787 return darwin_to_libusb (kresult);
1788 }
1789
1790 /* iterate through pipe references */
1791 for (UInt8 i = 1 ; i <= numep ; i++) {
1792 darwin_pipe_properties_t pipe_properties;
1793 kresult = darwin_get_pipe_properties(cInterface, i, &pipe_properties);
1794 if (kresult != kIOReturnSuccess) {
1795 /* probably a buggy device. try to get the endpoint address from the descriptors */
1796 struct libusb_config_descriptor *config;
1797 const struct libusb_interface_descriptor *if_desc;
1798 const struct libusb_endpoint_descriptor *endpoint_desc;
1799 UInt8 alt_setting;
1800
1801 kresult = (*IOINTERFACE(cInterface))->GetAlternateSetting (IOINTERFACE(cInterface), &alt_setting);
1802 if (kresult != kIOReturnSuccess) {
1803 usbi_err (HANDLE_CTX (dev_handle), "can't get alternate setting for interface");
1804 return darwin_to_libusb (kresult);
1805 }
1806
1807 rc = libusb_get_active_config_descriptor (dev_handle->dev, &config);
1808 if (LIBUSB_SUCCESS != rc) {
1809 return rc;
1810 }
1811
1812 if_desc = get_interface_descriptor_by_number (dev_handle, config, iface, alt_setting);
1813 if (if_desc == NULL) {
1814 libusb_free_config_descriptor (config);
1815 return LIBUSB_ERROR_NOT_FOUND;
1816 }
1817
1818 endpoint_desc = if_desc->endpoint + i - 1;
1819
1820 cInterface->endpoint_addrs[i - 1] = endpoint_desc->bEndpointAddress;
1821 libusb_free_config_descriptor (config);
1822 } else {
1823 cInterface->endpoint_addrs[i - 1] = (UInt8)(((kUSBIn == pipe_properties.direction) << kUSBRqDirnShift) |
1824 (pipe_properties.number & LIBUSB_ENDPOINT_ADDRESS_MASK));
1825 }
1826
1827 usbi_dbg (ctx, "interface: %i pipe %i: dir: %i number: %i", iface, i, cInterface->endpoint_addrs[i - 1] >> kUSBRqDirnShift,
1828 cInterface->endpoint_addrs[i - 1] & LIBUSB_ENDPOINT_ADDRESS_MASK);
1829 }
1830
1831 cInterface->num_endpoints = numep;
1832
1833 return LIBUSB_SUCCESS;
1834 }
1835
1836 static int darwin_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1837 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
1838 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1839 io_service_t usbInterface = IO_OBJECT_NULL;
1840 IOReturn kresult;
1841 enum libusb_error ret;
1842 IOCFPlugInInterface **plugInInterface = NULL;
1843 SInt32 score;
1844
1845 /* current interface */
1846 struct darwin_interface *cInterface = &priv->interfaces[iface];
1847
1848 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
1849
1850 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1851 if (kresult != kIOReturnSuccess)
1852 return darwin_to_libusb (kresult);
1853
1854 /* make sure we have an interface */
1855 if (!usbInterface && dpriv->first_config != 0) {
1856 usbi_info (ctx, "no interface found; setting configuration: %d", dpriv->first_config);
1857
1858 /* set the configuration */
1859 ret = darwin_set_configuration (dev_handle, (int) dpriv->first_config);
1860 if (ret != LIBUSB_SUCCESS) {
1861 usbi_err (ctx, "could not set configuration");
1862 return ret;
1863 }
1864
1865 kresult = darwin_get_interface (dpriv->device, iface, &usbInterface);
1866 if (kresult != kIOReturnSuccess) {
1867 usbi_err (ctx, "darwin_get_interface: %s", darwin_error_str(kresult));
1868 return darwin_to_libusb (kresult);
1869 }
1870 }
1871
1872 if (!usbInterface) {
1873 usbi_info (ctx, "interface not found");
1874 return LIBUSB_ERROR_NOT_FOUND;
1875 }
1876
1877 /* get an interface to the device's interface */
1878 kresult = IOCreatePlugInInterfaceForService (usbInterface, kIOUSBInterfaceUserClientTypeID,
1879 kIOCFPlugInInterfaceID, &plugInInterface, &score);
1880
1881 /* ignore release error */
1882 (void)IOObjectRelease (usbInterface);
1883
1884 if (kresult != kIOReturnSuccess) {
1885 usbi_err (ctx, "IOCreatePlugInInterfaceForService: %s", darwin_error_str(kresult));
1886 return darwin_to_libusb (kresult);
1887 }
1888
1889 if (!plugInInterface) {
1890 usbi_err (ctx, "plugin interface not found");
1891 return LIBUSB_ERROR_NOT_FOUND;
1892 }
1893
1894 /* Do the actual claim */
1895 kresult = (*plugInInterface)->QueryInterface(plugInInterface,
1896 CFUUIDGetUUIDBytes(get_interface_interface_id()),
1897 (LPVOID *)&IOINTERFACE(cInterface));
1898 /* We no longer need the intermediate plug-in */
1899 /* Use release instead of IODestroyPlugInInterface to avoid stopping IOServices associated with this device */
1900 (*plugInInterface)->Release (plugInInterface);
1901 if (kresult != kIOReturnSuccess) {
1902 usbi_err (ctx, "QueryInterface: %s", darwin_error_str(kresult));
1903 return darwin_to_libusb (kresult);
1904 }
1905 if (!IOINTERFACE(cInterface)) {
1906 usbi_err (ctx, "QueryInterface: returned null interface");
1907 return LIBUSB_ERROR_OTHER;
1908 }
1909
1910 /* claim the interface */
1911 kresult = (*IOINTERFACE(cInterface))->USBInterfaceOpen(IOINTERFACE(cInterface));
1912 if (kresult != kIOReturnSuccess) {
1913 usbi_info (ctx, "USBInterfaceOpen: %s", darwin_error_str(kresult));
1914 return darwin_to_libusb (kresult);
1915 }
1916
1917 /* update list of endpoints */
1918 ret = get_endpoints (dev_handle, iface);
1919 if (ret) {
1920 /* this should not happen */
1921 darwin_release_interface (dev_handle, iface);
1922 usbi_err (ctx, "could not build endpoint table");
1923 return ret;
1924 }
1925
1926 cInterface->cfSource = NULL;
1927
1928 /* create async event source */
1929 kresult = (*IOINTERFACE(cInterface))->CreateInterfaceAsyncEventSource (IOINTERFACE(cInterface), &cInterface->cfSource);
1930 if (kresult != kIOReturnSuccess) {
1931 usbi_err (ctx, "could not create async event source");
1932
1933 /* can't continue without an async event source */
1934 (void)darwin_release_interface (dev_handle, iface);
1935
1936 return darwin_to_libusb (kresult);
1937 }
1938
1939 /* add the cfSource to the async thread's run loop */
1940 CFRunLoopAddSource(libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1941
1942 usbi_dbg (ctx, "interface opened");
1943
1944 return LIBUSB_SUCCESS;
1945 }
1946
1947 static int darwin_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
1948 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
1949 IOReturn kresult;
1950
1951 /* current interface */
1952 struct darwin_interface *cInterface = &priv->interfaces[iface];
1953
1954 /* Check to see if an interface is open */
1955 if (!IOINTERFACE(cInterface)) {
1956 return LIBUSB_SUCCESS;
1957 }
1958
1959 /* clean up endpoint data */
1960 cInterface->num_endpoints = 0;
1961
1962 /* delete the interface's async event source */
1963 if (cInterface->cfSource) {
1964 CFRunLoopRemoveSource (libusb_darwin_acfl, cInterface->cfSource, kCFRunLoopDefaultMode);
1965 CFRelease (cInterface->cfSource);
1966 cInterface->cfSource = NULL;
1967 }
1968
1969 kresult = (*IOINTERFACE(cInterface))->USBInterfaceClose(IOINTERFACE(cInterface));
1970 if (kresult != kIOReturnSuccess)
1971 usbi_warn (HANDLE_CTX (dev_handle), "USBInterfaceClose: %s", darwin_error_str(kresult));
1972
1973 ULONG refCount = (*IOINTERFACE(cInterface))->Release(IOINTERFACE(cInterface));
1974 if (refCount != 0) {
1975 usbi_warn (HANDLE_CTX (dev_handle), "Release final refCount: %u", refCount);
1976 }
1977
1978 IOINTERFACE(cInterface) = NULL;
1979
1980 return darwin_to_libusb (kresult);
1981 }
1982
1983 static int check_alt_setting_and_clear_halt(struct libusb_device_handle *dev_handle, uint8_t altsetting, struct darwin_interface *cInterface) {
1984 enum libusb_error ret;
1985 IOReturn kresult;
1986 uint8_t current_alt_setting;
1987
1988 kresult = (*IOINTERFACE(cInterface))->GetAlternateSetting (IOINTERFACE(cInterface), &current_alt_setting);
1989 if (kresult == kIOReturnSuccess && altsetting != current_alt_setting) {
1990 return LIBUSB_ERROR_PIPE;
1991 }
1992
1993 for (int i = 0 ; i < cInterface->num_endpoints ; i++) {
1994 ret = darwin_clear_halt(dev_handle, cInterface->endpoint_addrs[i]);
1995 if (LIBUSB_SUCCESS != ret) {
1996 usbi_warn(HANDLE_CTX (dev_handle), "error clearing pipe halt for endpoint %d", i);
1997 if (LIBUSB_ERROR_NOT_FOUND == ret) {
1998 /* may need to re-open the interface */
1999 return ret;
2000 }
2001 }
2002 }
2003
2004 return LIBUSB_SUCCESS;
2005 }
2006
2007 static int darwin_set_interface_altsetting(struct libusb_device_handle *dev_handle, uint8_t iface, uint8_t altsetting) {
2008 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
2009 IOReturn kresult;
2010 enum libusb_error ret;
2011
2012 /* current interface */
2013 struct darwin_interface *cInterface = &priv->interfaces[iface];
2014
2015 if (!IOINTERFACE(cInterface)) {
2016 return LIBUSB_ERROR_NO_DEVICE;
2017 }
2018
2019 kresult = (*IOINTERFACE(cInterface))->SetAlternateInterface (IOINTERFACE(cInterface), altsetting);
2020 if (kresult == kIOReturnSuccess) {
2021 /* update the list of endpoints */
2022 ret = get_endpoints (dev_handle, iface);
2023 if (ret) {
2024 /* this should not happen */
2025 darwin_release_interface (dev_handle, iface);
2026 usbi_err (HANDLE_CTX (dev_handle), "could not build endpoint table");
2027 }
2028 return ret;
2029 }
2030
2031 usbi_warn (HANDLE_CTX (dev_handle), "SetAlternateInterface: %s", darwin_error_str(kresult));
2032
2033 ret = darwin_to_libusb(kresult);
2034 if (ret != LIBUSB_ERROR_PIPE) {
2035 return ret;
2036 }
2037
2038 /* If a device only supports a default setting for the specified interface, then a STALL
2039 (kIOUSBPipeStalled) may be returned. Ref: USB 2.0 specs 9.4.10.
2040 Mimic the behaviour in e.g. the Linux kernel: in such case, reset all endpoints
2041 of the interface (as would have been done per 9.1.1.5) and return success. */
2042
2043 ret = check_alt_setting_and_clear_halt(dev_handle, altsetting, cInterface);
2044 if (LIBUSB_ERROR_NOT_FOUND == ret) {
2045 /* For some reason we need to reclaim the interface after the pipe error with some versions of macOS */
2046 ret = darwin_claim_interface (dev_handle, iface);
2047 if (LIBUSB_SUCCESS != ret) {
2048 darwin_release_interface (dev_handle, iface);
2049 usbi_err (HANDLE_CTX (dev_handle), "could not reclaim interface: %s", darwin_error_str(kresult));
2050 }
2051 ret = check_alt_setting_and_clear_halt(dev_handle, altsetting, cInterface);
2052 }
2053
2054 return ret;
2055 }
2056
2057 static int darwin_clear_halt(struct libusb_device_handle *dev_handle, unsigned char endpoint) {
2058 /* current interface */
2059 struct darwin_interface *cInterface;
2060 IOReturn kresult;
2061 uint8_t pipeRef;
2062
2063 /* determine the interface/endpoint to use */
2064 if (ep_to_pipeRef (dev_handle, endpoint, &pipeRef, NULL, &cInterface) != 0) {
2065 usbi_err (HANDLE_CTX (dev_handle), "endpoint not found on any open interface");
2066
2067 return LIBUSB_ERROR_NOT_FOUND;
2068 }
2069
2070 /* newer versions of darwin support clearing additional bits on the device's endpoint */
2071 kresult = (*IOINTERFACE(cInterface))->ClearPipeStallBothEnds(IOINTERFACE(cInterface), pipeRef);
2072 if (kresult != kIOReturnSuccess)
2073 usbi_warn (HANDLE_CTX (dev_handle), "ClearPipeStall: %s", darwin_error_str (kresult));
2074
2075 return darwin_to_libusb (kresult);
2076 }
2077
2078 static int darwin_restore_state (struct libusb_device_handle *dev_handle, uint8_t active_config,
2079 unsigned long claimed_interfaces) {
2080 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2081 struct darwin_device_handle_priv *priv = usbi_get_device_handle_priv(dev_handle);
2082 int open_count = dpriv->open_count;
2083 int ret;
2084
2085 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
2086
2087 /* clear claimed interfaces temporarily */
2088 dev_handle->claimed_interfaces = 0;
2089
2090 /* close and re-open the device */
2091 priv->is_open = false;
2092 dpriv->open_count = 1;
2093
2094 /* clean up open interfaces */
2095 darwin_close (dev_handle);
2096
2097 /* re-open the device */
2098 ret = darwin_open (dev_handle);
2099 dpriv->open_count = open_count;
2100 if (LIBUSB_SUCCESS != ret) {
2101 /* could not restore configuration */
2102 return LIBUSB_ERROR_NOT_FOUND;
2103 }
2104
2105 if (dpriv->active_config != active_config) {
2106 usbi_dbg (ctx, "darwin/restore_state: restoring configuration %d...", active_config);
2107
2108 ret = darwin_set_configuration (dev_handle, active_config);
2109 if (LIBUSB_SUCCESS != ret) {
2110 usbi_dbg (ctx, "darwin/restore_state: could not restore configuration");
2111 return LIBUSB_ERROR_NOT_FOUND;
2112 }
2113 }
2114
2115 usbi_dbg (ctx, "darwin/restore_state: reclaiming interfaces");
2116
2117 if (claimed_interfaces) {
2118 for (uint8_t iface = 0 ; iface < USB_MAXINTERFACES ; ++iface) {
2119 if (!(claimed_interfaces & (1U << iface))) {
2120 continue;
2121 }
2122
2123 usbi_dbg (ctx, "darwin/restore_state: re-claiming interface %u", iface);
2124
2125 ret = darwin_claim_interface (dev_handle, iface);
2126 if (LIBUSB_SUCCESS != ret) {
2127 usbi_dbg (ctx, "darwin/restore_state: could not claim interface %u", iface);
2128 return LIBUSB_ERROR_NOT_FOUND;
2129 }
2130
2131 dev_handle->claimed_interfaces |= 1U << iface;
2132 }
2133 }
2134
2135 usbi_dbg (ctx, "darwin/restore_state: device state restored");
2136
2137 return LIBUSB_SUCCESS;
2138 }
2139
2140 static int darwin_reenumerate_device (struct libusb_device_handle *dev_handle, bool capture) {
2141 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2142 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
2143 uint8_t active_config = dpriv->active_config;
2144 UInt32 options = 0;
2145 IOUSBDeviceDescriptor descriptor;
2146 IOUSBConfigurationDescriptorPtr cached_configuration;
2147 IOUSBConfigurationDescriptor *cached_configurations;
2148 IOReturn kresult;
2149 UInt8 i;
2150
2151 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
2152
2153 if (!dpriv->device) {
2154 usbi_warn(ctx, "darwin_reenumerate_device: device interface is NULL");
2155 return LIBUSB_ERROR_NO_DEVICE;
2156 }
2157
2158 if (atomic_exchange(&dpriv->in_reenumerate, true)) {
2159 /* ack, two (or more) threads are trying to reset the device! abort! */
2160 return LIBUSB_ERROR_NOT_FOUND;
2161 }
2162
2163 /* store copies of descriptors so they can be compared after the reset */
2164 memcpy (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor));
2165 cached_configurations = alloca (sizeof (*cached_configurations) * descriptor.bNumConfigurations);
2166
2167 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
2168 kresult = (*dpriv->device)->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
2169 if (kresult != kIOReturnSuccess) {
2170 atomic_store(&dpriv->in_reenumerate, false);
2171 return LIBUSB_ERROR_NOT_FOUND;
2172 }
2173 memcpy (cached_configurations + i, cached_configuration, sizeof (cached_configurations[i]));
2174 }
2175
2176 /* if we need to release capture */
2177 if (get_running_version() >= 101000) {
2178 if (capture) {
2179 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000
2180 options |= kUSBReEnumerateCaptureDeviceMask;
2181 #endif
2182 }
2183 } else {
2184 capture = false;
2185 }
2186
2187 /* from macOS 10.11 ResetDevice no longer does anything so just use USBDeviceReEnumerate */
2188 kresult = (*dpriv->device)->USBDeviceReEnumerate (dpriv->device, options);
2189 if (kresult != kIOReturnSuccess) {
2190 usbi_err (ctx, "USBDeviceReEnumerate: %s", darwin_error_str (kresult));
2191 atomic_store(&dpriv->in_reenumerate, false);
2192 return darwin_to_libusb (kresult);
2193 }
2194
2195 /* capture mode does not re-enumerate but it does require re-open */
2196 if (capture) {
2197 usbi_dbg (ctx, "darwin/reenumerate_device: restoring state...");
2198 atomic_store(&dpriv->in_reenumerate, false);
2199 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
2200 }
2201
2202 usbi_dbg (ctx, "darwin/reenumerate_device: waiting for re-enumeration to complete...");
2203
2204 struct timespec start;
2205 usbi_get_monotonic_time(&start);
2206
2207 while (atomic_load(&dpriv->in_reenumerate)) {
2208 const struct timespec delay = {.tv_sec = 0, .tv_nsec = 1000};
2209 nanosleep (&delay, NULL);
2210
2211 struct timespec now, delta;
2212 usbi_get_monotonic_time(&now);
2213 TIMESPEC_SUB(&now, &start, &delta);
2214 unsigned long long elapsed_us = ((unsigned long long)delta.tv_sec * USEC_PER_SEC) +
2215 ((unsigned long long)delta.tv_nsec / 1000ULL);
2216
2217 if (elapsed_us >= DARWIN_REENUMERATE_TIMEOUT_US) {
2218 usbi_err (ctx, "darwin/reenumerate_device: timeout waiting for reenumerate");
2219 atomic_store(&dpriv->in_reenumerate, false);
2220 return LIBUSB_ERROR_TIMEOUT;
2221 }
2222 }
2223
2224 /* compare descriptors */
2225 usbi_dbg (ctx, "darwin/reenumerate_device: checking whether descriptors changed");
2226
2227 if (memcmp (&descriptor, &dpriv->dev_descriptor, sizeof (descriptor)) != 0) {
2228 /* device descriptor changed. need to return not found. */
2229 usbi_dbg (ctx, "darwin/reenumerate_device: device descriptor changed");
2230 return LIBUSB_ERROR_NOT_FOUND;
2231 }
2232
2233 for (i = 0 ; i < descriptor.bNumConfigurations ; ++i) {
2234 kresult = (*dpriv->device)->GetConfigurationDescriptorPtr (dpriv->device, i, &cached_configuration);
2235 if (kresult != kIOReturnSuccess || memcmp (cached_configuration, cached_configurations + i, sizeof (cached_configurations[i])) != 0) {
2236 usbi_dbg (ctx, "darwin/reenumerate_device: configuration descriptor %d changed", i);
2237 return LIBUSB_ERROR_NOT_FOUND;
2238 }
2239 }
2240
2241 usbi_dbg (ctx, "darwin/reenumerate_device: device reset complete. restoring state...");
2242
2243 return darwin_restore_state (dev_handle, active_config, claimed_interfaces);
2244 }
2245
2246 static int darwin_reset_device (struct libusb_device_handle *dev_handle) {
2247 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2248 IOReturn kresult;
2249 enum libusb_error ret;
2250
2251 #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
2252 if (dpriv->capture_count > 0) {
2253 /* we have to use ResetDevice as USBDeviceReEnumerate() loses the authorization for capture */
2254 kresult = (*dpriv->device)->ResetDevice (dpriv->device);
2255 ret = darwin_to_libusb (kresult);
2256 } else {
2257 ret = darwin_reenumerate_device (dev_handle, false);
2258 }
2259 #else
2260 /* ResetDevice() is missing on non-macOS platforms */
2261 ret = darwin_reenumerate_device (dev_handle, false);
2262 if ((ret == LIBUSB_SUCCESS || ret == LIBUSB_ERROR_NOT_FOUND) && dpriv->capture_count > 0) {
2263 int capture_count;
2264 uint8_t active_config = dpriv->active_config;
2265 unsigned long claimed_interfaces = dev_handle->claimed_interfaces;
2266
2267 /* save old capture_count */
2268 capture_count = dpriv->capture_count;
2269 /* reset capture count */
2270 dpriv->capture_count = 0;
2271 /* attempt to detach kernel driver again as it is now re-attached */
2272 ret = darwin_detach_kernel_driver (dev_handle, 0);
2273 if (ret != LIBUSB_SUCCESS) {
2274 return ret;
2275 }
2276 /* restore capture_count */
2277 dpriv->capture_count = capture_count;
2278 /* restore configuration */
2279 ret = darwin_restore_state (dev_handle, active_config, claimed_interfaces);
2280 }
2281 #endif
2282 return ret;
2283 }
2284
2285 static io_service_t usb_find_interface_matching_location (const io_name_t class_name, UInt8 interface_number, UInt32 location) {
2286 CFMutableDictionaryRef matchingDict = IOServiceMatching (class_name);
2287 CFMutableDictionaryRef propertyMatchDict = CFDictionaryCreateMutable (kCFAllocatorDefault, 0,
2288 &kCFTypeDictionaryKeyCallBacks,
2289 &kCFTypeDictionaryValueCallBacks);
2290 CFTypeRef locationCF = CFNumberCreate (NULL, kCFNumberSInt32Type, &location);
2291 CFTypeRef interfaceCF = CFNumberCreate (NULL, kCFNumberSInt8Type, &interface_number);
2292
2293 CFDictionarySetValue (matchingDict, CFSTR(kIOPropertyMatchKey), propertyMatchDict);
2294 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBDevicePropertyLocationID), locationCF);
2295 CFDictionarySetValue (propertyMatchDict, CFSTR(kUSBHostMatchingPropertyInterfaceNumber), interfaceCF);
2296
2297 CFRelease (interfaceCF);
2298 CFRelease (locationCF);
2299 CFRelease (propertyMatchDict);
2300
2301 return IOServiceGetMatchingService (darwin_default_master_port, matchingDict);
2302 }
2303
2304 static int darwin_kernel_driver_active(struct libusb_device_handle *dev_handle, uint8_t interface) {
2305 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2306 io_service_t usb_interface, child = IO_OBJECT_NULL;
2307
2308 /* locate the IO registry entry for this interface */
2309 usb_interface = usb_find_interface_matching_location (kIOUSBHostInterfaceClassName, interface, dpriv->location);
2310 if (0 == usb_interface) {
2311 /* check for the legacy class entry */
2312 usb_interface = usb_find_interface_matching_location (kIOUSBInterfaceClassName, interface, dpriv->location);
2313 if (0 == usb_interface) {
2314 return LIBUSB_ERROR_NOT_FOUND;
2315 }
2316 }
2317
2318 /* if the IO object has a child entry in the IO Registry it has a kernel driver attached */
2319 (void) IORegistryEntryGetChildEntry (usb_interface, kIOServicePlane, &child);
2320 IOObjectRelease (usb_interface);
2321 if (IO_OBJECT_NULL != child) {
2322 IOObjectRelease (child);
2323 return 1;
2324 }
2325
2326 /* no driver */
2327 return 0;
2328 }
2329
2330 static void darwin_destroy_device(struct libusb_device *dev) {
2331 struct darwin_device_priv *dpriv = usbi_get_device_priv(dev);
2332
2333 if (dpriv->dev) {
2334 /* need to hold the lock in case this is the last reference to the device */
2335 usbi_mutex_lock(&darwin_cached_devices_mutex);
2336 darwin_deref_cached_device (dpriv->dev);
2337 dpriv->dev = NULL;
2338 usbi_mutex_unlock(&darwin_cached_devices_mutex);
2339 }
2340 }
2341
2342 static int submit_bulk_transfer(struct usbi_transfer *itransfer) {
2343 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2344
2345 IOReturn ret;
2346 uint8_t pipeRef;
2347
2348 struct darwin_interface *cInterface;
2349 darwin_pipe_properties_t pipe_properties;
2350
2351 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2352 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2353
2354 return LIBUSB_ERROR_NOT_FOUND;
2355 }
2356
2357 ret = darwin_get_pipe_properties(cInterface, pipeRef, &pipe_properties);
2358 if (kIOReturnSuccess != ret) {
2359 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
2360 darwin_error_str(ret), ret);
2361 return darwin_to_libusb (ret);
2362 }
2363
2364 if (0 != (transfer->length % pipe_properties.max_packet_size)) {
2365 /* do not need a zero packet */
2366 transfer->flags &= ~LIBUSB_TRANSFER_ADD_ZERO_PACKET;
2367 }
2368
2369 /* submit the request */
2370 /* timeouts are unavailable on interrupt endpoints */
2371 if (pipe_properties.transfer_type == kUSBInterrupt) {
2372 if (IS_XFERIN(transfer))
2373 ret = (*IOINTERFACE(cInterface))->ReadPipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2374 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
2375 else
2376 ret = (*IOINTERFACE(cInterface))->WritePipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2377 (UInt32)transfer->length, darwin_async_io_callback, itransfer);
2378 } else {
2379 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2380
2381 if (IS_XFERIN(transfer))
2382 ret = (*IOINTERFACE(cInterface))->ReadPipeAsyncTO(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2383 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
2384 darwin_async_io_callback, itransfer);
2385 else
2386 ret = (*IOINTERFACE(cInterface))->WritePipeAsyncTO(IOINTERFACE(cInterface), pipeRef, transfer->buffer,
2387 (UInt32)transfer->length, transfer->timeout, transfer->timeout,
2388 darwin_async_io_callback, itransfer);
2389 }
2390
2391 if (ret)
2392 usbi_err (TRANSFER_CTX (transfer), "bulk transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
2393 darwin_error_str(ret), ret);
2394
2395 return darwin_to_libusb (ret);
2396 }
2397
2398 #if MAX_INTERFACE_VERSION >= 550
2399 static int submit_stream_transfer(struct usbi_transfer *itransfer) {
2400 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2401 struct darwin_interface *cInterface;
2402 uint8_t pipeRef;
2403 IOReturn ret;
2404
2405 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2406 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2407
2408 return LIBUSB_ERROR_NOT_FOUND;
2409 }
2410
2411 if (get_interface_interface_version() < 550) {
2412 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version %d does not support bulk stream transfers",
2413 get_interface_interface_version());
2414 return LIBUSB_ERROR_NOT_SUPPORTED;
2415 }
2416
2417 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2418
2419 if (IS_XFERIN(transfer))
2420 ret = (*IOINTERFACE_V(cInterface, 550))->ReadStreamsPipeAsyncTO(IOINTERFACE(cInterface), pipeRef, itransfer->stream_id,
2421 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
2422 transfer->timeout, darwin_async_io_callback, itransfer);
2423 else
2424 ret = (*IOINTERFACE_V(cInterface, 550))->WriteStreamsPipeAsyncTO(IOINTERFACE(cInterface), pipeRef, itransfer->stream_id,
2425 transfer->buffer, (UInt32)transfer->length, transfer->timeout,
2426 transfer->timeout, darwin_async_io_callback, itransfer);
2427
2428 if (ret)
2429 usbi_err (TRANSFER_CTX (transfer), "bulk stream transfer failed (dir = %s): %s (code = 0x%08x)", IS_XFERIN(transfer) ? "In" : "Out",
2430 darwin_error_str(ret), ret);
2431
2432 return darwin_to_libusb (ret);
2433 }
2434 #endif
2435
2436 static int submit_iso_transfer(struct usbi_transfer *itransfer) {
2437 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2438 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2439
2440 IOReturn kresult;
2441 uint8_t pipeRef;
2442 UInt64 frame;
2443 AbsoluteTime atTime;
2444 int i;
2445 darwin_pipe_properties_t pipe_properties;
2446 struct darwin_interface *cInterface;
2447
2448 /* construct an array of IOUSBIsocFrames, reuse the old one if the sizes are the same */
2449 if (tpriv->num_iso_packets != transfer->num_iso_packets) {
2450 free(tpriv->isoc_framelist);
2451 tpriv->isoc_framelist = NULL;
2452 }
2453
2454 if (!tpriv->isoc_framelist) {
2455 tpriv->num_iso_packets = transfer->num_iso_packets;
2456 tpriv->isoc_framelist = (IOUSBIsocFrame*) calloc ((size_t)transfer->num_iso_packets, sizeof(IOUSBIsocFrame));
2457 if (!tpriv->isoc_framelist)
2458 return LIBUSB_ERROR_NO_MEM;
2459 }
2460
2461 /* copy the frame list from the libusb descriptor (the structures differ only is member order) */
2462 for (i = 0 ; i < transfer->num_iso_packets ; i++) {
2463 unsigned int length = transfer->iso_packet_desc[i].length;
2464 assert(length <= UINT16_MAX);
2465 tpriv->isoc_framelist[i].frReqCount = (UInt16)length;
2466 }
2467
2468 /* determine the interface/endpoint to use */
2469 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2470 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2471
2472 return LIBUSB_ERROR_NOT_FOUND;
2473 }
2474
2475 /* determine the properties of this endpoint and the speed of the device */
2476 kresult = darwin_get_pipe_properties(cInterface, pipeRef, &pipe_properties);
2477 if (kresult != kIOReturnSuccess) {
2478 usbi_err (TRANSFER_CTX (transfer), "failed to get pipe properties: %d", kresult);
2479 free(tpriv->isoc_framelist);
2480 tpriv->isoc_framelist = NULL;
2481
2482 return darwin_to_libusb (kresult);
2483 }
2484
2485 /* Last but not least we need the bus frame number */
2486 kresult = (*IOINTERFACE(cInterface))->GetBusFrameNumber(IOINTERFACE(cInterface), &frame, &atTime);
2487 if (kresult != kIOReturnSuccess) {
2488 usbi_err (TRANSFER_CTX (transfer), "failed to get bus frame number: %d", kresult);
2489 free(tpriv->isoc_framelist);
2490 tpriv->isoc_framelist = NULL;
2491
2492 return darwin_to_libusb (kresult);
2493 }
2494
2495 /* schedule for a frame a little in the future */
2496 frame += 4;
2497
2498 if (cInterface->frames[transfer->endpoint] && frame < cInterface->frames[transfer->endpoint])
2499 frame = cInterface->frames[transfer->endpoint];
2500
2501 /* submit the request */
2502 if (IS_XFERIN(transfer))
2503 kresult = (*IOINTERFACE(cInterface))->ReadIsochPipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer, frame,
2504 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
2505 itransfer);
2506 else
2507 kresult = (*IOINTERFACE(cInterface))->WriteIsochPipeAsync(IOINTERFACE(cInterface), pipeRef, transfer->buffer, frame,
2508 (UInt32)transfer->num_iso_packets, tpriv->isoc_framelist, darwin_async_io_callback,
2509 itransfer);
2510
2511 if (LIBUSB_SPEED_FULL == transfer->dev_handle->dev->speed)
2512 /* Full speed */
2513 cInterface->frames[transfer->endpoint] = frame + (UInt64)transfer->num_iso_packets * (1UL << (pipe_properties.interval - 1));
2514 else
2515 /* High/super speed */
2516 cInterface->frames[transfer->endpoint] = frame + (UInt64)transfer->num_iso_packets * (1UL << (pipe_properties.interval - 1)) / 8;
2517
2518 if (kresult != kIOReturnSuccess) {
2519 usbi_err (TRANSFER_CTX (transfer), "isochronous transfer failed (dir: %s): %s", IS_XFERIN(transfer) ? "In" : "Out",
2520 darwin_error_str(kresult));
2521 free (tpriv->isoc_framelist);
2522 tpriv->isoc_framelist = NULL;
2523 }
2524
2525 return darwin_to_libusb (kresult);
2526 }
2527
2528 static int submit_control_transfer(struct usbi_transfer *itransfer) {
2529 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2530 struct libusb_control_setup *setup = (struct libusb_control_setup *) transfer->buffer;
2531 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2532 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2533
2534 IOReturn kresult;
2535
2536 memset(&tpriv->req, 0, sizeof(tpriv->req));
2537
2538 /* IOUSBDeviceInterface expects the request in cpu endianness */
2539 tpriv->req.bmRequestType = setup->bmRequestType;
2540 tpriv->req.bRequest = setup->bRequest;
2541 /* these values should be in bus order from libusb_fill_control_setup */
2542 tpriv->req.wValue = OSSwapLittleToHostInt16 (setup->wValue);
2543 tpriv->req.wIndex = OSSwapLittleToHostInt16 (setup->wIndex);
2544 tpriv->req.wLength = OSSwapLittleToHostInt16 (setup->wLength);
2545 /* data is stored after the libusb control block */
2546 tpriv->req.pData = transfer->buffer + LIBUSB_CONTROL_SETUP_SIZE;
2547 tpriv->req.completionTimeout = transfer->timeout;
2548 tpriv->req.noDataTimeout = transfer->timeout;
2549
2550 itransfer->timeout_flags |= USBI_TRANSFER_OS_HANDLES_TIMEOUT;
2551
2552 /* all transfers in libusb-1.0 are async */
2553
2554 if (transfer->endpoint) {
2555 struct darwin_interface *cInterface;
2556 uint8_t pipeRef;
2557
2558 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface) != 0) {
2559 usbi_err (TRANSFER_CTX (transfer), "endpoint not found on any open interface");
2560
2561 return LIBUSB_ERROR_NOT_FOUND;
2562 }
2563
2564 kresult = (*IOINTERFACE(cInterface))->ControlRequestAsyncTO (IOINTERFACE(cInterface), pipeRef,
2565 &(tpriv->req), darwin_async_io_callback, itransfer);
2566 } else
2567 /* control request on endpoint 0 */
2568 kresult = (*dpriv->device)->DeviceRequestAsyncTO(dpriv->device, &(tpriv->req), darwin_async_io_callback, itransfer);
2569
2570 if (kresult != kIOReturnSuccess)
2571 usbi_err (TRANSFER_CTX (transfer), "control request failed: %s", darwin_error_str(kresult));
2572
2573 return darwin_to_libusb (kresult);
2574 }
2575
2576 static int darwin_submit_transfer(struct usbi_transfer *itransfer) {
2577 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2578
2579 switch (transfer->type) {
2580 case LIBUSB_TRANSFER_TYPE_CONTROL:
2581 return submit_control_transfer(itransfer);
2582 case LIBUSB_TRANSFER_TYPE_BULK:
2583 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2584 return submit_bulk_transfer(itransfer);
2585 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2586 return submit_iso_transfer(itransfer);
2587 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2588 #if MAX_INTERFACE_VERSION >= 550
2589 return submit_stream_transfer(itransfer);
2590 #else
2591 usbi_err (TRANSFER_CTX(transfer), "IOUSBFamily version does not support bulk stream transfers");
2592 return LIBUSB_ERROR_NOT_SUPPORTED;
2593 #endif
2594 default:
2595 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2596 return LIBUSB_ERROR_INVALID_PARAM;
2597 }
2598 }
2599
2600 static int cancel_control_transfer(struct usbi_transfer *itransfer) {
2601 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2602 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2603 IOReturn kresult;
2604
2605 usbi_warn (ITRANSFER_CTX (itransfer), "aborting all transactions control pipe");
2606
2607 if (!dpriv->device) {
2608 return LIBUSB_ERROR_NO_DEVICE;
2609 }
2610
2611 kresult = (*dpriv->device)->USBDeviceAbortPipeZero (dpriv->device);
2612
2613 return darwin_to_libusb (kresult);
2614 }
2615
2616 static int darwin_abort_transfers (struct usbi_transfer *itransfer) {
2617 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2618 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(transfer->dev_handle->dev);
2619 struct darwin_interface *cInterface;
2620 uint8_t pipeRef, iface;
2621 IOReturn kresult;
2622
2623 struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
2624
2625 if (ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, &iface, &cInterface) != 0) {
2626 usbi_err (ctx, "endpoint not found on any open interface");
2627
2628 return LIBUSB_ERROR_NOT_FOUND;
2629 }
2630
2631 if (!dpriv->device) {
2632 return LIBUSB_ERROR_NO_DEVICE;
2633 }
2634
2635 usbi_warn (ctx, "aborting all transactions on interface %d pipe %d", iface, pipeRef);
2636
2637 /* abort transactions */
2638 #if MAX_INTERFACE_VERSION >= 550
2639 if (LIBUSB_TRANSFER_TYPE_BULK_STREAM == transfer->type && get_interface_interface_version() >= 550) {
2640 kresult = (*IOINTERFACE_V(cInterface, 550))->AbortStreamsPipe (IOINTERFACE(cInterface), pipeRef, itransfer->stream_id);
2641 } else
2642 #endif
2643 {
2644 kresult = (*IOINTERFACE(cInterface))->AbortPipe (IOINTERFACE(cInterface), pipeRef);
2645 }
2646
2647
2648 if (get_interface_interface_version() <= 245) {
2649 /* with older releases of IOUSBFamily the OS always clears the host side data toggle. for
2650 consistency also clear the data toggle on the device. */
2651 usbi_dbg (ctx, "calling ClearPipeStallBothEnds to clear the data toggle bit");
2652 kresult = (*IOINTERFACE(cInterface))->ClearPipeStallBothEnds(IOINTERFACE(cInterface), pipeRef);
2653 }
2654
2655 return darwin_to_libusb (kresult);
2656 }
2657
2658 static int darwin_cancel_transfer(struct usbi_transfer *itransfer) {
2659 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2660
2661 switch (transfer->type) {
2662 case LIBUSB_TRANSFER_TYPE_CONTROL:
2663 return cancel_control_transfer(itransfer);
2664 case LIBUSB_TRANSFER_TYPE_BULK:
2665 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2666 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2667 return darwin_abort_transfers (itransfer);
2668 default:
2669 usbi_err (TRANSFER_CTX(transfer), "unknown endpoint type %d", transfer->type);
2670 return LIBUSB_ERROR_INVALID_PARAM;
2671 }
2672 }
2673
2674 static void darwin_async_io_callback (void *refcon, IOReturn result, void *arg0) {
2675 struct usbi_transfer *itransfer = (struct usbi_transfer *)refcon;
2676 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2677 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2678
2679 usbi_dbg (TRANSFER_CTX(transfer), "an async io operation has completed");
2680
2681 /* if requested write a zero packet */
2682 if (kIOReturnSuccess == result && IS_XFEROUT(transfer) && transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) {
2683 struct darwin_interface *cInterface;
2684 uint8_t pipeRef;
2685
2686 (void) ep_to_pipeRef (transfer->dev_handle, transfer->endpoint, &pipeRef, NULL, &cInterface);
2687
2688 (*IOINTERFACE(cInterface))->WritePipe (IOINTERFACE(cInterface), pipeRef, transfer->buffer, 0);
2689 }
2690
2691 tpriv->result = result;
2692 tpriv->size = (UInt32) (uintptr_t) arg0;
2693
2694 /* signal the core that this transfer is complete */
2695 usbi_signal_transfer_completion(itransfer);
2696 }
2697
2698 static enum libusb_transfer_status darwin_transfer_status (struct usbi_transfer *itransfer, IOReturn result) {
2699 if (itransfer->timeout_flags & USBI_TRANSFER_TIMED_OUT)
2700 result = kIOUSBTransactionTimeout;
2701
2702 struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
2703
2704 switch (result) {
2705 case kIOReturnUnderrun:
2706 case kIOReturnSuccess:
2707 return LIBUSB_TRANSFER_COMPLETED;
2708 case kIOReturnAborted:
2709 return LIBUSB_TRANSFER_CANCELLED;
2710 case kIOUSBPipeStalled:
2711 usbi_dbg (ctx, "transfer error: pipe is stalled");
2712 return LIBUSB_TRANSFER_STALL;
2713 case kIOReturnOverrun:
2714 usbi_warn (ctx, "transfer error: data overrun");
2715 return LIBUSB_TRANSFER_OVERFLOW;
2716 case kIOUSBTransactionTimeout:
2717 usbi_warn (ctx, "transfer error: timed out");
2718 itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
2719 return LIBUSB_TRANSFER_TIMED_OUT;
2720 default:
2721 usbi_warn (ctx, "transfer error: %s (value = 0x%08x)", darwin_error_str (result), result);
2722 return LIBUSB_TRANSFER_ERROR;
2723 }
2724 }
2725
2726 static int darwin_handle_transfer_completion (struct usbi_transfer *itransfer) {
2727 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2728 struct darwin_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2729 const unsigned char max_transfer_type = LIBUSB_TRANSFER_TYPE_BULK_STREAM;
2730 #ifdef ENABLE_LOGGING
2731 const char *transfer_types[] = {"control", "isoc", "bulk", "interrupt", "bulk-stream", NULL};
2732 #endif
2733 bool is_isoc = LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type;
2734 struct libusb_context *ctx = ITRANSFER_CTX (itransfer);
2735
2736 if (transfer->type > max_transfer_type) {
2737 usbi_err (ctx, "unknown endpoint type %d", transfer->type);
2738 return LIBUSB_ERROR_INVALID_PARAM;
2739 }
2740
2741 if (NULL == tpriv) {
2742 usbi_err (ctx, "malformed request is missing transfer priv");
2743 return LIBUSB_ERROR_INVALID_PARAM;
2744 }
2745
2746 usbi_dbg (ctx, "handling transfer completion type %s with kernel status %d", transfer_types[transfer->type], tpriv->result);
2747
2748 if (kIOReturnSuccess == tpriv->result || kIOReturnUnderrun == tpriv->result || kIOUSBTransactionTimeout == tpriv->result) {
2749 if (is_isoc && tpriv->isoc_framelist) {
2750 /* copy isochronous results back */
2751
2752 for (int i = 0; i < transfer->num_iso_packets ; i++) {
2753 struct libusb_iso_packet_descriptor *lib_desc = &transfer->iso_packet_desc[i];
2754 lib_desc->status = darwin_transfer_status (itransfer, tpriv->isoc_framelist[i].frStatus);
2755 lib_desc->actual_length = tpriv->isoc_framelist[i].frActCount;
2756 }
2757 } else if (!is_isoc) {
2758 itransfer->transferred += tpriv->size;
2759 }
2760 }
2761
2762 /* it is ok to handle cancelled transfers without calling usbi_handle_transfer_cancellation (we catch timeout transfers) */
2763 return usbi_handle_transfer_completion (itransfer, darwin_transfer_status (itransfer, tpriv->result));
2764 }
2765
2766 void usbi_get_monotonic_time(struct timespec *tp) {
2767 /* Check if the SDK is new enough to declare clock_gettime(), and the deployment target is at least 10.12. */
2768 #if ((MAC_OS_X_VERSION_MAX_ALLOWED >= 101200) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 101200))
2769 clock_gettime(CLOCK_MONOTONIC, tp);
2770 #else
2771 mach_timebase_info_data_t machTimeBaseInfo;
2772 mach_timebase_info(&machTimeBaseInfo);
2773
2774 uint64_t uptime = mach_absolute_time();
2775 uint64_t uptimeNano = uptime * machTimeBaseInfo.numer / machTimeBaseInfo.denom;
2776
2777 uint64_t uptimeSeconds = uptimeNano / NSEC_PER_SEC;
2778 uint64_t uptimeNanoRemainder = uptimeNano - (uptimeSeconds * NSEC_PER_SEC);
2779
2780 tp->tv_sec = uptimeSeconds;
2781 tp->tv_nsec = uptimeNanoRemainder;
2782 #endif
2783 }
2784
2785 void usbi_get_real_time(struct timespec *tp) {
2786 /* Check if the SDK is new enough to declare clock_gettime(), and the deployment target is at least 10.12. */
2787 #if ((MAC_OS_X_VERSION_MAX_ALLOWED >= 101200) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 101200))
2788 clock_gettime(CLOCK_REALTIME, tp);
2789 #else
2790 struct timeval tv;
2791 gettimeofday(&tv, NULL);
2792 tp->tv_sec = tv.tv_sec;
2793 tp->tv_nsec = tv.tv_usec * NSEC_PER_USEC;
2794 #endif
2795 }
2796
2797 #if MAX_INTERFACE_VERSION >= 550
2798 static int darwin_alloc_streams (struct libusb_device_handle *dev_handle, uint32_t num_streams, unsigned char *endpoints,
2799 int num_endpoints) {
2800 struct darwin_interface *cInterface;
2801 UInt32 supportsStreams;
2802 uint8_t pipeRef;
2803 int rc, i;
2804
2805 /* find the minimum number of supported streams on the endpoint list */
2806 for (i = 0 ; i < num_endpoints ; ++i) {
2807 rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2808 if (0 != rc) {
2809 return rc;
2810 }
2811
2812 (*IOINTERFACE_V(cInterface, 550))->SupportsStreams (IOINTERFACE(cInterface), pipeRef, &supportsStreams);
2813 if (num_streams > supportsStreams)
2814 num_streams = supportsStreams;
2815 }
2816
2817 /* it is an error if any endpoint in endpoints does not support streams */
2818 if (0 == num_streams)
2819 return LIBUSB_ERROR_INVALID_PARAM;
2820
2821 /* create the streams */
2822 for (i = 0 ; i < num_endpoints ; ++i) {
2823 (void) ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2824
2825 rc = (*IOINTERFACE_V(cInterface, 550))->CreateStreams (IOINTERFACE(cInterface), pipeRef, num_streams);
2826 if (kIOReturnSuccess != rc)
2827 return darwin_to_libusb(rc);
2828 }
2829
2830 assert(num_streams <= INT_MAX);
2831 return (int)num_streams;
2832 }
2833
2834 static int darwin_free_streams (struct libusb_device_handle *dev_handle, unsigned char *endpoints, int num_endpoints) {
2835 struct darwin_interface *cInterface;
2836 UInt32 supportsStreams;
2837 uint8_t pipeRef;
2838 int rc;
2839
2840 for (int i = 0 ; i < num_endpoints ; ++i) {
2841 rc = ep_to_pipeRef (dev_handle, endpoints[i], &pipeRef, NULL, &cInterface);
2842 if (0 != rc)
2843 return rc;
2844
2845 (*IOINTERFACE_V(cInterface, 550))->SupportsStreams (IOINTERFACE(cInterface), pipeRef, &supportsStreams);
2846 if (0 == supportsStreams)
2847 return LIBUSB_ERROR_INVALID_PARAM;
2848
2849 rc = (*IOINTERFACE_V(cInterface, 550))->CreateStreams (IOINTERFACE(cInterface), pipeRef, 0);
2850 if (kIOReturnSuccess != rc)
2851 return darwin_to_libusb(rc);
2852 }
2853
2854 return LIBUSB_SUCCESS;
2855 }
2856 #endif
2857
2858 #if MAX_INTERFACE_VERSION >= 700
2859
2860 /* macOS APIs for getting entitlement values */
2861
2862 #if !defined(TARGET_OS_OSX) || TARGET_OS_OSX == 1
2863 #include <Security/Security.h>
2864 #else
2865 typedef struct __SecTask *SecTaskRef;
2866 extern SecTaskRef SecTaskCreateFromSelf(CFAllocatorRef allocator);
2867 extern CFTypeRef SecTaskCopyValueForEntitlement(SecTaskRef task, CFStringRef entitlement, CFErrorRef *error);
2868 #endif
2869
2870 static bool darwin_has_capture_entitlements (void) {
2871 SecTaskRef task;
2872 CFTypeRef value;
2873 bool entitled;
2874
2875 task = SecTaskCreateFromSelf (kCFAllocatorDefault);
2876 if (task == NULL) {
2877 return false;
2878 }
2879 value = SecTaskCopyValueForEntitlement(task, CFSTR("com.apple.vm.device-access"), NULL);
2880 CFRelease (task);
2881 entitled = value && (CFGetTypeID (value) == CFBooleanGetTypeID ()) && CFBooleanGetValue (value);
2882 if (value) {
2883 CFRelease (value);
2884 }
2885 return entitled;
2886 }
2887
2888 static int darwin_reload_device (struct libusb_device_handle *dev_handle) {
2889 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2890 enum libusb_error err;
2891
2892 usbi_mutex_lock(&darwin_cached_devices_mutex);
2893 (*dpriv->device)->Release(dpriv->device);
2894 err = darwin_device_from_service (HANDLE_CTX (dev_handle), dpriv->service, &dpriv->device);
2895 usbi_mutex_unlock(&darwin_cached_devices_mutex);
2896
2897 return err;
2898 }
2899
2900 /* On macOS, we capture an entire device at once, not individual interfaces. */
2901
2902 static int darwin_detach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2903 UNUSED(interface);
2904 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2905 IOReturn kresult;
2906 enum libusb_error err;
2907 struct libusb_context *ctx = HANDLE_CTX (dev_handle);
2908
2909 if (get_interface_interface_version() < 700) {
2910 return LIBUSB_ERROR_NOT_SUPPORTED;
2911 }
2912
2913 if (dpriv->capture_count == 0) {
2914 usbi_dbg (ctx, "attempting to detach kernel driver from device");
2915
2916 if (darwin_has_capture_entitlements ()) {
2917 /* request authorization */
2918 kresult = IOServiceAuthorize (dpriv->service, kIOServiceInteractionAllowed);
2919 if (kresult != kIOReturnSuccess) {
2920 usbi_warn (ctx, "IOServiceAuthorize: %s", darwin_error_str(kresult));
2921 return darwin_to_libusb (kresult);
2922 }
2923
2924 /* we need start() to be called again for authorization status to refresh */
2925 err = darwin_reload_device (dev_handle);
2926 if (err != LIBUSB_SUCCESS) {
2927 return err;
2928 }
2929 } else {
2930 usbi_info (ctx, "no capture entitlements. may not be able to detach the kernel driver for this device");
2931 if (0 != geteuid()) {
2932 usbi_warn (ctx, "USB device capture requires either an entitlement (com.apple.vm.device-access) or root privilege");
2933 return LIBUSB_ERROR_ACCESS;
2934 }
2935 }
2936
2937 /* reset device to release existing drivers */
2938 err = darwin_reenumerate_device (dev_handle, true);
2939 if (err != LIBUSB_SUCCESS) {
2940 return err;
2941 }
2942 }
2943 dpriv->capture_count++;
2944 return LIBUSB_SUCCESS;
2945 }
2946
2947
2948 static int darwin_attach_kernel_driver (struct libusb_device_handle *dev_handle, uint8_t interface) {
2949 UNUSED(interface);
2950 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2951
2952 if (get_interface_interface_version() < 700) {
2953 return LIBUSB_ERROR_NOT_SUPPORTED;
2954 }
2955
2956 dpriv->capture_count--;
2957 if (dpriv->capture_count > 0) {
2958 return LIBUSB_SUCCESS;
2959 }
2960
2961 usbi_dbg (HANDLE_CTX (dev_handle), "reenumerating device for kernel driver attach");
2962
2963 /* reset device to attach kernel drivers */
2964 return darwin_reenumerate_device (dev_handle, false);
2965 }
2966
2967 static int darwin_capture_claim_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2968 enum libusb_error ret;
2969 if (dev_handle->auto_detach_kernel_driver && darwin_kernel_driver_active(dev_handle, iface)) {
2970 ret = darwin_detach_kernel_driver (dev_handle, iface);
2971 if (ret != LIBUSB_SUCCESS) {
2972 usbi_info (HANDLE_CTX (dev_handle), "failed to auto-detach the kernel driver for this device, ret=%d", ret);
2973 }
2974 }
2975
2976 return darwin_claim_interface (dev_handle, iface);
2977 }
2978
2979 static int darwin_capture_release_interface(struct libusb_device_handle *dev_handle, uint8_t iface) {
2980 enum libusb_error ret;
2981 struct darwin_cached_device *dpriv = DARWIN_CACHED_DEVICE(dev_handle->dev);
2982
2983 ret = darwin_release_interface (dev_handle, iface);
2984 if (ret != LIBUSB_SUCCESS) {
2985 return ret;
2986 }
2987
2988 if (dev_handle->auto_detach_kernel_driver && dpriv->capture_count > 0) {
2989 ret = darwin_attach_kernel_driver (dev_handle, iface);
2990 if (LIBUSB_SUCCESS != ret) {
2991 usbi_info (HANDLE_CTX (dev_handle), "on attempt to reattach the kernel driver got ret=%d", ret);
2992 }
2993 /* ignore the error as the interface was successfully released */
2994 }
2995
2996 return LIBUSB_SUCCESS;
2997 }
2998
2999 #endif
3000
3001 const struct usbi_os_backend usbi_backend = {
3002 .name = "Darwin",
3003 .caps = USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
3004 .init = darwin_init,
3005 .exit = darwin_exit,
3006 .set_option = NULL,
3007 .get_device_list = NULL,
3008 .get_device_string = darwin_get_device_string,
3009 .hotplug_poll = darwin_hotplug_poll,
3010 .wrap_sys_device = NULL,
3011 .open = darwin_open,
3012 .close = darwin_close,
3013 .get_active_config_descriptor = darwin_get_active_config_descriptor,
3014 .get_config_descriptor = darwin_get_config_descriptor,
3015 .get_config_descriptor_by_value = NULL,
3016 .get_configuration = darwin_get_configuration,
3017 .set_configuration = darwin_set_configuration,
3018
3019 #if MAX_INTERFACE_VERSION >= 700
3020 .claim_interface = darwin_capture_claim_interface,
3021 .release_interface = darwin_capture_release_interface,
3022 #else
3023 .claim_interface = darwin_claim_interface,
3024 .release_interface = darwin_release_interface,
3025 #endif
3026
3027 .set_interface_altsetting = darwin_set_interface_altsetting,
3028 .clear_halt = darwin_clear_halt,
3029 .reset_device = darwin_reset_device,
3030
3031 #if MAX_INTERFACE_VERSION >= 550
3032 .alloc_streams = darwin_alloc_streams,
3033 .free_streams = darwin_free_streams,
3034 #endif
3035
3036 .dev_mem_alloc = NULL,
3037 .dev_mem_free = NULL,
3038 .kernel_driver_active = darwin_kernel_driver_active,
3039
3040 #if MAX_INTERFACE_VERSION >= 700
3041 .detach_kernel_driver = darwin_detach_kernel_driver,
3042 .attach_kernel_driver = darwin_attach_kernel_driver,
3043 #endif
3044
3045 .destroy_device = darwin_destroy_device,
3046
3047 .submit_transfer = darwin_submit_transfer,
3048 .cancel_transfer = darwin_cancel_transfer,
3049 .clear_transfer_priv = NULL,
3050 .handle_events = NULL,
3051 .handle_transfer_completion = darwin_handle_transfer_completion,
3052
3053 .context_priv_size = 0,
3054 .device_priv_size = sizeof(struct darwin_device_priv),
3055 .device_handle_priv_size = sizeof(struct darwin_device_handle_priv),
3056 .transfer_priv_size = sizeof(struct darwin_transfer_priv),
3057 };