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