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