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