1 /*
2 * Copyright (C) 2016 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 #include "sysdeps.h"
18
19 #include "client/usb.h"
20
21 #include <stdint.h>
22 #include <stdlib.h>
23
24 #include <atomic>
25 #include <chrono>
26 #include <condition_variable>
27 #include <memory>
28 #include <mutex>
29 #include <string>
30 #include <thread>
31 #include <unordered_map>
32
33 #include <libusb/libusb.h>
34
35 #include <android-base/file.h>
36 #include <android-base/logging.h>
37 #include <android-base/stringprintf.h>
38 #include <android-base/strings.h>
39 #include <android-base/thread_annotations.h>
40
41 #include "adb.h"
42 #include "adb_utils.h"
43 #include "fdevent/fdevent.h"
44 #include "transfer_id.h"
45 #include "transport.h"
46
47 using android::base::ScopedLockAssertion;
48 using android::base::StringPrintf;
49
50 // RAII wrappers for libusb.
51 struct ConfigDescriptorDeleter {
operator ()ConfigDescriptorDeleter52 void operator()(libusb_config_descriptor* desc) { libusb_free_config_descriptor(desc); }
53 };
54
55 using unique_config_descriptor = std::unique_ptr<libusb_config_descriptor, ConfigDescriptorDeleter>;
56
57 struct DeviceDeleter {
operator ()DeviceDeleter58 void operator()(libusb_device* d) { libusb_unref_device(d); }
59 };
60
61 using unique_device = std::unique_ptr<libusb_device, DeviceDeleter>;
62
63 struct DeviceHandleDeleter {
operator ()DeviceHandleDeleter64 void operator()(libusb_device_handle* h) { libusb_close(h); }
65 };
66
67 using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>;
68
69 static void process_device(libusb_device* device_raw);
70
get_device_address(libusb_device * device)71 static std::string get_device_address(libusb_device* device) {
72 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device),
73 libusb_get_device_address(device));
74 }
75
76 #if defined(__linux__)
get_device_serial_path(libusb_device * device)77 static std::string get_device_serial_path(libusb_device* device) {
78 uint8_t ports[7];
79 int port_count = libusb_get_port_numbers(device, ports, 7);
80 if (port_count < 0) return "";
81
82 std::string path =
83 StringPrintf("/sys/bus/usb/devices/%d-%d", libusb_get_bus_number(device), ports[0]);
84 for (int port = 1; port < port_count; ++port) {
85 path += StringPrintf(".%d", ports[port]);
86 }
87 path += "/serial";
88 return path;
89 }
90 #endif
91
endpoint_is_output(uint8_t endpoint)92 static bool endpoint_is_output(uint8_t endpoint) {
93 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
94 }
95
should_perform_zero_transfer(size_t write_length,uint16_t zero_mask)96 static bool should_perform_zero_transfer(size_t write_length, uint16_t zero_mask) {
97 return write_length != 0 && zero_mask != 0 && (write_length & zero_mask) == 0;
98 }
99
100 struct LibusbConnection : public Connection {
101 struct ReadBlock {
102 LibusbConnection* self = nullptr;
103 libusb_transfer* transfer = nullptr;
104 Block block;
105 bool active = false;
106 };
107
108 struct WriteBlock {
109 LibusbConnection* self;
110 libusb_transfer* transfer;
111 Block block;
112 TransferId id;
113 };
114
LibusbConnectionLibusbConnection115 explicit LibusbConnection(unique_device device)
116 : device_(std::move(device)), device_address_(get_device_address(device_.get())) {}
117
~LibusbConnectionLibusbConnection118 ~LibusbConnection() { Stop(); }
119
HandlePacketLibusbConnection120 void HandlePacket(amessage& msg, std::optional<Block> payload) {
121 auto packet = std::make_unique<apacket>();
122 packet->msg = msg;
123 if (payload) {
124 packet->payload = std::move(*payload);
125 }
126 read_callback_(this, std::move(packet));
127 }
128
CleanupLibusbConnection129 void Cleanup(ReadBlock* read_block) REQUIRES(read_mutex_) {
130 libusb_free_transfer(read_block->transfer);
131 read_block->active = false;
132 read_block->transfer = nullptr;
133 if (terminating_) {
134 destruction_cv_.notify_one();
135 }
136 }
137
MaybeCleanupLibusbConnection138 bool MaybeCleanup(ReadBlock* read_block) REQUIRES(read_mutex_) {
139 if (read_block->transfer->status == LIBUSB_TRANSFER_CANCELLED) {
140 CHECK(terminating_);
141 }
142
143 if (terminating_) {
144 Cleanup(read_block);
145 return true;
146 }
147
148 return false;
149 }
150
header_read_cbLibusbConnection151 static void LIBUSB_CALL header_read_cb(libusb_transfer* transfer) {
152 auto read_block = static_cast<ReadBlock*>(transfer->user_data);
153 auto self = read_block->self;
154
155 std::lock_guard<std::mutex> lock(self->read_mutex_);
156 CHECK_EQ(read_block, &self->header_read_);
157 if (self->MaybeCleanup(read_block)) {
158 return;
159 }
160
161 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
162 std::string msg = StringPrintf("usb read failed: status = %d", transfer->status);
163 LOG(ERROR) << msg;
164 self->OnError(msg);
165 self->Cleanup(read_block);
166 return;
167 }
168
169 if (transfer->actual_length != sizeof(amessage)) {
170 std::string msg = StringPrintf("usb read: invalid length for header: %d",
171 transfer->actual_length);
172 LOG(ERROR) << msg;
173 self->OnError(msg);
174 self->Cleanup(read_block);
175 return;
176 }
177
178 CHECK(!self->incoming_header_);
179 amessage& amsg = self->incoming_header_.emplace();
180 memcpy(&amsg, transfer->buffer, sizeof(amsg));
181
182 if (amsg.data_length > MAX_PAYLOAD) {
183 std::string msg =
184 StringPrintf("usb read: payload length too long: %d", amsg.data_length);
185 LOG(ERROR) << msg;
186 self->OnError(msg);
187 self->Cleanup(&self->header_read_);
188 return;
189 } else if (amsg.data_length == 0) {
190 self->HandlePacket(amsg, std::nullopt);
191 self->incoming_header_.reset();
192 self->SubmitRead(read_block, sizeof(amessage));
193 } else {
194 read_block->active = false;
195 self->SubmitRead(&self->payload_read_, amsg.data_length);
196 }
197 }
198
payload_read_cbLibusbConnection199 static void LIBUSB_CALL payload_read_cb(libusb_transfer* transfer) {
200 auto read_block = static_cast<ReadBlock*>(transfer->user_data);
201 auto self = read_block->self;
202 std::lock_guard<std::mutex> lock(self->read_mutex_);
203
204 if (self->MaybeCleanup(&self->payload_read_)) {
205 return;
206 }
207
208 if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
209 std::string msg = StringPrintf("usb read failed: status = %d", transfer->status);
210 LOG(ERROR) << msg;
211 self->OnError(msg);
212 self->Cleanup(&self->payload_read_);
213 return;
214 }
215
216 if (transfer->actual_length != transfer->length) {
217 std::string msg =
218 StringPrintf("usb read: unexpected length for payload: wanted %d, got %d",
219 transfer->length, transfer->actual_length);
220 LOG(ERROR) << msg;
221 self->OnError(msg);
222 self->Cleanup(&self->payload_read_);
223 return;
224 }
225
226 CHECK(self->incoming_header_.has_value());
227 self->HandlePacket(*self->incoming_header_, std::move(read_block->block));
228 self->incoming_header_.reset();
229
230 read_block->active = false;
231 self->SubmitRead(&self->header_read_, sizeof(amessage));
232 }
233
write_cbLibusbConnection234 static void LIBUSB_CALL write_cb(libusb_transfer* transfer) {
235 auto write_block = static_cast<WriteBlock*>(transfer->user_data);
236 auto self = write_block->self;
237
238 bool succeeded = transfer->status == LIBUSB_TRANSFER_COMPLETED;
239
240 {
241 std::lock_guard<std::mutex> lock(self->write_mutex_);
242 libusb_free_transfer(transfer);
243 self->writes_.erase(write_block->id);
244
245 if (self->terminating_ && self->writes_.empty()) {
246 self->destruction_cv_.notify_one();
247 }
248 }
249
250 if (!succeeded) {
251 self->OnError("libusb write failed");
252 }
253 }
254
DoTlsHandshakeLibusbConnection255 bool DoTlsHandshake(RSA*, std::string*) final {
256 LOG(FATAL) << "tls not supported";
257 return false;
258 }
259
CreateReadLibusbConnection260 void CreateRead(ReadBlock* read, bool header) {
261 read->self = this;
262 read->transfer = libusb_alloc_transfer(0);
263 if (!read->transfer) {
264 LOG(FATAL) << "failed to allocate libusb_transfer for read";
265 }
266 libusb_fill_bulk_transfer(read->transfer, device_handle_.get(), read_endpoint_, nullptr, 0,
267 header ? header_read_cb : payload_read_cb, read, 0);
268 }
269
SubmitReadLibusbConnection270 void SubmitRead(ReadBlock* read, size_t length) {
271 read->block.resize(length);
272 read->transfer->buffer = reinterpret_cast<unsigned char*>(read->block.data());
273 read->transfer->length = length;
274 read->active = true;
275 int rc = libusb_submit_transfer(read->transfer);
276 if (rc != 0) {
277 LOG(ERROR) << "libusb_submit_transfer failed: " << libusb_strerror(rc);
278 }
279 }
280
SubmitWriteLibusbConnection281 void SubmitWrite(Block&& block) REQUIRES(write_mutex_) {
282 // TODO: Reuse write blocks.
283 auto write = std::make_unique<WriteBlock>();
284
285 write->self = this;
286 write->id = TransferId::write(next_write_id_++);
287 write->block = std::move(block);
288 write->transfer = libusb_alloc_transfer(0);
289 if (!write->transfer) {
290 LOG(FATAL) << "failed to allocate libusb_transfer for write";
291 }
292
293 libusb_fill_bulk_transfer(write->transfer, device_handle_.get(), write_endpoint_,
294 reinterpret_cast<unsigned char*>(write->block.data()),
295 write->block.size(), &write_cb, write.get(), 0);
296 libusb_submit_transfer(write->transfer);
297 writes_[write->id] = std::move(write);
298 }
299
WriteLibusbConnection300 bool Write(std::unique_ptr<apacket> packet) final {
301 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
302 Block header;
303 header.resize(sizeof(packet->msg));
304 memcpy(header.data(), &packet->msg, sizeof(packet->msg));
305
306 std::lock_guard<std::mutex> lock(write_mutex_);
307 if (terminating_) {
308 return false;
309 }
310
311 SubmitWrite(std::move(header));
312 if (!packet->payload.empty()) {
313 size_t payload_length = packet->payload.size();
314 SubmitWrite(std::move(packet->payload));
315
316 // If the payload is a multiple of the endpoint packet size, we
317 // need an explicit zero-sized transfer.
318 if (should_perform_zero_transfer(payload_length, zero_mask_)) {
319 LOG(INFO) << "submitting zero transfer for payload length " << payload_length;
320 Block empty;
321 SubmitWrite(std::move(empty));
322 }
323 }
324
325 return true;
326 }
327
GetDeviceDescriptorLibusbConnection328 std::optional<libusb_device_descriptor> GetDeviceDescriptor() {
329 libusb_device_descriptor device_desc;
330 int rc = libusb_get_device_descriptor(device_.get(), &device_desc);
331 if (rc != 0) {
332 LOG(WARNING) << "failed to get device descriptor for device at " << device_address_
333 << ": " << libusb_error_name(rc);
334 return {};
335 }
336 return device_desc;
337 }
338
FindInterfaceLibusbConnection339 bool FindInterface(libusb_device_descriptor* device_desc) {
340 if (device_desc->bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
341 // Assume that all Android devices have the device class set to per interface.
342 // TODO: Is this assumption valid?
343 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address_;
344 return false;
345 }
346
347 libusb_config_descriptor* config_raw;
348 int rc = libusb_get_active_config_descriptor(device_.get(), &config_raw);
349 if (rc != 0) {
350 LOG(WARNING) << "failed to get active config descriptor for device at "
351 << device_address_ << ": " << libusb_error_name(rc);
352 return false;
353 }
354 const unique_config_descriptor config(config_raw);
355
356 // Use size_t for interface_num so <iostream>s don't mangle it.
357 size_t interface_num;
358 uint16_t zero_mask = 0;
359 uint8_t bulk_in = 0, bulk_out = 0;
360 size_t packet_size = 0;
361 bool found_adb = false;
362
363 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
364 const libusb_interface& interface = config->interface[interface_num];
365
366 if (interface.num_altsetting == 0) {
367 continue;
368 }
369
370 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
371 if (!is_adb_interface(interface_desc.bInterfaceClass, interface_desc.bInterfaceSubClass,
372 interface_desc.bInterfaceProtocol)) {
373 LOG(VERBOSE) << "skipping non-adb interface at " << device_address_
374 << " (interface " << interface_num << ")";
375 continue;
376 }
377
378 if (interface.num_altsetting != 1) {
379 // Assume that interfaces with alternate settings aren't adb interfaces.
380 // TODO: Is this assumption valid?
381 LOG(WARNING) << "skipping interface with unexpected num_altsetting at "
382 << device_address_ << " (interface " << interface_num << ")";
383 continue;
384 }
385
386 LOG(VERBOSE) << "found potential adb interface at " << device_address_ << " (interface "
387 << interface_num << ")";
388
389 bool found_in = false;
390 bool found_out = false;
391 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
392 ++endpoint_num) {
393 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
394 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
395 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
396
397 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
398
399 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
400 continue;
401 }
402
403 if (endpoint_is_output(endpoint_addr) && !found_out) {
404 found_out = true;
405 bulk_out = endpoint_addr;
406 zero_mask = endpoint_desc.wMaxPacketSize - 1;
407 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
408 found_in = true;
409 bulk_in = endpoint_addr;
410 }
411
412 size_t endpoint_packet_size = endpoint_desc.wMaxPacketSize;
413 CHECK(endpoint_packet_size != 0);
414 if (packet_size == 0) {
415 packet_size = endpoint_packet_size;
416 } else {
417 CHECK(packet_size == endpoint_packet_size);
418 }
419 }
420
421 if (found_in && found_out) {
422 found_adb = true;
423 break;
424 } else {
425 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address_
426 << "(interface " << interface_num << "): missing bulk endpoints "
427 << "(found_in = " << found_in << ", found_out = " << found_out << ")";
428 }
429 }
430
431 if (!found_adb) {
432 return false;
433 }
434
435 interface_num_ = interface_num;
436 write_endpoint_ = bulk_out;
437 read_endpoint_ = bulk_in;
438 zero_mask_ = zero_mask;
439 return true;
440 }
441
GetSerialLibusbConnection442 std::string GetSerial() {
443 std::string serial;
444
445 auto device_desc = GetDeviceDescriptor();
446
447 serial.resize(255);
448 int rc = libusb_get_string_descriptor_ascii(
449 device_handle_.get(), device_desc->iSerialNumber,
450 reinterpret_cast<unsigned char*>(&serial[0]), serial.length());
451 if (rc == 0) {
452 LOG(WARNING) << "received empty serial from device at " << device_address_;
453 return {};
454 } else if (rc < 0) {
455 LOG(WARNING) << "failed to get serial from device at " << device_address_
456 << libusb_error_name(rc);
457 return {};
458 }
459 serial.resize(rc);
460
461 return serial;
462 }
463
OpenDeviceLibusbConnection464 bool OpenDevice(std::string* error) {
465 if (device_handle_) {
466 return true;
467 }
468
469 libusb_device_handle* handle_raw;
470 int rc = libusb_open(device_.get(), &handle_raw);
471 if (rc != 0) {
472 std::string err = StringPrintf("failed to open device: %s", libusb_strerror(rc));
473 LOG(ERROR) << err;
474
475 #if defined(__linux__)
476 std::string device_serial;
477 // libusb doesn't think we should be messing around with devices we don't have
478 // write access to, but Linux at least lets us get the serial number anyway.
479 if (!android::base::ReadFileToString(get_device_serial_path(device_.get()),
480 &device_serial)) {
481 // We don't actually want to treat an unknown serial as an error because
482 // devices aren't able to communicate a serial number in early bringup.
483 // http://b/20883914
484 serial_ = "<unknown>";
485 } else {
486 serial_ = android::base::Trim(device_serial);
487 }
488 #else
489 // On Mac OS and Windows, we're screwed. But I don't think this situation actually
490 // happens on those OSes.
491 #endif
492
493 if (error) {
494 *error = std::move(err);
495 }
496
497 return false;
498 }
499
500 unique_device_handle handle(handle_raw);
501 device_handle_ = std::move(handle);
502
503 auto device_desc = GetDeviceDescriptor();
504 if (!device_desc) {
505 device_handle_.reset();
506 return false;
507 }
508
509 if (!FindInterface(&device_desc.value())) {
510 device_handle_.reset();
511 return false;
512 }
513
514 serial_ = GetSerial();
515 return true;
516 }
517
StartImplLibusbConnection518 bool StartImpl(std::string* error) {
519 if (!OpenDevice(error)) {
520 return false;
521 }
522
523 LOG(DEBUG) << "successfully opened adb device at " << device_address_ << ", "
524 << StringPrintf("bulk_in = %#x, bulk_out = %#x", read_endpoint_,
525 write_endpoint_);
526
527 // WARNING: this isn't released via RAII.
528 int rc = libusb_claim_interface(device_handle_.get(), interface_num_);
529 if (rc != 0) {
530 LOG(WARNING) << "failed to claim adb interface for device '" << serial_ << "'"
531 << libusb_error_name(rc);
532 return false;
533 }
534
535 for (uint8_t endpoint : {read_endpoint_, write_endpoint_}) {
536 rc = libusb_clear_halt(device_handle_.get(), endpoint);
537 if (rc != 0) {
538 LOG(WARNING) << "failed to clear halt on device '" << serial_ << "' endpoint 0x"
539 << std::hex << endpoint << ": " << libusb_error_name(rc);
540 libusb_release_interface(device_handle_.get(), interface_num_);
541 return false;
542 }
543 }
544
545 LOG(INFO) << "registered new usb device '" << serial_ << "'";
546 std::lock_guard lock(read_mutex_);
547 CreateRead(&header_read_, true);
548 CreateRead(&payload_read_, false);
549 SubmitRead(&header_read_, sizeof(amessage));
550
551 return true;
552 }
553
OnErrorLibusbConnection554 void OnError(const std::string& error) {
555 std::call_once(error_flag_, [this, &error]() {
556 if (error_callback_) {
557 error_callback_(this, error);
558 }
559 });
560 }
561
ResetLibusbConnection562 virtual void Reset() override final {
563 Stop();
564
565 if (libusb_reset_device(device_handle_.get()) == 0) {
566 libusb_device* device = libusb_ref_device(device_.get());
567 fdevent_run_on_main_thread([device]() {
568 process_device(device);
569 libusb_unref_device(device);
570 });
571 }
572 }
573
StartLibusbConnection574 virtual void Start() override final {
575 std::string error;
576 if (!StartImpl(&error)) {
577 OnError(error);
578 return;
579 }
580 }
581
StopLibusbConnection582 virtual void Stop() override final {
583 // This is rather messy, because of the lifecyle of libusb_transfers.
584 //
585 // We can't call libusb_free_transfer for a submitted transfer, we have to cancel it
586 // and free it in the callback. Complicating things more, it's possible for us to be in
587 // the callback for a transfer as the destructor is being called, at which point cancelling
588 // the transfer won't do anything (and it's possible that we'll submit the transfer again
589 // in the callback).
590 //
591 // Resolve this by setting an atomic flag before we lock to cancel transfers, and take the
592 // lock in the callbacks before checking the flag.
593
594 if (terminating_) {
595 return;
596 }
597
598 terminating_ = true;
599
600 {
601 std::unique_lock<std::mutex> lock(write_mutex_);
602 ScopedLockAssertion assumed_locked(write_mutex_);
603
604 if (!writes_.empty()) {
605 for (auto& [id, write] : writes_) {
606 libusb_cancel_transfer(write->transfer);
607 }
608
609 destruction_cv_.wait(lock, [this]() {
610 ScopedLockAssertion assumed_locked(write_mutex_);
611 return writes_.empty();
612 });
613 }
614 }
615
616 {
617 std::unique_lock<std::mutex> lock(read_mutex_);
618 ScopedLockAssertion assumed_locked(read_mutex_);
619 if (header_read_.transfer) {
620 if (header_read_.active) {
621 libusb_cancel_transfer(header_read_.transfer);
622 } else {
623 libusb_free_transfer(header_read_.transfer);
624 }
625 }
626
627 if (payload_read_.transfer) {
628 if (payload_read_.active) {
629 libusb_cancel_transfer(payload_read_.transfer);
630 } else {
631 libusb_free_transfer(payload_read_.transfer);
632 }
633 }
634
635 destruction_cv_.wait(lock, [this]() {
636 ScopedLockAssertion assumed_locked(read_mutex_);
637 return !header_read_.active && !payload_read_.active;
638 });
639 }
640
641 if (device_handle_) {
642 libusb_release_interface(device_handle_.get(), interface_num_);
643 }
644
645 OnError("requested stop");
646 }
647
CreateLibusbConnection648 static std::optional<std::shared_ptr<LibusbConnection>> Create(unique_device device) {
649 auto connection = std::make_unique<LibusbConnection>(std::move(device));
650 if (!connection) {
651 LOG(FATAL) << "failed to construct LibusbConnection";
652 }
653
654 auto device_desc = connection->GetDeviceDescriptor();
655 if (!device_desc) {
656 return {};
657 }
658
659 if (!connection->FindInterface(&device_desc.value())) {
660 return {};
661 }
662
663 if (!connection->OpenDevice(nullptr)) {
664 return {};
665 }
666
667 return connection;
668 }
669
670 unique_device device_;
671 unique_device_handle device_handle_;
672 std::string device_address_;
673 std::string serial_ = "<unknown>";
674
675 uint32_t interface_num_;
676 uint8_t write_endpoint_;
677 uint8_t read_endpoint_;
678
679 std::mutex read_mutex_;
680 ReadBlock header_read_ GUARDED_BY(read_mutex_);
681 ReadBlock payload_read_ GUARDED_BY(read_mutex_);
682 std::optional<amessage> incoming_header_ GUARDED_BY(read_mutex_);
683 IOVector incoming_payload_ GUARDED_BY(read_mutex_);
684
685 std::mutex write_mutex_;
686 std::unordered_map<TransferId, std::unique_ptr<WriteBlock>> writes_ GUARDED_BY(write_mutex_);
687 std::atomic<size_t> next_write_id_ = 0;
688
689 std::once_flag error_flag_;
690 std::atomic<bool> terminating_ = false;
691 std::condition_variable destruction_cv_;
692
693 size_t zero_mask_ = 0;
694 };
695
696 static libusb_hotplug_callback_handle hotplug_handle;
697 static std::mutex usb_handles_mutex [[clang::no_destroy]];
698 static std::unordered_map<libusb_device*, std::weak_ptr<LibusbConnection>> usb_handles
699 [[clang::no_destroy]] GUARDED_BY(usb_handles_mutex);
700 static std::atomic<int> connecting_devices(0);
701
process_device(libusb_device * device_raw)702 static void process_device(libusb_device* device_raw) {
703 std::string device_address = get_device_address(device_raw);
704 LOG(INFO) << "device connected: " << device_address;
705
706 unique_device device(libusb_ref_device(device_raw));
707 auto connection_opt = LibusbConnection::Create(std::move(device));
708 if (!connection_opt) {
709 LOG(INFO) << "ignoring device: not an adb interface";
710 return;
711 }
712
713 auto connection = *connection_opt;
714 LOG(INFO) << "constructed LibusbConnection for device " << connection->serial_ << " ("
715 << device_address << ")";
716
717 register_usb_transport(connection, connection->serial_.c_str(), device_address.c_str(), true);
718 }
719
device_connected(libusb_device * device)720 static void device_connected(libusb_device* device) {
721 #if defined(__linux__)
722 // Android's host linux libusb uses netlink instead of udev for device hotplug notification,
723 // which means we can get hotplug notifications before udev has updated ownership/perms on the
724 // device. Since we're not going to be able to link against the system's libudev any time soon,
725 // hack around this by inserting a sleep.
726 libusb_ref_device(device);
727 auto thread = std::thread([device]() {
728 std::this_thread::sleep_for(std::chrono::seconds(1));
729 process_device(device);
730 if (--connecting_devices == 0) {
731 adb_notify_device_scan_complete();
732 }
733 libusb_unref_device(device);
734 });
735 thread.detach();
736 #else
737 process_device(device);
738 #endif
739 }
740
device_disconnected(libusb_device * device)741 static void device_disconnected(libusb_device* device) {
742 usb_handles_mutex.lock();
743 auto it = usb_handles.find(device);
744 if (it != usb_handles.end()) {
745 // We need to ensure that we don't destroy the LibusbConnection on this thread,
746 // as we're in a context with internal libusb mutexes held.
747 std::weak_ptr<LibusbConnection> connection_weak = it->second;
748 usb_handles.erase(it);
749 fdevent_run_on_main_thread([connection_weak]() {
750 auto connection = connection_weak.lock();
751 if (connection) {
752 connection->Stop();
753 LOG(INFO) << "libusb_hotplug: device disconnected: " << connection->serial_;
754 } else {
755 LOG(INFO) << "libusb_hotplug: device disconnected: (destroyed)";
756 }
757 });
758 }
759 usb_handles_mutex.unlock();
760 }
761
762 static auto& hotplug_queue = *new BlockingQueue<std::pair<libusb_hotplug_event, libusb_device*>>();
hotplug_thread()763 static void hotplug_thread() {
764 LOG(INFO) << "libusb hotplug thread started";
765 adb_thread_setname("libusb hotplug");
766 while (true) {
767 hotplug_queue.PopAll([](std::pair<libusb_hotplug_event, libusb_device*> pair) {
768 libusb_hotplug_event event = pair.first;
769 libusb_device* device = pair.second;
770 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
771 device_connected(device);
772 } else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) {
773 device_disconnected(device);
774 }
775 });
776 }
777 }
778
hotplug_callback(libusb_context *,libusb_device * device,libusb_hotplug_event event,void *)779 static LIBUSB_CALL int hotplug_callback(libusb_context*, libusb_device* device,
780 libusb_hotplug_event event, void*) {
781 // We're called with the libusb lock taken. Call these on a separate thread outside of this
782 // function so that the usb_handle mutex is always taken before the libusb mutex.
783 static std::once_flag once;
784 std::call_once(once, []() { std::thread(hotplug_thread).detach(); });
785
786 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
787 ++connecting_devices;
788 }
789 hotplug_queue.Push({event, device});
790 return 0;
791 }
792
793 namespace libusb {
794
usb_init()795 void usb_init() {
796 LOG(DEBUG) << "initializing libusb...";
797 int rc = libusb_init(nullptr);
798 if (rc != 0) {
799 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
800 }
801
802 // Register the hotplug callback.
803 rc = libusb_hotplug_register_callback(
804 nullptr,
805 static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
806 LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
807 LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY,
808 LIBUSB_CLASS_PER_INTERFACE, hotplug_callback, nullptr, &hotplug_handle);
809
810 if (rc != LIBUSB_SUCCESS) {
811 LOG(FATAL) << "failed to register libusb hotplug callback";
812 }
813
814 // Spawn a thread for libusb_handle_events.
815 std::thread([]() {
816 adb_thread_setname("libusb");
817 while (true) {
818 libusb_handle_events(nullptr);
819 }
820 }).detach();
821 }
822
823 } // namespace libusb
824