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