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