1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define TRACE_TAG USB
18 
19 #include "sysdeps.h"
20 
21 #include "client/usb.h"
22 
23 #include <CoreFoundation/CoreFoundation.h>
24 
25 #include <IOKit/IOKitLib.h>
26 #include <IOKit/IOCFPlugIn.h>
27 #include <IOKit/usb/IOUSBLib.h>
28 #include <IOKit/IOMessage.h>
29 #include <mach/mach_port.h>
30 
31 #include <inttypes.h>
32 #include <stdio.h>
33 
34 #include <atomic>
35 #include <chrono>
36 #include <memory>
37 #include <mutex>
38 #include <thread>
39 #include <vector>
40 
41 #include <android-base/logging.h>
42 #include <android-base/stringprintf.h>
43 #include <android-base/thread_annotations.h>
44 
45 #include "adb.h"
46 #include "transport.h"
47 
48 using namespace std::chrono_literals;
49 
50 struct usb_handle
51 {
52     UInt8 bulkIn;
53     UInt8 bulkOut;
54     IOUSBInterfaceInterface550** interface;
55     unsigned int zero_mask;
56     size_t max_packet_size;
57 
58     // For garbage collecting disconnected devices.
59     bool mark;
60     std::string devpath;
61     std::atomic<bool> dead;
62 
usb_handleusb_handle63     usb_handle()
64         : bulkIn(0),
65           bulkOut(0),
66           interface(nullptr),
67           zero_mask(0),
68           max_packet_size(0),
69           mark(false),
70           dead(false) {}
71 };
72 
73 static std::atomic<bool> usb_inited_flag;
74 
75 static auto& g_usb_handles_mutex = *new std::mutex();
76 static auto& g_usb_handles = *new std::vector<std::unique_ptr<usb_handle>>();
77 
IsKnownDevice(const std::string & devpath)78 static bool IsKnownDevice(const std::string& devpath) {
79     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
80     for (auto& usb : g_usb_handles) {
81         if (usb->devpath == devpath) {
82             // Set mark flag to indicate this device is still alive.
83             usb->mark = true;
84             return true;
85         }
86     }
87     return false;
88 }
89 
90 static void usb_kick_locked(usb_handle* handle);
91 
KickDisconnectedDevices()92 static void KickDisconnectedDevices() {
93     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
94     for (auto& usb : g_usb_handles) {
95         if (!usb->mark) {
96             usb_kick_locked(usb.get());
97         } else {
98             usb->mark = false;
99         }
100     }
101 }
102 
AddDevice(std::unique_ptr<usb_handle> handle)103 static void AddDevice(std::unique_ptr<usb_handle> handle) {
104     handle->mark = true;
105     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
106     g_usb_handles.push_back(std::move(handle));
107 }
108 
109 static void AndroidInterfaceAdded(io_iterator_t iterator);
110 static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface550** iface, UInt16 vendor,
111                                                   UInt16 product);
112 
113 // Flag-guarded (using host env variable) feature that turns on
114 // the ability to clear the device-side endpoint also before
115 // starting. See public bug https://issuetracker.google.com/issues/37055927
116 // for historical context.
clear_endpoints()117 static bool clear_endpoints() {
118     static const char* env(getenv("ADB_OSX_USB_CLEAR_ENDPOINTS"));
119     static bool result = env && strcmp("1", env) == 0;
120     return result;
121 }
122 
FindUSBDevices()123 static bool FindUSBDevices() {
124     // Create the matching dictionary to find the Android device's adb interface.
125     CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
126     if (!matchingDict) {
127         LOG(ERROR) << "couldn't create USB matching dictionary";
128         return false;
129     }
130     // Create an iterator for all I/O Registry objects that match the dictionary.
131     io_iterator_t iter = 0;
132     kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
133     if (kr != KERN_SUCCESS) {
134         LOG(ERROR) << "failed to get matching services";
135         return false;
136     }
137     // Iterate over all matching objects.
138     AndroidInterfaceAdded(iter);
139     IOObjectRelease(iter);
140     return true;
141 }
142 
143 static void
AndroidInterfaceAdded(io_iterator_t iterator)144 AndroidInterfaceAdded(io_iterator_t iterator)
145 {
146     kern_return_t            kr;
147     io_service_t             usbDevice;
148     io_service_t             usbInterface;
149     IOCFPlugInInterface      **plugInInterface = NULL;
150     IOUSBInterfaceInterface500  **iface = NULL;
151     IOUSBDeviceInterface500  **dev = NULL;
152     HRESULT                  result;
153     SInt32                   score;
154     uint32_t                 locationId;
155     UInt8                    if_class, subclass, protocol;
156     UInt16                   vendor;
157     UInt16                   product;
158     UInt8                    serialIndex;
159     char                     serial[256];
160     std::string devpath;
161 
162     while ((usbInterface = IOIteratorNext(iterator))) {
163         //* Create an intermediate interface plugin
164         kr = IOCreatePlugInInterfaceForService(usbInterface,
165                                                kIOUSBInterfaceUserClientTypeID,
166                                                kIOCFPlugInInterfaceID,
167                                                &plugInInterface, &score);
168         IOObjectRelease(usbInterface);
169         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
170             LOG(ERROR) << "Unable to create an interface plug-in (" << std::hex << kr << ")";
171             continue;
172         }
173 
174         //* This gets us the interface object
175         result = (*plugInInterface)->QueryInterface(
176             plugInInterface,
177             CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID500), (LPVOID*)&iface);
178         //* We only needed the plugin to get the interface, so discard it
179         (*plugInInterface)->Release(plugInInterface);
180         if (result || !iface) {
181             LOG(ERROR) << "Couldn't query the interface (" << std::hex << result << ")";
182             continue;
183         }
184 
185         kr = (*iface)->GetInterfaceClass(iface, &if_class);
186         kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
187         kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
188         if (!is_adb_interface(if_class, subclass, protocol)) {
189             // Ignore non-ADB devices (interface with incorrect
190             // class/subclass/protocol).
191             (*iface)->Release(iface);
192             continue;
193         }
194 
195         //* this gets us an ioservice, with which we will find the actual
196         //* device; after getting a plugin, and querying the interface, of
197         //* course.
198         //* Gotta love OS X
199         kr = (*iface)->GetDevice(iface, &usbDevice);
200         if (kIOReturnSuccess != kr || !usbDevice) {
201             LOG(ERROR) << "Couldn't grab device from interface (" << std::hex << kr << ")";
202             (*iface)->Release(iface);
203             continue;
204         }
205 
206         plugInInterface = NULL;
207         score = 0;
208         //* create an intermediate device plugin
209         kr = IOCreatePlugInInterfaceForService(usbDevice,
210                                                kIOUSBDeviceUserClientTypeID,
211                                                kIOCFPlugInInterfaceID,
212                                                &plugInInterface, &score);
213         //* only needed this to find the plugin
214         (void)IOObjectRelease(usbDevice);
215         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
216             LOG(ERROR) << "Unable to create a device plug-in (" << std::hex << kr << ")";
217             (*iface)->Release(iface);
218             continue;
219         }
220 
221         result = (*plugInInterface)->QueryInterface(plugInInterface,
222             CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID500), (LPVOID*)&dev);
223         //* only needed this to query the plugin
224         (*plugInInterface)->Release(plugInInterface);
225         if (result || !dev) {
226             LOG(ERROR) << "Couldn't create a device interface (" << std::hex << result << ")";
227             (*iface)->Release(iface);
228             continue;
229         }
230 
231         //* Now after all that, we actually have a ref to the device and
232         //* the interface that matched our criteria
233         kr = (*dev)->GetDeviceVendor(dev, &vendor);
234         kr = (*dev)->GetDeviceProduct(dev, &product);
235         kr = (*dev)->GetLocationID(dev, &locationId);
236         if (kr == KERN_SUCCESS) {
237             devpath = android::base::StringPrintf("usb:%" PRIu32 "X", locationId);
238             if (IsKnownDevice(devpath)) {
239                 (*dev)->Release(dev);
240                 (*iface)->Release(iface);
241                 continue;
242             }
243         }
244         kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
245 
246         if (serialIndex > 0) {
247             IOUSBDevRequest req;
248             UInt16          buffer[256];
249             UInt16          languages[128];
250 
251             memset(languages, 0, sizeof(languages));
252 
253             req.bmRequestType =
254                     USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
255             req.bRequest = kUSBRqGetDescriptor;
256             req.wValue = (kUSBStringDesc << 8) | 0;
257             req.wIndex = 0;
258             req.pData = languages;
259             req.wLength = sizeof(languages);
260             kr = (*dev)->DeviceRequest(dev, &req);
261 
262             if (kr == kIOReturnSuccess && req.wLenDone > 0) {
263 
264                 int langCount = (req.wLenDone - 2) / 2, lang;
265 
266                 for (lang = 1; lang <= langCount; lang++) {
267                     memset(buffer, 0, sizeof(buffer));
268                     memset(&req, 0, sizeof(req));
269 
270                     req.bmRequestType =
271                             USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
272                     req.bRequest = kUSBRqGetDescriptor;
273                     req.wValue = (kUSBStringDesc << 8) | serialIndex;
274                     req.wIndex = languages[lang];
275                     req.pData = buffer;
276                     req.wLength = sizeof(buffer);
277                     kr = (*dev)->DeviceRequest(dev, &req);
278 
279                     if (kr == kIOReturnSuccess && req.wLenDone > 0) {
280                         int i, count;
281 
282                         // skip first word, and copy the rest to the serial string,
283                         // changing shorts to bytes.
284                         count = (req.wLenDone - 1) / 2;
285                         for (i = 0; i < count; i++)
286                                 serial[i] = buffer[i + 1];
287                         serial[i] = 0;
288                         break;
289                     }
290                 }
291             }
292         }
293 
294         (*dev)->Release(dev);
295 
296         VLOG(USB) << android::base::StringPrintf("Found vid=%04x pid=%04x serial=%s\n",
297                         vendor, product, serial);
298         if (devpath.empty()) {
299             devpath = serial;
300         }
301         if (IsKnownDevice(devpath)) {
302             (*iface)->USBInterfaceClose(iface);
303             (*iface)->Release(iface);
304             continue;
305         }
306 
307         if (!transport_server_owns_device(devpath, serial)) {
308             // We aren't allowed to communicate with this device. Don't open this device.
309             D("ignoring device: not owned by this server dev_path: '%s', serial: '%s'",
310               devpath.c_str(), serial);
311             continue;
312         }
313 
314         std::unique_ptr<usb_handle> handle =
315             CheckInterface((IOUSBInterfaceInterface550**)iface, vendor, product);
316         if (handle == nullptr) {
317             LOG(ERROR) << "Could not find device interface";
318             (*iface)->Release(iface);
319             continue;
320         }
321         handle->devpath = devpath;
322         usb_handle* handle_p = handle.get();
323         VLOG(USB) << "Add usb device " << serial;
324         LOG(INFO) << "reported max packet size for " << serial << " is " << handle->max_packet_size;
325         AddDevice(std::move(handle));
326         register_usb_transport(reinterpret_cast<::usb_handle*>(handle_p), serial, devpath.c_str(),
327                                1);
328     }
329 }
330 
331 // Used to clear both the endpoints before starting.
332 // When adb quits, we might clear the host endpoint but not the device.
333 // So we make sure both sides are clear before starting up.
334 // Returns true if:
335 //      - the feature is disabled (OSX/host only)
336 //      - the feature is enabled and successfully clears both endpoints
337 // Returns false otherwise (if an error is encountered)
ClearPipeStallBothEnds(IOUSBInterfaceInterface550 ** interface,UInt8 bulkEp)338 static bool ClearPipeStallBothEnds(IOUSBInterfaceInterface550** interface, UInt8 bulkEp) {
339     // If feature-disabled, (silently) bypass clearing both
340     // endpoints (including device-side).
341     if (!clear_endpoints()) {
342         return true;
343     }
344 
345     IOReturn rc = (*interface)->ClearPipeStallBothEnds(interface, bulkEp);
346     if (rc != kIOReturnSuccess) {
347         LOG(ERROR) << "Could not clear pipe stall both ends: " << std::hex << rc;
348         return false;
349     }
350     return true;
351 }
352 
darwinErrorToString(IOReturn result)353 static std::string darwinErrorToString(IOReturn result) {
354     switch (result) {
355         case kIOReturnSuccess:
356             return "no error";
357         case kIOReturnNotOpen:
358             return "device not opened for exclusive access";
359         case kIOReturnNoDevice:
360             return "no connection to an IOService";
361         case kIOUSBNoAsyncPortErr:
362             return "no async port has been opened for interface";
363         case kIOReturnExclusiveAccess:
364             return "another process has device opened for exclusive access";
365         case kIOUSBPipeStalled:
366 #if defined(kUSBHostReturnPipeStalled)
367         case kUSBHostReturnPipeStalled:
368 #endif
369             return "pipe is stalled";
370         case kIOReturnError:
371             return "could not establish a connection to the Darwin kernel";
372         case kIOUSBTransactionTimeout:
373             return "transaction timed out";
374         case kIOReturnBadArgument:
375             return "invalid argument";
376         case kIOReturnAborted:
377             return "transaction aborted";
378         case kIOReturnNotResponding:
379             return "device not responding";
380         case kIOReturnOverrun:
381             return "data overrun";
382         case kIOReturnCannotWire:
383             return "physical memory can not be wired down";
384         case kIOReturnNoResources:
385             return "out of resources";
386         case kIOUSBHighSpeedSplitError:
387             return "high speed split error";
388         case kIOUSBUnknownPipeErr:
389             return "pipe ref not recognized";
390         default:
391             return std::format("unknown error ({:#x})", result);
392     }
393 }
394 
dumpEndpointProperties(const std::string & label,const IOUSBEndpointProperties & properties)395 static void dumpEndpointProperties(const std::string& label,
396                                    const IOUSBEndpointProperties& properties) {
397     VLOG(USB) << std::endl << label;
398     VLOG(USB) << "    wMaxPacketSize=" << properties.wMaxPacketSize;
399     VLOG(USB) << "    bTransferType=" << static_cast<unsigned>(properties.bTransferType);
400     VLOG(USB) << "    bDirection=" << static_cast<unsigned>(properties.bDirection);
401     VLOG(USB) << "    bAlternateSetting=" << static_cast<unsigned>(properties.bAlternateSetting);
402     VLOG(USB) << "    bMult=" << static_cast<unsigned>(properties.bMult);
403     VLOG(USB) << "    bMaxBurst=" << static_cast<unsigned>(properties.bMaxBurst);
404     VLOG(USB) << "    bEndpointNumber=" << static_cast<unsigned>(properties.bEndpointNumber);
405     VLOG(USB) << "    bInterval=" << static_cast<unsigned>(properties.bInterval);
406     VLOG(USB) << "    bMaxStreams=" << static_cast<unsigned>(properties.bMaxStreams);
407     VLOG(USB) << "    bSyncType=" << static_cast<unsigned>(properties.bSyncType);
408     VLOG(USB) << "    bUsageType=" << static_cast<unsigned>(properties.bUsageType);
409     VLOG(USB) << "    bVersion=" << static_cast<unsigned>(properties.bVersion);
410     VLOG(USB) << "    wBytesPerInterval=" << static_cast<unsigned>(properties.wBytesPerInterval);
411 }
412 
413 //* TODO: simplify this further since we only register to get ADB interface
414 //* subclass+protocol events
CheckInterface(IOUSBInterfaceInterface550 ** interface,UInt16 vendor,UInt16 product)415 static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface550** interface,
416                                                   UInt16 vendor, UInt16 product) {
417     std::unique_ptr<usb_handle> handle;
418     IOReturn kr;
419     UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
420     UInt8 endpoint;
421 
422     //* Now open the interface.  This will cause the pipes associated with
423     //* the endpoints in the interface descriptor to be instantiated
424     kr = (*interface)->USBInterfaceOpen(interface);
425     if (kr != kIOReturnSuccess) {
426         LOG(ERROR) << "Could not open interface: " << std::hex << kr;
427         return NULL;
428     }
429 
430     //* Get the number of endpoints associated with this interface
431     kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
432     if (kr != kIOReturnSuccess) {
433         LOG(ERROR) << "Unable to get number of endpoints: " << std::hex << kr;
434         goto err_get_num_ep;
435     }
436 
437     //* Get interface class, subclass and protocol
438     if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
439             (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
440             (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
441             LOG(ERROR) << "Unable to get interface class, subclass and protocol";
442             goto err_get_interface_class;
443     }
444 
445     //* check to make sure interface class, subclass and protocol match ADB
446     //* avoid opening mass storage endpoints
447     if (!is_adb_interface(interfaceClass, interfaceSubClass, interfaceProtocol)) {
448         goto err_bad_adb_interface;
449     }
450 
451     handle.reset(new usb_handle);
452     if (handle == nullptr) {
453         goto err_bad_adb_interface;
454     }
455 
456     //* Iterate over the endpoints for this interface and find the first
457     //* bulk in/out pipes available.  These will be our read/write pipes.
458     for (endpoint = 1; endpoint <= interfaceNumEndpoints; ++endpoint) {
459         VLOG(USB) << std::endl << "Inspecting endpoint " << static_cast<unsigned>(endpoint);
460         IOUSBEndpointProperties properties = {.bVersion = kUSBEndpointPropertiesVersion3};
461 
462         // We only call GetPipePropertiesV3 so it populates the IOUSBEndpointProperties field
463         // needed for GetEndpointPropertiesV3. We don't use wMaxPacketSize returned here
464         // because it is the FULL maxPacketSize which includes burst and mul.
465         kr = (*interface)->GetPipePropertiesV3(interface, endpoint, &properties);
466         if (kr != kIOReturnSuccess) {
467             LOG(ERROR) << "GetPipePropertiesV3 error : " << darwinErrorToString(kr);
468             goto err_get_pipe_props;
469         }
470         dumpEndpointProperties("GetPipePropertiesV3 values", properties);
471 
472         // GetEndpointPropertiesV3 needs IOUSBEndpointProperties fields bVersion, bAlternateSetting,
473         // bDirection, and bEndPointNumber to be set before calling. This was done by
474         // GetPipePropertiesV3.
475         kr = (*interface)->GetEndpointPropertiesV3(interface, &properties);
476         if (kr != kIOReturnSuccess) {
477             LOG(ERROR) << "GetEndpointPropertiesV3 error : " << darwinErrorToString(kr);
478             goto err_get_pipe_props;
479         }
480         dumpEndpointProperties("GetEndpointPropertiesV3 values", properties);
481 
482         if (properties.bTransferType != kUSBBulk) {
483             continue;
484         }
485 
486         if (properties.bDirection == kUSBIn) {
487             handle->bulkIn = endpoint;
488 
489             if (!ClearPipeStallBothEnds(interface, handle->bulkIn)) {
490                 goto err_get_pipe_props;
491             }
492         }
493 
494         if (properties.bDirection == kUSBOut) {
495             handle->bulkOut = endpoint;
496             handle->zero_mask = properties.wMaxPacketSize - 1;
497             handle->max_packet_size = properties.wMaxPacketSize;
498 
499             if (!ClearPipeStallBothEnds(interface, handle->bulkOut)) {
500                 goto err_get_pipe_props;
501             }
502         }
503     }
504 
505     handle->interface = interface;
506     return handle;
507 
508 err_get_pipe_props:
509 err_bad_adb_interface:
510 err_get_interface_class:
511 err_get_num_ep:
512     (*interface)->USBInterfaceClose(interface);
513     return nullptr;
514 }
515 
516 std::mutex& operate_device_lock = *new std::mutex();
517 
RunLoopThread()518 static void RunLoopThread() {
519     adb_thread_setname("RunLoop");
520 
521     VLOG(USB) << "RunLoopThread started";
522     while (true) {
523         {
524             std::lock_guard<std::mutex> lock_guard(operate_device_lock);
525             FindUSBDevices();
526             KickDisconnectedDevices();
527         }
528         // Signal the parent that we are running
529         usb_inited_flag = true;
530         std::this_thread::sleep_for(1s);
531     }
532     VLOG(USB) << "RunLoopThread done";
533 }
534 
usb_cleanup()535 void usb_cleanup() NO_THREAD_SAFETY_ANALYSIS {
536     VLOG(USB) << "Macos usb_cleanup";
537     // Wait until usb operations in RunLoopThread finish, and prevent further operations.
538     operate_device_lock.lock();
539     close_usb_devices();
540 }
541 
usb_init()542 void usb_init() {
543     static bool initialized = false;
544     if (!initialized) {
545         usb_inited_flag = false;
546 
547         std::thread(RunLoopThread).detach();
548 
549         // Wait for initialization to finish
550         while (!usb_inited_flag) {
551             std::this_thread::sleep_for(100ms);
552         }
553 
554         adb_notify_device_scan_complete();
555         initialized = true;
556     }
557 }
558 
usb_write(usb_handle * handle,const void * buf,int len)559 int usb_write(usb_handle *handle, const void *buf, int len)
560 {
561     IOReturn    result;
562 
563     if (!len)
564         return 0;
565 
566     if (!handle || handle->dead)
567         return -1;
568 
569     if (NULL == handle->interface) {
570         LOG(ERROR) << "usb_write interface was null";
571         return -1;
572     }
573 
574     if (0 == handle->bulkOut) {
575         LOG(ERROR) << "bulkOut endpoint not assigned";
576         return -1;
577     }
578 
579     result =
580         (*handle->interface)->WritePipe(handle->interface, handle->bulkOut, (void *)buf, len);
581 
582     if ((result == 0) && (handle->zero_mask)) {
583         /* we need 0-markers and our transfer */
584         if(!(len & handle->zero_mask)) {
585             result =
586                 (*handle->interface)->WritePipe(
587                         handle->interface, handle->bulkOut, (void *)buf, 0);
588         }
589     }
590 
591     if (!result)
592         return len;
593 
594     LOG(ERROR) << "usb_write failed with status: " << std::hex << result;
595     return -1;
596 }
597 
usb_read(usb_handle * handle,void * buf,int len)598 int usb_read(usb_handle *handle, void *buf, int len)
599 {
600     IOReturn result;
601     UInt32  numBytes = len;
602 
603     if (!len) {
604         return 0;
605     }
606 
607     if (!handle || handle->dead) {
608         return -1;
609     }
610 
611     if (NULL == handle->interface) {
612         LOG(ERROR) << "usb_read interface was null";
613         return -1;
614     }
615 
616     if (0 == handle->bulkIn) {
617         LOG(ERROR) << "bulkIn endpoint not assigned";
618         return -1;
619     }
620 
621     result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
622 
623     if (kIOUSBPipeStalled == result) {
624         LOG(ERROR) << "Pipe stalled, clearing stall.\n";
625         (*handle->interface)->ClearPipeStall(handle->interface, handle->bulkIn);
626         result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
627     }
628 
629     if (kIOReturnSuccess == result)
630         return numBytes;
631     else {
632         LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
633     }
634 
635     return -1;
636 }
637 
usb_close(usb_handle * handle)638 int usb_close(usb_handle *handle)
639 {
640     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
641     for (auto it = g_usb_handles.begin(); it != g_usb_handles.end(); ++it) {
642         if ((*it).get() == handle) {
643             g_usb_handles.erase(it);
644             break;
645         }
646     }
647     return 0;
648 }
649 
usb_reset(usb_handle * handle)650 void usb_reset(usb_handle* handle) {
651     // Unimplemented on OS X.
652     usb_kick(handle);
653 }
654 
usb_kick_locked(usb_handle * handle)655 static void usb_kick_locked(usb_handle *handle)
656 {
657     LOG(INFO) << "Kicking handle";
658     /* release the interface */
659     if (!handle)
660         return;
661 
662     if (!handle->dead)
663     {
664         handle->dead = true;
665         (*handle->interface)->USBInterfaceClose(handle->interface);
666         (*handle->interface)->Release(handle->interface);
667     }
668 }
669 
usb_kick(usb_handle * handle)670 void usb_kick(usb_handle *handle) {
671     // Use the lock to avoid multiple thread kicking the device at the same time.
672     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
673     usb_kick_locked(handle);
674 }
675 
usb_get_max_packet_size(usb_handle * handle)676 size_t usb_get_max_packet_size(usb_handle* handle) {
677     return handle->max_packet_size;
678 }
679