• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <CoreFoundation/CoreFoundation.h>
22 
23 #include <IOKit/IOKitLib.h>
24 #include <IOKit/IOCFPlugIn.h>
25 #include <IOKit/usb/IOUSBLib.h>
26 #include <IOKit/IOMessage.h>
27 #include <mach/mach_port.h>
28 
29 #include <inttypes.h>
30 #include <stdio.h>
31 
32 #include <atomic>
33 #include <memory>
34 #include <mutex>
35 #include <vector>
36 
37 #include <android-base/logging.h>
38 #include <android-base/stringprintf.h>
39 
40 #include "adb.h"
41 #include "transport.h"
42 
43 struct usb_handle
44 {
45     UInt8 bulkIn;
46     UInt8 bulkOut;
47     IOUSBInterfaceInterface190** interface;
48     unsigned int zero_mask;
49 
50     // For garbage collecting disconnected devices.
51     bool mark;
52     std::string devpath;
53     std::atomic<bool> dead;
54 
usb_handleusb_handle55     usb_handle() : bulkIn(0), bulkOut(0), interface(nullptr),
56         zero_mask(0), mark(false), dead(false) {
57     }
58 };
59 
60 static std::atomic<bool> usb_inited_flag;
61 
62 static auto& g_usb_handles_mutex = *new std::mutex();
63 static auto& g_usb_handles = *new std::vector<std::unique_ptr<usb_handle>>();
64 
IsKnownDevice(const std::string & devpath)65 static bool IsKnownDevice(const std::string& devpath) {
66     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
67     for (auto& usb : g_usb_handles) {
68         if (usb->devpath == devpath) {
69             // Set mark flag to indicate this device is still alive.
70             usb->mark = true;
71             return true;
72         }
73     }
74     return false;
75 }
76 
77 static void usb_kick_locked(usb_handle* handle);
78 
KickDisconnectedDevices()79 static void KickDisconnectedDevices() {
80     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
81     for (auto& usb : g_usb_handles) {
82         if (!usb->mark) {
83             usb_kick_locked(usb.get());
84         } else {
85             usb->mark = false;
86         }
87     }
88 }
89 
AddDevice(std::unique_ptr<usb_handle> handle)90 static void AddDevice(std::unique_ptr<usb_handle> handle) {
91     handle->mark = true;
92     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
93     g_usb_handles.push_back(std::move(handle));
94 }
95 
96 static void AndroidInterfaceAdded(io_iterator_t iterator);
97 static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface190 **iface,
98                                                   UInt16 vendor, UInt16 product);
99 
FindUSBDevices()100 static bool FindUSBDevices() {
101     // Create the matching dictionary to find the Android device's adb interface.
102     CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
103     if (!matchingDict) {
104         LOG(ERROR) << "couldn't create USB matching dictionary";
105         return false;
106     }
107     // Create an iterator for all I/O Registry objects that match the dictionary.
108     io_iterator_t iter = 0;
109     kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
110     if (kr != KERN_SUCCESS) {
111         LOG(ERROR) << "failed to get matching services";
112         return false;
113     }
114     // Iterate over all matching objects.
115     AndroidInterfaceAdded(iter);
116     IOObjectRelease(iter);
117     return true;
118 }
119 
120 static void
AndroidInterfaceAdded(io_iterator_t iterator)121 AndroidInterfaceAdded(io_iterator_t iterator)
122 {
123     kern_return_t            kr;
124     io_service_t             usbDevice;
125     io_service_t             usbInterface;
126     IOCFPlugInInterface      **plugInInterface = NULL;
127     IOUSBInterfaceInterface220  **iface = NULL;
128     IOUSBDeviceInterface197  **dev = NULL;
129     HRESULT                  result;
130     SInt32                   score;
131     uint32_t                 locationId;
132     UInt8                    if_class, subclass, protocol;
133     UInt16                   vendor;
134     UInt16                   product;
135     UInt8                    serialIndex;
136     char                     serial[256];
137     std::string devpath;
138 
139     while ((usbInterface = IOIteratorNext(iterator))) {
140         //* Create an intermediate interface plugin
141         kr = IOCreatePlugInInterfaceForService(usbInterface,
142                                                kIOUSBInterfaceUserClientTypeID,
143                                                kIOCFPlugInInterfaceID,
144                                                &plugInInterface, &score);
145         IOObjectRelease(usbInterface);
146         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
147             LOG(ERROR) << "Unable to create an interface plug-in (" << std::hex << kr << ")";
148             continue;
149         }
150 
151         //* This gets us the interface object
152         result = (*plugInInterface)->QueryInterface(
153             plugInInterface,
154             CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID*)&iface);
155         //* We only needed the plugin to get the interface, so discard it
156         (*plugInInterface)->Release(plugInInterface);
157         if (result || !iface) {
158             LOG(ERROR) << "Couldn't query the interface (" << std::hex << result << ")";
159             continue;
160         }
161 
162         kr = (*iface)->GetInterfaceClass(iface, &if_class);
163         kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
164         kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
165         if(if_class != ADB_CLASS || subclass != ADB_SUBCLASS || protocol != ADB_PROTOCOL) {
166             // Ignore non-ADB devices.
167             LOG(DEBUG) << "Ignoring interface with incorrect class/subclass/protocol - " << if_class
168                        << ", " << subclass << ", " << protocol;
169             (*iface)->Release(iface);
170             continue;
171         }
172 
173         //* this gets us an ioservice, with which we will find the actual
174         //* device; after getting a plugin, and querying the interface, of
175         //* course.
176         //* Gotta love OS X
177         kr = (*iface)->GetDevice(iface, &usbDevice);
178         if (kIOReturnSuccess != kr || !usbDevice) {
179             LOG(ERROR) << "Couldn't grab device from interface (" << std::hex << kr << ")";
180             (*iface)->Release(iface);
181             continue;
182         }
183 
184         plugInInterface = NULL;
185         score = 0;
186         //* create an intermediate device plugin
187         kr = IOCreatePlugInInterfaceForService(usbDevice,
188                                                kIOUSBDeviceUserClientTypeID,
189                                                kIOCFPlugInInterfaceID,
190                                                &plugInInterface, &score);
191         //* only needed this to find the plugin
192         (void)IOObjectRelease(usbDevice);
193         if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
194             LOG(ERROR) << "Unable to create a device plug-in (" << std::hex << kr << ")";
195             (*iface)->Release(iface);
196             continue;
197         }
198 
199         result = (*plugInInterface)->QueryInterface(plugInInterface,
200             CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID*)&dev);
201         //* only needed this to query the plugin
202         (*plugInInterface)->Release(plugInInterface);
203         if (result || !dev) {
204             LOG(ERROR) << "Couldn't create a device interface (" << std::hex << result << ")";
205             (*iface)->Release(iface);
206             continue;
207         }
208 
209         //* Now after all that, we actually have a ref to the device and
210         //* the interface that matched our criteria
211         kr = (*dev)->GetDeviceVendor(dev, &vendor);
212         kr = (*dev)->GetDeviceProduct(dev, &product);
213         kr = (*dev)->GetLocationID(dev, &locationId);
214         if (kr == KERN_SUCCESS) {
215             devpath = android::base::StringPrintf("usb:%" PRIu32 "X", locationId);
216             if (IsKnownDevice(devpath)) {
217                 (*dev)->Release(dev);
218                 (*iface)->Release(iface);
219                 continue;
220             }
221         }
222         kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
223 
224         if (serialIndex > 0) {
225             IOUSBDevRequest req;
226             UInt16          buffer[256];
227             UInt16          languages[128];
228 
229             memset(languages, 0, sizeof(languages));
230 
231             req.bmRequestType =
232                     USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
233             req.bRequest = kUSBRqGetDescriptor;
234             req.wValue = (kUSBStringDesc << 8) | 0;
235             req.wIndex = 0;
236             req.pData = languages;
237             req.wLength = sizeof(languages);
238             kr = (*dev)->DeviceRequest(dev, &req);
239 
240             if (kr == kIOReturnSuccess && req.wLenDone > 0) {
241 
242                 int langCount = (req.wLenDone - 2) / 2, lang;
243 
244                 for (lang = 1; lang <= langCount; lang++) {
245 
246                     memset(buffer, 0, sizeof(buffer));
247                     memset(&req, 0, sizeof(req));
248 
249                     req.bmRequestType =
250                             USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
251                     req.bRequest = kUSBRqGetDescriptor;
252                     req.wValue = (kUSBStringDesc << 8) | serialIndex;
253                     req.wIndex = languages[lang];
254                     req.pData = buffer;
255                     req.wLength = sizeof(buffer);
256                     kr = (*dev)->DeviceRequest(dev, &req);
257 
258                     if (kr == kIOReturnSuccess && req.wLenDone > 0) {
259                         int i, count;
260 
261                         // skip first word, and copy the rest to the serial string,
262                         // changing shorts to bytes.
263                         count = (req.wLenDone - 1) / 2;
264                         for (i = 0; i < count; i++)
265                                 serial[i] = buffer[i + 1];
266                         serial[i] = 0;
267                         break;
268                     }
269                 }
270             }
271         }
272 
273         (*dev)->Release(dev);
274 
275         VLOG(USB) << android::base::StringPrintf("Found vid=%04x pid=%04x serial=%s\n",
276                         vendor, product, serial);
277         if (devpath.empty()) {
278             devpath = serial;
279         }
280         if (IsKnownDevice(devpath)) {
281             (*iface)->USBInterfaceClose(iface);
282             (*iface)->Release(iface);
283             continue;
284         }
285 
286         std::unique_ptr<usb_handle> handle = CheckInterface((IOUSBInterfaceInterface190**)iface,
287                                                             vendor, product);
288         if (handle == nullptr) {
289             LOG(ERROR) << "Could not find device interface";
290             (*iface)->Release(iface);
291             continue;
292         }
293         handle->devpath = devpath;
294         usb_handle* handle_p = handle.get();
295         VLOG(USB) << "Add usb device " << serial;
296         AddDevice(std::move(handle));
297         register_usb_transport(handle_p, serial, devpath.c_str(), 1);
298     }
299 }
300 
301 // Used to clear both the endpoints before starting.
302 // When adb quits, we might clear the host endpoint but not the device.
303 // So we make sure both sides are clear before starting up.
ClearPipeStallBothEnds(IOUSBInterfaceInterface190 ** interface,UInt8 bulkEp)304 static bool ClearPipeStallBothEnds(IOUSBInterfaceInterface190** interface, UInt8 bulkEp) {
305     IOReturn rc = (*interface)->ClearPipeStallBothEnds(interface, bulkEp);
306     if (rc != kIOReturnSuccess) {
307         LOG(ERROR) << "Could not clear pipe stall both ends: " << std::hex << rc;
308         return false;
309     }
310     return true;
311 }
312 
313 //* TODO: simplify this further since we only register to get ADB interface
314 //* subclass+protocol events
315 static std::unique_ptr<usb_handle>
CheckInterface(IOUSBInterfaceInterface190 ** interface,UInt16 vendor,UInt16 product)316 CheckInterface(IOUSBInterfaceInterface190 **interface, UInt16 vendor, UInt16 product)
317 {
318     std::unique_ptr<usb_handle> handle;
319     IOReturn kr;
320     UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
321     UInt8 endpoint;
322 
323     //* Now open the interface.  This will cause the pipes associated with
324     //* the endpoints in the interface descriptor to be instantiated
325     kr = (*interface)->USBInterfaceOpen(interface);
326     if (kr != kIOReturnSuccess) {
327         LOG(ERROR) << "Could not open interface: " << std::hex << kr;
328         return NULL;
329     }
330 
331     //* Get the number of endpoints associated with this interface
332     kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
333     if (kr != kIOReturnSuccess) {
334         LOG(ERROR) << "Unable to get number of endpoints: " << std::hex << kr;
335         goto err_get_num_ep;
336     }
337 
338     //* Get interface class, subclass and protocol
339     if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
340             (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
341             (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
342             LOG(ERROR) << "Unable to get interface class, subclass and protocol";
343             goto err_get_interface_class;
344     }
345 
346     //* check to make sure interface class, subclass and protocol match ADB
347     //* avoid opening mass storage endpoints
348     if (!is_adb_interface(vendor, product, interfaceClass, interfaceSubClass, interfaceProtocol)) {
349         goto err_bad_adb_interface;
350     }
351 
352     handle.reset(new usb_handle);
353     if (handle == nullptr) {
354         goto err_bad_adb_interface;
355     }
356 
357     //* Iterate over the endpoints for this interface and find the first
358     //* bulk in/out pipes available.  These will be our read/write pipes.
359     for (endpoint = 1; endpoint <= interfaceNumEndpoints; endpoint++) {
360         UInt8   transferType;
361         UInt16  maxPacketSize;
362         UInt8   interval;
363         UInt8   number;
364         UInt8   direction;
365 
366         kr = (*interface)->GetPipeProperties(interface, endpoint, &direction,
367                 &number, &transferType, &maxPacketSize, &interval);
368         if (kr != kIOReturnSuccess) {
369             LOG(ERROR) << "FindDeviceInterface - could not get pipe properties: "
370                        << std::hex << kr;
371             goto err_get_pipe_props;
372         }
373 
374         if (kUSBBulk != transferType) continue;
375 
376         if (kUSBIn == direction) {
377             handle->bulkIn = endpoint;
378             if (!ClearPipeStallBothEnds(interface, handle->bulkIn)) goto err_get_pipe_props;
379         }
380 
381         if (kUSBOut == direction) {
382             handle->bulkOut = endpoint;
383             if (!ClearPipeStallBothEnds(interface, handle->bulkOut)) goto err_get_pipe_props;
384         }
385 
386         handle->zero_mask = maxPacketSize - 1;
387     }
388 
389     handle->interface = interface;
390     return handle;
391 
392 err_get_pipe_props:
393 err_bad_adb_interface:
394 err_get_interface_class:
395 err_get_num_ep:
396     (*interface)->USBInterfaceClose(interface);
397     return nullptr;
398 }
399 
400 std::mutex& operate_device_lock = *new std::mutex();
401 
RunLoopThread(void * unused)402 static void RunLoopThread(void* unused) {
403     adb_thread_setname("RunLoop");
404 
405     VLOG(USB) << "RunLoopThread started";
406     while (true) {
407         {
408             std::lock_guard<std::mutex> lock_guard(operate_device_lock);
409             FindUSBDevices();
410             KickDisconnectedDevices();
411         }
412         // Signal the parent that we are running
413         usb_inited_flag = true;
414         adb_sleep_ms(1000);
415     }
416     VLOG(USB) << "RunLoopThread done";
417 }
418 
usb_cleanup()419 static void usb_cleanup() {
420     VLOG(USB) << "usb_cleanup";
421     // Wait until usb operations in RunLoopThread finish, and prevent further operations.
422     operate_device_lock.lock();
423     close_usb_devices();
424 }
425 
usb_init()426 void usb_init() {
427     static bool initialized = false;
428     if (!initialized) {
429         atexit(usb_cleanup);
430 
431         usb_inited_flag = false;
432 
433         if (!adb_thread_create(RunLoopThread, nullptr)) {
434             fatal_errno("cannot create RunLoop thread");
435         }
436 
437         // Wait for initialization to finish
438         while (!usb_inited_flag) {
439             adb_sleep_ms(100);
440         }
441 
442         initialized = true;
443     }
444 }
445 
usb_write(usb_handle * handle,const void * buf,int len)446 int usb_write(usb_handle *handle, const void *buf, int len)
447 {
448     IOReturn    result;
449 
450     if (!len)
451         return 0;
452 
453     if (!handle || handle->dead)
454         return -1;
455 
456     if (NULL == handle->interface) {
457         LOG(ERROR) << "usb_write interface was null";
458         return -1;
459     }
460 
461     if (0 == handle->bulkOut) {
462         LOG(ERROR) << "bulkOut endpoint not assigned";
463         return -1;
464     }
465 
466     result =
467         (*handle->interface)->WritePipe(handle->interface, handle->bulkOut, (void *)buf, len);
468 
469     if ((result == 0) && (handle->zero_mask)) {
470         /* we need 0-markers and our transfer */
471         if(!(len & handle->zero_mask)) {
472             result =
473                 (*handle->interface)->WritePipe(
474                         handle->interface, handle->bulkOut, (void *)buf, 0);
475         }
476     }
477 
478     if (0 == result)
479         return 0;
480 
481     LOG(ERROR) << "usb_write failed with status: " << std::hex << result;
482     return -1;
483 }
484 
usb_read(usb_handle * handle,void * buf,int len)485 int usb_read(usb_handle *handle, void *buf, int len)
486 {
487     IOReturn result;
488     UInt32  numBytes = len;
489 
490     if (!len) {
491         return 0;
492     }
493 
494     if (!handle || handle->dead) {
495         return -1;
496     }
497 
498     if (NULL == handle->interface) {
499         LOG(ERROR) << "usb_read interface was null";
500         return -1;
501     }
502 
503     if (0 == handle->bulkIn) {
504         LOG(ERROR) << "bulkIn endpoint not assigned";
505         return -1;
506     }
507 
508     result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
509 
510     if (kIOUSBPipeStalled == result) {
511         LOG(ERROR) << "Pipe stalled, clearing stall.\n";
512         (*handle->interface)->ClearPipeStall(handle->interface, handle->bulkIn);
513         result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
514     }
515 
516     if (kIOReturnSuccess == result)
517         return 0;
518     else {
519         LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
520     }
521 
522     return -1;
523 }
524 
usb_close(usb_handle * handle)525 int usb_close(usb_handle *handle)
526 {
527     std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
528     for (auto it = g_usb_handles.begin(); it != g_usb_handles.end(); ++it) {
529         if ((*it).get() == handle) {
530             g_usb_handles.erase(it);
531             break;
532         }
533     }
534     return 0;
535 }
536 
usb_kick_locked(usb_handle * handle)537 static void usb_kick_locked(usb_handle *handle)
538 {
539     LOG(INFO) << "Kicking handle";
540     /* release the interface */
541     if (!handle)
542         return;
543 
544     if (!handle->dead)
545     {
546         handle->dead = true;
547         (*handle->interface)->USBInterfaceClose(handle->interface);
548         (*handle->interface)->Release(handle->interface);
549     }
550 }
551 
usb_kick(usb_handle * handle)552 void usb_kick(usb_handle *handle) {
553     // Use the lock to avoid multiple thread kicking the device at the same time.
554     std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
555     usb_kick_locked(handle);
556 }
557