Home | History | Annotate | Download | only in adb
      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 <winsock2.h>  // winsock.h *must* be included before windows.h.
     22 #include <adb_api.h>
     23 #include <errno.h>
     24 #include <stdio.h>
     25 #include <stdlib.h>
     26 #include <usb100.h>
     27 #include <windows.h>
     28 #include <winerror.h>
     29 
     30 #include <android-base/errors.h>
     31 
     32 #include "adb.h"
     33 #include "transport.h"
     34 
     35 /** Structure usb_handle describes our connection to the usb device via
     36   AdbWinApi.dll. This structure is returned from usb_open() routine and
     37   is expected in each subsequent call that is accessing the device.
     38 
     39   Most members are protected by usb_lock, except for adb_{read,write}_pipe which
     40   rely on AdbWinApi.dll's handle validation and AdbCloseHandle(endpoint)'s
     41   ability to break a thread out of pipe IO.
     42 */
     43 struct usb_handle {
     44   /// Previous entry in the list of opened usb handles
     45   usb_handle *prev;
     46 
     47   /// Next entry in the list of opened usb handles
     48   usb_handle *next;
     49 
     50   /// Handle to USB interface
     51   ADBAPIHANDLE  adb_interface;
     52 
     53   /// Handle to USB read pipe (endpoint)
     54   ADBAPIHANDLE  adb_read_pipe;
     55 
     56   /// Handle to USB write pipe (endpoint)
     57   ADBAPIHANDLE  adb_write_pipe;
     58 
     59   /// Interface name
     60   wchar_t*      interface_name;
     61 
     62   /// Mask for determining when to use zero length packets
     63   unsigned zero_mask;
     64 };
     65 
     66 /// Class ID assigned to the device by androidusb.sys
     67 static const GUID usb_class_id = ANDROID_USB_CLASS_ID;
     68 
     69 /// List of opened usb handles
     70 static usb_handle handle_list = {
     71   .prev = &handle_list,
     72   .next = &handle_list,
     73 };
     74 
     75 /// Locker for the list of opened usb handles
     76 ADB_MUTEX_DEFINE( usb_lock );
     77 
     78 /// Checks if there is opened usb handle in handle_list for this device.
     79 int known_device(const wchar_t* dev_name);
     80 
     81 /// Checks if there is opened usb handle in handle_list for this device.
     82 /// usb_lock mutex must be held before calling this routine.
     83 int known_device_locked(const wchar_t* dev_name);
     84 
     85 /// Registers opened usb handle (adds it to handle_list).
     86 int register_new_device(usb_handle* handle);
     87 
     88 /// Checks if interface (device) matches certain criteria
     89 int recognized_device(usb_handle* handle);
     90 
     91 /// Enumerates present and available interfaces (devices), opens new ones and
     92 /// registers usb transport for them.
     93 void find_devices();
     94 
     95 /// Kicks all USB devices
     96 static void kick_devices();
     97 
     98 /// Entry point for thread that polls (every second) for new usb interfaces.
     99 /// This routine calls find_devices in infinite loop.
    100 static void device_poll_thread(void*);
    101 
    102 /// Initializes this module
    103 void usb_init();
    104 
    105 /// Opens usb interface (device) by interface (device) name.
    106 usb_handle* do_usb_open(const wchar_t* interface_name);
    107 
    108 /// Writes data to the opened usb handle
    109 int usb_write(usb_handle* handle, const void* data, int len);
    110 
    111 /// Reads data using the opened usb handle
    112 int usb_read(usb_handle *handle, void* data, int len);
    113 
    114 /// Cleans up opened usb handle
    115 void usb_cleanup_handle(usb_handle* handle);
    116 
    117 /// Cleans up (but don't close) opened usb handle
    118 void usb_kick(usb_handle* handle);
    119 
    120 /// Closes opened usb handle
    121 int usb_close(usb_handle* handle);
    122 
    123 int known_device_locked(const wchar_t* dev_name) {
    124   usb_handle* usb;
    125 
    126   if (NULL != dev_name) {
    127     // Iterate through the list looking for the name match.
    128     for(usb = handle_list.next; usb != &handle_list; usb = usb->next) {
    129       // In Windows names are not case sensetive!
    130       if((NULL != usb->interface_name) &&
    131          (0 == wcsicmp(usb->interface_name, dev_name))) {
    132         return 1;
    133       }
    134     }
    135   }
    136 
    137   return 0;
    138 }
    139 
    140 int known_device(const wchar_t* dev_name) {
    141   int ret = 0;
    142 
    143   if (NULL != dev_name) {
    144     adb_mutex_lock(&usb_lock);
    145     ret = known_device_locked(dev_name);
    146     adb_mutex_unlock(&usb_lock);
    147   }
    148 
    149   return ret;
    150 }
    151 
    152 int register_new_device(usb_handle* handle) {
    153   if (NULL == handle)
    154     return 0;
    155 
    156   adb_mutex_lock(&usb_lock);
    157 
    158   // Check if device is already in the list
    159   if (known_device_locked(handle->interface_name)) {
    160     adb_mutex_unlock(&usb_lock);
    161     return 0;
    162   }
    163 
    164   // Not in the list. Add this handle to the list.
    165   handle->next = &handle_list;
    166   handle->prev = handle_list.prev;
    167   handle->prev->next = handle;
    168   handle->next->prev = handle;
    169 
    170   adb_mutex_unlock(&usb_lock);
    171 
    172   return 1;
    173 }
    174 
    175 void device_poll_thread(void*) {
    176   adb_thread_setname("Device Poll");
    177   D("Created device thread");
    178 
    179   while(1) {
    180     find_devices();
    181     adb_sleep_ms(1000);
    182   }
    183 }
    184 
    185 static LRESULT CALLBACK _power_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam,
    186                                            LPARAM lParam) {
    187   switch (uMsg) {
    188   case WM_POWERBROADCAST:
    189     switch (wParam) {
    190     case PBT_APMRESUMEAUTOMATIC:
    191       // Resuming from sleep or hibernation, so kick all existing USB devices
    192       // and then allow the device_poll_thread to redetect USB devices from
    193       // scratch. If we don't do this, existing USB devices will never respond
    194       // to us because they'll be waiting for the connect/auth handshake.
    195       D("Received (WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC) notification, "
    196         "so kicking all USB devices\n");
    197       kick_devices();
    198       return TRUE;
    199     }
    200   }
    201   return DefWindowProcW(hwnd, uMsg, wParam, lParam);
    202 }
    203 
    204 static void _power_notification_thread(void*) {
    205   // This uses a thread with its own window message pump to get power
    206   // notifications. If adb runs from a non-interactive service account, this
    207   // might not work (not sure). If that happens to not work, we could use
    208   // heavyweight WMI APIs to get power notifications. But for the common case
    209   // of a developer's interactive session, a window message pump is more
    210   // appropriate.
    211   D("Created power notification thread");
    212   adb_thread_setname("Power Notifier");
    213 
    214   // Window class names are process specific.
    215   static const WCHAR kPowerNotificationWindowClassName[] =
    216     L"PowerNotificationWindow";
    217 
    218   // Get the HINSTANCE corresponding to the module that _power_window_proc
    219   // is in (the main module).
    220   const HINSTANCE instance = GetModuleHandleW(NULL);
    221   if (!instance) {
    222     // This is such a common API call that this should never fail.
    223     fatal("GetModuleHandleW failed: %s",
    224           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    225   }
    226 
    227   WNDCLASSEXW wndclass;
    228   memset(&wndclass, 0, sizeof(wndclass));
    229   wndclass.cbSize = sizeof(wndclass);
    230   wndclass.lpfnWndProc = _power_window_proc;
    231   wndclass.hInstance = instance;
    232   wndclass.lpszClassName = kPowerNotificationWindowClassName;
    233   if (!RegisterClassExW(&wndclass)) {
    234     fatal("RegisterClassExW failed: %s",
    235           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    236   }
    237 
    238   if (!CreateWindowExW(WS_EX_NOACTIVATE, kPowerNotificationWindowClassName,
    239                        L"ADB Power Notification Window", WS_POPUP, 0, 0, 0, 0,
    240                        NULL, NULL, instance, NULL)) {
    241     fatal("CreateWindowExW failed: %s",
    242           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    243   }
    244 
    245   MSG msg;
    246   while (GetMessageW(&msg, NULL, 0, 0)) {
    247     TranslateMessage(&msg);
    248     DispatchMessageW(&msg);
    249   }
    250 
    251   // GetMessageW() will return false if a quit message is posted. We don't
    252   // do that, but it might be possible for that to occur when logging off or
    253   // shutting down. Not a big deal since the whole process will be going away
    254   // soon anyway.
    255   D("Power notification thread exiting");
    256 }
    257 
    258 void usb_init() {
    259   if (!adb_thread_create(device_poll_thread, nullptr)) {
    260     fatal_errno("cannot create device poll thread");
    261   }
    262   if (!adb_thread_create(_power_notification_thread, nullptr)) {
    263     fatal_errno("cannot create power notification thread");
    264   }
    265 }
    266 
    267 usb_handle* do_usb_open(const wchar_t* interface_name) {
    268   unsigned long name_len = 0;
    269 
    270   // Allocate our handle
    271   usb_handle* ret = (usb_handle*)calloc(1, sizeof(usb_handle));
    272   if (NULL == ret) {
    273     D("Could not allocate %u bytes for usb_handle: %s", sizeof(usb_handle),
    274       strerror(errno));
    275     goto fail;
    276   }
    277 
    278   // Set linkers back to the handle
    279   ret->next = ret;
    280   ret->prev = ret;
    281 
    282   // Create interface.
    283   ret->adb_interface = AdbCreateInterfaceByName(interface_name);
    284   if (NULL == ret->adb_interface) {
    285     D("AdbCreateInterfaceByName failed: %s",
    286       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    287     goto fail;
    288   }
    289 
    290   // Open read pipe (endpoint)
    291   ret->adb_read_pipe =
    292     AdbOpenDefaultBulkReadEndpoint(ret->adb_interface,
    293                                    AdbOpenAccessTypeReadWrite,
    294                                    AdbOpenSharingModeReadWrite);
    295   if (NULL == ret->adb_read_pipe) {
    296     D("AdbOpenDefaultBulkReadEndpoint failed: %s",
    297       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    298     goto fail;
    299   }
    300 
    301   // Open write pipe (endpoint)
    302   ret->adb_write_pipe =
    303     AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
    304                                     AdbOpenAccessTypeReadWrite,
    305                                     AdbOpenSharingModeReadWrite);
    306   if (NULL == ret->adb_write_pipe) {
    307     D("AdbOpenDefaultBulkWriteEndpoint failed: %s",
    308       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    309     goto fail;
    310   }
    311 
    312   // Save interface name
    313   // First get expected name length
    314   AdbGetInterfaceName(ret->adb_interface,
    315                       NULL,
    316                       &name_len,
    317                       false);
    318   if (0 == name_len) {
    319     D("AdbGetInterfaceName returned name length of zero: %s",
    320       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    321     goto fail;
    322   }
    323 
    324   ret->interface_name = (wchar_t*)malloc(name_len * sizeof(ret->interface_name[0]));
    325   if (NULL == ret->interface_name) {
    326     D("Could not allocate %lu characters for interface_name: %s", name_len, strerror(errno));
    327     goto fail;
    328   }
    329 
    330   // Now save the name
    331   if (!AdbGetInterfaceName(ret->adb_interface,
    332                            ret->interface_name,
    333                            &name_len,
    334                            false)) {
    335     D("AdbGetInterfaceName failed: %s",
    336       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    337     goto fail;
    338   }
    339 
    340   // We're done at this point
    341   return ret;
    342 
    343 fail:
    344   if (NULL != ret) {
    345     usb_cleanup_handle(ret);
    346     free(ret);
    347   }
    348 
    349   return NULL;
    350 }
    351 
    352 int usb_write(usb_handle* handle, const void* data, int len) {
    353   unsigned long time_out = 5000;
    354   unsigned long written = 0;
    355   int err = 0;
    356 
    357   D("usb_write %d", len);
    358   if (NULL == handle) {
    359     D("usb_write was passed NULL handle");
    360     err = EINVAL;
    361     goto fail;
    362   }
    363 
    364   // Perform write
    365   if (!AdbWriteEndpointSync(handle->adb_write_pipe,
    366                             (void*)data,
    367                             (unsigned long)len,
    368                             &written,
    369                             time_out)) {
    370     D("AdbWriteEndpointSync failed: %s",
    371       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    372     err = EIO;
    373     goto fail;
    374   }
    375 
    376   // Make sure that we've written what we were asked to write
    377   D("usb_write got: %ld, expected: %d", written, len);
    378   if (written != (unsigned long)len) {
    379     // If this occurs, this code should be changed to repeatedly call
    380     // AdbWriteEndpointSync() until all bytes are written.
    381     D("AdbWriteEndpointSync was supposed to write %d, but only wrote %ld",
    382       len, written);
    383     err = EIO;
    384     goto fail;
    385   }
    386 
    387   if (handle->zero_mask && (len & handle->zero_mask) == 0) {
    388     // Send a zero length packet
    389     if (!AdbWriteEndpointSync(handle->adb_write_pipe,
    390                               (void*)data,
    391                               0,
    392                               &written,
    393                               time_out)) {
    394       D("AdbWriteEndpointSync of zero length packet failed: %s",
    395         android::base::SystemErrorCodeToString(GetLastError()).c_str());
    396       err = EIO;
    397       goto fail;
    398     }
    399   }
    400 
    401   return 0;
    402 
    403 fail:
    404   // Any failure should cause us to kick the device instead of leaving it a
    405   // zombie state with potential to hang.
    406   if (NULL != handle) {
    407     D("Kicking device due to error in usb_write");
    408     usb_kick(handle);
    409   }
    410 
    411   D("usb_write failed");
    412   errno = err;
    413   return -1;
    414 }
    415 
    416 int usb_read(usb_handle *handle, void* data, int len) {
    417   unsigned long time_out = 0;
    418   unsigned long read = 0;
    419   int err = 0;
    420 
    421   D("usb_read %d", len);
    422   if (NULL == handle) {
    423     D("usb_read was passed NULL handle");
    424     err = EINVAL;
    425     goto fail;
    426   }
    427 
    428   while (len > 0) {
    429     if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read,
    430                              time_out)) {
    431       D("AdbReadEndpointSync failed: %s",
    432         android::base::SystemErrorCodeToString(GetLastError()).c_str());
    433       err = EIO;
    434       goto fail;
    435     }
    436     D("usb_read got: %ld, expected: %d", read, len);
    437 
    438     data = (char *)data + read;
    439     len -= read;
    440   }
    441 
    442   return 0;
    443 
    444 fail:
    445   // Any failure should cause us to kick the device instead of leaving it a
    446   // zombie state with potential to hang.
    447   if (NULL != handle) {
    448     D("Kicking device due to error in usb_read");
    449     usb_kick(handle);
    450   }
    451 
    452   D("usb_read failed");
    453   errno = err;
    454   return -1;
    455 }
    456 
    457 // Wrapper around AdbCloseHandle() that logs diagnostics.
    458 static void _adb_close_handle(ADBAPIHANDLE adb_handle) {
    459   if (!AdbCloseHandle(adb_handle)) {
    460     D("AdbCloseHandle(%p) failed: %s", adb_handle,
    461       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    462   }
    463 }
    464 
    465 void usb_cleanup_handle(usb_handle* handle) {
    466   D("usb_cleanup_handle");
    467   if (NULL != handle) {
    468     if (NULL != handle->interface_name)
    469       free(handle->interface_name);
    470     // AdbCloseHandle(pipe) will break any threads out of pending IO calls and
    471     // wait until the pipe no longer uses the interface. Then we can
    472     // AdbCloseHandle() the interface.
    473     if (NULL != handle->adb_write_pipe)
    474       _adb_close_handle(handle->adb_write_pipe);
    475     if (NULL != handle->adb_read_pipe)
    476       _adb_close_handle(handle->adb_read_pipe);
    477     if (NULL != handle->adb_interface)
    478       _adb_close_handle(handle->adb_interface);
    479 
    480     handle->interface_name = NULL;
    481     handle->adb_write_pipe = NULL;
    482     handle->adb_read_pipe = NULL;
    483     handle->adb_interface = NULL;
    484   }
    485 }
    486 
    487 static void usb_kick_locked(usb_handle* handle) {
    488   // The reason the lock must be acquired before calling this function is in
    489   // case multiple threads are trying to kick the same device at the same time.
    490   usb_cleanup_handle(handle);
    491 }
    492 
    493 void usb_kick(usb_handle* handle) {
    494   D("usb_kick");
    495   if (NULL != handle) {
    496     adb_mutex_lock(&usb_lock);
    497 
    498     usb_kick_locked(handle);
    499 
    500     adb_mutex_unlock(&usb_lock);
    501   } else {
    502     errno = EINVAL;
    503   }
    504 }
    505 
    506 int usb_close(usb_handle* handle) {
    507   D("usb_close");
    508 
    509   if (NULL != handle) {
    510     // Remove handle from the list
    511     adb_mutex_lock(&usb_lock);
    512 
    513     if ((handle->next != handle) && (handle->prev != handle)) {
    514       handle->next->prev = handle->prev;
    515       handle->prev->next = handle->next;
    516       handle->prev = handle;
    517       handle->next = handle;
    518     }
    519 
    520     adb_mutex_unlock(&usb_lock);
    521 
    522     // Cleanup handle
    523     usb_cleanup_handle(handle);
    524     free(handle);
    525   }
    526 
    527   return 0;
    528 }
    529 
    530 int recognized_device(usb_handle* handle) {
    531   if (NULL == handle)
    532     return 0;
    533 
    534   // Check vendor and product id first
    535   USB_DEVICE_DESCRIPTOR device_desc;
    536 
    537   if (!AdbGetUsbDeviceDescriptor(handle->adb_interface,
    538                                  &device_desc)) {
    539     D("AdbGetUsbDeviceDescriptor failed: %s",
    540       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    541     return 0;
    542   }
    543 
    544   // Then check interface properties
    545   USB_INTERFACE_DESCRIPTOR interf_desc;
    546 
    547   if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface,
    548                                     &interf_desc)) {
    549     D("AdbGetUsbInterfaceDescriptor failed: %s",
    550       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    551     return 0;
    552   }
    553 
    554   // Must have two endpoints
    555   if (2 != interf_desc.bNumEndpoints) {
    556     return 0;
    557   }
    558 
    559   if (is_adb_interface(device_desc.idVendor, device_desc.idProduct,
    560       interf_desc.bInterfaceClass, interf_desc.bInterfaceSubClass, interf_desc.bInterfaceProtocol)) {
    561 
    562     if(interf_desc.bInterfaceProtocol == 0x01) {
    563       AdbEndpointInformation endpoint_info;
    564       // assuming zero is a valid bulk endpoint ID
    565       if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
    566         handle->zero_mask = endpoint_info.max_packet_size - 1;
    567         D("device zero_mask: 0x%x", handle->zero_mask);
    568       } else {
    569         D("AdbGetEndpointInformation failed: %s",
    570           android::base::SystemErrorCodeToString(GetLastError()).c_str());
    571       }
    572     }
    573 
    574     return 1;
    575   }
    576 
    577   return 0;
    578 }
    579 
    580 void find_devices() {
    581   usb_handle* handle = NULL;
    582   char entry_buffer[2048];
    583   AdbInterfaceInfo* next_interface = (AdbInterfaceInfo*)(&entry_buffer[0]);
    584   unsigned long entry_buffer_size = sizeof(entry_buffer);
    585 
    586   // Enumerate all present and active interfaces.
    587   ADBAPIHANDLE enum_handle =
    588     AdbEnumInterfaces(usb_class_id, true, true, true);
    589 
    590   if (NULL == enum_handle) {
    591     D("AdbEnumInterfaces failed: %s",
    592       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    593     return;
    594   }
    595 
    596   while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
    597     // Lets see if we already have this device in the list
    598     if (!known_device(next_interface->device_name)) {
    599       // This seems to be a new device. Open it!
    600       handle = do_usb_open(next_interface->device_name);
    601       if (NULL != handle) {
    602         // Lets see if this interface (device) belongs to us
    603         if (recognized_device(handle)) {
    604           D("adding a new device %ls", next_interface->device_name);
    605 
    606           // We don't request a wchar_t string from AdbGetSerialNumber() because of a bug in
    607           // adb_winusb_interface.cpp:CopyMemory(buffer, ser_num->bString, bytes_written) where the
    608           // last parameter should be (str_len * sizeof(wchar_t)). The bug reads 2 bytes past the
    609           // end of a stack buffer in the best case, and in the unlikely case of a long serial
    610           // number, it will read 2 bytes past the end of a heap allocation. This doesn't affect the
    611           // resulting string, but we should avoid the bad reads in the first place.
    612           char serial_number[512];
    613           unsigned long serial_number_len = sizeof(serial_number);
    614           if (AdbGetSerialNumber(handle->adb_interface,
    615                                 serial_number,
    616                                 &serial_number_len,
    617                                 true)) {
    618             // Lets make sure that we don't duplicate this device
    619             if (register_new_device(handle)) {
    620               register_usb_transport(handle, serial_number, NULL, 1);
    621             } else {
    622               D("register_new_device failed for %ls", next_interface->device_name);
    623               usb_cleanup_handle(handle);
    624               free(handle);
    625             }
    626           } else {
    627             D("cannot get serial number: %s",
    628               android::base::SystemErrorCodeToString(GetLastError()).c_str());
    629             usb_cleanup_handle(handle);
    630             free(handle);
    631           }
    632         } else {
    633           usb_cleanup_handle(handle);
    634           free(handle);
    635         }
    636       }
    637     }
    638 
    639     entry_buffer_size = sizeof(entry_buffer);
    640   }
    641 
    642   if (GetLastError() != ERROR_NO_MORE_ITEMS) {
    643     // Only ERROR_NO_MORE_ITEMS is expected at the end of enumeration.
    644     D("AdbNextInterface failed: %s",
    645       android::base::SystemErrorCodeToString(GetLastError()).c_str());
    646   }
    647 
    648   _adb_close_handle(enum_handle);
    649 }
    650 
    651 static void kick_devices() {
    652   // Need to acquire lock to safely walk the list which might be modified
    653   // by another thread.
    654   adb_mutex_lock(&usb_lock);
    655   for (usb_handle* usb = handle_list.next; usb != &handle_list; usb = usb->next) {
    656     usb_kick_locked(usb);
    657   }
    658   adb_mutex_unlock(&usb_lock);
    659 }
    660