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