summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.clang-format-21
-rw-r--r--.clang-format-41
-rw-r--r--adb/Android.mk24
-rw-r--r--adb/adb.cpp181
-rw-r--r--adb/adb.h19
-rw-r--r--adb/adb_client.cpp67
-rw-r--r--adb/adb_client.h4
-rw-r--r--adb/adb_listeners.cpp33
-rw-r--r--adb/adb_listeners.h2
-rw-r--r--adb/adb_trace.cpp4
-rw-r--r--adb/adb_trace.h3
-rw-r--r--adb/adb_utils.cpp4
-rw-r--r--adb/adb_utils.h2
-rw-r--r--adb/bugreport.cpp4
-rw-r--r--adb/client/main.cpp66
-rw-r--r--adb/client/usb_dispatch.cpp14
-rw-r--r--adb/client/usb_libusb.cpp472
-rw-r--r--adb/client/usb_linux.cpp54
-rw-r--r--adb/client/usb_osx.cpp31
-rw-r--r--adb/client/usb_windows.cpp34
-rw-r--r--adb/commandline.cpp387
-rw-r--r--adb/commandline.h1
-rw-r--r--adb/daemon/main.cpp13
-rw-r--r--adb/daemon/mdns.cpp10
-rw-r--r--adb/daemon/usb.cpp6
-rw-r--r--adb/diagnose_usb.cpp43
-rw-r--r--adb/fdevent.cpp89
-rw-r--r--adb/fdevent.h8
-rw-r--r--adb/fdevent_test.cpp37
-rw-r--r--adb/fdevent_test.h14
-rw-r--r--adb/services.cpp12
-rw-r--r--adb/set_verity_enable_state_service.cpp134
-rw-r--r--adb/shell_service.cpp8
-rw-r--r--adb/socket_test.cpp30
-rw-r--r--adb/sockets.cpp2
-rw-r--r--adb/sysdeps.h133
-rw-r--r--adb/sysdeps/network.h (renamed from bootstat/uptime_parser.h)19
-rw-r--r--adb/sysdeps/posix/network.cpp127
-rw-r--r--adb/sysdeps_test.cpp99
-rw-r--r--adb/sysdeps_win32.cpp29
-rw-r--r--adb/test_device.py99
-rw-r--r--adb/transport.cpp100
-rw-r--r--adb/transport.h29
-rw-r--r--adb/transport_local.cpp19
-rw-r--r--adb/transport_mdns.cpp23
-rw-r--r--adb/transport_test.cpp7
-rw-r--r--adb/transport_usb.cpp110
-rw-r--r--adb/usb.h6
-rw-r--r--base/Android.bp35
-rw-r--r--base/chrono_utils.cpp37
-rw-r--r--base/chrono_utils_test.cpp46
-rw-r--r--base/file.cpp22
-rw-r--r--base/include/android-base/chrono_utils.h37
-rw-r--r--base/include/android-base/logging.h69
-rw-r--r--base/include/android-base/properties.h9
-rw-r--r--base/include/android-base/scopeguard.h60
-rw-r--r--base/properties.cpp33
-rw-r--r--base/properties_test.cpp32
-rw-r--r--base/scopeguard_test.cpp46
-rw-r--r--[-rwxr-xr-x]base/utf8.cpp0
-rw-r--r--[-rwxr-xr-x]base/utf8_test.cpp0
-rw-r--r--bootstat/Android.bp2
-rw-r--r--bootstat/AndroidTest.xml26
-rw-r--r--bootstat/boot_event_record_store.cpp9
-rw-r--r--bootstat/boot_event_record_store_test.cpp18
-rw-r--r--bootstat/bootstat.cpp21
-rw-r--r--debuggerd/Android.bp13
-rw-r--r--debuggerd/client/debuggerd_client.cpp4
-rw-r--r--debuggerd/crash_dump.cpp1
-rw-r--r--debuggerd/handler/debuggerd_fallback.cpp17
-rw-r--r--debuggerd/handler/debuggerd_handler.cpp68
-rw-r--r--debuggerd/include/debuggerd/protocol.h1
-rw-r--r--debuggerd/include/debuggerd/tombstoned.h2
-rw-r--r--debuggerd/libdebuggerd/utility.cpp46
-rw-r--r--debuggerd/tombstoned/tombstoned.cpp258
-rw-r--r--debuggerd/tombstoned/tombstoned.rc1
-rw-r--r--debuggerd/tombstoned_client.cpp34
-rw-r--r--debuggerd/util.cpp2
-rw-r--r--demangle/demangle.cpp88
-rw-r--r--fastboot/Android.mk8
-rw-r--r--fastboot/README.md10
-rw-r--r--fastboot/engine.cpp75
-rw-r--r--fastboot/fastboot.cpp578
-rw-r--r--fastboot/fastboot.h9
-rw-r--r--fastboot/protocol.cpp125
-rw-r--r--fs_mgr/Android.bp62
-rw-r--r--fs_mgr/Android.mk29
-rw-r--r--fs_mgr/fs_mgr.cpp42
-rw-r--r--fs_mgr/fs_mgr_avb.cpp179
-rw-r--r--fs_mgr/fs_mgr_avb_ops.cpp16
-rw-r--r--fs_mgr/fs_mgr_boot_config.cpp2
-rw-r--r--fs_mgr/fs_mgr_priv_avb_ops.h2
-rw-r--r--fs_mgr/include/fs_mgr.h1
l---------include/system2
-rw-r--r--init/Android.mk21
-rw-r--r--init/README.md126
-rw-r--r--init/action.cpp161
-rw-r--r--init/action.h80
-rw-r--r--init/bootchart.cpp3
-rw-r--r--init/builtins.cpp111
-rw-r--r--init/builtins.h13
-rw-r--r--init/descriptors.cpp14
-rw-r--r--init/devices.cpp1012
-rw-r--r--init/devices.h109
-rw-r--r--init/devices_test.cpp409
-rw-r--r--init/import_parser.cpp22
-rw-r--r--init/import_parser.h25
-rw-r--r--init/init.cpp117
-rw-r--r--init/init.h5
-rw-r--r--init/init_first_stage.cpp16
-rw-r--r--init/init_parser.cpp55
-rw-r--r--init/init_parser.h78
-rw-r--r--init/init_parser_test.cpp20
-rw-r--r--init/init_test.cpp187
-rw-r--r--init/keychords.cpp4
-rw-r--r--init/keyutils.h44
-rw-r--r--init/keyword_map.h23
-rw-r--r--init/log.h2
-rw-r--r--init/parser.cpp23
-rw-r--r--init/parser.h6
-rw-r--r--init/property_service.cpp56
-rw-r--r--init/property_service.h3
-rw-r--r--init/reboot.cpp8
-rw-r--r--init/reboot.h2
-rw-r--r--init/service.cpp165
-rw-r--r--init/service.h30
-rw-r--r--init/service_test.cpp2
-rw-r--r--init/signal_handler.cpp9
-rw-r--r--init/ueventd.cpp95
-rw-r--r--init/ueventd.h19
-rw-r--r--init/ueventd_keywords.h15
-rw-r--r--init/ueventd_parser.cpp241
-rw-r--r--init/util.cpp191
-rw-r--r--init/util.h54
-rw-r--r--init/util_test.cpp139
-rw-r--r--init/watchdogd.cpp8
-rw-r--r--libappfuse/Android.bp1
-rw-r--r--libappfuse/AndroidTest.xml26
-rw-r--r--libbacktrace/Android.bp2
-rw-r--r--libbacktrace/BacktraceAsyncSafeLog.h41
-rw-r--r--libbacktrace/BacktraceCurrent.cpp17
-rw-r--r--libbacktrace/ThreadEntry.cpp4
-rw-r--r--libbinderwrapper/Android.bp61
-rw-r--r--libbinderwrapper/Android.mk62
-rw-r--r--libcutils/Android.bp6
-rw-r--r--libcutils/ashmem-dev.c1
-rw-r--r--libcutils/canned_fs_config.c13
-rw-r--r--libcutils/fs_config.cpp (renamed from libcutils/fs_config.c)148
-rw-r--r--libcutils/include/cutils/bitops.h85
-rw-r--r--libcutils/include/cutils/sockets.h2
-rw-r--r--libcutils/include/private/android_filesystem_config.h3
-rw-r--r--libcutils/native_handle.c42
-rw-r--r--libcutils/sched_policy.cpp66
-rw-r--r--libcutils/socket_loopback_server_unix.c88
-rw-r--r--libcutils/tests/Android.bp5
-rw-r--r--libcutils/tests/AndroidTest.xml26
-rw-r--r--libcutils/tests/AshmemTest.cpp82
-rw-r--r--libcutils/tests/fs_config.cpp201
l---------libkeyutils/.clang-format1
-rw-r--r--libkeyutils/Android.bp16
-rw-r--r--libkeyutils/include/keyutils.h56
-rw-r--r--libkeyutils/keyutils.cpp71
-rw-r--r--libkeyutils/keyutils_test.cpp46
-rw-r--r--liblog/event.logtags1
-rw-r--r--liblog/event_tag_map.cpp66
-rw-r--r--liblog/fake_log_device.c81
-rw-r--r--liblog/fake_log_device.h2
-rw-r--r--liblog/fake_writer.c4
-rw-r--r--liblog/include/log/log.h26
-rw-r--r--liblog/include/log/log_event_list.h10
-rw-r--r--liblog/include/log/log_safetynet.h44
-rw-r--r--liblog/include/log/log_time.h10
-rw-r--r--liblog/include_vndk/log/log.h1
l---------liblog/include_vndk/log/log_safetynet.h1
-rw-r--r--liblog/liblog.map.txt1
-rw-r--r--liblog/logger_write.c50
-rw-r--r--liblog/logprint.c43
-rw-r--r--liblog/tests/Android.mk9
-rw-r--r--liblog/tests/liblog_benchmark.cpp26
l---------libmemunreachable/.clang-format1
-rw-r--r--libmemunreachable/Android.bp11
-rw-r--r--libmemunreachable/HeapWalker.cpp12
-rw-r--r--libmemunreachable/LeakPipe.cpp10
-rw-r--r--libmemunreachable/LeakPipe.h18
-rw-r--r--libmemunreachable/MemUnreachable.cpp42
-rw-r--r--libmemunreachable/PtracerThread.cpp8
-rw-r--r--libmemunreachable/ScopedPipe.h2
-rw-r--r--libmemunreachable/ScopedSignalHandler.h18
-rw-r--r--libmemunreachable/ThreadCapture.cpp26
-rw-r--r--libmemunreachable/log.h26
-rw-r--r--libmemunreachable/tests/DisableMalloc_test.cpp4
-rw-r--r--libmemunreachable/tests/MemUnreachable_test.cpp10
-rw-r--r--libmemunreachable/tests/ThreadCapture_test.cpp2
-rw-r--r--libmetricslogger/Android.bp1
-rw-r--r--libmetricslogger/include/metricslogger/metrics_logger.h15
-rw-r--r--libmetricslogger/metrics_logger.cpp16
-rw-r--r--libmetricslogger/metrics_logger_test.cpp8
l---------libnativebridge/.clang-format1
-rw-r--r--libnativebridge/Android.bp2
-rw-r--r--libnativebridge/native_bridge.cc28
-rw-r--r--libnativebridge/tests/Android.bp53
-rw-r--r--libnativebridge/tests/Android.mk2
-rw-r--r--libnativebridge/tests/Android.nativebridge-dummy.mk108
-rw-r--r--libnativebridge/tests/DummyNativeBridge3.cpp4
-rw-r--r--libnativebridge/tests/NativeBridge3InitAnonymousNamespace_test.cpp22
l---------libnativeloader/.clang-format1
-rw-r--r--libnativeloader/native_loader.cpp12
-rw-r--r--libnetutils/Android.bp14
-rw-r--r--libnetutils/dhcptool.c47
-rw-r--r--libprocessgroup/Android.bp11
-rw-r--r--libprocessgroup/Android.mk19
-rw-r--r--libprocessgroup/include/processgroup/processgroup.h5
-rw-r--r--libprocessgroup/processgroup.cpp181
-rw-r--r--libsparse/Android.bp15
-rw-r--r--libsparse/output_file.c2
-rw-r--r--libsparse/output_file.h8
-rw-r--r--libsparse/sparse_file.h7
-rw-r--r--libsparse/sparse_format.h8
-rw-r--r--libsparse/sparse_read.cpp (renamed from libsparse/sparse_read.c)75
-rw-r--r--libunwindstack/Android.bp14
-rw-r--r--libunwindstack/DwarfCfa.cpp713
-rw-r--r--libunwindstack/DwarfCfa.h255
-rw-r--r--libunwindstack/DwarfEncoding.h47
-rw-r--r--libunwindstack/DwarfError.h (renamed from bootstat/uptime_parser.cpp)32
-rw-r--r--libunwindstack/DwarfLocation.h41
-rw-r--r--libunwindstack/DwarfMemory.cpp248
-rw-r--r--libunwindstack/DwarfMemory.h72
-rw-r--r--libunwindstack/DwarfOp.cpp462
-rw-r--r--libunwindstack/DwarfOp.h1636
-rw-r--r--libunwindstack/DwarfStructs.h52
-rw-r--r--libunwindstack/ElfInterface.cpp34
-rw-r--r--libunwindstack/ElfInterfaceArm.cpp12
-rw-r--r--libunwindstack/MapInfo.cpp86
-rw-r--r--libunwindstack/MapInfo.h1
-rw-r--r--libunwindstack/Maps.cpp196
-rw-r--r--libunwindstack/Maps.h107
-rw-r--r--libunwindstack/Memory.cpp59
-rw-r--r--libunwindstack/Memory.h28
-rw-r--r--libunwindstack/Symbols.cpp110
-rw-r--r--libunwindstack/Symbols.h64
-rw-r--r--libunwindstack/tests/DwarfCfaLogTest.cpp814
-rw-r--r--libunwindstack/tests/DwarfCfaTest.cpp959
-rw-r--r--libunwindstack/tests/DwarfMemoryTest.cpp472
-rw-r--r--libunwindstack/tests/DwarfOpLogTest.cpp68
-rw-r--r--libunwindstack/tests/DwarfOpTest.cpp1593
-rw-r--r--libunwindstack/tests/MapInfoTest.cpp220
-rw-r--r--libunwindstack/tests/MapsTest.cpp237
-rw-r--r--libunwindstack/tests/MemoryBuffer.cpp77
-rw-r--r--libunwindstack/tests/MemoryFake.h12
-rw-r--r--libunwindstack/tests/MemoryFileTest.cpp57
-rw-r--r--libunwindstack/tests/MemoryLocalTest.cpp27
-rw-r--r--libunwindstack/tests/MemoryRangeTest.cpp34
-rw-r--r--libunwindstack/tests/MemoryRemoteTest.cpp13
-rw-r--r--libunwindstack/tests/MemoryTest.cpp126
-rw-r--r--libunwindstack/tests/SymbolsTest.cpp335
-rw-r--r--libusbhost/Android.bp35
-rw-r--r--libusbhost/Android.mk56
-rw-r--r--libusbhost/usbhost.c2
-rw-r--r--libutils/Android.bp10
-rw-r--r--libutils/FileMap.cpp24
-rw-r--r--lmkd/Android.bp13
-rw-r--r--lmkd/Android.mk12
-rw-r--r--logcat/event.logtags3
-rw-r--r--logcat/logcat.cpp1
-rw-r--r--logcat/tests/logcat_test.cpp196
-rw-r--r--logd/Android.mk39
-rw-r--r--logd/FlushCommand.cpp4
-rw-r--r--logd/LogAudit.cpp4
-rw-r--r--logd/LogBuffer.cpp172
-rw-r--r--logd/LogBuffer.h28
-rw-r--r--logd/LogBufferElement.cpp4
-rw-r--r--logd/LogBufferInterface.cpp (renamed from init/ueventd_parser.h)25
-rw-r--r--logd/LogBufferInterface.h43
-rw-r--r--logd/LogKlog.cpp2
-rw-r--r--logd/LogListener.cpp53
-rw-r--r--logd/LogListener.h14
-rw-r--r--logd/LogReader.cpp11
-rw-r--r--logd/LogStatistics.cpp324
-rw-r--r--logd/LogStatistics.h220
-rw-r--r--logd/LogTimes.cpp10
-rw-r--r--logd/LogTimes.h7
-rw-r--r--logd/LogUtils.h2
-rw-r--r--logd/event.logtags1
-rw-r--r--logd/logd.rc4
-rw-r--r--logd/main.cpp32
-rw-r--r--logd/tests/Android.mk35
-rw-r--r--logd/tests/AndroidTest.xml27
-rw-r--r--logd/tests/logd_test.cpp282
-rw-r--r--platform_tools_tool_version.mk (renamed from trusty/storage/interface/Android.mk)21
-rw-r--r--rootdir/etc/ld.config.txt4
-rw-r--r--rootdir/init.usb.configfs.rc14
-rw-r--r--rootdir/ueventd.rc39
-rw-r--r--shell_and_utilities/Android.bp13
-rw-r--r--shell_and_utilities/README.md157
-rw-r--r--trusty/Android.bp7
-rw-r--r--trusty/gatekeeper/Android.bp46
-rw-r--r--trusty/gatekeeper/Android.mk46
-rw-r--r--trusty/keymaster/Android.bp67
-rw-r--r--trusty/keymaster/Android.mk67
-rw-r--r--trusty/keymaster/keymaster_ipc.h15
-rw-r--r--trusty/keymaster/module.cpp27
-rw-r--r--trusty/keymaster/trusty_keymaster_device.cpp868
-rw-r--r--trusty/keymaster/trusty_keymaster_device.h161
-rw-r--r--trusty/keymaster/trusty_keymaster_ipc.cpp (renamed from trusty/keymaster/trusty_keymaster_ipc.c)24
-rw-r--r--trusty/keymaster/trusty_keymaster_ipc.h9
-rw-r--r--trusty/keymaster/trusty_keymaster_main.cpp230
-rw-r--r--trusty/libtrusty/Android.bp26
-rw-r--r--trusty/libtrusty/Android.mk36
-rw-r--r--trusty/libtrusty/tipc-test/Android.bp26
-rw-r--r--trusty/libtrusty/tipc-test/Android.mk29
-rw-r--r--trusty/nvram/Android.bp61
-rw-r--r--trusty/nvram/Android.mk43
-rw-r--r--trusty/storage/interface/Android.bp20
-rw-r--r--trusty/storage/lib/Android.bp35
-rw-r--r--trusty/storage/lib/Android.mk37
-rw-r--r--trusty/storage/proxy/Android.bp38
-rw-r--r--trusty/storage/proxy/Android.mk41
-rw-r--r--trusty/storage/proxy/proxy.c1
-rw-r--r--trusty/storage/tests/Android.bp36
-rw-r--r--trusty/storage/tests/Android.mk29
320 files changed, 18236 insertions, 5961 deletions
diff --git a/.clang-format-2 b/.clang-format-2
index aab4665d6..41591ce34 100644
--- a/.clang-format-2
+++ b/.clang-format-2
@@ -1,4 +1,5 @@
1BasedOnStyle: Google 1BasedOnStyle: Google
2AllowShortFunctionsOnASingleLine: Inline
2ColumnLimit: 100 3ColumnLimit: 100
3CommentPragmas: NOLINT:.* 4CommentPragmas: NOLINT:.*
4DerivePointerAlignment: false 5DerivePointerAlignment: false
diff --git a/.clang-format-4 b/.clang-format-4
index 1497447fe..ae4a45135 100644
--- a/.clang-format-4
+++ b/.clang-format-4
@@ -1,5 +1,6 @@
1BasedOnStyle: Google 1BasedOnStyle: Google
2AccessModifierOffset: -2 2AccessModifierOffset: -2
3AllowShortFunctionsOnASingleLine: Inline
3ColumnLimit: 100 4ColumnLimit: 100
4CommentPragmas: NOLINT:.* 5CommentPragmas: NOLINT:.*
5DerivePointerAlignment: false 6DerivePointerAlignment: false
diff --git a/adb/Android.mk b/adb/Android.mk
index e84120542..382c8cb78 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -5,23 +5,27 @@
5 5
6LOCAL_PATH:= $(call my-dir) 6LOCAL_PATH:= $(call my-dir)
7 7
8include $(LOCAL_PATH)/../platform_tools_tool_version.mk
9
8adb_host_sanitize := 10adb_host_sanitize :=
9adb_target_sanitize := 11adb_target_sanitize :=
10 12
11adb_version := $(shell git -C $(LOCAL_PATH) rev-parse --short=12 HEAD 2>/dev/null)-android
12
13ADB_COMMON_CFLAGS := \ 13ADB_COMMON_CFLAGS := \
14 -Wall -Wextra -Werror \ 14 -Wall -Wextra -Werror \
15 -Wno-unused-parameter \ 15 -Wno-unused-parameter \
16 -Wno-missing-field-initializers \ 16 -Wno-missing-field-initializers \
17 -Wvla \ 17 -Wvla \
18 -DADB_REVISION='"$(adb_version)"' \ 18 -DADB_VERSION="\"$(tool_version)\"" \
19 19
20ADB_COMMON_linux_CFLAGS := \ 20ADB_COMMON_posix_CFLAGS := \
21 -Wexit-time-destructors \ 21 -Wexit-time-destructors \
22 -Wthread-safety \
23
24ADB_COMMON_linux_CFLAGS := \
25 $(ADB_COMMON_posix_CFLAGS) \
22 26
23ADB_COMMON_darwin_CFLAGS := \ 27ADB_COMMON_darwin_CFLAGS := \
24 -Wexit-time-destructors \ 28 $(ADB_COMMON_posix_CFLAGS) \
25 29
26# Define windows.h and tchar.h Unicode preprocessor symbols so that 30# Define windows.h and tchar.h Unicode preprocessor symbols so that
27# CreateFile(), _tfopen(), etc. map to versions that take wchar_t*, breaking the 31# CreateFile(), _tfopen(), etc. map to versions that take wchar_t*, breaking the
@@ -81,12 +85,14 @@ LIBADB_windows_CFLAGS := \
81 85
82LIBADB_darwin_SRC_FILES := \ 86LIBADB_darwin_SRC_FILES := \
83 sysdeps_unix.cpp \ 87 sysdeps_unix.cpp \
88 sysdeps/posix/network.cpp \
84 client/usb_dispatch.cpp \ 89 client/usb_dispatch.cpp \
85 client/usb_libusb.cpp \ 90 client/usb_libusb.cpp \
86 client/usb_osx.cpp \ 91 client/usb_osx.cpp \
87 92
88LIBADB_linux_SRC_FILES := \ 93LIBADB_linux_SRC_FILES := \
89 sysdeps_unix.cpp \ 94 sysdeps_unix.cpp \
95 sysdeps/posix/network.cpp \
90 client/usb_dispatch.cpp \ 96 client/usb_dispatch.cpp \
91 client/usb_libusb.cpp \ 97 client/usb_libusb.cpp \
92 client/usb_linux.cpp \ 98 client/usb_linux.cpp \
@@ -123,6 +129,7 @@ LOCAL_SRC_FILES := \
123 $(LIBADB_SRC_FILES) \ 129 $(LIBADB_SRC_FILES) \
124 adbd_auth.cpp \ 130 adbd_auth.cpp \
125 jdwp_service.cpp \ 131 jdwp_service.cpp \
132 sysdeps/posix/network.cpp \
126 133
127LOCAL_SANITIZE := $(adb_target_sanitize) 134LOCAL_SANITIZE := $(adb_target_sanitize)
128 135
@@ -217,15 +224,15 @@ LOCAL_SRC_FILES_linux := $(LIBADB_TEST_linux_SRCS)
217LOCAL_SRC_FILES_darwin := $(LIBADB_TEST_darwin_SRCS) 224LOCAL_SRC_FILES_darwin := $(LIBADB_TEST_darwin_SRCS)
218LOCAL_SRC_FILES_windows := $(LIBADB_TEST_windows_SRCS) 225LOCAL_SRC_FILES_windows := $(LIBADB_TEST_windows_SRCS)
219LOCAL_SANITIZE := $(adb_host_sanitize) 226LOCAL_SANITIZE := $(adb_host_sanitize)
220LOCAL_SHARED_LIBRARIES := libbase
221LOCAL_STATIC_LIBRARIES := \ 227LOCAL_STATIC_LIBRARIES := \
222 libadb \ 228 libadb \
229 libbase \
223 libcrypto_utils \ 230 libcrypto_utils \
224 libcrypto \ 231 libcrypto \
225 libcutils \ 232 libcutils \
226 libdiagnose_usb \ 233 libdiagnose_usb \
227 libmdnssd \ 234 libmdnssd \
228 libgmock_host 235 libgmock_host \
229 236
230LOCAL_STATIC_LIBRARIES_linux := libusb 237LOCAL_STATIC_LIBRARIES_linux := libusb
231LOCAL_STATIC_LIBRARIES_darwin := libusb 238LOCAL_STATIC_LIBRARIES_darwin := libusb
@@ -293,7 +300,7 @@ LOCAL_STATIC_LIBRARIES := \
293 libcrypto \ 300 libcrypto \
294 libdiagnose_usb \ 301 libdiagnose_usb \
295 liblog \ 302 liblog \
296 libmdnssd 303 libmdnssd \
297 304
298# Don't use libcutils on Windows. 305# Don't use libcutils on Windows.
299LOCAL_STATIC_LIBRARIES_darwin := libcutils 306LOCAL_STATIC_LIBRARIES_darwin := libcutils
@@ -360,6 +367,7 @@ LOCAL_SANITIZE := $(adb_target_sanitize)
360LOCAL_STRIP_MODULE := keep_symbols 367LOCAL_STRIP_MODULE := keep_symbols
361LOCAL_STATIC_LIBRARIES := \ 368LOCAL_STATIC_LIBRARIES := \
362 libadbd \ 369 libadbd \
370 libavb_user \
363 libbase \ 371 libbase \
364 libbootloader_message \ 372 libbootloader_message \
365 libfs_mgr \ 373 libfs_mgr \
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 577e9b996..808d8ff2e 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -31,6 +31,8 @@
31#include <time.h> 31#include <time.h>
32 32
33#include <chrono> 33#include <chrono>
34#include <condition_variable>
35#include <mutex>
34#include <string> 36#include <string>
35#include <thread> 37#include <thread>
36#include <vector> 38#include <vector>
@@ -48,6 +50,7 @@
48#include "adb_io.h" 50#include "adb_io.h"
49#include "adb_listeners.h" 51#include "adb_listeners.h"
50#include "adb_utils.h" 52#include "adb_utils.h"
53#include "sysdeps/chrono.h"
51#include "transport.h" 54#include "transport.h"
52 55
53#if !ADB_HOST 56#if !ADB_HOST
@@ -59,10 +62,12 @@ using namespace std::chrono_literals;
59 62
60std::string adb_version() { 63std::string adb_version() {
61 // Don't change the format of this --- it's parsed by ddmlib. 64 // Don't change the format of this --- it's parsed by ddmlib.
62 return android::base::StringPrintf("Android Debug Bridge version %d.%d.%d\n" 65 return android::base::StringPrintf(
63 "Revision %s\n", 66 "Android Debug Bridge version %d.%d.%d\n"
64 ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION, 67 "Version %s\n"
65 ADB_REVISION); 68 "Installed as %s\n",
69 ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION, ADB_VERSION,
70 android::base::GetExecutablePath().c_str());
66} 71}
67 72
68void fatal(const char *fmt, ...) { 73void fatal(const char *fmt, ...) {
@@ -251,6 +256,19 @@ void send_connect(atransport* t) {
251 send_packet(cp, t); 256 send_packet(cp, t);
252} 257}
253 258
259#if ADB_HOST
260
261void SendConnectOnHost(atransport* t) {
262 // Send an empty message before A_CNXN message. This is because the data toggle of the ep_out on
263 // host and ep_in on device may not be the same.
264 apacket* p = get_apacket();
265 CHECK(p);
266 send_packet(p, t);
267 send_connect(t);
268}
269
270#endif
271
254// qual_overwrite is used to overwrite a qualifier string. dst is a 272// qual_overwrite is used to overwrite a qualifier string. dst is a
255// pointer to a char pointer. It is assumed that if *dst is non-NULL, it 273// pointer to a char pointer. It is assumed that if *dst is non-NULL, it
256// was malloc'ed and needs to freed. *dst will be set to a dup of src. 274// was malloc'ed and needs to freed. *dst will be set to a dup of src.
@@ -297,29 +315,25 @@ void parse_banner(const std::string& banner, atransport* t) {
297 const std::string& type = pieces[0]; 315 const std::string& type = pieces[0];
298 if (type == "bootloader") { 316 if (type == "bootloader") {
299 D("setting connection_state to kCsBootloader"); 317 D("setting connection_state to kCsBootloader");
300 t->connection_state = kCsBootloader; 318 t->SetConnectionState(kCsBootloader);
301 update_transports();
302 } else if (type == "device") { 319 } else if (type == "device") {
303 D("setting connection_state to kCsDevice"); 320 D("setting connection_state to kCsDevice");
304 t->connection_state = kCsDevice; 321 t->SetConnectionState(kCsDevice);
305 update_transports();
306 } else if (type == "recovery") { 322 } else if (type == "recovery") {
307 D("setting connection_state to kCsRecovery"); 323 D("setting connection_state to kCsRecovery");
308 t->connection_state = kCsRecovery; 324 t->SetConnectionState(kCsRecovery);
309 update_transports();
310 } else if (type == "sideload") { 325 } else if (type == "sideload") {
311 D("setting connection_state to kCsSideload"); 326 D("setting connection_state to kCsSideload");
312 t->connection_state = kCsSideload; 327 t->SetConnectionState(kCsSideload);
313 update_transports();
314 } else { 328 } else {
315 D("setting connection_state to kCsHost"); 329 D("setting connection_state to kCsHost");
316 t->connection_state = kCsHost; 330 t->SetConnectionState(kCsHost);
317 } 331 }
318} 332}
319 333
320static void handle_new_connection(atransport* t, apacket* p) { 334static void handle_new_connection(atransport* t, apacket* p) {
321 if (t->connection_state != kCsOffline) { 335 if (t->GetConnectionState() != kCsOffline) {
322 t->connection_state = kCsOffline; 336 t->SetConnectionState(kCsOffline);
323 handle_offline(t); 337 handle_offline(t);
324 } 338 }
325 339
@@ -338,6 +352,8 @@ static void handle_new_connection(atransport* t, apacket* p) {
338 send_auth_request(t); 352 send_auth_request(t);
339 } 353 }
340#endif 354#endif
355
356 update_transports();
341} 357}
342 358
343void handle_packet(apacket *p, atransport *t) 359void handle_packet(apacket *p, atransport *t)
@@ -353,10 +369,10 @@ void handle_packet(apacket *p, atransport *t)
353 if (p->msg.arg0){ 369 if (p->msg.arg0){
354 send_packet(p, t); 370 send_packet(p, t);
355#if ADB_HOST 371#if ADB_HOST
356 send_connect(t); 372 SendConnectOnHost(t);
357#endif 373#endif
358 } else { 374 } else {
359 t->connection_state = kCsOffline; 375 t->SetConnectionState(kCsOffline);
360 handle_offline(t); 376 handle_offline(t);
361 send_packet(p, t); 377 send_packet(p, t);
362 } 378 }
@@ -370,7 +386,9 @@ void handle_packet(apacket *p, atransport *t)
370 switch (p->msg.arg0) { 386 switch (p->msg.arg0) {
371#if ADB_HOST 387#if ADB_HOST
372 case ADB_AUTH_TOKEN: 388 case ADB_AUTH_TOKEN:
373 t->connection_state = kCsUnauthorized; 389 if (t->GetConnectionState() == kCsOffline) {
390 t->SetConnectionState(kCsUnauthorized);
391 }
374 send_auth_response(p->data, p->msg.data_length, t); 392 send_auth_response(p->data, p->msg.data_length, t);
375 break; 393 break;
376#else 394#else
@@ -389,7 +407,7 @@ void handle_packet(apacket *p, atransport *t)
389 break; 407 break;
390#endif 408#endif
391 default: 409 default:
392 t->connection_state = kCsOffline; 410 t->SetConnectionState(kCsOffline);
393 handle_offline(t); 411 handle_offline(t);
394 break; 412 break;
395 } 413 }
@@ -505,8 +523,8 @@ static bool _make_handle_noninheritable(HANDLE h) {
505 if (!_try_make_handle_noninheritable(h)) { 523 if (!_try_make_handle_noninheritable(h)) {
506 // Show the handle value to give us a clue in case we have problems 524 // Show the handle value to give us a clue in case we have problems
507 // with pseudo-handle values. 525 // with pseudo-handle values.
508 fprintf(stderr, "Cannot make handle 0x%p non-inheritable: %s\n", 526 fprintf(stderr, "adb: cannot make handle 0x%p non-inheritable: %s\n", h,
509 h, android::base::SystemErrorCodeToString(GetLastError()).c_str()); 527 android::base::SystemErrorCodeToString(GetLastError()).c_str());
510 return false; 528 return false;
511 } 529 }
512 530
@@ -521,7 +539,7 @@ static bool _create_anonymous_pipe(unique_handle* pipe_read_out,
521 HANDLE pipe_read_raw = NULL; 539 HANDLE pipe_read_raw = NULL;
522 HANDLE pipe_write_raw = NULL; 540 HANDLE pipe_write_raw = NULL;
523 if (!CreatePipe(&pipe_read_raw, &pipe_write_raw, sa, 0)) { 541 if (!CreatePipe(&pipe_read_raw, &pipe_write_raw, sa, 0)) {
524 fprintf(stderr, "Cannot create pipe: %s\n", 542 fprintf(stderr, "adb: CreatePipe failed: %s\n",
525 android::base::SystemErrorCodeToString(GetLastError()).c_str()); 543 android::base::SystemErrorCodeToString(GetLastError()).c_str());
526 return false; 544 return false;
527 } 545 }
@@ -552,7 +570,8 @@ static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
552 std::unique_ptr<FILE, decltype(&fclose)> stream(nullptr, fclose); 570 std::unique_ptr<FILE, decltype(&fclose)> stream(nullptr, fclose);
553 571
554 if (original_fd == -1) { 572 if (original_fd == -1) {
555 fprintf(stderr, "Failed to get file descriptor for %s: %s\n", output_name, strerror(errno)); 573 fprintf(stderr, "adb: failed to get file descriptor for %s: %s\n", output_name,
574 strerror(errno));
556 return EXIT_FAILURE; 575 return EXIT_FAILURE;
557 } 576 }
558 577
@@ -564,7 +583,7 @@ static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
564 // call this function if subprocesses may be started concurrently. 583 // call this function if subprocesses may be started concurrently.
565 const int fd = dup(original_fd); 584 const int fd = dup(original_fd);
566 if (fd == -1) { 585 if (fd == -1) {
567 fprintf(stderr, "Failed to duplicate file descriptor for %s: %s\n", output_name, 586 fprintf(stderr, "adb: failed to duplicate file descriptor for %s: %s\n", output_name,
568 strerror(errno)); 587 strerror(errno));
569 return EXIT_FAILURE; 588 return EXIT_FAILURE;
570 } 589 }
@@ -572,7 +591,7 @@ static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
572 // Note that although we call fdopen() below with a binary flag, it may not adhere to that 591 // Note that although we call fdopen() below with a binary flag, it may not adhere to that
573 // flag, so we have to set the mode manually. 592 // flag, so we have to set the mode manually.
574 if (_setmode(fd, _O_BINARY) == -1) { 593 if (_setmode(fd, _O_BINARY) == -1) {
575 fprintf(stderr, "Failed to set binary mode for duplicate of %s: %s\n", output_name, 594 fprintf(stderr, "adb: failed to set binary mode for duplicate of %s: %s\n", output_name,
576 strerror(errno)); 595 strerror(errno));
577 unix_close(fd); 596 unix_close(fd);
578 return EXIT_FAILURE; 597 return EXIT_FAILURE;
@@ -580,7 +599,7 @@ static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
580 599
581 stream.reset(fdopen(fd, "wb")); 600 stream.reset(fdopen(fd, "wb"));
582 if (stream.get() == nullptr) { 601 if (stream.get() == nullptr) {
583 fprintf(stderr, "Failed to open duplicate stream for %s: %s\n", output_name, 602 fprintf(stderr, "adb: failed to open duplicate stream for %s: %s\n", output_name,
584 strerror(errno)); 603 strerror(errno));
585 unix_close(fd); 604 unix_close(fd);
586 return EXIT_FAILURE; 605 return EXIT_FAILURE;
@@ -589,7 +608,7 @@ static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
589 // Unbuffer the stream because it will be buffered by default and we want subprocess output 608 // Unbuffer the stream because it will be buffered by default and we want subprocess output
590 // to be shown immediately. 609 // to be shown immediately.
591 if (setvbuf(stream.get(), NULL, _IONBF, 0) == -1) { 610 if (setvbuf(stream.get(), NULL, _IONBF, 0) == -1) {
592 fprintf(stderr, "Failed to unbuffer %s: %s\n", output_name, strerror(errno)); 611 fprintf(stderr, "adb: failed to unbuffer %s: %s\n", output_name, strerror(errno));
593 return EXIT_FAILURE; 612 return EXIT_FAILURE;
594 } 613 }
595 614
@@ -606,7 +625,7 @@ static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
606 if (err == ERROR_BROKEN_PIPE) { 625 if (err == ERROR_BROKEN_PIPE) {
607 return EXIT_SUCCESS; 626 return EXIT_SUCCESS;
608 } else { 627 } else {
609 fprintf(stderr, "Failed to read from %s: %s\n", output_name, 628 fprintf(stderr, "adb: failed to read from %s: %s\n", output_name,
610 android::base::SystemErrorCodeToString(err).c_str()); 629 android::base::SystemErrorCodeToString(err).c_str());
611 return EXIT_FAILURE; 630 return EXIT_FAILURE;
612 } 631 }
@@ -617,8 +636,8 @@ static unsigned _redirect_pipe_thread(HANDLE h, DWORD nStdHandle) {
617 // fwrite() actually calls adb_fwrite() which can write UTF-8 to the console. 636 // fwrite() actually calls adb_fwrite() which can write UTF-8 to the console.
618 const size_t bytes_written = fwrite(buf, 1, bytes_read, stream.get()); 637 const size_t bytes_written = fwrite(buf, 1, bytes_read, stream.get());
619 if (bytes_written != bytes_read) { 638 if (bytes_written != bytes_read) {
620 fprintf(stderr, "Only wrote %zu of %lu bytes to %s\n", bytes_written, bytes_read, 639 fprintf(stderr, "adb: error: only wrote %zu of %lu bytes to %s\n", bytes_written,
621 output_name); 640 bytes_read, output_name);
622 return EXIT_FAILURE; 641 return EXIT_FAILURE;
623 } 642 }
624 } 643 }
@@ -661,7 +680,7 @@ int launch_server(const std::string& socket_spec) {
661 FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 680 FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
662 FILE_ATTRIBUTE_NORMAL, NULL)); 681 FILE_ATTRIBUTE_NORMAL, NULL));
663 if (nul_read.get() == INVALID_HANDLE_VALUE) { 682 if (nul_read.get() == INVALID_HANDLE_VALUE) {
664 fprintf(stderr, "Cannot open 'nul': %s\n", 683 fprintf(stderr, "adb: CreateFileW 'nul' failed: %s\n",
665 android::base::SystemErrorCodeToString(GetLastError()).c_str()); 684 android::base::SystemErrorCodeToString(GetLastError()).c_str());
666 return -1; 685 return -1;
667 } 686 }
@@ -723,8 +742,7 @@ int launch_server(const std::string& socket_spec) {
723 // If this fires, either handle values are larger than 32-bits or else 742 // If this fires, either handle values are larger than 32-bits or else
724 // there is a bug in our casting. 743 // there is a bug in our casting.
725 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx 744 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
726 fprintf(stderr, "Cannot fit pipe handle value into 32-bits: 0x%p\n", 745 fprintf(stderr, "adb: cannot fit pipe handle value into 32-bits: 0x%p\n", ack_write.get());
727 ack_write.get());
728 return -1; 746 return -1;
729 } 747 }
730 748
@@ -734,7 +752,7 @@ int launch_server(const std::string& socket_spec) {
734 arraysize(program_path)); 752 arraysize(program_path));
735 if ((module_result >= arraysize(program_path)) || (module_result == 0)) { 753 if ((module_result >= arraysize(program_path)) || (module_result == 0)) {
736 // String truncation or some other error. 754 // String truncation or some other error.
737 fprintf(stderr, "Cannot get executable path: %s\n", 755 fprintf(stderr, "adb: cannot get executable path: %s\n",
738 android::base::SystemErrorCodeToString(GetLastError()).c_str()); 756 android::base::SystemErrorCodeToString(GetLastError()).c_str());
739 return -1; 757 return -1;
740 } 758 }
@@ -759,7 +777,7 @@ int launch_server(const std::string& socket_spec) {
759 NULL, /* use parent's starting directory */ 777 NULL, /* use parent's starting directory */
760 &startup, /* startup info, i.e. std handles */ 778 &startup, /* startup info, i.e. std handles */
761 &pinfo )) { 779 &pinfo )) {
762 fprintf(stderr, "Cannot create process: %s\n", 780 fprintf(stderr, "adb: CreateProcessW failed: %s\n",
763 android::base::SystemErrorCodeToString(GetLastError()).c_str()); 781 android::base::SystemErrorCodeToString(GetLastError()).c_str());
764 return -1; 782 return -1;
765 } 783 }
@@ -789,7 +807,7 @@ int launch_server(const std::string& socket_spec) {
789 _beginthreadex(NULL, 0, _redirect_stdout_thread, stdout_read.get(), 807 _beginthreadex(NULL, 0, _redirect_stdout_thread, stdout_read.get(),
790 0, NULL))); 808 0, NULL)));
791 if (stdout_thread.get() == nullptr) { 809 if (stdout_thread.get() == nullptr) {
792 fprintf(stderr, "Cannot create thread: %s\n", strerror(errno)); 810 fprintf(stderr, "adb: cannot create thread: %s\n", strerror(errno));
793 return -1; 811 return -1;
794 } 812 }
795 stdout_read.release(); // Transfer ownership to new thread 813 stdout_read.release(); // Transfer ownership to new thread
@@ -798,7 +816,7 @@ int launch_server(const std::string& socket_spec) {
798 _beginthreadex(NULL, 0, _redirect_stderr_thread, stderr_read.get(), 816 _beginthreadex(NULL, 0, _redirect_stderr_thread, stderr_read.get(),
799 0, NULL))); 817 0, NULL)));
800 if (stderr_thread.get() == nullptr) { 818 if (stderr_thread.get() == nullptr) {
801 fprintf(stderr, "Cannot create thread: %s\n", strerror(errno)); 819 fprintf(stderr, "adb: cannot create thread: %s\n", strerror(errno));
802 return -1; 820 return -1;
803 } 821 }
804 stderr_read.release(); // Transfer ownership to new thread 822 stderr_read.release(); // Transfer ownership to new thread
@@ -843,22 +861,20 @@ int launch_server(const std::string& socket_spec) {
843 if (wait_result == WAIT_TIMEOUT) { 861 if (wait_result == WAIT_TIMEOUT) {
844 // Threads did not finish after waiting a little while. Perhaps the 862 // Threads did not finish after waiting a little while. Perhaps the
845 // server didn't close pipes, or it is hung. 863 // server didn't close pipes, or it is hung.
846 fprintf(stderr, "Timed-out waiting for threads to finish reading from " 864 fprintf(stderr, "adb: timed out waiting for threads to finish reading from ADB server\n");
847 "ADB Server\n");
848 // Process handles are signaled when the process exits, so if we wait 865 // Process handles are signaled when the process exits, so if we wait
849 // on the handle for 0 seconds and it returns 'timeout', that means that 866 // on the handle for 0 seconds and it returns 'timeout', that means that
850 // the process is still running. 867 // the process is still running.
851 if (WaitForSingleObject(process_handle.get(), 0) == WAIT_TIMEOUT) { 868 if (WaitForSingleObject(process_handle.get(), 0) == WAIT_TIMEOUT) {
852 // We could TerminateProcess(), but that seems somewhat presumptive. 869 // We could TerminateProcess(), but that seems somewhat presumptive.
853 fprintf(stderr, "ADB Server is running: process id %lu\n", 870 fprintf(stderr, "adb: server is running with process id %lu\n", pinfo.dwProcessId);
854 pinfo.dwProcessId);
855 } 871 }
856 return -1; 872 return -1;
857 } 873 }
858 874
859 if (wait_result != WAIT_OBJECT_0) { 875 if (wait_result != WAIT_OBJECT_0) {
860 fprintf(stderr, "Unexpected result waiting for threads: %lu: %s\n", 876 fprintf(stderr, "adb: unexpected result waiting for threads: %lu: %s\n", wait_result,
861 wait_result, android::base::SystemErrorCodeToString(GetLastError()).c_str()); 877 android::base::SystemErrorCodeToString(GetLastError()).c_str());
862 return -1; 878 return -1;
863 } 879 }
864 880
@@ -892,7 +908,7 @@ int launch_server(const std::string& socket_spec) {
892 int result = execl(path.c_str(), "adb", "-L", socket_spec.c_str(), "fork-server", "server", 908 int result = execl(path.c_str(), "adb", "-L", socket_spec.c_str(), "fork-server", "server",
893 "--reply-fd", reply_fd, NULL); 909 "--reply-fd", reply_fd, NULL);
894 // this should not return 910 // this should not return
895 fprintf(stderr, "OOPS! execl returned %d, errno: %d\n", result, errno); 911 fprintf(stderr, "adb: execl returned %d: %s\n", result, strerror(errno));
896 } else { 912 } else {
897 // parent side of the fork 913 // parent side of the fork
898 914
@@ -1032,26 +1048,21 @@ static int SendOkay(int fd, const std::string& s) {
1032 SendProtocolString(fd, s); 1048 SendProtocolString(fd, s);
1033 return 0; 1049 return 0;
1034} 1050}
1035#endif
1036 1051
1037int handle_host_request(const char* service, TransportType type, 1052int handle_host_request(const char* service, TransportType type,
1038 const char* serial, int reply_fd, asocket* s) { 1053 const char* serial, int reply_fd, asocket* s) {
1039 if (strcmp(service, "kill") == 0) { 1054 if (strcmp(service, "kill") == 0) {
1040 fprintf(stderr, "adb server killed by remote request\n"); 1055 fprintf(stderr, "adb server killed by remote request\n");
1041 fflush(stdout); 1056 fflush(stdout);
1042 SendOkay(reply_fd);
1043 1057
1044 // On Windows, if the process exits with open sockets that 1058 // Send a reply even though we don't read it anymore, so that old versions
1045 // shutdown(SD_SEND) has not been called on, TCP RST segments will be 1059 // of adb that do read it don't spew error messages.
1046 // sent to the peers which will cause their next recv() to error-out 1060 SendOkay(reply_fd);
1047 // with WSAECONNRESET. In the case of this code, that means the client
1048 // may not read the OKAY sent above.
1049 adb_shutdown(reply_fd);
1050 1061
1062 // Rely on process exit to close the socket for us.
1051 android::base::quick_exit(0); 1063 android::base::quick_exit(0);
1052 } 1064 }
1053 1065
1054#if ADB_HOST
1055 // "transport:" is used for switching transport with a specified serial number 1066 // "transport:" is used for switching transport with a specified serial number
1056 // "transport-usb:" is used for switching transport to the only USB transport 1067 // "transport-usb:" is used for switching transport to the only USB transport
1057 // "transport-local:" is used for switching transport to the only local transport 1068 // "transport-local:" is used for switching transport to the only local transport
@@ -1096,16 +1107,10 @@ int handle_host_request(const char* service, TransportType type,
1096 if (!strcmp(service, "reconnect-offline")) { 1107 if (!strcmp(service, "reconnect-offline")) {
1097 std::string response; 1108 std::string response;
1098 close_usb_devices([&response](const atransport* transport) { 1109 close_usb_devices([&response](const atransport* transport) {
1099 switch (transport->connection_state) { 1110 switch (transport->GetConnectionState()) {
1100 case kCsOffline: 1111 case kCsOffline:
1101 case kCsUnauthorized: 1112 case kCsUnauthorized:
1102 response += "reconnecting "; 1113 response += "reconnecting " + transport->serial_name() + "\n";
1103 if (transport->serial) {
1104 response += transport->serial;
1105 } else {
1106 response += "<unknown>";
1107 }
1108 response += "\n";
1109 return true; 1114 return true;
1110 default: 1115 default:
1111 return false; 1116 return false;
@@ -1129,7 +1134,6 @@ int handle_host_request(const char* service, TransportType type,
1129 return 0; 1134 return 0;
1130 } 1135 }
1131 1136
1132#if ADB_HOST
1133 if (!strcmp(service, "host-features")) { 1137 if (!strcmp(service, "host-features")) {
1134 FeatureSet features = supported_features(); 1138 FeatureSet features = supported_features();
1135 // Abuse features to report libusb status. 1139 // Abuse features to report libusb status.
@@ -1139,7 +1143,6 @@ int handle_host_request(const char* service, TransportType type,
1139 SendOkay(reply_fd, FeatureSetToString(features)); 1143 SendOkay(reply_fd, FeatureSetToString(features));
1140 return 0; 1144 return 0;
1141 } 1145 }
1142#endif
1143 1146
1144 // remove TCP transport 1147 // remove TCP transport
1145 if (!strncmp(service, "disconnect:", 11)) { 1148 if (!strncmp(service, "disconnect:", 11)) {
@@ -1209,15 +1212,59 @@ int handle_host_request(const char* service, TransportType type,
1209 } 1212 }
1210 1213
1211 if (!strcmp(service, "reconnect")) { 1214 if (!strcmp(service, "reconnect")) {
1212 if (s->transport != nullptr) { 1215 std::string response;
1213 kick_transport(s->transport); 1216 atransport* t = acquire_one_transport(type, serial, nullptr, &response, true);
1217 if (t != nullptr) {
1218 kick_transport(t);
1219 response =
1220 "reconnecting " + t->serial_name() + " [" + t->connection_state_name() + "]\n";
1214 } 1221 }
1215 return SendOkay(reply_fd, "done"); 1222 return SendOkay(reply_fd, response);
1216 } 1223 }
1217#endif // ADB_HOST
1218 1224
1219 int ret = handle_forward_request(service, type, serial, reply_fd); 1225 int ret = handle_forward_request(service, type, serial, reply_fd);
1220 if (ret >= 0) 1226 if (ret >= 0)
1221 return ret - 1; 1227 return ret - 1;
1222 return -1; 1228 return -1;
1223} 1229}
1230
1231static auto& init_mutex = *new std::mutex();
1232static auto& init_cv = *new std::condition_variable();
1233static bool device_scan_complete = false;
1234static bool transports_ready = false;
1235
1236void update_transport_status() {
1237 bool result = iterate_transports([](const atransport* t) {
1238 if (t->type == kTransportUsb && t->online != 1) {
1239 return false;
1240 }
1241 return true;
1242 });
1243
1244 bool ready;
1245 {
1246 std::lock_guard<std::mutex> lock(init_mutex);
1247 transports_ready = result;
1248 ready = transports_ready && device_scan_complete;
1249 }
1250
1251 if (ready) {
1252 init_cv.notify_all();
1253 }
1254}
1255
1256void adb_notify_device_scan_complete() {
1257 {
1258 std::lock_guard<std::mutex> lock(init_mutex);
1259 device_scan_complete = true;
1260 }
1261
1262 update_transport_status();
1263}
1264
1265void adb_wait_for_device_initialization() {
1266 std::unique_lock<std::mutex> lock(init_mutex);
1267 init_cv.wait_for(lock, 3s, []() { return device_scan_complete && transports_ready; });
1268}
1269
1270#endif // ADB_HOST
diff --git a/adb/adb.h b/adb/adb.h
index aea5fb86b..d6b2b818f 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -139,7 +139,7 @@ int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply
139int get_available_local_transport_index(); 139int get_available_local_transport_index();
140#endif 140#endif
141int init_socket_transport(atransport *t, int s, int port, int local); 141int init_socket_transport(atransport *t, int s, int port, int local);
142void init_usb_transport(atransport *t, usb_handle *usb, ConnectionState state); 142void init_usb_transport(atransport* t, usb_handle* usb);
143 143
144std::string getEmulatorSerialString(int console_port); 144std::string getEmulatorSerialString(int console_port);
145#if ADB_HOST 145#if ADB_HOST
@@ -222,7 +222,24 @@ void handle_online(atransport *t);
222void handle_offline(atransport *t); 222void handle_offline(atransport *t);
223 223
224void send_connect(atransport *t); 224void send_connect(atransport *t);
225#if ADB_HOST
226void SendConnectOnHost(atransport* t);
227#endif
225 228
226void parse_banner(const std::string&, atransport* t); 229void parse_banner(const std::string&, atransport* t);
227 230
231// On startup, the adb server needs to wait until all of the connected devices are ready.
232// To do this, we need to know when the scan has identified all of the potential new transports, and
233// when each transport becomes ready.
234// TODO: Do this for mDNS as well, instead of just USB?
235
236// We've found all of the transports we potentially care about.
237void adb_notify_device_scan_complete();
238
239// One or more transports have changed status, check to see if we're ready.
240void update_transport_status();
241
242// Wait until device scan has completed and every transport is ready, or a timeout elapses.
243void adb_wait_for_device_initialization();
244
228#endif 245#endif
diff --git a/adb/adb_client.cpp b/adb/adb_client.cpp
index ef52189f2..f5d0f02df 100644
--- a/adb/adb_client.cpp
+++ b/adb/adb_client.cpp
@@ -28,12 +28,15 @@
28#include <sys/stat.h> 28#include <sys/stat.h>
29#include <sys/types.h> 29#include <sys/types.h>
30 30
31#include <condition_variable>
32#include <mutex>
31#include <string> 33#include <string>
32#include <thread> 34#include <thread>
33#include <vector> 35#include <vector>
34 36
35#include <android-base/stringprintf.h> 37#include <android-base/stringprintf.h>
36#include <android-base/strings.h> 38#include <android-base/strings.h>
39#include <android-base/thread_annotations.h>
37#include <cutils/sockets.h> 40#include <cutils/sockets.h>
38 41
39#include "adb_io.h" 42#include "adb_io.h"
@@ -120,7 +123,7 @@ bool adb_status(int fd, std::string* error) {
120 return false; 123 return false;
121} 124}
122 125
123int _adb_connect(const std::string& service, std::string* error) { 126static int _adb_connect(const std::string& service, std::string* error) {
124 D("_adb_connect: %s", service.c_str()); 127 D("_adb_connect: %s", service.c_str());
125 if (service.empty() || service.size() > MAX_PAYLOAD_V1) { 128 if (service.empty() || service.size() > MAX_PAYLOAD_V1) {
126 *error = android::base::StringPrintf("bad service name length (%zd)", 129 *error = android::base::StringPrintf("bad service name length (%zd)",
@@ -136,8 +139,7 @@ int _adb_connect(const std::string& service, std::string* error) {
136 return -2; 139 return -2;
137 } 140 }
138 141
139 if ((memcmp(&service[0],"host",4) != 0 || service == "host:reconnect") && 142 if (memcmp(&service[0], "host", 4) != 0 && switch_socket_transport(fd, error)) {
140 switch_socket_transport(fd, error)) {
141 return -1; 143 return -1;
142 } 144 }
143 145
@@ -147,42 +149,58 @@ int _adb_connect(const std::string& service, std::string* error) {
147 return -1; 149 return -1;
148 } 150 }
149 151
150 if (service != "reconnect") { 152 if (!adb_status(fd, error)) {
151 if (!adb_status(fd, error)) { 153 adb_close(fd);
152 adb_close(fd); 154 return -1;
153 return -1;
154 }
155 } 155 }
156 156
157 D("_adb_connect: return fd %d", fd); 157 D("_adb_connect: return fd %d", fd);
158 return fd; 158 return fd;
159} 159}
160 160
161bool adb_kill_server() {
162 D("adb_kill_server");
163 std::string reason;
164 int fd = socket_spec_connect(__adb_server_socket_spec, &reason);
165 if (fd < 0) {
166 fprintf(stderr, "cannot connect to daemon at %s: %s\n", __adb_server_socket_spec,
167 reason.c_str());
168 return true;
169 }
170
171 if (!SendProtocolString(fd, "host:kill")) {
172 fprintf(stderr, "error: write failure during connection: %s\n", strerror(errno));
173 return false;
174 }
175
176 ReadOrderlyShutdown(fd);
177 return true;
178}
179
161int adb_connect(const std::string& service, std::string* error) { 180int adb_connect(const std::string& service, std::string* error) {
162 // first query the adb server's version 181 // first query the adb server's version
163 int fd = _adb_connect("host:version", error); 182 int fd = _adb_connect("host:version", error);
164 183
165 D("adb_connect: service %s", service.c_str()); 184 D("adb_connect: service %s", service.c_str());
166 if (fd == -2 && !is_local_socket_spec(__adb_server_socket_spec)) { 185 if (fd == -2 && !is_local_socket_spec(__adb_server_socket_spec)) {
167 fprintf(stderr,"** Cannot start server on remote host\n"); 186 fprintf(stderr, "* cannot start server on remote host\n");
168 // error is the original network connection error 187 // error is the original network connection error
169 return fd; 188 return fd;
170 } else if (fd == -2) { 189 } else if (fd == -2) {
171 fprintf(stdout, "* daemon not running. starting it now at %s *\n", __adb_server_socket_spec); 190 fprintf(stderr, "* daemon not running; starting now at %s\n", __adb_server_socket_spec);
172 start_server: 191 start_server:
173 if (launch_server(__adb_server_socket_spec)) { 192 if (launch_server(__adb_server_socket_spec)) {
174 fprintf(stderr,"* failed to start daemon *\n"); 193 fprintf(stderr, "* failed to start daemon\n");
175 // launch_server() has already printed detailed error info, so just 194 // launch_server() has already printed detailed error info, so just
176 // return a generic error string about the overall adb_connect() 195 // return a generic error string about the overall adb_connect()
177 // that the caller requested. 196 // that the caller requested.
178 *error = "cannot connect to daemon"; 197 *error = "cannot connect to daemon";
179 return -1; 198 return -1;
180 } else { 199 } else {
181 fprintf(stdout,"* daemon started successfully *\n"); 200 fprintf(stderr, "* daemon started successfully\n");
182 } 201 }
183 // Give the server some time to start properly and detect devices. 202 // The server will wait until it detects all of its connected devices before acking.
184 std::this_thread::sleep_for(3s); 203 // Fall through to _adb_connect.
185 // fall through to _adb_connect
186 } else { 204 } else {
187 // If a server is already running, check its version matches. 205 // If a server is already running, check its version matches.
188 int version = ADB_SERVER_VERSION - 1; 206 int version = ADB_SERVER_VERSION - 1;
@@ -213,20 +231,9 @@ int adb_connect(const std::string& service, std::string* error) {
213 } 231 }
214 232
215 if (version != ADB_SERVER_VERSION) { 233 if (version != ADB_SERVER_VERSION) {
216 printf("adb server version (%d) doesn't match this client (%d); killing...\n", 234 fprintf(stderr, "adb server version (%d) doesn't match this client (%d); killing...\n",
217 version, ADB_SERVER_VERSION); 235 version, ADB_SERVER_VERSION);
218 fd = _adb_connect("host:kill", error); 236 adb_kill_server();
219 if (fd >= 0) {
220 ReadOrderlyShutdown(fd);
221 adb_close(fd);
222 } else {
223 // If we couldn't connect to the server or had some other error,
224 // report it, but still try to start the server.
225 fprintf(stderr, "error: %s\n", error->c_str());
226 }
227
228 /* XXX can we better detect its death? */
229 std::this_thread::sleep_for(2s);
230 goto start_server; 237 goto start_server;
231 } 238 }
232 } 239 }
@@ -240,7 +247,7 @@ int adb_connect(const std::string& service, std::string* error) {
240 if (fd == -1) { 247 if (fd == -1) {
241 D("_adb_connect error: %s", error->c_str()); 248 D("_adb_connect error: %s", error->c_str());
242 } else if(fd == -2) { 249 } else if(fd == -2) {
243 fprintf(stderr,"** daemon still not running\n"); 250 fprintf(stderr, "* daemon still not running\n");
244 } 251 }
245 D("adb_connect: return fd %d", fd); 252 D("adb_connect: return fd %d", fd);
246 253
diff --git a/adb/adb_client.h b/adb/adb_client.h
index d07c1e96b..fabec0050 100644
--- a/adb/adb_client.h
+++ b/adb/adb_client.h
@@ -26,7 +26,9 @@
26// Connect to adb, connect to the named service, and return a valid fd for 26// Connect to adb, connect to the named service, and return a valid fd for
27// interacting with that service upon success or a negative number on failure. 27// interacting with that service upon success or a negative number on failure.
28int adb_connect(const std::string& service, std::string* _Nonnull error); 28int adb_connect(const std::string& service, std::string* _Nonnull error);
29int _adb_connect(const std::string& service, std::string* _Nonnull error); 29
30// Kill the currently running adb server, if it exists.
31bool adb_kill_server();
30 32
31// Connect to adb, connect to the named service, returns true if the connection 33// Connect to adb, connect to the named service, returns true if the connection
32// succeeded AND the service returned OKAY. Outputs any returned error otherwise. 34// succeeded AND the service returned OKAY. Outputs any returned error otherwise.
diff --git a/adb/adb_listeners.cpp b/adb/adb_listeners.cpp
index 18b14923c..30cb29b88 100644
--- a/adb/adb_listeners.cpp
+++ b/adb/adb_listeners.cpp
@@ -19,8 +19,12 @@
19#include <stdio.h> 19#include <stdio.h>
20#include <stdlib.h> 20#include <stdlib.h>
21 21
22#include <algorithm>
23#include <list>
24
22#include <android-base/stringprintf.h> 25#include <android-base/stringprintf.h>
23#include <android-base/strings.h> 26#include <android-base/strings.h>
27#include <android-base/thread_annotations.h>
24#include <cutils/sockets.h> 28#include <cutils/sockets.h>
25 29
26#include "socket_spec.h" 30#include "socket_spec.h"
@@ -64,8 +68,9 @@ alistener::~alistener() {
64 68
65// listener_list retains ownership of all created alistener objects. Removing an alistener from 69// listener_list retains ownership of all created alistener objects. Removing an alistener from
66// this list will cause it to be deleted. 70// this list will cause it to be deleted.
71static auto& listener_list_mutex = *new std::mutex();
67typedef std::list<std::unique_ptr<alistener>> ListenerList; 72typedef std::list<std::unique_ptr<alistener>> ListenerList;
68static ListenerList& listener_list = *new ListenerList(); 73static ListenerList& listener_list GUARDED_BY(listener_list_mutex) = *new ListenerList();
69 74
70static void ss_listener_event_func(int _fd, unsigned ev, void *_l) { 75static void ss_listener_event_func(int _fd, unsigned ev, void *_l) {
71 if (ev & FDE_READ) { 76 if (ev & FDE_READ) {
@@ -108,7 +113,8 @@ static void listener_event_func(int _fd, unsigned ev, void* _l)
108} 113}
109 114
110// Called as a transport disconnect function. |arg| is the raw alistener*. 115// Called as a transport disconnect function. |arg| is the raw alistener*.
111static void listener_disconnect(void* arg, atransport*) { 116static void listener_disconnect(void* arg, atransport*) EXCLUDES(listener_list_mutex) {
117 std::lock_guard<std::mutex> lock(listener_list_mutex);
112 for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) { 118 for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) {
113 if (iter->get() == arg) { 119 if (iter->get() == arg) {
114 (*iter)->transport = nullptr; 120 (*iter)->transport = nullptr;
@@ -119,7 +125,8 @@ static void listener_disconnect(void* arg, atransport*) {
119} 125}
120 126
121// Write the list of current listeners (network redirections) into a string. 127// Write the list of current listeners (network redirections) into a string.
122std::string format_listeners() { 128std::string format_listeners() EXCLUDES(listener_list_mutex) {
129 std::lock_guard<std::mutex> lock(listener_list_mutex);
123 std::string result; 130 std::string result;
124 for (auto& l : listener_list) { 131 for (auto& l : listener_list) {
125 // Ignore special listeners like those for *smartsocket* 132 // Ignore special listeners like those for *smartsocket*
@@ -135,7 +142,9 @@ std::string format_listeners() {
135 return result; 142 return result;
136} 143}
137 144
138InstallStatus remove_listener(const char* local_name, atransport* transport) { 145InstallStatus remove_listener(const char* local_name, atransport* transport)
146 EXCLUDES(listener_list_mutex) {
147 std::lock_guard<std::mutex> lock(listener_list_mutex);
139 for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) { 148 for (auto iter = listener_list.begin(); iter != listener_list.end(); ++iter) {
140 if (local_name == (*iter)->local_name) { 149 if (local_name == (*iter)->local_name) {
141 listener_list.erase(iter); 150 listener_list.erase(iter);
@@ -145,7 +154,8 @@ InstallStatus remove_listener(const char* local_name, atransport* transport) {
145 return INSTALL_STATUS_LISTENER_NOT_FOUND; 154 return INSTALL_STATUS_LISTENER_NOT_FOUND;
146} 155}
147 156
148void remove_all_listeners() { 157void remove_all_listeners() EXCLUDES(listener_list_mutex) {
158 std::lock_guard<std::mutex> lock(listener_list_mutex);
149 auto iter = listener_list.begin(); 159 auto iter = listener_list.begin();
150 while (iter != listener_list.end()) { 160 while (iter != listener_list.end()) {
151 // Never remove smart sockets. 161 // Never remove smart sockets.
@@ -157,9 +167,18 @@ void remove_all_listeners() {
157 } 167 }
158} 168}
159 169
170void close_smartsockets() EXCLUDES(listener_list_mutex) {
171 std::lock_guard<std::mutex> lock(listener_list_mutex);
172 auto pred = [](const std::unique_ptr<alistener>& listener) {
173 return listener->local_name == "*smartsocket*";
174 };
175 listener_list.erase(std::remove_if(listener_list.begin(), listener_list.end(), pred));
176}
177
160InstallStatus install_listener(const std::string& local_name, const char* connect_to, 178InstallStatus install_listener(const std::string& local_name, const char* connect_to,
161 atransport* transport, int no_rebind, int* resolved_tcp_port, 179 atransport* transport, int no_rebind, int* resolved_tcp_port,
162 std::string* error) { 180 std::string* error) EXCLUDES(listener_list_mutex) {
181 std::lock_guard<std::mutex> lock(listener_list_mutex);
163 for (auto& l : listener_list) { 182 for (auto& l : listener_list) {
164 if (local_name == l->local_name) { 183 if (local_name == l->local_name) {
165 // Can't repurpose a smartsocket. 184 // Can't repurpose a smartsocket.
@@ -212,7 +231,7 @@ InstallStatus install_listener(const std::string& local_name, const char* connec
212 231
213 if (transport) { 232 if (transport) {
214 listener->disconnect.opaque = listener.get(); 233 listener->disconnect.opaque = listener.get();
215 listener->disconnect.func = listener_disconnect; 234 listener->disconnect.func = listener_disconnect;
216 transport->AddDisconnect(&listener->disconnect); 235 transport->AddDisconnect(&listener->disconnect);
217 } 236 }
218 237
diff --git a/adb/adb_listeners.h b/adb/adb_listeners.h
index 8eba00a5e..70a2ee121 100644
--- a/adb/adb_listeners.h
+++ b/adb/adb_listeners.h
@@ -41,4 +41,6 @@ std::string format_listeners();
41InstallStatus remove_listener(const char* local_name, atransport* transport); 41InstallStatus remove_listener(const char* local_name, atransport* transport);
42void remove_all_listeners(void); 42void remove_all_listeners(void);
43 43
44void close_smartsockets();
45
44#endif /* __ADB_LISTENERS_H */ 46#endif /* __ADB_LISTENERS_H */
diff --git a/adb/adb_trace.cpp b/adb/adb_trace.cpp
index c369d6077..eac923d4d 100644
--- a/adb/adb_trace.cpp
+++ b/adb/adb_trace.cpp
@@ -155,7 +155,7 @@ void adb_trace_init(char** argv) {
155 } 155 }
156#endif 156#endif
157 157
158#if !defined(_WIN32) 158#if ADB_HOST && !defined(_WIN32)
159 // adb historically ignored $ANDROID_LOG_TAGS but passed it through to logcat. 159 // adb historically ignored $ANDROID_LOG_TAGS but passed it through to logcat.
160 // If set, move it out of the way so that libbase logging doesn't try to parse it. 160 // If set, move it out of the way so that libbase logging doesn't try to parse it.
161 std::string log_tags; 161 std::string log_tags;
@@ -168,7 +168,7 @@ void adb_trace_init(char** argv) {
168 168
169 android::base::InitLogging(argv, &AdbLogger); 169 android::base::InitLogging(argv, &AdbLogger);
170 170
171#if !defined(_WIN32) 171#if ADB_HOST && !defined(_WIN32)
172 // Put $ANDROID_LOG_TAGS back so we can pass it to logcat. 172 // Put $ANDROID_LOG_TAGS back so we can pass it to logcat.
173 if (!log_tags.empty()) setenv("ANDROID_LOG_TAGS", log_tags.c_str(), 1); 173 if (!log_tags.empty()) setenv("ANDROID_LOG_TAGS", log_tags.c_str(), 1);
174#endif 174#endif
diff --git a/adb/adb_trace.h b/adb/adb_trace.h
index aaffa2967..fc6560cfb 100644
--- a/adb/adb_trace.h
+++ b/adb/adb_trace.h
@@ -58,6 +58,9 @@ extern int adb_trace_mask;
58void adb_trace_init(char**); 58void adb_trace_init(char**);
59void adb_trace_enable(AdbTrace trace_tag); 59void adb_trace_enable(AdbTrace trace_tag);
60 60
61// Include <atomic> before stdatomic.h (introduced in cutils/trace.h) to avoid compile error.
62#include <atomic>
63
61#define ATRACE_TAG ATRACE_TAG_ADB 64#define ATRACE_TAG ATRACE_TAG_ADB
62#include <cutils/trace.h> 65#include <cutils/trace.h>
63#include <utils/Trace.h> 66#include <utils/Trace.h>
diff --git a/adb/adb_utils.cpp b/adb/adb_utils.cpp
index 31d3dc63a..6f2403d03 100644
--- a/adb/adb_utils.cpp
+++ b/adb/adb_utils.cpp
@@ -267,8 +267,8 @@ void AdbCloser::Close(int fd) {
267 adb_close(fd); 267 adb_close(fd);
268} 268}
269 269
270int usage(const char* fmt, ...) { 270int syntax_error(const char* fmt, ...) {
271 fprintf(stderr, "adb: "); 271 fprintf(stderr, "adb: usage: ");
272 272
273 va_list ap; 273 va_list ap;
274 va_start(ap, fmt); 274 va_start(ap, fmt);
diff --git a/adb/adb_utils.h b/adb/adb_utils.h
index e0ad10380..c1d5549b0 100644
--- a/adb/adb_utils.h
+++ b/adb/adb_utils.h
@@ -21,7 +21,7 @@
21 21
22#include <android-base/macros.h> 22#include <android-base/macros.h>
23 23
24int usage(const char*, ...); 24int syntax_error(const char*, ...);
25 25
26void close_stdin(); 26void close_stdin();
27 27
diff --git a/adb/bugreport.cpp b/adb/bugreport.cpp
index d159d6ae7..d0cc072ab 100644
--- a/adb/bugreport.cpp
+++ b/adb/bugreport.cpp
@@ -137,7 +137,7 @@ class BugreportStandardStreamsCallback : public StandardStreamsCallbackInterface
137 SetSrcFile(&line[strlen(BUGZ_OK_PREFIX)]); 137 SetSrcFile(&line[strlen(BUGZ_OK_PREFIX)]);
138 } else if (android::base::StartsWith(line, BUGZ_FAIL_PREFIX)) { 138 } else if (android::base::StartsWith(line, BUGZ_FAIL_PREFIX)) {
139 const char* error_message = &line[strlen(BUGZ_FAIL_PREFIX)]; 139 const char* error_message = &line[strlen(BUGZ_FAIL_PREFIX)];
140 fprintf(stderr, "Device failed to take a zipped bugreport: %s\n", error_message); 140 fprintf(stderr, "adb: device failed to take a zipped bugreport: %s\n", error_message);
141 status_ = -1; 141 status_ = -1;
142 } else if (show_progress_ && android::base::StartsWith(line, BUGZ_PROGRESS_PREFIX)) { 142 } else if (show_progress_ && android::base::StartsWith(line, BUGZ_PROGRESS_PREFIX)) {
143 // progress_line should have the following format: 143 // progress_line should have the following format:
@@ -196,7 +196,7 @@ class BugreportStandardStreamsCallback : public StandardStreamsCallbackInterface
196}; 196};
197 197
198int Bugreport::DoIt(TransportType transport_type, const char* serial, int argc, const char** argv) { 198int Bugreport::DoIt(TransportType transport_type, const char* serial, int argc, const char** argv) {
199 if (argc > 2) return usage("usage: adb bugreport [PATH]"); 199 if (argc > 2) return syntax_error("adb bugreport [PATH]");
200 200
201 // Gets bugreportz version. 201 // Gets bugreportz version.
202 std::string bugz_stdout, bugz_stderr; 202 std::string bugz_stdout, bugz_stderr;
diff --git a/adb/client/main.cpp b/adb/client/main.cpp
index 606203cb4..bd9ad01f3 100644
--- a/adb/client/main.cpp
+++ b/adb/client/main.cpp
@@ -92,6 +92,16 @@ static BOOL WINAPI ctrlc_handler(DWORD type) {
92} 92}
93#endif 93#endif
94 94
95void adb_server_cleanup() {
96 // Upon exit, we want to clean up in the following order:
97 // 1. close_smartsockets, so that we don't get any new clients
98 // 2. kick_all_transports, to avoid writing only part of a packet to a transport.
99 // 3. usb_cleanup, to tear down the USB stack.
100 close_smartsockets();
101 kick_all_transports();
102 usb_cleanup();
103}
104
95int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply_fd) { 105int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply_fd) {
96#if defined(_WIN32) 106#if defined(_WIN32)
97 // adb start-server starts us up with stdout and stderr hooked up to 107 // adb start-server starts us up with stdout and stderr hooked up to
@@ -111,12 +121,13 @@ int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply
111 SetConsoleCtrlHandler(ctrlc_handler, TRUE); 121 SetConsoleCtrlHandler(ctrlc_handler, TRUE);
112#else 122#else
113 signal(SIGINT, [](int) { 123 signal(SIGINT, [](int) {
114 android::base::quick_exit(0); 124 fdevent_run_on_main_thread([]() { android::base::quick_exit(0); });
115 }); 125 });
116#endif 126#endif
117 127
118 init_transport_registration(); 128 android::base::at_quick_exit(adb_server_cleanup);
119 129
130 init_transport_registration();
120 init_mdns_transport_discovery(); 131 init_mdns_transport_discovery();
121 132
122 usb_init(); 133 usb_init();
@@ -156,33 +167,38 @@ int adb_server_main(int is_daemon, const std::string& socket_spec, int ack_reply
156 } 167 }
157#endif 168#endif
158 169
159 // Inform our parent that we are up and running. 170 // Wait for the USB scan to complete before notifying the parent that we're up.
171 // We need to perform this in a thread, because we would otherwise block the event loop.
172 std::thread notify_thread([ack_reply_fd]() {
173 adb_wait_for_device_initialization();
160 174
161 // Any error output written to stderr now goes to adb.log. We could 175 // Any error output written to stderr now goes to adb.log. We could
162 // keep around a copy of the stderr fd and use that to write any errors 176 // keep around a copy of the stderr fd and use that to write any errors
163 // encountered by the following code, but that is probably overkill. 177 // encountered by the following code, but that is probably overkill.
164#if defined(_WIN32) 178#if defined(_WIN32)
165 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd); 179 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
166 const CHAR ack[] = "OK\n"; 180 const CHAR ack[] = "OK\n";
167 const DWORD bytes_to_write = arraysize(ack) - 1; 181 const DWORD bytes_to_write = arraysize(ack) - 1;
168 DWORD written = 0; 182 DWORD written = 0;
169 if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) { 183 if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) {
170 fatal("adb: cannot write ACK to handle 0x%p: %s", ack_reply_handle, 184 fatal("adb: cannot write ACK to handle 0x%p: %s", ack_reply_handle,
171 android::base::SystemErrorCodeToString(GetLastError()).c_str()); 185 android::base::SystemErrorCodeToString(GetLastError()).c_str());
172 } 186 }
173 if (written != bytes_to_write) { 187 if (written != bytes_to_write) {
174 fatal("adb: cannot write %lu bytes of ACK: only wrote %lu bytes", 188 fatal("adb: cannot write %lu bytes of ACK: only wrote %lu bytes", bytes_to_write,
175 bytes_to_write, written); 189 written);
176 } 190 }
177 CloseHandle(ack_reply_handle); 191 CloseHandle(ack_reply_handle);
178#else 192#else
179 // TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not 193 // TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not
180 // "OKAY". 194 // "OKAY".
181 if (!android::base::WriteStringToFd("OK\n", ack_reply_fd)) { 195 if (!android::base::WriteStringToFd("OK\n", ack_reply_fd)) {
182 fatal_errno("error writing ACK to fd %d", ack_reply_fd); 196 fatal_errno("error writing ACK to fd %d", ack_reply_fd);
183 } 197 }
184 unix_close(ack_reply_fd); 198 unix_close(ack_reply_fd);
185#endif 199#endif
200 });
201 notify_thread.detach();
186 } 202 }
187 203
188 D("Event loop starting"); 204 D("Event loop starting");
diff --git a/adb/client/usb_dispatch.cpp b/adb/client/usb_dispatch.cpp
index bfc8e164b..ce5773175 100644
--- a/adb/client/usb_dispatch.cpp
+++ b/adb/client/usb_dispatch.cpp
@@ -27,6 +27,14 @@ void usb_init() {
27 } 27 }
28} 28}
29 29
30void usb_cleanup() {
31 if (should_use_libusb()) {
32 libusb::usb_cleanup();
33 } else {
34 native::usb_cleanup();
35 }
36}
37
30int usb_write(usb_handle* h, const void* data, int len) { 38int usb_write(usb_handle* h, const void* data, int len) {
31 return should_use_libusb() 39 return should_use_libusb()
32 ? libusb::usb_write(reinterpret_cast<libusb::usb_handle*>(h), data, len) 40 ? libusb::usb_write(reinterpret_cast<libusb::usb_handle*>(h), data, len)
@@ -48,3 +56,9 @@ void usb_kick(usb_handle* h) {
48 should_use_libusb() ? libusb::usb_kick(reinterpret_cast<libusb::usb_handle*>(h)) 56 should_use_libusb() ? libusb::usb_kick(reinterpret_cast<libusb::usb_handle*>(h))
49 : native::usb_kick(reinterpret_cast<native::usb_handle*>(h)); 57 : native::usb_kick(reinterpret_cast<native::usb_handle*>(h));
50} 58}
59
60size_t usb_get_max_packet_size(usb_handle* h) {
61 return should_use_libusb()
62 ? libusb::usb_get_max_packet_size(reinterpret_cast<libusb::usb_handle*>(h))
63 : native::usb_get_max_packet_size(reinterpret_cast<native::usb_handle*>(h));
64}
diff --git a/adb/client/usb_libusb.cpp b/adb/client/usb_libusb.cpp
index 7adb26213..fc32469fa 100644
--- a/adb/client/usb_libusb.cpp
+++ b/adb/client/usb_libusb.cpp
@@ -62,12 +62,11 @@ struct DeviceHandleDeleter {
62using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>; 62using unique_device_handle = std::unique_ptr<libusb_device_handle, DeviceHandleDeleter>;
63 63
64struct transfer_info { 64struct transfer_info {
65 transfer_info(const char* name, uint16_t zero_mask) : 65 transfer_info(const char* name, uint16_t zero_mask, bool is_bulk_out)
66 name(name), 66 : name(name),
67 transfer(libusb_alloc_transfer(0)), 67 transfer(libusb_alloc_transfer(0)),
68 zero_mask(zero_mask) 68 is_bulk_out(is_bulk_out),
69 { 69 zero_mask(zero_mask) {}
70 }
71 70
72 ~transfer_info() { 71 ~transfer_info() {
73 libusb_free_transfer(transfer); 72 libusb_free_transfer(transfer);
@@ -75,6 +74,7 @@ struct transfer_info {
75 74
76 const char* name; 75 const char* name;
77 libusb_transfer* transfer; 76 libusb_transfer* transfer;
77 bool is_bulk_out;
78 bool transfer_complete; 78 bool transfer_complete;
79 std::condition_variable cv; 79 std::condition_variable cv;
80 std::mutex mutex; 80 std::mutex mutex;
@@ -91,17 +91,17 @@ namespace libusb {
91struct usb_handle : public ::usb_handle { 91struct usb_handle : public ::usb_handle {
92 usb_handle(const std::string& device_address, const std::string& serial, 92 usb_handle(const std::string& device_address, const std::string& serial,
93 unique_device_handle&& device_handle, uint8_t interface, uint8_t bulk_in, 93 unique_device_handle&& device_handle, uint8_t interface, uint8_t bulk_in,
94 uint8_t bulk_out, size_t zero_mask) 94 uint8_t bulk_out, size_t zero_mask, size_t max_packet_size)
95 : device_address(device_address), 95 : device_address(device_address),
96 serial(serial), 96 serial(serial),
97 closing(false), 97 closing(false),
98 device_handle(device_handle.release()), 98 device_handle(device_handle.release()),
99 read("read", zero_mask), 99 read("read", zero_mask, false),
100 write("write", zero_mask), 100 write("write", zero_mask, true),
101 interface(interface), 101 interface(interface),
102 bulk_in(bulk_in), 102 bulk_in(bulk_in),
103 bulk_out(bulk_out) { 103 bulk_out(bulk_out),
104 } 104 max_packet_size(max_packet_size) {}
105 105
106 ~usb_handle() { 106 ~usb_handle() {
107 Close(); 107 Close();
@@ -144,19 +144,47 @@ struct usb_handle : public ::usb_handle {
144 uint8_t interface; 144 uint8_t interface;
145 uint8_t bulk_in; 145 uint8_t bulk_in;
146 uint8_t bulk_out; 146 uint8_t bulk_out;
147
148 size_t max_packet_size;
147}; 149};
148 150
149static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>(); 151static auto& usb_handles = *new std::unordered_map<std::string, std::unique_ptr<usb_handle>>();
150static auto& usb_handles_mutex = *new std::mutex(); 152static auto& usb_handles_mutex = *new std::mutex();
151 153
152static std::thread* device_poll_thread = nullptr; 154static libusb_hotplug_callback_handle hotplug_handle;
153static std::atomic<bool> terminate_device_poll_thread(false);
154 155
155static std::string get_device_address(libusb_device* device) { 156static std::string get_device_address(libusb_device* device) {
156 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device), 157 return StringPrintf("usb:%d:%d", libusb_get_bus_number(device),
157 libusb_get_device_address(device)); 158 libusb_get_device_address(device));
158} 159}
159 160
161#if defined(__linux__)
162static std::string get_device_serial_path(libusb_device* device) {
163 uint8_t ports[7];
164 int port_count = libusb_get_port_numbers(device, ports, 7);
165 if (port_count < 0) return "";
166
167 std::string path =
168 StringPrintf("/sys/bus/usb/devices/%d-%d", libusb_get_bus_number(device), ports[0]);
169 for (int port = 1; port < port_count; ++port) {
170 path += StringPrintf(".%d", ports[port]);
171 }
172 path += "/serial";
173 return path;
174}
175
176static std::string get_device_dev_path(libusb_device* device) {
177 uint8_t ports[7];
178 int port_count = libusb_get_port_numbers(device, ports, 7);
179 if (port_count < 0) return "";
180 return StringPrintf("/dev/bus/usb/%03u/%03u", libusb_get_bus_number(device), ports[0]);
181}
182
183static bool is_device_accessible(libusb_device* device) {
184 return access(get_device_dev_path(device).c_str(), R_OK | W_OK) == 0;
185}
186#endif
187
160static bool endpoint_is_output(uint8_t endpoint) { 188static bool endpoint_is_output(uint8_t endpoint) {
161 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT; 189 return (endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT;
162} 190}
@@ -166,191 +194,245 @@ static bool should_perform_zero_transfer(uint8_t endpoint, size_t write_length,
166 (write_length & zero_mask) == 0; 194 (write_length & zero_mask) == 0;
167} 195}
168 196
169static void poll_for_devices() { 197static void process_device(libusb_device* device) {
170 libusb_device** list; 198 std::string device_address = get_device_address(device);
171 adb_thread_setname("device poll"); 199 std::string device_serial;
172 while (!terminate_device_poll_thread) {
173 const ssize_t device_count = libusb_get_device_list(nullptr, &list);
174 200
175 LOG(VERBOSE) << "found " << device_count << " attached devices"; 201 // Figure out if we want to open the device.
202 libusb_device_descriptor device_desc;
203 int rc = libusb_get_device_descriptor(device, &device_desc);
204 if (rc != 0) {
205 LOG(WARNING) << "failed to get device descriptor for device at " << device_address << ": "
206 << libusb_error_name(rc);
207 return;
208 }
176 209
177 for (ssize_t i = 0; i < device_count; ++i) { 210 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) {
178 libusb_device* device = list[i]; 211 // Assume that all Android devices have the device class set to per interface.
179 std::string device_address = get_device_address(device); 212 // TODO: Is this assumption valid?
180 std::string device_serial; 213 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address;
214 return;
215 }
181 216
182 // Figure out if we want to open the device. 217 libusb_config_descriptor* config_raw;
183 libusb_device_descriptor device_desc; 218 rc = libusb_get_active_config_descriptor(device, &config_raw);
184 int rc = libusb_get_device_descriptor(device, &device_desc); 219 if (rc != 0) {
185 if (rc != 0) { 220 LOG(WARNING) << "failed to get active config descriptor for device at " << device_address
186 LOG(WARNING) << "failed to get device descriptor for device at " << device_address 221 << ": " << libusb_error_name(rc);
187 << ": " << libusb_error_name(rc); 222 return;
188 } 223 }
224 const unique_config_descriptor config(config_raw);
189 225
190 if (device_desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE) { 226 // Use size_t for interface_num so <iostream>s don't mangle it.
191 // Assume that all Android devices have the device class set to per interface. 227 size_t interface_num;
192 // TODO: Is this assumption valid? 228 uint16_t zero_mask;
193 LOG(VERBOSE) << "skipping device with incorrect class at " << device_address; 229 uint8_t bulk_in = 0, bulk_out = 0;
194 continue; 230 size_t packet_size = 0;
195 } 231 bool found_adb = false;
232
233 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
234 const libusb_interface& interface = config->interface[interface_num];
235 if (interface.num_altsetting != 1) {
236 // Assume that interfaces with alternate settings aren't adb interfaces.
237 // TODO: Is this assumption valid?
238 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at " << device_address
239 << " (interface " << interface_num << ")";
240 continue;
241 }
196 242
197 libusb_config_descriptor* config_raw; 243 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
198 rc = libusb_get_active_config_descriptor(device, &config_raw); 244 if (!is_adb_interface(interface_desc.bInterfaceClass, interface_desc.bInterfaceSubClass,
199 if (rc != 0) { 245 interface_desc.bInterfaceProtocol)) {
200 LOG(WARNING) << "failed to get active config descriptor for device at " 246 LOG(VERBOSE) << "skipping non-adb interface at " << device_address << " (interface "
201 << device_address << ": " << libusb_error_name(rc); 247 << interface_num << ")";
202 continue; 248 continue;
203 } 249 }
204 const unique_config_descriptor config(config_raw); 250
205 251 LOG(VERBOSE) << "found potential adb interface at " << device_address << " (interface "
206 // Use size_t for interface_num so <iostream>s don't mangle it. 252 << interface_num << ")";
207 size_t interface_num;
208 uint16_t zero_mask;
209 uint8_t bulk_in = 0, bulk_out = 0;
210 bool found_adb = false;
211
212 for (interface_num = 0; interface_num < config->bNumInterfaces; ++interface_num) {
213 const libusb_interface& interface = config->interface[interface_num];
214 if (interface.num_altsetting != 1) {
215 // Assume that interfaces with alternate settings aren't adb interfaces.
216 // TODO: Is this assumption valid?
217 LOG(VERBOSE) << "skipping interface with incorrect num_altsetting at "
218 << device_address << " (interface " << interface_num << ")";
219 continue;
220 }
221
222 const libusb_interface_descriptor& interface_desc = interface.altsetting[0];
223 if (!is_adb_interface(interface_desc.bInterfaceClass,
224 interface_desc.bInterfaceSubClass,
225 interface_desc.bInterfaceProtocol)) {
226 LOG(VERBOSE) << "skipping non-adb interface at " << device_address
227 << " (interface " << interface_num << ")";
228 continue;
229 }
230
231 LOG(VERBOSE) << "found potential adb interface at " << device_address
232 << " (interface " << interface_num << ")";
233
234 bool found_in = false;
235 bool found_out = false;
236 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints;
237 ++endpoint_num) {
238 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
239 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
240 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
241
242 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
243
244 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
245 continue;
246 }
247
248 if (endpoint_is_output(endpoint_addr) && !found_out) {
249 found_out = true;
250 bulk_out = endpoint_addr;
251 zero_mask = endpoint_desc.wMaxPacketSize - 1;
252 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
253 found_in = true;
254 bulk_in = endpoint_addr;
255 }
256 }
257
258 if (found_in && found_out) {
259 found_adb = true;
260 break;
261 } else {
262 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
263 << "(interface " << interface_num << "): missing bulk endpoints "
264 << "(found_in = " << found_in << ", found_out = " << found_out
265 << ")";
266 }
267 }
268 253
269 if (!found_adb) { 254 bool found_in = false;
270 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address; 255 bool found_out = false;
256 for (size_t endpoint_num = 0; endpoint_num < interface_desc.bNumEndpoints; ++endpoint_num) {
257 const auto& endpoint_desc = interface_desc.endpoint[endpoint_num];
258 const uint8_t endpoint_addr = endpoint_desc.bEndpointAddress;
259 const uint8_t endpoint_attr = endpoint_desc.bmAttributes;
260
261 const uint8_t transfer_type = endpoint_attr & LIBUSB_TRANSFER_TYPE_MASK;
262
263 if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK) {
271 continue; 264 continue;
272 } 265 }
273 266
274 { 267 if (endpoint_is_output(endpoint_addr) && !found_out) {
275 std::unique_lock<std::mutex> lock(usb_handles_mutex); 268 found_out = true;
276 if (usb_handles.find(device_address) != usb_handles.end()) { 269 bulk_out = endpoint_addr;
277 LOG(VERBOSE) << "device at " << device_address 270 zero_mask = endpoint_desc.wMaxPacketSize - 1;
278 << " has already been registered, skipping"; 271 } else if (!endpoint_is_output(endpoint_addr) && !found_in) {
279 continue; 272 found_in = true;
280 } 273 bulk_in = endpoint_addr;
281 } 274 }
282 275
283 libusb_device_handle* handle_raw; 276 size_t endpoint_packet_size = endpoint_desc.wMaxPacketSize;
284 rc = libusb_open(list[i], &handle_raw); 277 CHECK(endpoint_packet_size != 0);
285 if (rc != 0) { 278 if (packet_size == 0) {
286 LOG(WARNING) << "failed to open usb device at " << device_address << ": " 279 packet_size = endpoint_packet_size;
287 << libusb_error_name(rc); 280 } else {
288 continue; 281 CHECK(packet_size == endpoint_packet_size);
289 } 282 }
283 }
290 284
291 unique_device_handle handle(handle_raw); 285 if (found_in && found_out) {
292 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", " 286 found_adb = true;
293 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out); 287 break;
288 } else {
289 LOG(VERBOSE) << "rejecting potential adb interface at " << device_address
290 << "(interface " << interface_num << "): missing bulk endpoints "
291 << "(found_in = " << found_in << ", found_out = " << found_out << ")";
292 }
293 }
294 294
295 device_serial.resize(255); 295 if (!found_adb) {
296 rc = libusb_get_string_descriptor_ascii( 296 LOG(VERBOSE) << "skipping device with no adb interfaces at " << device_address;
297 handle_raw, device_desc.iSerialNumber, 297 return;
298 reinterpret_cast<unsigned char*>(&device_serial[0]), device_serial.length()); 298 }
299 if (rc == 0) {
300 LOG(WARNING) << "received empty serial from device at " << device_address;
301 continue;
302 } else if (rc < 0) {
303 LOG(WARNING) << "failed to get serial from device at " << device_address
304 << libusb_error_name(rc);
305 continue;
306 }
307 device_serial.resize(rc);
308 299
309 // Try to reset the device. 300 {
310 rc = libusb_reset_device(handle_raw); 301 std::unique_lock<std::mutex> lock(usb_handles_mutex);
311 if (rc != 0) { 302 if (usb_handles.find(device_address) != usb_handles.end()) {
312 LOG(WARNING) << "failed to reset opened device '" << device_serial 303 LOG(VERBOSE) << "device at " << device_address
313 << "': " << libusb_error_name(rc); 304 << " has already been registered, skipping";
314 continue; 305 return;
315 } 306 }
307 }
308
309 bool writable = true;
310 libusb_device_handle* handle_raw = nullptr;
311 rc = libusb_open(device, &handle_raw);
312 unique_device_handle handle(handle_raw);
313 if (rc == 0) {
314 LOG(DEBUG) << "successfully opened adb device at " << device_address << ", "
315 << StringPrintf("bulk_in = %#x, bulk_out = %#x", bulk_in, bulk_out);
316
317 device_serial.resize(255);
318 rc = libusb_get_string_descriptor_ascii(handle_raw, device_desc.iSerialNumber,
319 reinterpret_cast<unsigned char*>(&device_serial[0]),
320 device_serial.length());
321 if (rc == 0) {
322 LOG(WARNING) << "received empty serial from device at " << device_address;
323 return;
324 } else if (rc < 0) {
325 LOG(WARNING) << "failed to get serial from device at " << device_address
326 << libusb_error_name(rc);
327 return;
328 }
329 device_serial.resize(rc);
330
331 // WARNING: this isn't released via RAII.
332 rc = libusb_claim_interface(handle.get(), interface_num);
333 if (rc != 0) {
334 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'"
335 << libusb_error_name(rc);
336 return;
337 }
316 338
317 // WARNING: this isn't released via RAII. 339 for (uint8_t endpoint : {bulk_in, bulk_out}) {
318 rc = libusb_claim_interface(handle.get(), interface_num); 340 rc = libusb_clear_halt(handle.get(), endpoint);
319 if (rc != 0) { 341 if (rc != 0) {
320 LOG(WARNING) << "failed to claim adb interface for device '" << device_serial << "'" 342 LOG(WARNING) << "failed to clear halt on device '" << device_serial
343 << "' endpoint 0x" << std::hex << endpoint << ": "
321 << libusb_error_name(rc); 344 << libusb_error_name(rc);
322 continue; 345 libusb_release_interface(handle.get(), interface_num);
346 return;
323 } 347 }
348 }
349 } else {
350 LOG(WARNING) << "failed to open usb device at " << device_address << ": "
351 << libusb_error_name(rc);
352 writable = false;
353
354#if defined(__linux__)
355 // libusb doesn't think we should be messing around with devices we don't have
356 // write access to, but Linux at least lets us get the serial number anyway.
357 if (!android::base::ReadFileToString(get_device_serial_path(device), &device_serial)) {
358 // We don't actually want to treat an unknown serial as an error because
359 // devices aren't able to communicate a serial number in early bringup.
360 // http://b/20883914
361 device_serial = "unknown";
362 }
363 device_serial = android::base::Trim(device_serial);
364#else
365 // On Mac OS and Windows, we're screwed. But I don't think this situation actually
366 // happens on those OSes.
367 return;
368#endif
369 }
324 370
325 for (uint8_t endpoint : {bulk_in, bulk_out}) { 371 auto result =
326 rc = libusb_clear_halt(handle.get(), endpoint); 372 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle),
327 if (rc != 0) { 373 interface_num, bulk_in, bulk_out, zero_mask, packet_size);
328 LOG(WARNING) << "failed to clear halt on device '" << device_serial 374 usb_handle* usb_handle_raw = result.get();
329 << "' endpoint 0x" << std::hex << endpoint << ": "
330 << libusb_error_name(rc);
331 libusb_release_interface(handle.get(), interface_num);
332 continue;
333 }
334 }
335 375
336 auto result = 376 {
337 std::make_unique<usb_handle>(device_address, device_serial, std::move(handle), 377 std::unique_lock<std::mutex> lock(usb_handles_mutex);
338 interface_num, bulk_in, bulk_out, zero_mask); 378 usb_handles[device_address] = std::move(result);
339 usb_handle* usb_handle_raw = result.get(); 379 }
340 380
341 { 381 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), writable);
342 std::unique_lock<std::mutex> lock(usb_handles_mutex); 382 LOG(INFO) << "registered new usb device '" << device_serial << "'";
343 usb_handles[device_address] = std::move(result); 383}
384
385static std::atomic<int> connecting_devices(0);
386
387static void device_connected(libusb_device* device) {
388#if defined(__linux__)
389 // Android's host linux libusb uses netlink instead of udev for device hotplug notification,
390 // which means we can get hotplug notifications before udev has updated ownership/perms on the
391 // device. Since we're not going to be able to link against the system's libudev any time soon,
392 // hack around this by checking for accessibility in a loop.
393 ++connecting_devices;
394 auto thread = std::thread([device]() {
395 std::string device_path = get_device_dev_path(device);
396 auto start = std::chrono::steady_clock::now();
397 while (std::chrono::steady_clock::now() - start < 500ms) {
398 if (is_device_accessible(device)) {
399 break;
344 } 400 }
401 std::this_thread::sleep_for(10ms);
402 }
345 403
346 register_usb_transport(usb_handle_raw, device_serial.c_str(), device_address.c_str(), 1); 404 process_device(device);
405 --connecting_devices;
406 });
407 thread.detach();
408#else
409 process_device(device);
410#endif
411}
412
413static void device_disconnected(libusb_device* device) {
414 std::string device_address = get_device_address(device);
347 415
348 LOG(INFO) << "registered new usb device '" << device_serial << "'"; 416 LOG(INFO) << "device disconnected: " << device_address;
417 std::unique_lock<std::mutex> lock(usb_handles_mutex);
418 auto it = usb_handles.find(device_address);
419 if (it != usb_handles.end()) {
420 if (!it->second->device_handle) {
421 // If the handle is null, we were never able to open the device.
422 unregister_usb_transport(it->second.get());
349 } 423 }
350 libusb_free_device_list(list, 1); 424 usb_handles.erase(it);
425 }
426}
351 427
352 std::this_thread::sleep_for(500ms); 428static int hotplug_callback(libusb_context*, libusb_device* device, libusb_hotplug_event event,
429 void*) {
430 if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) {
431 device_connected(device);
432 } else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) {
433 device_disconnected(device);
353 } 434 }
435 return 0;
354} 436}
355 437
356void usb_init() { 438void usb_init() {
@@ -360,6 +442,24 @@ void usb_init() {
360 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc); 442 LOG(FATAL) << "failed to initialize libusb: " << libusb_error_name(rc);
361 } 443 }
362 444
445 // Register the hotplug callback.
446 rc = libusb_hotplug_register_callback(
447 nullptr, static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED |
448 LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
449 LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY,
450 LIBUSB_CLASS_PER_INTERFACE, hotplug_callback, nullptr, &hotplug_handle);
451
452 if (rc != LIBUSB_SUCCESS) {
453 LOG(FATAL) << "failed to register libusb hotplug callback";
454 }
455
456 // Wait for all of the connecting devices to finish.
457 while (connecting_devices != 0) {
458 std::this_thread::sleep_for(10ms);
459 }
460
461 adb_notify_device_scan_complete();
462
363 // Spawn a thread for libusb_handle_events. 463 // Spawn a thread for libusb_handle_events.
364 std::thread([]() { 464 std::thread([]() {
365 adb_thread_setname("libusb"); 465 adb_thread_setname("libusb");
@@ -367,19 +467,10 @@ void usb_init() {
367 libusb_handle_events(nullptr); 467 libusb_handle_events(nullptr);
368 } 468 }
369 }).detach(); 469 }).detach();
470}
370 471
371 // Spawn a thread to do device enumeration. 472void usb_cleanup() {
372 // TODO: Use libusb_hotplug_* instead? 473 libusb_hotplug_deregister_callback(nullptr, hotplug_handle);
373 device_poll_thread = new std::thread(poll_for_devices);
374 android::base::at_quick_exit([]() {
375 terminate_device_poll_thread = true;
376 std::unique_lock<std::mutex> lock(usb_handles_mutex);
377 for (auto& it : usb_handles) {
378 it.second->Close();
379 }
380 lock.unlock();
381 device_poll_thread->join();
382 });
383} 474}
384 475
385// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result. 476// Dispatch a libusb transfer, unlock |device_lock|, and then wait for the result.
@@ -405,7 +496,8 @@ static int perform_usb_transfer(usb_handle* h, transfer_info* info,
405 return; 496 return;
406 } 497 }
407 498
408 if (transfer->actual_length != transfer->length) { 499 // usb_read() can return when receiving some data.
500 if (info->is_bulk_out && transfer->actual_length != transfer->length) {
409 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting"; 501 LOG(DEBUG) << info->name << " transfer incomplete, resubmitting";
410 transfer->length -= transfer->actual_length; 502 transfer->length -= transfer->actual_length;
411 transfer->buffer += transfer->actual_length; 503 transfer->buffer += transfer->actual_length;
@@ -499,8 +591,12 @@ int usb_read(usb_handle* h, void* d, int len) {
499 info->transfer->num_iso_packets = 0; 591 info->transfer->num_iso_packets = 0;
500 592
501 int rc = perform_usb_transfer(h, info, std::move(lock)); 593 int rc = perform_usb_transfer(h, info, std::move(lock));
502 LOG(DEBUG) << "usb_read(" << len << ") = " << rc; 594 LOG(DEBUG) << "usb_read(" << len << ") = " << rc << ", actual_length "
503 return rc; 595 << info->transfer->actual_length;
596 if (rc < 0) {
597 return rc;
598 }
599 return info->transfer->actual_length;
504} 600}
505 601
506int usb_close(usb_handle* h) { 602int usb_close(usb_handle* h) {
@@ -516,4 +612,10 @@ int usb_close(usb_handle* h) {
516void usb_kick(usb_handle* h) { 612void usb_kick(usb_handle* h) {
517 h->Close(); 613 h->Close();
518} 614}
615
616size_t usb_get_max_packet_size(usb_handle* h) {
617 CHECK(h->max_packet_size != 0);
618 return h->max_packet_size;
619}
620
519} // namespace libusb 621} // namespace libusb
diff --git a/adb/client/usb_linux.cpp b/adb/client/usb_linux.cpp
index 13b7674fc..a7df0ed51 100644
--- a/adb/client/usb_linux.cpp
+++ b/adb/client/usb_linux.cpp
@@ -65,6 +65,7 @@ struct usb_handle : public ::usb_handle {
65 unsigned char ep_in; 65 unsigned char ep_in;
66 unsigned char ep_out; 66 unsigned char ep_out;
67 67
68 size_t max_packet_size;
68 unsigned zero_mask; 69 unsigned zero_mask;
69 unsigned writeable = 1; 70 unsigned writeable = 1;
70 71
@@ -120,9 +121,9 @@ static inline bool contains_non_digit(const char* name) {
120} 121}
121 122
122static void find_usb_device(const std::string& base, 123static void find_usb_device(const std::string& base,
123 void (*register_device_callback) 124 void (*register_device_callback)(const char*, const char*,
124 (const char*, const char*, unsigned char, unsigned char, int, int, unsigned)) 125 unsigned char, unsigned char, int, int,
125{ 126 unsigned, size_t)) {
126 std::unique_ptr<DIR, int(*)(DIR*)> bus_dir(opendir(base.c_str()), closedir); 127 std::unique_ptr<DIR, int(*)(DIR*)> bus_dir(opendir(base.c_str()), closedir);
127 if (!bus_dir) return; 128 if (!bus_dir) return;
128 129
@@ -144,6 +145,7 @@ static void find_usb_device(const std::string& base,
144 struct usb_interface_descriptor* interface; 145 struct usb_interface_descriptor* interface;
145 struct usb_endpoint_descriptor *ep1, *ep2; 146 struct usb_endpoint_descriptor *ep1, *ep2;
146 unsigned zero_mask = 0; 147 unsigned zero_mask = 0;
148 size_t max_packet_size = 0;
147 unsigned vid, pid; 149 unsigned vid, pid;
148 150
149 if (contains_non_digit(de->d_name)) continue; 151 if (contains_non_digit(de->d_name)) continue;
@@ -251,7 +253,8 @@ static void find_usb_device(const std::string& base,
251 continue; 253 continue;
252 } 254 }
253 /* aproto 01 needs 0 termination */ 255 /* aproto 01 needs 0 termination */
254 if(interface->bInterfaceProtocol == 0x01) { 256 if (interface->bInterfaceProtocol == 0x01) {
257 max_packet_size = ep1->wMaxPacketSize;
255 zero_mask = ep1->wMaxPacketSize - 1; 258 zero_mask = ep1->wMaxPacketSize - 1;
256 } 259 }
257 260
@@ -281,9 +284,9 @@ static void find_usb_device(const std::string& base,
281 } 284 }
282 } 285 }
283 286
284 register_device_callback(dev_name.c_str(), devpath, 287 register_device_callback(dev_name.c_str(), devpath, local_ep_in,
285 local_ep_in, local_ep_out, 288 local_ep_out, interface->bInterfaceNumber,
286 interface->bInterfaceNumber, device->iSerialNumber, zero_mask); 289 device->iSerialNumber, zero_mask, max_packet_size);
287 break; 290 break;
288 } 291 }
289 } else { 292 } else {
@@ -401,7 +404,6 @@ static int usb_bulk_read(usb_handle* h, void* data, int len) {
401 } 404 }
402} 405}
403 406
404
405int usb_write(usb_handle *h, const void *_data, int len) 407int usb_write(usb_handle *h, const void *_data, int len)
406{ 408{
407 D("++ usb_write ++"); 409 D("++ usb_write ++");
@@ -429,19 +431,16 @@ int usb_read(usb_handle *h, void *_data, int len)
429 int n; 431 int n;
430 432
431 D("++ usb_read ++"); 433 D("++ usb_read ++");
432 while(len > 0) { 434 int orig_len = len;
435 while (len == orig_len) {
433 int xfer = len; 436 int xfer = len;
434 437
435 D("[ usb read %d fd = %d], path=%s", xfer, h->fd, h->path.c_str()); 438 D("[ usb read %d fd = %d], path=%s", xfer, h->fd, h->path.c_str());
436 n = usb_bulk_read(h, data, xfer); 439 n = usb_bulk_read(h, data, xfer);
437 D("[ usb read %d ] = %d, path=%s", xfer, n, h->path.c_str()); 440 D("[ usb read %d ] = %d, path=%s", xfer, n, h->path.c_str());
438 if(n != xfer) { 441 if (n <= 0) {
439 if((errno == ETIMEDOUT) && (h->fd != -1)) { 442 if((errno == ETIMEDOUT) && (h->fd != -1)) {
440 D("[ timeout ]"); 443 D("[ timeout ]");
441 if(n > 0){
442 data += n;
443 len -= n;
444 }
445 continue; 444 continue;
446 } 445 }
447 D("ERROR: n = %d, errno = %d (%s)", 446 D("ERROR: n = %d, errno = %d (%s)",
@@ -449,12 +448,12 @@ int usb_read(usb_handle *h, void *_data, int len)
449 return -1; 448 return -1;
450 } 449 }
451 450
452 len -= xfer; 451 len -= n;
453 data += xfer; 452 data += n;
454 } 453 }
455 454
456 D("-- usb_read --"); 455 D("-- usb_read --");
457 return 0; 456 return orig_len - len;
458} 457}
459 458
460void usb_kick(usb_handle* h) { 459void usb_kick(usb_handle* h) {
@@ -501,10 +500,13 @@ int usb_close(usb_handle* h) {
501 return 0; 500 return 0;
502} 501}
503 502
504static void register_device(const char* dev_name, const char* dev_path, 503size_t usb_get_max_packet_size(usb_handle* h) {
505 unsigned char ep_in, unsigned char ep_out, 504 return h->max_packet_size;
506 int interface, int serial_index, 505}
507 unsigned zero_mask) { 506
507static void register_device(const char* dev_name, const char* dev_path, unsigned char ep_in,
508 unsigned char ep_out, int interface, int serial_index,
509 unsigned zero_mask, size_t max_packet_size) {
508 // Since Linux will not reassign the device ID (and dev_name) as long as the 510 // Since Linux will not reassign the device ID (and dev_name) as long as the
509 // device is open, we can add to the list here once we open it and remove 511 // device is open, we can add to the list here once we open it and remove
510 // from the list when we're finally closed and everything will work out 512 // from the list when we're finally closed and everything will work out
@@ -527,6 +529,7 @@ static void register_device(const char* dev_name, const char* dev_path,
527 usb->ep_in = ep_in; 529 usb->ep_in = ep_in;
528 usb->ep_out = ep_out; 530 usb->ep_out = ep_out;
529 usb->zero_mask = zero_mask; 531 usb->zero_mask = zero_mask;
532 usb->max_packet_size = max_packet_size;
530 533
531 // Initialize mark so we don't get garbage collected after the device scan. 534 // Initialize mark so we don't get garbage collected after the device scan.
532 usb->mark = true; 535 usb->mark = true;
@@ -574,7 +577,7 @@ static void register_device(const char* dev_name, const char* dev_path,
574 register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable); 577 register_usb_transport(done_usb, serial.c_str(), dev_path, done_usb->writeable);
575} 578}
576 579
577static void device_poll_thread(void*) { 580static void device_poll_thread() {
578 adb_thread_setname("device poll"); 581 adb_thread_setname("device poll");
579 D("Created device thread"); 582 D("Created device thread");
580 while (true) { 583 while (true) {
@@ -593,8 +596,9 @@ void usb_init() {
593 actions.sa_handler = [](int) {}; 596 actions.sa_handler = [](int) {};
594 sigaction(SIGALRM, &actions, nullptr); 597 sigaction(SIGALRM, &actions, nullptr);
595 598
596 if (!adb_thread_create(device_poll_thread, nullptr)) { 599 std::thread(device_poll_thread).detach();
597 fatal_errno("cannot create device_poll thread");
598 }
599} 600}
601
602void usb_cleanup() {}
603
600} // namespace native 604} // namespace native
diff --git a/adb/client/usb_osx.cpp b/adb/client/usb_osx.cpp
index d4fc7c0eb..4e1480f7b 100644
--- a/adb/client/usb_osx.cpp
+++ b/adb/client/usb_osx.cpp
@@ -38,6 +38,7 @@
38 38
39#include <android-base/logging.h> 39#include <android-base/logging.h>
40#include <android-base/stringprintf.h> 40#include <android-base/stringprintf.h>
41#include <android-base/thread_annotations.h>
41 42
42#include "adb.h" 43#include "adb.h"
43#include "transport.h" 44#include "transport.h"
@@ -51,15 +52,21 @@ struct usb_handle
51 UInt8 bulkOut; 52 UInt8 bulkOut;
52 IOUSBInterfaceInterface190** interface; 53 IOUSBInterfaceInterface190** interface;
53 unsigned int zero_mask; 54 unsigned int zero_mask;
55 size_t max_packet_size;
54 56
55 // For garbage collecting disconnected devices. 57 // For garbage collecting disconnected devices.
56 bool mark; 58 bool mark;
57 std::string devpath; 59 std::string devpath;
58 std::atomic<bool> dead; 60 std::atomic<bool> dead;
59 61
60 usb_handle() : bulkIn(0), bulkOut(0), interface(nullptr), 62 usb_handle()
61 zero_mask(0), mark(false), dead(false) { 63 : bulkIn(0),
62 } 64 bulkOut(0),
65 interface(nullptr),
66 zero_mask(0),
67 max_packet_size(0),
68 mark(false),
69 dead(false) {}
63}; 70};
64 71
65static std::atomic<bool> usb_inited_flag; 72static std::atomic<bool> usb_inited_flag;
@@ -390,6 +397,7 @@ CheckInterface(IOUSBInterfaceInterface190 **interface, UInt16 vendor, UInt16 pro
390 } 397 }
391 398
392 handle->zero_mask = maxPacketSize - 1; 399 handle->zero_mask = maxPacketSize - 1;
400 handle->max_packet_size = maxPacketSize;
393 } 401 }
394 402
395 handle->interface = interface; 403 handle->interface = interface;
@@ -405,7 +413,7 @@ err_get_num_ep:
405 413
406std::mutex& operate_device_lock = *new std::mutex(); 414std::mutex& operate_device_lock = *new std::mutex();
407 415
408static void RunLoopThread(void* unused) { 416static void RunLoopThread() {
409 adb_thread_setname("RunLoop"); 417 adb_thread_setname("RunLoop");
410 418
411 VLOG(USB) << "RunLoopThread started"; 419 VLOG(USB) << "RunLoopThread started";
@@ -422,7 +430,7 @@ static void RunLoopThread(void* unused) {
422 VLOG(USB) << "RunLoopThread done"; 430 VLOG(USB) << "RunLoopThread done";
423} 431}
424 432
425static void usb_cleanup() { 433void usb_cleanup() NO_THREAD_SAFETY_ANALYSIS {
426 VLOG(USB) << "usb_cleanup"; 434 VLOG(USB) << "usb_cleanup";
427 // Wait until usb operations in RunLoopThread finish, and prevent further operations. 435 // Wait until usb operations in RunLoopThread finish, and prevent further operations.
428 operate_device_lock.lock(); 436 operate_device_lock.lock();
@@ -432,13 +440,9 @@ static void usb_cleanup() {
432void usb_init() { 440void usb_init() {
433 static bool initialized = false; 441 static bool initialized = false;
434 if (!initialized) { 442 if (!initialized) {
435 atexit(usb_cleanup);
436
437 usb_inited_flag = false; 443 usb_inited_flag = false;
438 444
439 if (!adb_thread_create(RunLoopThread, nullptr)) { 445 std::thread(RunLoopThread).detach();
440 fatal_errno("cannot create RunLoop thread");
441 }
442 446
443 // Wait for initialization to finish 447 // Wait for initialization to finish
444 while (!usb_inited_flag) { 448 while (!usb_inited_flag) {
@@ -520,7 +524,7 @@ int usb_read(usb_handle *handle, void *buf, int len)
520 } 524 }
521 525
522 if (kIOReturnSuccess == result) 526 if (kIOReturnSuccess == result)
523 return 0; 527 return numBytes;
524 else { 528 else {
525 LOG(ERROR) << "usb_read failed with status: " << std::hex << result; 529 LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
526 } 530 }
@@ -560,4 +564,9 @@ void usb_kick(usb_handle *handle) {
560 std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex); 564 std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
561 usb_kick_locked(handle); 565 usb_kick_locked(handle);
562} 566}
567
568size_t usb_get_max_packet_size(usb_handle* handle) {
569 return handle->max_packet_size;
570}
571
563} // namespace native 572} // namespace native
diff --git a/adb/client/usb_windows.cpp b/adb/client/usb_windows.cpp
index 640e91ec3..1620e6ec4 100644
--- a/adb/client/usb_windows.cpp
+++ b/adb/client/usb_windows.cpp
@@ -65,6 +65,9 @@ struct usb_handle {
65 /// Interface name 65 /// Interface name
66 wchar_t* interface_name; 66 wchar_t* interface_name;
67 67
68 /// Maximum packet size.
69 unsigned max_packet_size;
70
68 /// Mask for determining when to use zero length packets 71 /// Mask for determining when to use zero length packets
69 unsigned zero_mask; 72 unsigned zero_mask;
70}; 73};
@@ -103,7 +106,7 @@ static void kick_devices();
103 106
104/// Entry point for thread that polls (every second) for new usb interfaces. 107/// Entry point for thread that polls (every second) for new usb interfaces.
105/// This routine calls find_devices in infinite loop. 108/// This routine calls find_devices in infinite loop.
106static void device_poll_thread(void*); 109static void device_poll_thread();
107 110
108/// Initializes this module 111/// Initializes this module
109void usb_init(); 112void usb_init();
@@ -174,7 +177,7 @@ int register_new_device(usb_handle* handle) {
174 return 1; 177 return 1;
175} 178}
176 179
177void device_poll_thread(void*) { 180void device_poll_thread() {
178 adb_thread_setname("Device Poll"); 181 adb_thread_setname("Device Poll");
179 D("Created device thread"); 182 D("Created device thread");
180 183
@@ -203,7 +206,7 @@ static LRESULT CALLBACK _power_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam,
203 return DefWindowProcW(hwnd, uMsg, wParam, lParam); 206 return DefWindowProcW(hwnd, uMsg, wParam, lParam);
204} 207}
205 208
206static void _power_notification_thread(void*) { 209static void _power_notification_thread() {
207 // This uses a thread with its own window message pump to get power 210 // This uses a thread with its own window message pump to get power
208 // notifications. If adb runs from a non-interactive service account, this 211 // notifications. If adb runs from a non-interactive service account, this
209 // might not work (not sure). If that happens to not work, we could use 212 // might not work (not sure). If that happens to not work, we could use
@@ -258,14 +261,12 @@ static void _power_notification_thread(void*) {
258} 261}
259 262
260void usb_init() { 263void usb_init() {
261 if (!adb_thread_create(device_poll_thread, nullptr)) { 264 std::thread(device_poll_thread).detach();
262 fatal_errno("cannot create device poll thread"); 265 std::thread(_power_notification_thread).detach();
263 }
264 if (!adb_thread_create(_power_notification_thread, nullptr)) {
265 fatal_errno("cannot create power notification thread");
266 }
267} 266}
268 267
268void usb_cleanup() {}
269
269usb_handle* do_usb_open(const wchar_t* interface_name) { 270usb_handle* do_usb_open(const wchar_t* interface_name) {
270 unsigned long name_len = 0; 271 unsigned long name_len = 0;
271 272
@@ -419,6 +420,7 @@ int usb_read(usb_handle *handle, void* data, int len) {
419 unsigned long time_out = 0; 420 unsigned long time_out = 0;
420 unsigned long read = 0; 421 unsigned long read = 0;
421 int err = 0; 422 int err = 0;
423 int orig_len = len;
422 424
423 D("usb_read %d", len); 425 D("usb_read %d", len);
424 if (NULL == handle) { 426 if (NULL == handle) {
@@ -427,9 +429,8 @@ int usb_read(usb_handle *handle, void* data, int len) {
427 goto fail; 429 goto fail;
428 } 430 }
429 431
430 while (len > 0) { 432 while (len == orig_len) {
431 if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read, 433 if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read, time_out)) {
432 time_out)) {
433 D("AdbReadEndpointSync failed: %s", 434 D("AdbReadEndpointSync failed: %s",
434 android::base::SystemErrorCodeToString(GetLastError()).c_str()); 435 android::base::SystemErrorCodeToString(GetLastError()).c_str());
435 err = EIO; 436 err = EIO;
@@ -437,11 +438,11 @@ int usb_read(usb_handle *handle, void* data, int len) {
437 } 438 }
438 D("usb_read got: %ld, expected: %d", read, len); 439 D("usb_read got: %ld, expected: %d", read, len);
439 440
440 data = (char *)data + read; 441 data = (char*)data + read;
441 len -= read; 442 len -= read;
442 } 443 }
443 444
444 return 0; 445 return orig_len - len;
445 446
446fail: 447fail:
447 // Any failure should cause us to kick the device instead of leaving it a 448 // Any failure should cause us to kick the device instead of leaving it a
@@ -526,6 +527,10 @@ int usb_close(usb_handle* handle) {
526 return 0; 527 return 0;
527} 528}
528 529
530size_t usb_get_max_packet_size(usb_handle* handle) {
531 return handle->max_packet_size;
532}
533
529int recognized_device(usb_handle* handle) { 534int recognized_device(usb_handle* handle) {
530 if (NULL == handle) 535 if (NULL == handle)
531 return 0; 536 return 0;
@@ -561,6 +566,7 @@ int recognized_device(usb_handle* handle) {
561 AdbEndpointInformation endpoint_info; 566 AdbEndpointInformation endpoint_info;
562 // assuming zero is a valid bulk endpoint ID 567 // assuming zero is a valid bulk endpoint ID
563 if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) { 568 if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
569 handle->max_packet_size = endpoint_info.max_packet_size;
564 handle->zero_mask = endpoint_info.max_packet_size - 1; 570 handle->zero_mask = endpoint_info.max_packet_size - 1;
565 D("device zero_mask: 0x%x", handle->zero_mask); 571 D("device zero_mask: 0x%x", handle->zero_mask);
566 } else { 572 } else {
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 4979eef5c..f49c69daf 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -68,20 +68,17 @@ static int uninstall_app(TransportType t, const char* serial, int argc, const ch
68static int install_app_legacy(TransportType t, const char* serial, int argc, const char** argv); 68static int install_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
69static int uninstall_app_legacy(TransportType t, const char* serial, int argc, const char** argv); 69static int uninstall_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
70 70
71static auto& gProductOutPath = *new std::string();
72extern int gListenAll; 71extern int gListenAll;
73 72
74DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr); 73DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
75 74
76static std::string product_file(const char *extra) { 75static std::string product_file(const char* file) {
77 if (gProductOutPath.empty()) { 76 const char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
78 fprintf(stderr, "adb: Product directory not specified; " 77 if (ANDROID_PRODUCT_OUT == nullptr) {
79 "use -p or define ANDROID_PRODUCT_OUT\n"); 78 fprintf(stderr, "adb: product directory not specified; set $ANDROID_PRODUCT_OUT\n");
80 exit(1); 79 exit(1);
81 } 80 }
82 81 return android::base::StringPrintf("%s%s%s", ANDROID_PRODUCT_OUT, OS_PATH_SEPARATOR_STR, file);
83 return android::base::StringPrintf("%s%s%s",
84 gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra);
85} 82}
86 83
87static void help() { 84static void help() {
@@ -92,11 +89,7 @@ static void help() {
92 " -a listen on all network interfaces, not just localhost\n" 89 " -a listen on all network interfaces, not just localhost\n"
93 " -d use USB device (error if multiple devices connected)\n" 90 " -d use USB device (error if multiple devices connected)\n"
94 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n" 91 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
95 " -s SERIAL\n" 92 " -s SERIAL use device with given serial (overrides $ANDROID_SERIAL)\n"
96 " use device with given serial number (overrides $ANDROID_SERIAL)\n"
97 " -p PRODUCT\n"
98 " name or path ('angler'/'out/target/product/angler');\n"
99 " default $ANDROID_PRODUCT_OUT\n"
100 " -H name of adb server host [default=localhost]\n" 93 " -H name of adb server host [default=localhost]\n"
101 " -P port of adb server [default=5037]\n" 94 " -P port of adb server [default=5037]\n"
102 " -L SOCKET listen on given socket for adb server [default=tcp:localhost:5037]\n" 95 " -L SOCKET listen on given socket for adb server [default=tcp:localhost:5037]\n"
@@ -138,9 +131,8 @@ static void help() {
138 " pull [-a] REMOTE... LOCAL\n" 131 " pull [-a] REMOTE... LOCAL\n"
139 " copy files/dirs from device\n" 132 " copy files/dirs from device\n"
140 " -a: preserve file timestamp and mode\n" 133 " -a: preserve file timestamp and mode\n"
141 " sync [DIR]\n" 134 " sync [system|vendor|oem|data|all]\n"
142 " copy all changed files to device; if DIR is \"system\", \"vendor\", \"oem\",\n" 135 " sync a local build from $ANDROID_PRODUCT_OUT to the device (default all)\n"
143 " or \"data\", only sync that partition (default all)\n"
144 " -l: list but don't copy\n" 136 " -l: list but don't copy\n"
145 "\n" 137 "\n"
146 "shell:\n" 138 "shell:\n"
@@ -169,15 +161,7 @@ static void help() {
169 " '-k': keep the data and cache directories\n" 161 " '-k': keep the data and cache directories\n"
170 "\n" 162 "\n"
171 "backup/restore:\n" 163 "backup/restore:\n"
172 " backup [-f FILE] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [PACKAGE...]\n" 164 " to show usage run \"adb shell bu help\"\n"
173 " write an archive of the device's data to FILE [default=backup.adb]\n"
174 " package list optional if -all/-shared are supplied\n"
175 " -apk/-noapk: do/don't back up .apk files (default -noapk)\n"
176 " -obb/-noobb: do/don't back up .obb files (default -noobb)\n"
177 " -shared|-noshared: do/don't back up shared storage (default -noshared)\n"
178 " -all: back up all installed applications\n"
179 " -system|-nosystem: include system apps in -all (default -system)\n"
180 " restore FILE restore device contents from FILE\n"
181 "\n" 165 "\n"
182 "debugging:\n" 166 "debugging:\n"
183 " bugreport [PATH]\n" 167 " bugreport [PATH]\n"
@@ -220,6 +204,7 @@ static void help() {
220 " kill-server kill the server if it is running\n" 204 " kill-server kill the server if it is running\n"
221 " reconnect kick connection from host side to force reconnect\n" 205 " reconnect kick connection from host side to force reconnect\n"
222 " reconnect device kick connection from device side to force reconnect\n" 206 " reconnect device kick connection from device side to force reconnect\n"
207 " reconnect offline reset offline/unauthorized devices to force reconnect\n"
223 "\n" 208 "\n"
224 "environment variables:\n" 209 "environment variables:\n"
225 " $ADB_TRACE\n" 210 " $ADB_TRACE\n"
@@ -663,13 +648,8 @@ static int RemoteShell(bool use_shell_protocol, const std::string& type_arg,
663#endif 648#endif
664 649
665 // TODO: combine read_and_dump with stdin_read_thread to make life simpler? 650 // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
666 int exit_code = 1; 651 std::thread(stdin_read_thread_loop, args).detach();
667 if (!adb_thread_create(stdin_read_thread_loop, args)) { 652 int exit_code = read_and_dump(fd, use_shell_protocol);
668 PLOG(ERROR) << "error starting stdin read thread";
669 delete args;
670 } else {
671 exit_code = read_and_dump(fd, use_shell_protocol);
672 }
673 653
674 // TODO: properly exit stdin_read_thread_loop and close |fd|. 654 // TODO: properly exit stdin_read_thread_loop and close |fd|.
675 655
@@ -703,8 +683,7 @@ static int adb_shell(int argc, const char** argv) {
703 switch (opt) { 683 switch (opt) {
704 case 'e': 684 case 'e':
705 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) { 685 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
706 fprintf(stderr, "error: -e requires a single-character argument or 'none'\n"); 686 return syntax_error("-e requires a single-character argument or 'none'");
707 return 1;
708 } 687 }
709 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0]; 688 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
710 break; 689 break;
@@ -782,55 +761,46 @@ static int adb_shell(int argc, const char** argv) {
782 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command); 761 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command);
783} 762}
784 763
785static int adb_download_buffer(const char* service, const char* filename) { 764static int adb_sideload_legacy(const char* filename, int in_fd, int size) {
786 std::string content;
787 if (!android::base::ReadFileToString(filename, &content)) {
788 fprintf(stderr, "error: couldn't read %s: %s\n", filename, strerror(errno));
789 return -1;
790 }
791
792 const uint8_t* data = reinterpret_cast<const uint8_t*>(content.data());
793 unsigned sz = content.size();
794
795 std::string error; 765 std::string error;
796 int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error); 766 int out_fd = adb_connect(android::base::StringPrintf("sideload:%d", size), &error);
797 if (fd < 0) { 767 if (out_fd < 0) {
798 fprintf(stderr,"error: %s\n", error.c_str()); 768 fprintf(stderr, "adb: pre-KitKat sideload connection failed: %s\n", error.c_str());
799 return -1; 769 return -1;
800 } 770 }
801 771
802 int opt = CHUNK_SIZE; 772 int opt = CHUNK_SIZE;
803 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt)); 773 opt = adb_setsockopt(out_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
804 774
805 unsigned total = sz; 775 char buf[CHUNK_SIZE];
806 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); 776 int total = size;
807 777 while (size > 0) {
808 const char* x = strrchr(service, ':'); 778 unsigned xfer = (size > CHUNK_SIZE) ? CHUNK_SIZE : size;
809 if (x) service = x + 1; 779 if (!ReadFdExactly(in_fd, buf, xfer)) {
810 780 fprintf(stderr, "adb: failed to read data from %s: %s\n", filename, strerror(errno));
811 while (sz > 0) { 781 adb_close(out_fd);
812 unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz; 782 return -1;
813 if (!WriteFdExactly(fd, ptr, xfer)) { 783 }
784 if (!WriteFdExactly(out_fd, buf, xfer)) {
814 std::string error; 785 std::string error;
815 adb_status(fd, &error); 786 adb_status(out_fd, &error);
816 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str()); 787 fprintf(stderr, "adb: failed to write data: %s\n", error.c_str());
817 adb_close(fd); 788 adb_close(out_fd);
818 return -1; 789 return -1;
819 } 790 }
820 sz -= xfer; 791 size -= xfer;
821 ptr += xfer; 792 printf("sending: '%s' %4d%% \r", filename, (int)(100LL - ((100LL * size) / (total))));
822 printf("sending: '%s' %4d%% \r", filename, (int)(100LL - ((100LL * sz) / (total))));
823 fflush(stdout); 793 fflush(stdout);
824 } 794 }
825 printf("\n"); 795 printf("\n");
826 796
827 if (!adb_status(fd, &error)) { 797 if (!adb_status(out_fd, &error)) {
828 fprintf(stderr,"* error response '%s' *\n", error.c_str()); 798 fprintf(stderr, "adb: error response: %s\n", error.c_str());
829 adb_close(fd); 799 adb_close(out_fd);
830 return -1; 800 return -1;
831 } 801 }
832 802
833 adb_close(fd); 803 adb_close(out_fd);
834 return 0; 804 return 0;
835} 805}
836 806
@@ -856,19 +826,18 @@ static int adb_download_buffer(const char* service, const char* filename) {
856 * we hang up. 826 * we hang up.
857 */ 827 */
858static int adb_sideload_host(const char* filename) { 828static int adb_sideload_host(const char* filename) {
859 fprintf(stderr, "opening '%s'...\n", filename); 829 // TODO: use a LinePrinter instead...
860 struct stat sb; 830 struct stat sb;
861 if (stat(filename, &sb) == -1) { 831 if (stat(filename, &sb) == -1) {
862 fprintf(stderr, "failed to stat file %s: %s\n", filename, strerror(errno)); 832 fprintf(stderr, "adb: failed to stat file %s: %s\n", filename, strerror(errno));
863 return -1; 833 return -1;
864 } 834 }
865 unique_fd package_fd(adb_open(filename, O_RDONLY)); 835 unique_fd package_fd(adb_open(filename, O_RDONLY));
866 if (package_fd == -1) { 836 if (package_fd == -1) {
867 fprintf(stderr, "failed to open file %s: %s\n", filename, strerror(errno)); 837 fprintf(stderr, "adb: failed to open file %s: %s\n", filename, strerror(errno));
868 return -1; 838 return -1;
869 } 839 }
870 840
871 fprintf(stderr, "connecting...\n");
872 std::string service = android::base::StringPrintf( 841 std::string service = android::base::StringPrintf(
873 "sideload-host:%d:%d", static_cast<int>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE); 842 "sideload-host:%d:%d", static_cast<int>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
874 std::string error; 843 std::string error;
@@ -876,8 +845,9 @@ static int adb_sideload_host(const char* filename) {
876 if (device_fd < 0) { 845 if (device_fd < 0) {
877 // Try falling back to the older (<= K) sideload method. Maybe this 846 // Try falling back to the older (<= K) sideload method. Maybe this
878 // is an older device that doesn't support sideload-host. 847 // is an older device that doesn't support sideload-host.
879 fprintf(stderr, "falling back to older sideload method...\n"); 848 fprintf(stderr, "adb: sideload connection failed: %s\n", error.c_str());
880 return adb_download_buffer("sideload", filename); 849 fprintf(stderr, "adb: trying pre-KitKat sideload method...\n");
850 return adb_sideload_legacy(filename, package_fd, static_cast<int>(sb.st_size));
881 } 851 }
882 852
883 int opt = SIDELOAD_HOST_BLOCK_SIZE; 853 int opt = SIDELOAD_HOST_BLOCK_SIZE;
@@ -889,7 +859,7 @@ static int adb_sideload_host(const char* filename) {
889 int last_percent = -1; 859 int last_percent = -1;
890 while (true) { 860 while (true) {
891 if (!ReadFdExactly(device_fd, buf, 8)) { 861 if (!ReadFdExactly(device_fd, buf, 8)) {
892 fprintf(stderr, "* failed to read command: %s\n", strerror(errno)); 862 fprintf(stderr, "adb: failed to read command: %s\n", strerror(errno));
893 return -1; 863 return -1;
894 } 864 }
895 buf[8] = '\0'; 865 buf[8] = '\0';
@@ -905,7 +875,7 @@ static int adb_sideload_host(const char* filename) {
905 875
906 size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE; 876 size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
907 if (offset >= static_cast<size_t>(sb.st_size)) { 877 if (offset >= static_cast<size_t>(sb.st_size)) {
908 fprintf(stderr, "* attempt to read block %d past end\n", block); 878 fprintf(stderr, "adb: failed to read block %d past end\n", block);
909 return -1; 879 return -1;
910 } 880 }
911 881
@@ -915,17 +885,17 @@ static int adb_sideload_host(const char* filename) {
915 } 885 }
916 886
917 if (adb_lseek(package_fd, offset, SEEK_SET) != static_cast<int>(offset)) { 887 if (adb_lseek(package_fd, offset, SEEK_SET) != static_cast<int>(offset)) {
918 fprintf(stderr, "* failed to seek to package block: %s\n", strerror(errno)); 888 fprintf(stderr, "adb: failed to seek to package block: %s\n", strerror(errno));
919 return -1; 889 return -1;
920 } 890 }
921 if (!ReadFdExactly(package_fd, buf, to_write)) { 891 if (!ReadFdExactly(package_fd, buf, to_write)) {
922 fprintf(stderr, "* failed to read package block: %s\n", strerror(errno)); 892 fprintf(stderr, "adb: failed to read package block: %s\n", strerror(errno));
923 return -1; 893 return -1;
924 } 894 }
925 895
926 if (!WriteFdExactly(device_fd, buf, to_write)) { 896 if (!WriteFdExactly(device_fd, buf, to_write)) {
927 adb_status(device_fd, &error); 897 adb_status(device_fd, &error);
928 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str()); 898 fprintf(stderr, "adb: failed to write data '%s' *\n", error.c_str());
929 return -1; 899 return -1;
930 } 900 }
931 xfer += to_write; 901 xfer += to_write;
@@ -957,19 +927,13 @@ static int ppp(int argc, const char** argv) {
957 fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]); 927 fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]);
958 return -1; 928 return -1;
959#else 929#else
960 if (argc < 2) { 930 if (argc < 2) return syntax_error("adb %s <adb service name> [ppp opts]", argv[0]);
961 fprintf(stderr, "usage: adb %s <adb service name> [ppp opts]\n",
962 argv[0]);
963
964 return 1;
965 }
966 931
967 const char* adb_service_name = argv[1]; 932 const char* adb_service_name = argv[1];
968 std::string error; 933 std::string error;
969 int fd = adb_connect(adb_service_name, &error); 934 int fd = adb_connect(adb_service_name, &error);
970 if (fd < 0) { 935 if (fd < 0) {
971 fprintf(stderr,"Error: Could not open adb service: %s. Error: %s\n", 936 fprintf(stderr, "adb: could not open adb service %s: %s\n", adb_service_name, error.c_str());
972 adb_service_name, error.c_str());
973 return 1; 937 return 1;
974 } 938 }
975 939
@@ -1188,10 +1152,7 @@ static int backup(int argc, const char** argv) {
1188 /* find, extract, and use any -f argument */ 1152 /* find, extract, and use any -f argument */
1189 for (int i = 1; i < argc; i++) { 1153 for (int i = 1; i < argc; i++) {
1190 if (!strcmp("-f", argv[i])) { 1154 if (!strcmp("-f", argv[i])) {
1191 if (i == argc-1) { 1155 if (i == argc - 1) return syntax_error("backup -f passed with no filename");
1192 fprintf(stderr, "adb: backup -f passed with no filename.\n");
1193 return EXIT_FAILURE;
1194 }
1195 filename = argv[i+1]; 1156 filename = argv[i+1];
1196 for (int j = i+2; j <= argc; ) { 1157 for (int j = i+2; j <= argc; ) {
1197 argv[i++] = argv[j++]; 1158 argv[i++] = argv[j++];
@@ -1203,10 +1164,7 @@ static int backup(int argc, const char** argv) {
1203 1164
1204 // Bare "adb backup" or "adb backup -f filename" are not valid invocations --- 1165 // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
1205 // a list of packages is required. 1166 // a list of packages is required.
1206 if (argc < 2) { 1167 if (argc < 2) return syntax_error("backup either needs a list of packages or -all/-shared");
1207 fprintf(stderr, "adb: backup either needs a list of packages or -all/-shared.\n");
1208 return EXIT_FAILURE;
1209 }
1210 1168
1211 adb_unlink(filename); 1169 adb_unlink(filename);
1212 int outFd = adb_creat(filename, 0640); 1170 int outFd = adb_creat(filename, 0640);
@@ -1231,7 +1189,7 @@ static int backup(int argc, const char** argv) {
1231 return EXIT_FAILURE; 1189 return EXIT_FAILURE;
1232 } 1190 }
1233 1191
1234 printf("Now unlock your device and confirm the backup operation...\n"); 1192 fprintf(stdout, "Now unlock your device and confirm the backup operation...\n");
1235 fflush(stdout); 1193 fflush(stdout);
1236 1194
1237 copy_to_file(fd, outFd); 1195 copy_to_file(fd, outFd);
@@ -1242,7 +1200,7 @@ static int backup(int argc, const char** argv) {
1242} 1200}
1243 1201
1244static int restore(int argc, const char** argv) { 1202static int restore(int argc, const char** argv) {
1245 if (argc != 2) return usage("restore requires an argument"); 1203 if (argc != 2) return syntax_error("restore requires an argument");
1246 1204
1247 const char* filename = argv[1]; 1205 const char* filename = argv[1];
1248 int tarFd = adb_open(filename, O_RDONLY); 1206 int tarFd = adb_open(filename, O_RDONLY);
@@ -1259,7 +1217,9 @@ static int restore(int argc, const char** argv) {
1259 return -1; 1217 return -1;
1260 } 1218 }
1261 1219
1262 printf("Now unlock your device and confirm the restore operation.\n"); 1220 fprintf(stdout, "Now unlock your device and confirm the restore operation.\n");
1221 fflush(stdout);
1222
1263 copy_to_file(tarFd, fd); 1223 copy_to_file(tarFd, fd);
1264 1224
1265 // Provide an in-band EOD marker in case the archive file is malformed 1225 // Provide an in-band EOD marker in case the archive file is malformed
@@ -1273,66 +1233,6 @@ static int restore(int argc, const char** argv) {
1273 return 0; 1233 return 0;
1274} 1234}
1275 1235
1276/* <hint> may be:
1277 * - A simple product name
1278 * e.g., "sooner"
1279 * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir
1280 * e.g., "out/target/product/sooner"
1281 * - An absolute path to the PRODUCT_OUT dir
1282 * e.g., "/src/device/out/target/product/sooner"
1283 *
1284 * Given <hint>, try to construct an absolute path to the
1285 * ANDROID_PRODUCT_OUT dir.
1286 */
1287static std::string find_product_out_path(const std::string& hint) {
1288 if (hint.empty()) {
1289 return "";
1290 }
1291
1292 // If it's already absolute, don't bother doing any work.
1293 if (adb_is_absolute_host_path(hint.c_str())) {
1294 return hint;
1295 }
1296
1297 // If any of the OS_PATH_SEPARATORS is found, assume it's a relative path;
1298 // make it absolute.
1299 // NOLINT: Do not complain if OS_PATH_SEPARATORS has only one character.
1300 if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) { // NOLINT
1301 std::string cwd;
1302 if (!getcwd(&cwd)) {
1303 perror("adb: getcwd failed");
1304 return "";
1305 }
1306 return android::base::StringPrintf("%s%c%s", cwd.c_str(), OS_PATH_SEPARATOR, hint.c_str());
1307 }
1308
1309 // It's a string without any slashes. Try to do something with it.
1310 //
1311 // Try to find the root of the build tree, and build a PRODUCT_OUT
1312 // path from there.
1313 char* top = getenv("ANDROID_BUILD_TOP");
1314 if (top == nullptr) {
1315 fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n");
1316 return "";
1317 }
1318
1319 std::string path = top;
1320 path += OS_PATH_SEPARATOR_STR;
1321 path += "out";
1322 path += OS_PATH_SEPARATOR_STR;
1323 path += "target";
1324 path += OS_PATH_SEPARATOR_STR;
1325 path += "product";
1326 path += OS_PATH_SEPARATOR_STR;
1327 path += hint;
1328 if (!directory_exists(path)) {
1329 fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; "
1330 "\"%s\" doesn't exist\n", hint.c_str(), path.c_str());
1331 return "";
1332 }
1333 return path;
1334}
1335
1336static void parse_push_pull_args(const char** arg, int narg, 1236static void parse_push_pull_args(const char** arg, int narg,
1337 std::vector<const char*>* srcs, 1237 std::vector<const char*>* srcs,
1338 const char** dst, bool* copy_attrs) { 1238 const char** dst, bool* copy_attrs) {
@@ -1351,7 +1251,7 @@ static void parse_push_pull_args(const char** arg, int narg,
1351 } else if (!strcmp(*arg, "--")) { 1251 } else if (!strcmp(*arg, "--")) {
1352 ignore_flags = true; 1252 ignore_flags = true;
1353 } else { 1253 } else {
1354 fprintf(stderr, "adb: unrecognized option '%s'\n", *arg); 1254 syntax_error("unrecognized option '%s'", *arg);
1355 exit(1); 1255 exit(1);
1356 } 1256 }
1357 } 1257 }
@@ -1423,17 +1323,6 @@ int adb_commandline(int argc, const char** argv) {
1423 signal(SIGPIPE, SIG_IGN); 1323 signal(SIGPIPE, SIG_IGN);
1424#endif 1324#endif
1425 1325
1426 // If defined, this should be an absolute path to
1427 // the directory containing all of the various system images
1428 // for a particular product. If not defined, and the adb
1429 // command requires this information, then the user must
1430 // specify the path using "-p".
1431 char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
1432 if (ANDROID_PRODUCT_OUT != nullptr) {
1433 gProductOutPath = ANDROID_PRODUCT_OUT;
1434 }
1435 // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint
1436
1437 const char* server_host_str = nullptr; 1326 const char* server_host_str = nullptr;
1438 const char* server_port_str = nullptr; 1327 const char* server_port_str = nullptr;
1439 const char* server_socket_str = nullptr; 1328 const char* server_socket_str = nullptr;
@@ -1450,7 +1339,7 @@ int adb_commandline(int argc, const char** argv) {
1450 /* this is a special flag used only when the ADB client launches the ADB Server */ 1339 /* this is a special flag used only when the ADB client launches the ADB Server */
1451 is_daemon = 1; 1340 is_daemon = 1;
1452 } else if (!strcmp(argv[0], "--reply-fd")) { 1341 } else if (!strcmp(argv[0], "--reply-fd")) {
1453 if (argc < 2) return usage("--reply-fd requires an argument"); 1342 if (argc < 2) return syntax_error("--reply-fd requires an argument");
1454 const char* reply_fd_str = argv[1]; 1343 const char* reply_fd_str = argv[1];
1455 argc--; 1344 argc--;
1456 argv++; 1345 argv++;
@@ -1459,26 +1348,11 @@ int adb_commandline(int argc, const char** argv) {
1459 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str); 1348 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
1460 return 1; 1349 return 1;
1461 } 1350 }
1462 } else if (!strncmp(argv[0], "-p", 2)) {
1463 const char* product = nullptr;
1464 if (argv[0][2] == '\0') {
1465 if (argc < 2) return usage("-p requires an argument");
1466 product = argv[1];
1467 argc--;
1468 argv++;
1469 } else {
1470 product = argv[0] + 2;
1471 }
1472 gProductOutPath = find_product_out_path(product);
1473 if (gProductOutPath.empty()) {
1474 fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product);
1475 return 1;
1476 }
1477 } else if (argv[0][0]=='-' && argv[0][1]=='s') { 1351 } else if (argv[0][0]=='-' && argv[0][1]=='s') {
1478 if (isdigit(argv[0][2])) { 1352 if (isdigit(argv[0][2])) {
1479 serial = argv[0] + 2; 1353 serial = argv[0] + 2;
1480 } else { 1354 } else {
1481 if (argc < 2 || argv[0][2] != '\0') return usage("-s requires an argument"); 1355 if (argc < 2 || argv[0][2] != '\0') return syntax_error("-s requires an argument");
1482 serial = argv[1]; 1356 serial = argv[1];
1483 argc--; 1357 argc--;
1484 argv++; 1358 argv++;
@@ -1491,7 +1365,7 @@ int adb_commandline(int argc, const char** argv) {
1491 gListenAll = 1; 1365 gListenAll = 1;
1492 } else if (!strncmp(argv[0], "-H", 2)) { 1366 } else if (!strncmp(argv[0], "-H", 2)) {
1493 if (argv[0][2] == '\0') { 1367 if (argv[0][2] == '\0') {
1494 if (argc < 2) return usage("-H requires an argument"); 1368 if (argc < 2) return syntax_error("-H requires an argument");
1495 server_host_str = argv[1]; 1369 server_host_str = argv[1];
1496 argc--; 1370 argc--;
1497 argv++; 1371 argv++;
@@ -1500,7 +1374,7 @@ int adb_commandline(int argc, const char** argv) {
1500 } 1374 }
1501 } else if (!strncmp(argv[0], "-P", 2)) { 1375 } else if (!strncmp(argv[0], "-P", 2)) {
1502 if (argv[0][2] == '\0') { 1376 if (argv[0][2] == '\0') {
1503 if (argc < 2) return usage("-P requires an argument"); 1377 if (argc < 2) return syntax_error("-P requires an argument");
1504 server_port_str = argv[1]; 1378 server_port_str = argv[1];
1505 argc--; 1379 argc--;
1506 argv++; 1380 argv++;
@@ -1508,7 +1382,7 @@ int adb_commandline(int argc, const char** argv) {
1508 server_port_str = argv[0] + 2; 1382 server_port_str = argv[0] + 2;
1509 } 1383 }
1510 } else if (!strcmp(argv[0], "-L")) { 1384 } else if (!strcmp(argv[0], "-L")) {
1511 if (argc < 2) return usage("-L requires an argument"); 1385 if (argc < 2) return syntax_error("-L requires an argument");
1512 server_socket_str = argv[1]; 1386 server_socket_str = argv[1];
1513 argc--; 1387 argc--;
1514 argv++; 1388 argv++;
@@ -1521,8 +1395,7 @@ int adb_commandline(int argc, const char** argv) {
1521 } 1395 }
1522 1396
1523 if ((server_host_str || server_port_str) && server_socket_str) { 1397 if ((server_host_str || server_port_str) && server_socket_str) {
1524 fprintf(stderr, "adb: -L is incompatible with -H or -P\n"); 1398 return syntax_error("-L is incompatible with -H or -P");
1525 exit(1);
1526 } 1399 }
1527 1400
1528 // If -L, -H, or -P are specified, ignore environment variables. 1401 // If -L, -H, or -P are specified, ignore environment variables.
@@ -1617,8 +1490,7 @@ int adb_commandline(int argc, const char** argv) {
1617 } else if (argc == 2 && !strcmp(argv[1], "-l")) { 1490 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
1618 listopt = argv[1]; 1491 listopt = argv[1];
1619 } else { 1492 } else {
1620 fprintf(stderr, "Usage: adb devices [-l]\n"); 1493 return syntax_error("adb devices [-l]");
1621 return 1;
1622 } 1494 }
1623 1495
1624 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt); 1496 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
@@ -1626,19 +1498,13 @@ int adb_commandline(int argc, const char** argv) {
1626 return adb_query_command(query); 1498 return adb_query_command(query);
1627 } 1499 }
1628 else if (!strcmp(argv[0], "connect")) { 1500 else if (!strcmp(argv[0], "connect")) {
1629 if (argc != 2) { 1501 if (argc != 2) return syntax_error("adb connect <host>[:<port>]");
1630 fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
1631 return 1;
1632 }
1633 1502
1634 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]); 1503 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1635 return adb_query_command(query); 1504 return adb_query_command(query);
1636 } 1505 }
1637 else if (!strcmp(argv[0], "disconnect")) { 1506 else if (!strcmp(argv[0], "disconnect")) {
1638 if (argc > 2) { 1507 if (argc > 2) return syntax_error("adb disconnect [<host>[:<port>]]");
1639 fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
1640 return 1;
1641 }
1642 1508
1643 std::string query = android::base::StringPrintf("host:disconnect:%s", 1509 std::string query = android::base::StringPrintf("host:disconnect:%s",
1644 (argc == 2) ? argv[1] : ""); 1510 (argc == 2) ? argv[1] : "");
@@ -1653,10 +1519,7 @@ int adb_commandline(int argc, const char** argv) {
1653 else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) { 1519 else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
1654 int exec_in = !strcmp(argv[0], "exec-in"); 1520 int exec_in = !strcmp(argv[0], "exec-in");
1655 1521
1656 if (argc < 2) { 1522 if (argc < 2) return syntax_error("adb %s command", argv[0]);
1657 fprintf(stderr, "Usage: adb %s command\n", argv[0]);
1658 return 1;
1659 }
1660 1523
1661 std::string cmd = "exec:"; 1524 std::string cmd = "exec:";
1662 cmd += argv[1]; 1525 cmd += argv[1];
@@ -1683,28 +1546,10 @@ int adb_commandline(int argc, const char** argv) {
1683 return 0; 1546 return 0;
1684 } 1547 }
1685 else if (!strcmp(argv[0], "kill-server")) { 1548 else if (!strcmp(argv[0], "kill-server")) {
1686 std::string error; 1549 return adb_kill_server() ? 0 : 1;
1687 int fd = _adb_connect("host:kill", &error);
1688 if (fd == -2) {
1689 // Failed to make network connection to server. Don't output the
1690 // network error since that is expected.
1691 fprintf(stderr,"* server not running *\n");
1692 // Successful exit code because the server is already "killed".
1693 return 0;
1694 } else if (fd == -1) {
1695 // Some other error.
1696 fprintf(stderr, "error: %s\n", error.c_str());
1697 return 1;
1698 } else {
1699 // Successfully connected, kill command sent, okay status came back.
1700 // Server should exit() in a moment, if not already.
1701 ReadOrderlyShutdown(fd);
1702 adb_close(fd);
1703 return 0;
1704 }
1705 } 1550 }
1706 else if (!strcmp(argv[0], "sideload")) { 1551 else if (!strcmp(argv[0], "sideload")) {
1707 if (argc != 2) return usage("sideload requires an argument"); 1552 if (argc != 2) return syntax_error("sideload requires an argument");
1708 if (adb_sideload_host(argv[1])) { 1553 if (adb_sideload_host(argv[1])) {
1709 return 1; 1554 return 1;
1710 } else { 1555 } else {
@@ -1738,7 +1583,7 @@ int adb_commandline(int argc, const char** argv) {
1738 bool reverse = !strcmp(argv[0], "reverse"); 1583 bool reverse = !strcmp(argv[0], "reverse");
1739 ++argv; 1584 ++argv;
1740 --argc; 1585 --argc;
1741 if (argc < 1) return usage("%s requires an argument", argv[0]); 1586 if (argc < 1) return syntax_error("%s requires an argument", argv[0]);
1742 1587
1743 // Determine the <host-prefix> for this command. 1588 // Determine the <host-prefix> for this command.
1744 std::string host_prefix; 1589 std::string host_prefix;
@@ -1758,24 +1603,24 @@ int adb_commandline(int argc, const char** argv) {
1758 1603
1759 std::string cmd, error; 1604 std::string cmd, error;
1760 if (strcmp(argv[0], "--list") == 0) { 1605 if (strcmp(argv[0], "--list") == 0) {
1761 if (argc != 1) return usage("--list doesn't take any arguments"); 1606 if (argc != 1) return syntax_error("--list doesn't take any arguments");
1762 return adb_query_command(host_prefix + ":list-forward"); 1607 return adb_query_command(host_prefix + ":list-forward");
1763 } else if (strcmp(argv[0], "--remove-all") == 0) { 1608 } else if (strcmp(argv[0], "--remove-all") == 0) {
1764 if (argc != 1) return usage("--remove-all doesn't take any arguments"); 1609 if (argc != 1) return syntax_error("--remove-all doesn't take any arguments");
1765 cmd = host_prefix + ":killforward-all"; 1610 cmd = host_prefix + ":killforward-all";
1766 } else if (strcmp(argv[0], "--remove") == 0) { 1611 } else if (strcmp(argv[0], "--remove") == 0) {
1767 // forward --remove <local> 1612 // forward --remove <local>
1768 if (argc != 2) return usage("--remove requires an argument"); 1613 if (argc != 2) return syntax_error("--remove requires an argument");
1769 cmd = host_prefix + ":killforward:" + argv[1]; 1614 cmd = host_prefix + ":killforward:" + argv[1];
1770 } else if (strcmp(argv[0], "--no-rebind") == 0) { 1615 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1771 // forward --no-rebind <local> <remote> 1616 // forward --no-rebind <local> <remote>
1772 if (argc != 3) return usage("--no-rebind takes two arguments"); 1617 if (argc != 3) return syntax_error("--no-rebind takes two arguments");
1773 if (forward_targets_are_valid(argv[1], argv[2], &error)) { 1618 if (forward_targets_are_valid(argv[1], argv[2], &error)) {
1774 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2]; 1619 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2];
1775 } 1620 }
1776 } else { 1621 } else {
1777 // forward <local> <remote> 1622 // forward <local> <remote>
1778 if (argc != 2) return usage("forward takes two arguments"); 1623 if (argc != 2) return syntax_error("forward takes two arguments");
1779 if (forward_targets_are_valid(argv[0], argv[1], &error)) { 1624 if (forward_targets_are_valid(argv[0], argv[1], &error)) {
1780 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1]; 1625 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
1781 } 1626 }
@@ -1804,7 +1649,7 @@ int adb_commandline(int argc, const char** argv) {
1804 } 1649 }
1805 /* do_sync_*() commands */ 1650 /* do_sync_*() commands */
1806 else if (!strcmp(argv[0], "ls")) { 1651 else if (!strcmp(argv[0], "ls")) {
1807 if (argc != 2) return usage("ls requires an argument"); 1652 if (argc != 2) return syntax_error("ls requires an argument");
1808 return do_sync_ls(argv[1]) ? 0 : 1; 1653 return do_sync_ls(argv[1]) ? 0 : 1;
1809 } 1654 }
1810 else if (!strcmp(argv[0], "push")) { 1655 else if (!strcmp(argv[0], "push")) {
@@ -1813,7 +1658,7 @@ int adb_commandline(int argc, const char** argv) {
1813 const char* dst = nullptr; 1658 const char* dst = nullptr;
1814 1659
1815 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs); 1660 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
1816 if (srcs.empty() || !dst) return usage("push requires an argument"); 1661 if (srcs.empty() || !dst) return syntax_error("push requires an argument");
1817 return do_sync_push(srcs, dst) ? 0 : 1; 1662 return do_sync_push(srcs, dst) ? 0 : 1;
1818 } 1663 }
1819 else if (!strcmp(argv[0], "pull")) { 1664 else if (!strcmp(argv[0], "pull")) {
@@ -1822,22 +1667,22 @@ int adb_commandline(int argc, const char** argv) {
1822 const char* dst = "."; 1667 const char* dst = ".";
1823 1668
1824 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs); 1669 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
1825 if (srcs.empty()) return usage("pull requires an argument"); 1670 if (srcs.empty()) return syntax_error("pull requires an argument");
1826 return do_sync_pull(srcs, dst, copy_attrs) ? 0 : 1; 1671 return do_sync_pull(srcs, dst, copy_attrs) ? 0 : 1;
1827 } 1672 }
1828 else if (!strcmp(argv[0], "install")) { 1673 else if (!strcmp(argv[0], "install")) {
1829 if (argc < 2) return usage("install requires an argument"); 1674 if (argc < 2) return syntax_error("install requires an argument");
1830 if (_use_legacy_install()) { 1675 if (_use_legacy_install()) {
1831 return install_app_legacy(transport_type, serial, argc, argv); 1676 return install_app_legacy(transport_type, serial, argc, argv);
1832 } 1677 }
1833 return install_app(transport_type, serial, argc, argv); 1678 return install_app(transport_type, serial, argc, argv);
1834 } 1679 }
1835 else if (!strcmp(argv[0], "install-multiple")) { 1680 else if (!strcmp(argv[0], "install-multiple")) {
1836 if (argc < 2) return usage("install-multiple requires an argument"); 1681 if (argc < 2) return syntax_error("install-multiple requires an argument");
1837 return install_multiple_app(transport_type, serial, argc, argv); 1682 return install_multiple_app(transport_type, serial, argc, argv);
1838 } 1683 }
1839 else if (!strcmp(argv[0], "uninstall")) { 1684 else if (!strcmp(argv[0], "uninstall")) {
1840 if (argc < 2) return usage("uninstall requires an argument"); 1685 if (argc < 2) return syntax_error("uninstall requires an argument");
1841 if (_use_legacy_install()) { 1686 if (_use_legacy_install()) {
1842 return uninstall_app_legacy(transport_type, serial, argc, argv); 1687 return uninstall_app_legacy(transport_type, serial, argc, argv);
1843 } 1688 }
@@ -1860,12 +1705,14 @@ int adb_commandline(int argc, const char** argv) {
1860 // A local path or "android"/"data" arg was specified. 1705 // A local path or "android"/"data" arg was specified.
1861 src = argv[1]; 1706 src = argv[1];
1862 } else { 1707 } else {
1863 return usage("usage: adb sync [-l] [PARTITION]"); 1708 return syntax_error("adb sync [-l] [PARTITION]");
1864 } 1709 }
1865 1710
1711 if (src == "all") src = "";
1712
1866 if (src != "" && 1713 if (src != "" &&
1867 src != "system" && src != "data" && src != "vendor" && src != "oem") { 1714 src != "system" && src != "data" && src != "vendor" && src != "oem") {
1868 return usage("don't know how to sync %s partition", src.c_str()); 1715 return syntax_error("don't know how to sync %s partition", src.c_str());
1869 } 1716 }
1870 1717
1871 std::string system_src_path = product_file("system"); 1718 std::string system_src_path = product_file("system");
@@ -1917,7 +1764,7 @@ int adb_commandline(int argc, const char** argv) {
1917 return restore(argc, argv); 1764 return restore(argc, argv);
1918 } 1765 }
1919 else if (!strcmp(argv[0], "keygen")) { 1766 else if (!strcmp(argv[0], "keygen")) {
1920 if (argc != 2) return usage("keygen requires an argument"); 1767 if (argc != 2) return syntax_error("keygen requires an argument");
1921 // Always print key generation information for keygen command. 1768 // Always print key generation information for keygen command.
1922 adb_trace_enable(AUTH); 1769 adb_trace_enable(AUTH);
1923 return adb_auth_keygen(argv[1]); 1770 return adb_auth_keygen(argv[1]);
@@ -1960,7 +1807,7 @@ int adb_commandline(int argc, const char** argv) {
1960 return adb_query_command("host:host-features"); 1807 return adb_query_command("host:host-features");
1961 } else if (!strcmp(argv[0], "reconnect")) { 1808 } else if (!strcmp(argv[0], "reconnect")) {
1962 if (argc == 1) { 1809 if (argc == 1) {
1963 return adb_query_command("host:reconnect"); 1810 return adb_query_command(format_host_command(argv[0], transport_type, serial));
1964 } else if (argc == 2) { 1811 } else if (argc == 2) {
1965 if (!strcmp(argv[1], "device")) { 1812 if (!strcmp(argv[1], "device")) {
1966 std::string err; 1813 std::string err;
@@ -1970,12 +1817,12 @@ int adb_commandline(int argc, const char** argv) {
1970 std::string err; 1817 std::string err;
1971 return adb_query_command("host:reconnect-offline"); 1818 return adb_query_command("host:reconnect-offline");
1972 } else { 1819 } else {
1973 return usage("usage: adb reconnect [device|offline]"); 1820 return syntax_error("adb reconnect [device|offline]");
1974 } 1821 }
1975 } 1822 }
1976 } 1823 }
1977 1824
1978 usage("unknown command %s", argv[0]); 1825 syntax_error("unknown command %s", argv[0]);
1979 return 1; 1826 return 1;
1980} 1827}
1981 1828
@@ -2002,19 +1849,18 @@ static int install_app(TransportType transport, const char* serial, int argc, co
2002 // The last argument must be the APK file 1849 // The last argument must be the APK file
2003 const char* file = argv[argc - 1]; 1850 const char* file = argv[argc - 1];
2004 if (!android::base::EndsWithIgnoreCase(file, ".apk")) { 1851 if (!android::base::EndsWithIgnoreCase(file, ".apk")) {
2005 fprintf(stderr, "Filename doesn't end .apk: %s\n", file); 1852 return syntax_error("filename doesn't end .apk: %s", file);
2006 return EXIT_FAILURE;
2007 } 1853 }
2008 1854
2009 struct stat sb; 1855 struct stat sb;
2010 if (stat(file, &sb) == -1) { 1856 if (stat(file, &sb) == -1) {
2011 fprintf(stderr, "Failed to stat %s: %s\n", file, strerror(errno)); 1857 fprintf(stderr, "adb: failed to stat %s: %s\n", file, strerror(errno));
2012 return 1; 1858 return 1;
2013 } 1859 }
2014 1860
2015 int localFd = adb_open(file, O_RDONLY); 1861 int localFd = adb_open(file, O_RDONLY);
2016 if (localFd < 0) { 1862 if (localFd < 0) {
2017 fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno)); 1863 fprintf(stderr, "adb: failed to open %s: %s\n", file, strerror(errno));
2018 return 1; 1864 return 1;
2019 } 1865 }
2020 1866
@@ -2032,7 +1878,7 @@ static int install_app(TransportType transport, const char* serial, int argc, co
2032 1878
2033 int remoteFd = adb_connect(cmd, &error); 1879 int remoteFd = adb_connect(cmd, &error);
2034 if (remoteFd < 0) { 1880 if (remoteFd < 0) {
2035 fprintf(stderr, "Connect error for write: %s\n", error.c_str()); 1881 fprintf(stderr, "adb: connect error for write: %s\n", error.c_str());
2036 adb_close(localFd); 1882 adb_close(localFd);
2037 return 1; 1883 return 1;
2038 } 1884 }
@@ -2044,12 +1890,12 @@ static int install_app(TransportType transport, const char* serial, int argc, co
2044 adb_close(localFd); 1890 adb_close(localFd);
2045 adb_close(remoteFd); 1891 adb_close(remoteFd);
2046 1892
2047 if (strncmp("Success", buf, 7)) { 1893 if (!strncmp("Success", buf, 7)) {
2048 fprintf(stderr, "Failed to install %s: %s", file, buf); 1894 fputs(buf, stdout);
2049 return 1; 1895 return 0;
2050 } 1896 }
2051 fputs(buf, stderr); 1897 fprintf(stderr, "adb: failed to install %s: %s", file, buf);
2052 return 0; 1898 return 1;
2053} 1899}
2054 1900
2055static int install_multiple_app(TransportType transport, const char* serial, int argc, 1901static int install_multiple_app(TransportType transport, const char* serial, int argc,
@@ -2071,10 +1917,7 @@ static int install_multiple_app(TransportType transport, const char* serial, int
2071 } 1917 }
2072 } 1918 }