blob: 2823cbaf6cd5697e2dfb00afdcf050ad9fe7455d [file] [log] [blame]
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG ADB
Dan Albertdb6fe642015-03-19 15:21:08 -070018
19#include "sysdeps.h"
20
Dan Albertb302d122015-02-24 15:51:19 -080021#include <assert.h>
22#include <ctype.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080023#include <errno.h>
Elliott Hughesd1a5b2b2015-04-17 14:07:52 -070024#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <limits.h>
26#include <stdarg.h>
Dan Albertb302d122015-02-24 15:51:19 -080027#include <stdint.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080031#include <sys/stat.h>
Dan Albertb302d122015-02-24 15:51:19 -080032#include <sys/types.h>
Joshua Duong290ccb52019-11-20 14:18:43 -080033#include <iostream>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080034
David Pursell8a5a5aa2015-09-08 17:17:02 -070035#include <memory>
Elliott Hughes170b5682015-04-17 10:59:34 -070036#include <string>
Elliott Hughes73925982016-11-15 12:37:32 -080037#include <thread>
Josh Gao5d093b22015-10-30 16:57:19 -070038#include <vector>
Elliott Hughes170b5682015-04-17 10:59:34 -070039
Elliott Hughese0a6e2a2016-05-26 22:43:19 -070040#include <android-base/file.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080041#include <android-base/logging.h>
Tao Wucaedcb52016-09-16 13:01:24 -070042#include <android-base/parseint.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080043#include <android-base/stringprintf.h>
44#include <android-base/strings.h>
Elliott Hughes170b5682015-04-17 10:59:34 -070045
Yabin Cui6704a3c2014-11-17 14:48:25 -080046#if !defined(_WIN32)
Elliott Hughes4c5e8042015-11-04 13:07:47 -080047#include <sys/ioctl.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080048#include <termios.h>
Lee Shombertb796cd52022-03-22 12:19:06 -070049#else
50#define _POSIX
51#include <signal.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080052#endif
53
Shukang Zhou420ad552020-02-13 17:01:39 -080054#include <google/protobuf/text_format.h>
55
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080056#include "adb.h"
Nick Kralevich6183c962014-11-13 15:17:29 -080057#include "adb_auth.h"
Dan Albert66a91b02015-02-24 21:26:58 -080058#include "adb_client.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000059#include "adb_install.h"
Dan Albert66a91b02015-02-24 21:26:58 -080060#include "adb_io.h"
Josh Gaoea7457b2016-08-30 15:39:25 -070061#include "adb_unique_fd.h"
Elliott Hughes38104452015-04-17 13:57:15 -070062#include "adb_utils.h"
Shukang Zhou420ad552020-02-13 17:01:39 -080063#include "app_processes.pb.h"
Felipe Leme042c3512016-07-19 17:07:22 -070064#include "bugreport.h"
Josh Gaoc7b74592018-07-25 15:55:25 -070065#include "client/file_sync_client.h"
Felipe Leme042c3512016-07-19 17:07:22 -070066#include "commandline.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000067#include "fastdeploy.h"
Alex Buynytskyy175ce292020-02-13 06:52:04 -080068#include "incremental_server.h"
David Pursell22fc5e92015-09-30 13:35:42 -070069#include "services.h"
Josh Gao076b5ba2018-07-25 16:07:26 -070070#include "shell_protocol.h"
Josh Gao70267e42016-11-15 18:55:47 -080071#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080072
Matt Gumbel411775c2012-11-14 10:16:17 -080073extern int gListenAll;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080074
Felipe Leme60192aa2016-07-26 12:14:39 -070075DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
76
Elliott Hughes145ac022018-04-03 10:54:39 -070077static std::string product_file(const std::string& file) {
Elliott Hughes314db002017-05-01 11:04:31 -070078 const char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
79 if (ANDROID_PRODUCT_OUT == nullptr) {
Elliott Hughes0119a912018-10-22 17:02:51 -070080 error_exit("product directory not specified; set $ANDROID_PRODUCT_OUT");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080081 }
Elliott Hughes145ac022018-04-03 10:54:39 -070082 return std::string{ANDROID_PRODUCT_OUT} + OS_PATH_SEPARATOR_STR + file;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080083}
84
Elliott Hughes38104452015-04-17 13:57:15 -070085static void help() {
Elliott Hughes687f8b42016-09-28 15:25:47 -070086 fprintf(stdout, "%s\n", adb_version().c_str());
Felipe Lemee4893a22016-07-29 17:57:00 -070087 // clang-format off
Elliott Hughes687f8b42016-09-28 15:25:47 -070088 fprintf(stdout,
89 "global options:\n"
Vince Harron5703eb32021-11-12 12:40:58 -080090 " -a listen on all network interfaces, not just localhost\n"
91 " -d use USB device (error if multiple devices connected)\n"
92 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
93 " -s SERIAL use device with given serial (overrides $ANDROID_SERIAL)\n"
94 " -t ID use device with given transport id\n"
95 " -H name of adb server host [default=localhost]\n"
96 " -P port of adb server [default=5037]\n"
97 " -L SOCKET listen on given socket for adb server"
98 " [default=tcp:localhost:5037]\n"
99 " --one-device SERIAL|USB only allowed with 'start-server' or 'server nodaemon', server"
100 " will only connect to one USB device, specified by a serial number or USB device"
101 " address.\n"
Lee Shombertb796cd52022-03-22 12:19:06 -0700102 " --exit-on-write-error exit if stdout is closed\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800103 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700104 "general commands:\n"
105 " devices [-l] list connected devices (-l for long output)\n"
106 " help show this help message\n"
107 " version show version num\n"
Elliott Hughes52746b02015-06-12 14:26:29 -0700108 "\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800109 "networking:\n"
Joshua Duong290ccb52019-11-20 14:18:43 -0800110 " connect HOST[:PORT] connect to a device via TCP/IP [default port=5555]\n"
111 " disconnect [HOST[:PORT]]\n"
112 " disconnect from given TCP/IP device [default port=5555], or all\n"
Joshua Duong64979d02020-05-05 10:46:17 -0700113 " pair HOST[:PORT] [PAIRING CODE]\n"
114 " pair with a device for secure TCP/IP communication\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700115 " forward --list list all forward socket connections\n"
116 " forward [--no-rebind] LOCAL REMOTE\n"
117 " forward socket connection using:\n"
118 " tcp:<port> (<local> may be \"tcp:0\" to pick any open port)\n"
119 " localabstract:<unix domain socket name>\n"
120 " localreserved:<unix domain socket name>\n"
121 " localfilesystem:<unix domain socket name>\n"
Shaju Mathew93c8e3c2022-07-27 08:19:01 +0000122 " dev:<character device name>\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700123 " jdwp:<process pid> (remote only)\n"
Andrew Walbranebf09dd2021-03-03 18:06:12 +0000124 " vsock:<CID>:<port> (remote only)\n"
Daniel Colascione3e124692019-11-13 17:49:37 -0800125 " acceptfd:<fd> (listen only)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700126 " forward --remove LOCAL remove specific forward socket connection\n"
127 " forward --remove-all remove all forward socket connections\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700128 " reverse --list list all reverse socket connections from device\n"
129 " reverse [--no-rebind] REMOTE LOCAL\n"
130 " reverse socket connection using:\n"
131 " tcp:<port> (<remote> may be \"tcp:0\" to pick any open port)\n"
132 " localabstract:<unix domain socket name>\n"
133 " localreserved:<unix domain socket name>\n"
134 " localfilesystem:<unix domain socket name>\n"
135 " reverse --remove REMOTE remove specific reverse socket connection\n"
136 " reverse --remove-all remove all reverse socket connections from device\n"
Joshua Duonge22e1612020-03-31 10:58:50 -0700137 " mdns check check if mdns discovery is available\n"
Joshua Duong5f63d112020-03-31 08:39:24 -0700138 " mdns services list all discovered services\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800139 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700140 "file transfer:\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700141 " push [--sync] [-z ALGORITHM] [-Z] LOCAL... REMOTE\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700142 " copy local files/directories to device\n"
Dan Albert8449e062017-05-18 22:56:48 -0700143 " --sync: only push files that are newer on the host than the device\n"
Josh Gao8a410a02020-03-30 23:25:16 -0700144 " -n: dry run: push files to device without storing to the filesystem\n"
Elliott Hughes09988782022-02-23 15:33:15 -0800145 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800146 " -Z: disable compression\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700147 " pull [-a] [-z ALGORITHM] [-Z] REMOTE... LOCAL\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700148 " copy files/dirs from device\n"
149 " -a: preserve file timestamp and mode\n"
Elliott Hughes09988782022-02-23 15:33:15 -0800150 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800151 " -Z: disable compression\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700152 " sync [-l] [-z ALGORITHM] [-Z] [all|data|odm|oem|product|system|system_ext|vendor]\n"
Elliott Hughes314db002017-05-01 11:04:31 -0700153 " sync a local build from $ANDROID_PRODUCT_OUT to the device (default all)\n"
Josh Gao8a410a02020-03-30 23:25:16 -0700154 " -n: dry run: push files to device without storing to the filesystem\n"
Elliott Hughesc4b9b972019-07-30 10:32:53 -0700155 " -l: list files that would be copied, but don't copy them\n"
Elliott Hughes09988782022-02-23 15:33:15 -0800156 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800157 " -Z: disable compression\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800158 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700159 "shell:\n"
160 " shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]\n"
161 " run remote shell command (interactive shell if no command given)\n"
162 " -e: choose escape character, or \"none\"; default '~'\n"
163 " -n: don't read from stdin\n"
Elliott Hughes63cb1812019-12-13 16:43:10 -0800164 " -T: disable pty allocation\n"
165 " -t: allocate a pty if on a tty (-tt: force pty allocation)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700166 " -x: disable remote exit codes and stdout/stderr separation\n"
167 " emu COMMAND run emulator console command\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800168 "\n"
Elliott Hughesf8a41042019-01-11 13:50:05 -0800169 "app installation (see also `adb shell cmd package help`):\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700170 " install [-lrtsdg] [--instant] PACKAGE\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700171 " push a single package to the device and install it\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700172 " install-multiple [-lrtsdpg] [--instant] PACKAGE...\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700173 " push multiple APKs to the device for a single package and install them\n"
174 " install-multi-package [-lrtsdpg] [--instant] PACKAGE...\n"
175 " push one or more packages to the device and install them atomically\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700176 " -r: replace existing application\n"
177 " -t: allow test packages\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700178 " -d: allow version code downgrade (debuggable packages only)\n"
179 " -p: partial application install (install-multiple only)\n"
180 " -g: grant all runtime permissions\n"
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700181 " --abi ABI: override platform's default ABI\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700182 " --instant: cause the app to be installed as an ephemeral install app\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000183 " --no-streaming: always push APK to device and invoke Package Manager as separate steps\n"
184 " --streaming: force streaming APK directly into Package Manager\n"
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000185 " --fastdeploy: use fast deploy\n"
186 " --no-fastdeploy: prevent use of fast deploy\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000187 " --force-agent: force update of deployment agent when using fast deploy\n"
188 " --date-check-agent: update deployment agent when local version is newer and using fast deploy\n"
189 " --version-check-agent: update deployment agent when local version has different version code and using fast deploy\n"
190#ifndef _WIN32
191 " --local-agent: locate agent files from local source build (instead of SDK location)\n"
192#endif
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700193 " (See also `adb shell pm help` for more options.)\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000194 //TODO--installlog <filename>
Elliott Hughes687f8b42016-09-28 15:25:47 -0700195 " uninstall [-k] PACKAGE\n"
196 " remove this app package from the device\n"
197 " '-k': keep the data and cache directories\n"
198 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700199 "debugging:\n"
200 " bugreport [PATH]\n"
201 " write bugreport to given PATH [default=bugreport.zip];\n"
202 " if PATH is a directory, the bug report is saved in that directory.\n"
203 " devices that don't support zipped bug reports output to stdout.\n"
204 " jdwp list pids of processes hosting a JDWP transport\n"
205 " logcat show device log (logcat --help for more)\n"
206 "\n"
207 "security:\n"
208 " disable-verity disable dm-verity checking on userdebug builds\n"
209 " enable-verity re-enable dm-verity checking on userdebug builds\n"
210 " keygen FILE\n"
211 " generate adb public/private key; private key stored in FILE,\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700212 "\n"
213 "scripting:\n"
Elliott Hughes3657e9d2020-03-10 16:57:47 -0700214 " wait-for[-TRANSPORT]-STATE...\n"
215 " wait for device to be in a given state\n"
Tao Bao9d6eca52019-04-07 23:24:03 -0700216 " STATE: device, recovery, rescue, sideload, bootloader, or disconnect\n"
Josh Gaob32f5ac2019-02-22 14:01:36 -0800217 " TRANSPORT: usb, local, or any [default=any]\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700218 " get-state print offline | bootloader | device\n"
219 " get-serialno print <serial-number>\n"
220 " get-devpath print <device-path>\n"
David Anderson63b8a452018-11-21 13:43:22 -0800221 " remount [-R]\n"
222 " remount partitions read-write. if a reboot is required, -R will\n"
223 " will automatically reboot the device.\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700224 " reboot [bootloader|recovery|sideload|sideload-auto-reboot]\n"
225 " reboot the device; defaults to booting system image but\n"
226 " supports bootloader and recovery too. sideload reboots\n"
227 " into recovery and automatically starts sideload mode,\n"
228 " sideload-auto-reboot is the same but reboots after sideloading.\n"
229 " sideload OTAPACKAGE sideload the given full OTA package\n"
230 " root restart adbd with root permissions\n"
231 " unroot restart adbd without root permissions\n"
bohua49faa82018-10-24 10:38:33 -0700232 " usb restart adbd listening on USB\n"
233 " tcpip PORT restart adbd listening on TCP on PORT\n"
Tim1b29ed32010-02-16 20:18:29 +0000234 "\n"
Yabin Cuid78ed222016-04-05 13:50:44 -0700235 "internal debugging:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700236 " start-server ensure that there is a server running\n"
237 " kill-server kill the server if it is running\n"
238 " reconnect kick connection from host side to force reconnect\n"
239 " reconnect device kick connection from device side to force reconnect\n"
Yabin Cui3cf1b362017-03-10 16:01:01 -0800240 " reconnect offline reset offline/unauthorized devices to force reconnect\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700241 "\n"
Josh Gao8e7c9722021-06-17 04:19:45 -0700242 "usb:\n"
243 " attach attach a detached USB device\n"
244 " detach detach from a USB device to allow use by other processes\n"
245 ""
Elliott Hughes52746b02015-06-12 14:26:29 -0700246 "environment variables:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700247 " $ADB_TRACE\n"
248 " comma-separated list of debug info to log:\n"
249 " all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp\n"
250 " $ADB_VENDOR_KEYS colon-separated list of keys (files or directories)\n"
251 " $ANDROID_SERIAL serial number to connect to (see -s)\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000252 " $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help)\n"
253 " $ADB_LOCAL_TRANSPORT_MAX_PORT max emulator scan port (default 5585, 16 emus)\n"
Joshua Duong2ed15ac2020-04-23 09:46:12 -0700254 " $ADB_MDNS_AUTO_CONNECT comma-separated list of mdns services to allow auto-connect (default adb-tls-connect)\n"
Fabien Sanglardb75cb862022-12-15 01:54:17 +0000255 "\n"
256 "Online documentation: https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/master/docs/user/adb.1.md\n"
257 "\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000258 );
Felipe Lemee4893a22016-07-29 17:57:00 -0700259 // clang-format on
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800260}
261
Yabin Cui6704a3c2014-11-17 14:48:25 -0800262#if defined(_WIN32)
263
Elliott Hughes6a096932015-04-16 16:47:02 -0700264// Implemented in sysdeps_win32.cpp.
Elliott Hughesa8265792015-11-03 11:18:40 -0800265void stdin_raw_init();
266void stdin_raw_restore();
Yabin Cui6704a3c2014-11-17 14:48:25 -0800267
268#else
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100269static termios g_saved_terminal_state;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800270
Elliott Hughesa8265792015-11-03 11:18:40 -0800271static void stdin_raw_init() {
272 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800273
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100274 termios tio;
Elliott Hughesa8265792015-11-03 11:18:40 -0800275 if (tcgetattr(STDIN_FILENO, &tio)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800276
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100277 cfmakeraw(&tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800278
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100279 // No timeout but request at least one character per read.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800280 tio.c_cc[VTIME] = 0;
281 tio.c_cc[VMIN] = 1;
282
Elliott Hughesa8265792015-11-03 11:18:40 -0800283 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800284}
285
Elliott Hughesa8265792015-11-03 11:18:40 -0800286static void stdin_raw_restore() {
287 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800288}
289#endif
290
Lee Shombertb796cd52022-03-22 12:19:06 -0700291int read_and_dump_protocol(borrowed_fd fd, StandardStreamsCallbackInterface* callback) {
292 int exit_code = 0;
293 std::unique_ptr<ShellProtocol> protocol = std::make_unique<ShellProtocol>(fd);
294 if (!protocol) {
295 LOG(ERROR) << "failed to allocate memory for ShellProtocol object";
296 return 1;
297 }
298 while (protocol->Read()) {
299 if (protocol->id() == ShellProtocol::kIdStdout) {
300 if (!callback->OnStdout(protocol->data(), protocol->data_length())) {
301 exit_code = SIGPIPE + 128;
302 break;
303 }
304 } else if (protocol->id() == ShellProtocol::kIdStderr) {
305 if (!callback->OnStderr(protocol->data(), protocol->data_length())) {
306 exit_code = SIGPIPE + 128;
307 break;
308 }
309 } else if (protocol->id() == ShellProtocol::kIdExit) {
310 // data() returns a char* which doesn't have defined signedness.
311 // Cast to uint8_t to prevent 255 from being sign extended to INT_MIN,
312 // which doesn't get truncated on Windows.
313 exit_code = static_cast<uint8_t>(protocol->data()[0]);
314 }
315 }
316 return exit_code;
317}
318
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700319int read_and_dump(borrowed_fd fd, bool use_shell_protocol,
320 StandardStreamsCallbackInterface* callback) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700321 int exit_code = 0;
Felipe Leme5ad50902016-06-06 16:05:36 -0700322 if (fd < 0) return exit_code;
323
David Pursell8a5a5aa2015-09-08 17:17:02 -0700324 if (use_shell_protocol) {
Lee Shombertb796cd52022-03-22 12:19:06 -0700325 exit_code = read_and_dump_protocol(fd, callback);
326 } else {
327 char raw_buffer[BUFSIZ];
328 char* buffer_ptr = raw_buffer;
329 while (true) {
330 D("read_and_dump(): pre adb_read(fd=%d)", fd.get());
331 int length = adb_read(fd, raw_buffer, sizeof(raw_buffer));
332 D("read_and_dump(): post adb_read(fd=%d): length=%d", fd.get(), length);
333 if (length <= 0) {
334 break;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700335 }
Lee Shombertb796cd52022-03-22 12:19:06 -0700336 if (!callback->OnStdout(buffer_ptr, length)) {
337 break;
Felipe Lemeb6447032016-04-01 17:43:27 -0700338 }
Lee Shombertb796cd52022-03-22 12:19:06 -0700339 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800340 }
David Pursell8a5a5aa2015-09-08 17:17:02 -0700341
Felipe Leme60192aa2016-07-26 12:14:39 -0700342 return callback->Done(exit_code);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800343}
344
Christopher Tatee0e9f562016-07-06 13:22:22 -0700345static void stdinout_raw_prologue(int inFd, int outFd, int& old_stdin_mode, int& old_stdout_mode) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700346 if (inFd == STDIN_FILENO) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800347 stdin_raw_init();
Spencer Lowe7af2d32015-05-22 16:48:31 -0700348#ifdef _WIN32
349 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY);
350 if (old_stdin_mode == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700351 PLOG(FATAL) << "could not set stdin to binary";
Spencer Lowe7af2d32015-05-22 16:48:31 -0700352 }
353#endif
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700354 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800355
Spencer Lowe7af2d32015-05-22 16:48:31 -0700356#ifdef _WIN32
357 if (outFd == STDOUT_FILENO) {
358 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY);
359 if (old_stdout_mode == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700360 PLOG(FATAL) << "could not set stdout to binary";
Spencer Lowe7af2d32015-05-22 16:48:31 -0700361 }
362 }
363#endif
Christopher Tatee0e9f562016-07-06 13:22:22 -0700364}
365
366static void stdinout_raw_epilogue(int inFd, int outFd, int old_stdin_mode, int old_stdout_mode) {
367 if (inFd == STDIN_FILENO) {
368 stdin_raw_restore();
369#ifdef _WIN32
370 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700371 PLOG(FATAL) << "could not restore stdin mode";
Christopher Tatee0e9f562016-07-06 13:22:22 -0700372 }
373#endif
374 }
375
376#ifdef _WIN32
377 if (outFd == STDOUT_FILENO) {
378 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700379 PLOG(FATAL) << "could not restore stdout mode";
Christopher Tatee0e9f562016-07-06 13:22:22 -0700380 }
381 }
382#endif
383}
384
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800385bool copy_to_file(int inFd, int outFd) {
386 bool result = true;
Yurii Zubrytskyie59c1bd2019-06-27 13:47:34 -0700387 std::vector<char> buf(64 * 1024);
Christopher Tatee0e9f562016-07-06 13:22:22 -0700388 int len;
389 long total = 0;
390 int old_stdin_mode = -1;
391 int old_stdout_mode = -1;
392
393 D("copy_to_file(%d -> %d)", inFd, outFd);
394
395 stdinout_raw_prologue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowe7af2d32015-05-22 16:48:31 -0700396
Elliott Hughes7cf35752015-04-17 17:03:59 -0700397 while (true) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700398 if (inFd == STDIN_FILENO) {
Elliott Hughesc3462f42018-09-05 12:13:11 -0700399 len = unix_read(inFd, buf.data(), buf.size());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700400 } else {
Elliott Hughesc3462f42018-09-05 12:13:11 -0700401 len = adb_read(inFd, buf.data(), buf.size());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700402 }
Christopher Tate73779122011-04-21 12:53:28 -0700403 if (len == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700404 D("copy_to_file() : read 0 bytes; exiting");
Christopher Tate73779122011-04-21 12:53:28 -0700405 break;
406 }
407 if (len < 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700408 D("copy_to_file(): read failed: %s", strerror(errno));
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800409 result = false;
Christopher Tate73779122011-04-21 12:53:28 -0700410 break;
411 }
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700412 if (outFd == STDOUT_FILENO) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700413 fwrite(buf.data(), 1, len, stdout);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700414 fflush(stdout);
415 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700416 adb_write(outFd, buf.data(), len);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700417 }
Christopher Tatefba22972011-06-01 17:56:23 -0700418 total += len;
Christopher Tate73779122011-04-21 12:53:28 -0700419 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800420
Christopher Tatee0e9f562016-07-06 13:22:22 -0700421 stdinout_raw_epilogue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowe7af2d32015-05-22 16:48:31 -0700422
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800423 D("copy_to_file() finished with %s after %lu bytes", result ? "success" : "failure", total);
424 return result;
Christopher Tate73779122011-04-21 12:53:28 -0700425}
426
Elliott Hughesa8265792015-11-03 11:18:40 -0800427static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800428 // Old devices can't handle window size changes.
429 if (shell == nullptr) return;
430
Spencer Low55441402015-11-07 17:34:39 -0800431#if defined(_WIN32)
432 struct winsize {
433 unsigned short ws_row;
434 unsigned short ws_col;
435 unsigned short ws_xpixel;
436 unsigned short ws_ypixel;
437 };
438#endif
439
Elliott Hughesa8265792015-11-03 11:18:40 -0800440 winsize ws;
Spencer Low55441402015-11-07 17:34:39 -0800441
442#if defined(_WIN32)
443 // If stdout is redirected to a non-console, we won't be able to get the
444 // console size, but that makes sense.
445 const intptr_t intptr_handle = _get_osfhandle(STDOUT_FILENO);
446 if (intptr_handle == -1) return;
447
448 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
449
450 CONSOLE_SCREEN_BUFFER_INFO info;
451 memset(&info, 0, sizeof(info));
452 if (!GetConsoleScreenBufferInfo(handle, &info)) return;
453
454 memset(&ws, 0, sizeof(ws));
455 // The number of visible rows, excluding offscreen scroll-back rows which are in info.dwSize.Y.
456 ws.ws_row = info.srWindow.Bottom - info.srWindow.Top + 1;
457 // If the user has disabled "Wrap text output on resize", they can make the screen buffer wider
458 // than the window, in which case we should use the width of the buffer.
459 ws.ws_col = info.dwSize.X;
460#else
Elliott Hughesa8265792015-11-03 11:18:40 -0800461 if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
Spencer Low55441402015-11-07 17:34:39 -0800462#endif
Elliott Hughesa8265792015-11-03 11:18:40 -0800463
464 // Send the new window size as human-readable ASCII for debugging convenience.
465 size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
466 ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
467 shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
Elliott Hughesa8265792015-11-03 11:18:40 -0800468}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800469
David Pursell8a5a5aa2015-09-08 17:17:02 -0700470// Used to pass multiple values to the stdin read thread.
471struct StdinReadArgs {
472 int stdin_fd, write_fd;
David Pursell3fe11f62015-10-06 15:30:03 -0700473 bool raw_stdin;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700474 std::unique_ptr<ShellProtocol> protocol;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800475 char escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700476};
477
David Pursell8a5a5aa2015-09-08 17:17:02 -0700478// Loops to read from stdin and push the data to the given FD.
479// The argument should be a pointer to a StdinReadArgs object. This function
480// will take ownership of the object and delete it when finished.
Josh Gao382ea6e2016-02-12 14:31:15 -0800481static void stdin_read_thread_loop(void* x) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700482 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800483
Elliott Hughesa8265792015-11-03 11:18:40 -0800484#if !defined(_WIN32)
485 // Mask SIGTTIN in case we're in a backgrounded process.
Josh Gaof344ecf2015-10-23 15:03:31 -0700486 sigset_t sigset;
487 sigemptyset(&sigset);
488 sigaddset(&sigset, SIGTTIN);
489 pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
490#endif
491
Spencer Low55441402015-11-07 17:34:39 -0800492#if defined(_WIN32)
493 // _get_interesting_input_record_uncached() causes unix_read_interruptible()
494 // to return -1 with errno == EINTR if the window size changes.
495#else
Elliott Hughesa8265792015-11-03 11:18:40 -0800496 // Unblock SIGWINCH for this thread, so our read(2) below will be
497 // interrupted if the window size changes.
498 sigset_t mask;
499 sigemptyset(&mask);
500 sigaddset(&mask, SIGWINCH);
501 pthread_sigmask(SIG_UNBLOCK, &mask, nullptr);
502#endif
503
504 // Set up the initial window size.
505 send_window_size_change(args->stdin_fd, args->protocol);
506
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800507 char raw_buffer[BUFSIZ];
David Pursell8a5a5aa2015-09-08 17:17:02 -0700508 char* buffer_ptr = raw_buffer;
509 size_t buffer_size = sizeof(raw_buffer);
Elliott Hughesa8265792015-11-03 11:18:40 -0800510 if (args->protocol != nullptr) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700511 buffer_ptr = args->protocol->data();
512 buffer_size = args->protocol->data_capacity();
513 }
514
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800515 // If we need to parse escape sequences, make life easy.
516 if (args->raw_stdin && args->escape_char != '\0') {
517 buffer_size = 1;
518 }
519
520 enum EscapeState { kMidFlow, kStartOfLine, kInEscape };
521 EscapeState state = kStartOfLine;
522
Elliott Hughesb628cb12015-08-03 10:38:08 -0700523 while (true) {
Spencer Low55441402015-11-07 17:34:39 -0800524 // Use unix_read_interruptible() rather than adb_read() for stdin.
525 D("stdin_read_thread_loop(): pre unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
526 int r = unix_read_interruptible(args->stdin_fd, buffer_ptr,
527 buffer_size);
Elliott Hughesa8265792015-11-03 11:18:40 -0800528 if (r == -1 && errno == EINTR) {
529 send_window_size_change(args->stdin_fd, args->protocol);
530 continue;
531 }
Spencer Low55441402015-11-07 17:34:39 -0800532 D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
David Pursell3fe11f62015-10-06 15:30:03 -0700533 if (r <= 0) {
534 // Only devices using the shell protocol know to close subprocess
535 // stdin. For older devices we want to just leave the connection
536 // open, otherwise an unpredictable amount of return data could
537 // be lost due to the FD closing before all data has been received.
538 if (args->protocol) {
539 args->protocol->Write(ShellProtocol::kIdCloseStdin, 0);
540 }
541 break;
542 }
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800543 // If we made stdin raw, check input for escape sequences. In
David Pursell3fe11f62015-10-06 15:30:03 -0700544 // this situation signals like Ctrl+C are sent remotely rather than
545 // interpreted locally so this provides an emergency out if the remote
546 // process starts ignoring the signal. SSH also does this, see the
547 // "escape characters" section on the ssh man page for more info.
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800548 if (args->raw_stdin && args->escape_char != '\0') {
549 char ch = buffer_ptr[0];
550 if (ch == args->escape_char) {
551 if (state == kStartOfLine) {
552 state = kInEscape;
553 // Swallow the escape character.
554 continue;
555 } else {
556 state = kMidFlow;
557 }
558 } else {
559 if (state == kInEscape) {
560 if (ch == '.') {
561 fprintf(stderr,"\r\n[ disconnected ]\r\n");
Elliott Hughesa8265792015-11-03 11:18:40 -0800562 stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700563 exit(0);
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800564 } else {
565 // We swallowed an escape character that wasn't part of
566 // a valid escape sequence; time to cough it up.
567 buffer_ptr[0] = args->escape_char;
568 buffer_ptr[1] = ch;
569 ++r;
David Pursell3fe11f62015-10-06 15:30:03 -0700570 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800571 }
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800572 state = (ch == '\n' || ch == '\r') ? kStartOfLine : kMidFlow;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800573 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800574 }
David Pursell8a5a5aa2015-09-08 17:17:02 -0700575 if (args->protocol) {
576 if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) {
577 break;
578 }
579 } else {
580 if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) {
581 break;
582 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800583 }
584 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800585}
586
David Pursell3fe11f62015-10-06 15:30:03 -0700587// Returns a shell service string with the indicated arguments and command.
588static std::string ShellServiceString(bool use_shell_protocol,
589 const std::string& type_arg,
590 const std::string& command) {
591 std::vector<std::string> args;
592 if (use_shell_protocol) {
593 args.push_back(kShellServiceArgShellProtocol);
Elliott Hughes401847e2015-11-18 12:45:48 -0800594
595 const char* terminal_type = getenv("TERM");
596 if (terminal_type != nullptr) {
597 args.push_back(std::string("TERM=") + terminal_type);
598 }
David Pursell3fe11f62015-10-06 15:30:03 -0700599 }
600 if (!type_arg.empty()) {
601 args.push_back(type_arg);
602 }
603
604 // Shell service string can look like: shell[,arg1,arg2,...]:[command].
605 return android::base::StringPrintf("shell%s%s:%s",
606 args.empty() ? "" : ",",
607 android::base::Join(args, ',').c_str(),
608 command.c_str());
609}
610
611// Connects to a shell on the device and read/writes data.
612//
613// Note: currently this function doesn't properly clean up resources; the
614// FD connected to the adb server is never closed and the stdin read thread
615// may never exit.
616//
617// On success returns the remote exit code if |use_shell_protocol| is true,
618// 0 otherwise. On failure returns 1.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800619static int RemoteShell(bool use_shell_protocol, const std::string& type_arg, char escape_char,
620 bool empty_command, const std::string& service_string) {
Josh Gao05012022017-06-16 15:34:34 -0700621 // Old devices can't handle a service string that's longer than MAX_PAYLOAD_V1.
622 // Use |use_shell_protocol| to determine whether to allow a command longer than that.
623 if (service_string.size() > MAX_PAYLOAD_V1 && !use_shell_protocol) {
624 fprintf(stderr, "error: shell command too long\n");
625 return 1;
626 }
627
David Pursell3fe11f62015-10-06 15:30:03 -0700628 // Make local stdin raw if the device allocates a PTY, which happens if:
629 // 1. We are explicitly asking for a PTY shell, or
630 // 2. We don't specify shell type and are starting an interactive session.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800631 bool raw_stdin = (type_arg == kShellServiceArgPty || (type_arg.empty() && empty_command));
David Pursell3fe11f62015-10-06 15:30:03 -0700632
Elliott Hughes04a98c22015-04-29 08:35:59 -0700633 std::string error;
David Pursella07dbad2015-09-22 10:43:08 -0700634 int fd = adb_connect(service_string, &error);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700635 if (fd < 0) {
636 fprintf(stderr,"error: %s\n", error.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800637 return 1;
638 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800639
David Pursell8a5a5aa2015-09-08 17:17:02 -0700640 StdinReadArgs* args = new StdinReadArgs;
641 if (!args) {
642 LOG(ERROR) << "couldn't allocate StdinReadArgs object";
Elliott Hughesd0269c92015-04-21 19:39:52 -0700643 return 1;
644 }
David Pursell3fe11f62015-10-06 15:30:03 -0700645 args->stdin_fd = STDIN_FILENO;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700646 args->write_fd = fd;
David Pursell3fe11f62015-10-06 15:30:03 -0700647 args->raw_stdin = raw_stdin;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800648 args->escape_char = escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700649 if (use_shell_protocol) {
Josh Gaof2a988c2018-03-07 16:51:08 -0800650 args->protocol = std::make_unique<ShellProtocol>(args->write_fd);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700651 }
Elliott Hughesd0269c92015-04-21 19:39:52 -0700652
Elliott Hughesa8265792015-11-03 11:18:40 -0800653 if (raw_stdin) stdin_raw_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800654
Elliott Hughesa8265792015-11-03 11:18:40 -0800655#if !defined(_WIN32)
656 // Ensure our process is notified if the local window size changes.
657 // We use sigaction(2) to ensure that the SA_RESTART flag is not set,
658 // because the whole reason we're sending signals is to unblock the read(2)!
659 // That also means we don't need to do anything in the signal handler:
660 // the side effect of delivering the signal is all we need.
661 struct sigaction sa;
662 memset(&sa, 0, sizeof(sa));
663 sa.sa_handler = [](int) {};
664 sa.sa_flags = 0;
665 sigaction(SIGWINCH, &sa, nullptr);
666
667 // Now block SIGWINCH in this thread (the main thread) and all threads spawned
668 // from it. The stdin read thread will unblock this signal to ensure that it's
669 // the thread that receives the signal.
670 sigset_t mask;
671 sigemptyset(&mask);
672 sigaddset(&mask, SIGWINCH);
673 pthread_sigmask(SIG_BLOCK, &mask, nullptr);
674#endif
675
676 // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
Josh Gao0f3312a2017-04-12 17:00:49 -0700677 std::thread(stdin_read_thread_loop, args).detach();
678 int exit_code = read_and_dump(fd, use_shell_protocol);
Elliott Hughesf2517142015-05-05 13:41:21 -0700679
Elliott Hughesa8265792015-11-03 11:18:40 -0800680 // TODO: properly exit stdin_read_thread_loop and close |fd|.
David Pursell3fe11f62015-10-06 15:30:03 -0700681
Elliott Hughesa8265792015-11-03 11:18:40 -0800682 // TODO: we should probably install signal handlers for this.
683 // TODO: can we use atexit? even on Windows?
684 if (raw_stdin) stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700685
David Pursell8a5a5aa2015-09-08 17:17:02 -0700686 return exit_code;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800687}
688
Josh Gao91d53b52016-01-31 19:12:26 -0800689static int adb_shell(int argc, const char** argv) {
Elliott Hughes02e33782016-10-19 14:47:11 -0700690 enum PtyAllocationMode { kPtyAuto, kPtyNo, kPtyYes, kPtyDefinitely };
691
692 // Defaults.
Josh Gao291733b2020-04-16 19:34:43 -0700693 char escape_char = '~'; // -e
Shaju Mathewbf7da1c2021-10-30 13:47:11 -0700694 auto&& features = adb_get_feature_set_or_die();
Josh Gao291733b2020-04-16 19:34:43 -0700695 bool use_shell_protocol = CanUseFeature(*features, kFeatureShell2); // -x
Elliott Hughes02e33782016-10-19 14:47:11 -0700696 PtyAllocationMode tty = use_shell_protocol ? kPtyAuto : kPtyDefinitely; // -t/-T
Elliott Hughesda945812015-04-29 12:28:13 -0700697
Elliott Hughesa8265792015-11-03 11:18:40 -0800698 // Parse shell-specific command-line options.
Elliott Hughes02e33782016-10-19 14:47:11 -0700699 argv[0] = "adb shell"; // So getopt(3) error messages start "adb shell".
Huihong Luo323874f2017-08-17 15:23:08 -0700700#ifdef _WIN32
701 // fixes "adb shell -l" crash on Windows, b/37284906
702 __argv = const_cast<char**>(argv);
703#endif
Elliott Hughes02e33782016-10-19 14:47:11 -0700704 optind = 1; // argv[0] is always "shell", so set `optind` appropriately.
705 int opt;
706 while ((opt = getopt(argc, const_cast<char**>(argv), "+e:ntTx")) != -1) {
707 switch (opt) {
708 case 'e':
709 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
Elliott Hughes0119a912018-10-22 17:02:51 -0700710 error_exit("-e requires a single-character argument or 'none'");
Elliott Hughes02e33782016-10-19 14:47:11 -0700711 }
712 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
713 break;
714 case 'n':
715 close_stdin();
716 break;
717 case 'x':
718 // This option basically asks for historical behavior, so set options that
719 // correspond to the historical defaults. This is slightly weird in that -Tx
720 // is fine (because we'll undo the -T) but -xT isn't, but that does seem to
721 // be our least worst choice...
722 use_shell_protocol = false;
723 tty = kPtyDefinitely;
724 escape_char = '~';
725 break;
726 case 't':
727 // Like ssh, -t arguments are cumulative so that multiple -t's
728 // are needed to force a PTY.
729 tty = (tty >= kPtyYes) ? kPtyDefinitely : kPtyYes;
730 break;
731 case 'T':
732 tty = kPtyNo;
733 break;
734 default:
735 // getopt(3) already printed an error message for us.
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800736 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800737 }
Elliott Hughesda945812015-04-29 12:28:13 -0700738 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800739
Elliott Hughes02e33782016-10-19 14:47:11 -0700740 bool is_interactive = (optind == argc);
David Pursell182dc322016-01-27 16:07:52 -0800741
Elliott Hughes02e33782016-10-19 14:47:11 -0700742 std::string shell_type_arg = kShellServiceArgPty;
743 if (tty == kPtyNo) {
744 shell_type_arg = kShellServiceArgRaw;
745 } else if (tty == kPtyAuto) {
746 // If stdin isn't a TTY, default to a raw shell; this lets
747 // things like `adb shell < my_script.sh` work as expected.
748 // Non-interactive shells should also not have a pty.
749 if (!unix_isatty(STDIN_FILENO) || !is_interactive) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800750 shell_type_arg = kShellServiceArgRaw;
Elliott Hughes02e33782016-10-19 14:47:11 -0700751 }
752 } else if (tty == kPtyYes) {
753 // A single -t arg isn't enough to override implicit -T.
754 if (!unix_isatty(STDIN_FILENO)) {
755 fprintf(stderr,
756 "Remote PTY will not be allocated because stdin is not a terminal.\n"
757 "Use multiple -t options to force remote PTY allocation.\n");
758 shell_type_arg = kShellServiceArgRaw;
759 }
760 }
761
762 D("shell -e 0x%x t=%d use_shell_protocol=%s shell_type_arg=%s\n",
763 escape_char, tty,
764 use_shell_protocol ? "true" : "false",
765 (shell_type_arg == kShellServiceArgPty) ? "pty" : "raw");
766
767 // Raw mode is only supported when talking to a new device *and* using the shell protocol.
768 if (!use_shell_protocol) {
769 if (shell_type_arg != kShellServiceArgPty) {
770 fprintf(stderr, "error: %s only supports allocating a pty\n",
Josh Gao291733b2020-04-16 19:34:43 -0700771 !CanUseFeature(*features, kFeatureShell2) ? "device" : "-x");
Elliott Hughes02e33782016-10-19 14:47:11 -0700772 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800773 } else {
Elliott Hughes02e33782016-10-19 14:47:11 -0700774 // If we're not using the shell protocol, the type argument must be empty.
775 shell_type_arg = "";
Elliott Hughesa8265792015-11-03 11:18:40 -0800776 }
David Purselle570b982015-09-14 15:33:50 -0700777 }
Elliott Hughesa8265792015-11-03 11:18:40 -0800778
779 std::string command;
Elliott Hughes02e33782016-10-19 14:47:11 -0700780 if (optind < argc) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800781 // We don't escape here, just like ssh(1). http://b/20564385.
Elliott Hughes02e33782016-10-19 14:47:11 -0700782 command = android::base::Join(std::vector<const char*>(argv + optind, argv + argc), ' ');
Elliott Hughesa8265792015-11-03 11:18:40 -0800783 }
784
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800785 std::string service_string = ShellServiceString(use_shell_protocol, shell_type_arg, command);
786 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command.empty(),
787 service_string);
788}
789
790static int adb_abb(int argc, const char** argv) {
Shaju Mathewbf7da1c2021-10-30 13:47:11 -0700791 auto&& features = adb_get_feature_set_or_die();
Josh Gao291733b2020-04-16 19:34:43 -0700792 if (!CanUseFeature(*features, kFeatureAbb)) {
Alex Buynytskyye1fa8142019-01-17 13:13:56 -0800793 error_exit("abb is not supported by the device");
794 }
795
Alex Buynytskyyee1221d2019-06-27 10:33:54 -0700796 optind = 1; // argv[0] is always "abb", so set `optind` appropriately.
797
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800798 // Defaults.
799 constexpr char escape_char = '~'; // -e
800 constexpr bool use_shell_protocol = true;
801 constexpr auto shell_type_arg = kShellServiceArgRaw;
802 constexpr bool empty_command = false;
803
Alex Buynytskyyee1221d2019-06-27 10:33:54 -0700804 std::vector<const char*> args(argv + optind, argv + argc);
805 std::string service_string = "abb:" + android::base::Join(args, ABB_ARG_DELIMETER);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800806
807 D("abb -e 0x%x [%*.s]\n", escape_char, static_cast<int>(service_string.size()),
808 service_string.data());
809
810 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, empty_command,
811 service_string);
David Purselle570b982015-09-14 15:33:50 -0700812}
813
Josh Gaofff240a2020-01-08 12:39:52 -0800814static int adb_shell_noinput(int argc, const char** argv) {
815#if !defined(_WIN32)
816 unique_fd fd(adb_open("/dev/null", O_RDONLY));
817 CHECK_NE(STDIN_FILENO, fd.get());
818 dup2(fd.get(), STDIN_FILENO);
819#endif
820 return adb_shell(argc, argv);
821}
822
Elliott Hughes9548e562017-05-02 14:31:59 -0700823static int adb_sideload_legacy(const char* filename, int in_fd, int size) {
Elliott Hughes04a98c22015-04-29 08:35:59 -0700824 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -0800825 unique_fd out_fd(adb_connect(android::base::StringPrintf("sideload:%d", size), &error));
Elliott Hughes9548e562017-05-02 14:31:59 -0700826 if (out_fd < 0) {
827 fprintf(stderr, "adb: pre-KitKat sideload connection failed: %s\n", error.c_str());
Doug Zongker6b217ed2012-01-09 14:54:53 -0800828 return -1;
829 }
830
831 int opt = CHUNK_SIZE;
Elliott Hughes9548e562017-05-02 14:31:59 -0700832 opt = adb_setsockopt(out_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
Doug Zongker6b217ed2012-01-09 14:54:53 -0800833
Elliott Hughes9548e562017-05-02 14:31:59 -0700834 char buf[CHUNK_SIZE];
835 int total = size;
836 while (size > 0) {
837 unsigned xfer = (size > CHUNK_SIZE) ? CHUNK_SIZE : size;
838 if (!ReadFdExactly(in_fd, buf, xfer)) {
839 fprintf(stderr, "adb: failed to read data from %s: %s\n", filename, strerror(errno));
Doug Zongker6b217ed2012-01-09 14:54:53 -0800840 return -1;
841 }
Elliott Hughes9548e562017-05-02 14:31:59 -0700842 if (!WriteFdExactly(out_fd, buf, xfer)) {
843 std::string error;
844 adb_status(out_fd, &error);
845 fprintf(stderr, "adb: failed to write data: %s\n", error.c_str());
Elliott Hughes9548e562017-05-02 14:31:59 -0700846 return -1;
847 }
848 size -= xfer;
849 printf("sending: '%s' %4d%% \r", filename, (int)(100LL - ((100LL * size) / (total))));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700850 fflush(stdout);
Doug Zongker6b217ed2012-01-09 14:54:53 -0800851 }
Elliott Hughes96038eb2017-03-21 17:14:18 -0700852 printf("\n");
Doug Zongker6b217ed2012-01-09 14:54:53 -0800853
Elliott Hughes9548e562017-05-02 14:31:59 -0700854 if (!adb_status(out_fd, &error)) {
855 fprintf(stderr, "adb: error response: %s\n", error.c_str());
Doug Zongker6b217ed2012-01-09 14:54:53 -0800856 return -1;
857 }
858
Doug Zongker6b217ed2012-01-09 14:54:53 -0800859 return 0;
860}
861
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700862#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE)
863
Tao Baoe23e6c72019-04-07 23:24:03 -0700864// Connects to the sideload / rescue service on the device (served by minadbd) and sends over the
865// data in an OTA package.
866//
867// It uses a simple protocol as follows.
868//
869// - The connect message includes the total number of bytes in the file and a block size chosen by
870// us.
871//
872// - The other side sends the desired block number as eight decimal digits (e.g. "00000023" for
873// block 23). Blocks are numbered from zero.
874//
875// - We send back the data of the requested block. The last block is likely to be partial; when the
876// last block is requested we only send the part of the block that exists, it's not padded up to
877// the block size.
878//
879// - When the other side sends "DONEDONE" or "FAILFAIL" instead of a block number, we have done all
880// the data transfer.
881//
882static int adb_sideload_install(const char* filename, bool rescue_mode) {
Elliott Hughes65bc2272017-04-18 14:34:16 -0700883 // TODO: use a LinePrinter instead...
Elliott Hughes96038eb2017-03-21 17:14:18 -0700884 struct stat sb;
885 if (stat(filename, &sb) == -1) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700886 fprintf(stderr, "adb: failed to stat file %s: %s\n", filename, strerror(errno));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700887 return -1;
888 }
889 unique_fd package_fd(adb_open(filename, O_RDONLY));
890 if (package_fd == -1) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700891 fprintf(stderr, "adb: failed to open file %s: %s\n", filename, strerror(errno));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700892 return -1;
893 }
894
Tao Baoe23e6c72019-04-07 23:24:03 -0700895 std::string service = android::base::StringPrintf(
896 "%s:%" PRId64 ":%d", rescue_mode ? "rescue-install" : "sideload-host",
897 static_cast<int64_t>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700898 std::string error;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700899 unique_fd device_fd(adb_connect(service, &error));
900 if (device_fd < 0) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700901 fprintf(stderr, "adb: sideload connection failed: %s\n", error.c_str());
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700902
Tao Baoe23e6c72019-04-07 23:24:03 -0700903 if (rescue_mode) {
904 return -1;
905 }
906
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700907 // If this is a small enough package, maybe this is an older device that doesn't
908 // support sideload-host. Try falling back to the older (<= K) sideload method.
909 if (sb.st_size > INT_MAX) {
910 return -1;
911 }
Elliott Hughes9548e562017-05-02 14:31:59 -0700912 fprintf(stderr, "adb: trying pre-KitKat sideload method...\n");
Josh Gao90228a62019-04-25 14:04:57 -0700913 return adb_sideload_legacy(filename, package_fd.get(), static_cast<int>(sb.st_size));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700914 }
915
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700916 int opt = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700917 adb_setsockopt(device_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
918
919 char buf[SIDELOAD_HOST_BLOCK_SIZE];
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700920
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700921 int64_t xfer = 0;
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700922 int last_percent = -1;
Elliott Hughes7cf35752015-04-17 17:03:59 -0700923 while (true) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700924 if (!ReadFdExactly(device_fd, buf, 8)) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700925 fprintf(stderr, "adb: failed to read command: %s\n", strerror(errno));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700926 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700927 }
Elliott Hughesda945812015-04-29 12:28:13 -0700928 buf[8] = '\0';
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700929
xunchang8829d152019-04-22 23:14:28 -0700930 if (strcmp(kMinadbdServicesExitSuccess, buf) == 0 ||
931 strcmp(kMinadbdServicesExitFailure, buf) == 0) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700932 printf("\rTotal xfer: %.2fx%*s\n",
Elliott Hughes96038eb2017-03-21 17:14:18 -0700933 static_cast<double>(xfer) / (sb.st_size ? sb.st_size : 1),
934 static_cast<int>(strlen(filename) + 10), "");
xunchang8829d152019-04-22 23:14:28 -0700935 if (strcmp(kMinadbdServicesExitFailure, buf) == 0) {
Tao Baoe23e6c72019-04-07 23:24:03 -0700936 return 1;
937 }
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700938 return 0;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700939 }
940
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700941 int64_t block = strtoll(buf, nullptr, 10);
942 int64_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
943 if (offset >= static_cast<int64_t>(sb.st_size)) {
944 fprintf(stderr,
945 "adb: failed to read block %" PRId64 " at offset %" PRId64 ", past end %" PRId64
946 "\n",
947 block, offset, static_cast<int64_t>(sb.st_size));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700948 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700949 }
Elliott Hughes96038eb2017-03-21 17:14:18 -0700950
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700951 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700952 if ((offset + SIDELOAD_HOST_BLOCK_SIZE) > static_cast<int64_t>(sb.st_size)) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700953 to_write = sb.st_size - offset;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700954 }
955
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700956 if (adb_lseek(package_fd, offset, SEEK_SET) != offset) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700957 fprintf(stderr, "adb: failed to seek to package block: %s\n", strerror(errno));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700958 return -1;
959 }
960 if (!ReadFdExactly(package_fd, buf, to_write)) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700961 fprintf(stderr, "adb: failed to read package block: %s\n", strerror(errno));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700962 return -1;
963 }
964
965 if (!WriteFdExactly(device_fd, buf, to_write)) {
966 adb_status(device_fd, &error);
Elliott Hughes9548e562017-05-02 14:31:59 -0700967 fprintf(stderr, "adb: failed to write data '%s' *\n", error.c_str());
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700968 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700969 }
970 xfer += to_write;
971
972 // For normal OTA packages, we expect to transfer every byte
973 // twice, plus a bit of overhead (one read during
974 // verification, one read of each byte for installation, plus
975 // extra access to things like the zip central directory).
976 // This estimate of the completion becomes 100% when we've
977 // transferred ~2.13 (=100/47) times the package size.
Elliott Hughes96038eb2017-03-21 17:14:18 -0700978 int percent = static_cast<int>(xfer * 47LL / (sb.st_size ? sb.st_size : 1));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700979 if (percent != last_percent) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700980 printf("\rserving: '%s' (~%d%%) ", filename, percent);
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700981 fflush(stdout);
982 last_percent = percent;
983 }
984 }
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700985}
986
xunchang8829d152019-04-22 23:14:28 -0700987static int adb_wipe_devices() {
988 auto wipe_devices_message_size = strlen(kMinadbdServicesExitSuccess);
989 std::string error;
990 unique_fd fd(adb_connect(
991 android::base::StringPrintf("rescue-wipe:userdata:%zu", wipe_devices_message_size),
992 &error));
993 if (fd < 0) {
994 fprintf(stderr, "adb: wipe device connection failed: %s\n", error.c_str());
995 return 1;
996 }
997
998 std::string message(wipe_devices_message_size, '\0');
999 if (!ReadFdExactly(fd, message.data(), wipe_devices_message_size)) {
1000 fprintf(stderr, "adb: failed to read wipe result: %s\n", strerror(errno));
1001 return 1;
1002 }
1003
1004 if (message == kMinadbdServicesExitSuccess) {
1005 return 0;
1006 }
1007
1008 if (message != kMinadbdServicesExitFailure) {
1009 fprintf(stderr, "adb: got unexpected message from rescue wipe %s\n", message.c_str());
1010 }
1011 return 1;
1012}
1013
Josh Gao4ce212e2019-03-11 15:39:44 -07001014static bool wait_for_device(const char* service,
1015 std::optional<std::chrono::milliseconds> timeout = std::nullopt) {
Josh Gao63cede32016-04-13 12:14:16 -07001016 std::vector<std::string> components = android::base::Split(service, "-");
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001017 if (components.size() < 3) {
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001018 fprintf(stderr, "adb: couldn't parse 'wait-for' command: %s\n", service);
1019 return false;
1020 }
1021
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001022 // If the first thing after "wait-for-" wasn't a TRANSPORT, insert whatever
1023 // the current transport implies.
1024 if (components[2] != "usb" && components[2] != "local" && components[2] != "any") {
1025 TransportType t;
1026 adb_get_transport(&t, nullptr, nullptr);
Josh Gao63cede32016-04-13 12:14:16 -07001027 auto it = components.begin() + 2;
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001028 if (t == kTransportUsb) {
Josh Gao63cede32016-04-13 12:14:16 -07001029 components.insert(it, "usb");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001030 } else if (t == kTransportLocal) {
Josh Gao63cede32016-04-13 12:14:16 -07001031 components.insert(it, "local");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001032 } else {
Josh Gao63cede32016-04-13 12:14:16 -07001033 components.insert(it, "any");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001034 }
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001035 }
1036
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001037 // Stitch it back together and send it over...
Josh Gaob39e4152017-08-16 16:57:01 -07001038 std::string cmd = format_host_command(android::base::Join(components, "-").c_str());
Josh Gao4ce212e2019-03-11 15:39:44 -07001039 if (timeout) {
1040 std::thread([timeout]() {
1041 std::this_thread::sleep_for(*timeout);
1042 fprintf(stderr, "timeout expired while waiting for device\n");
1043 _exit(1);
1044 }).detach();
1045 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001046 return adb_command(cmd);
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001047}
1048
Josh Gaod1d03392016-03-04 15:16:18 -08001049static bool adb_root(const char* command) {
1050 std::string error;
Josh Gaod1d03392016-03-04 15:16:18 -08001051
Josh Gaoff707d32019-02-22 15:20:27 -08001052 TransportId transport_id;
1053 unique_fd fd(adb_connect(&transport_id, android::base::StringPrintf("%s:", command), &error));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001054 if (fd < 0) {
Josh Gaod1d03392016-03-04 15:16:18 -08001055 fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
1056 return false;
1057 }
1058
1059 // Figure out whether we actually did anything.
1060 char buf[256];
1061 char* cur = buf;
1062 ssize_t bytes_left = sizeof(buf);
1063 while (bytes_left > 0) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001064 ssize_t bytes_read = adb_read(fd, cur, bytes_left);
Josh Gaod1d03392016-03-04 15:16:18 -08001065 if (bytes_read == 0) {
1066 break;
1067 } else if (bytes_read < 0) {
1068 fprintf(stderr, "adb: error while reading for %s: %s\n", command, strerror(errno));
1069 return false;
1070 }
1071 cur += bytes_read;
1072 bytes_left -= bytes_read;
1073 }
1074
1075 if (bytes_left == 0) {
1076 fprintf(stderr, "adb: unexpected output length for %s\n", command);
1077 return false;
1078 }
1079
Junyong Sun88dd2462020-01-15 16:34:58 +08001080 fwrite(buf, 1, sizeof(buf) - bytes_left, stdout);
Josh Gaod1d03392016-03-04 15:16:18 -08001081 fflush(stdout);
Josh Gaod1d03392016-03-04 15:16:18 -08001082 if (cur != buf && strstr(buf, "restarting") == nullptr) {
1083 return true;
1084 }
1085
Josh Gaoff707d32019-02-22 15:20:27 -08001086 // Wait for the device to go away.
Josh Gao4ce212e2019-03-11 15:39:44 -07001087 TransportType previous_type;
1088 const char* previous_serial;
1089 TransportId previous_id;
1090 adb_get_transport(&previous_type, &previous_serial, &previous_id);
1091
Josh Gaoff707d32019-02-22 15:20:27 -08001092 adb_set_transport(kTransportAny, nullptr, transport_id);
1093 wait_for_device("wait-for-disconnect");
Josh Gao4ce212e2019-03-11 15:39:44 -07001094
1095 // Wait for the device to come back.
1096 // If we were using a specific transport ID, there's nothing we can wait for.
1097 if (previous_id == 0) {
1098 adb_set_transport(previous_type, previous_serial, 0);
Josh Gao04ef6962020-10-15 18:32:55 -07001099 wait_for_device("wait-for-device", 12000ms);
Josh Gao4ce212e2019-03-11 15:39:44 -07001100 }
1101
Josh Gaod3d9cbf2016-06-16 14:00:09 -07001102 return true;
Josh Gaod1d03392016-03-04 15:16:18 -08001103}
1104
Josh Gaob39e4152017-08-16 16:57:01 -07001105int send_shell_command(const std::string& command, bool disable_shell_protocol,
1106 StandardStreamsCallbackInterface* callback) {
Josh Gaoc2705962019-01-23 15:36:42 -08001107 unique_fd fd;
David Pursell9650d862016-01-21 19:56:50 -08001108 bool use_shell_protocol = false;
1109
Elliott Hughes170b5682015-04-17 10:59:34 -07001110 while (true) {
David Pursell9650d862016-01-21 19:56:50 -08001111 bool attempt_connection = true;
1112
Felipe Leme60192aa2016-07-26 12:14:39 -07001113 // Use shell protocol if it's supported and the caller doesn't explicitly
1114 // disable it.
David Pursell9650d862016-01-21 19:56:50 -08001115 if (!disable_shell_protocol) {
Josh Gao291733b2020-04-16 19:34:43 -07001116 auto&& features = adb_get_feature_set(nullptr);
1117 if (features) {
1118 use_shell_protocol = CanUseFeature(*features, kFeatureShell2);
David Pursell9650d862016-01-21 19:56:50 -08001119 } else {
1120 // Device was unreachable.
1121 attempt_connection = false;
1122 }
Elliott Hughes04a98c22015-04-29 08:35:59 -07001123 }
David Pursell9650d862016-01-21 19:56:50 -08001124
1125 if (attempt_connection) {
1126 std::string error;
1127 std::string service_string = ShellServiceString(use_shell_protocol, "", command);
1128
Josh Gaoc2705962019-01-23 15:36:42 -08001129 fd.reset(adb_connect(service_string, &error));
David Pursell9650d862016-01-21 19:56:50 -08001130 if (fd >= 0) {
1131 break;
1132 }
1133 }
1134
Felipe Leme60192aa2016-07-26 12:14:39 -07001135 fprintf(stderr, "- waiting for device -\n");
Josh Gaob39e4152017-08-16 16:57:01 -07001136 if (!wait_for_device("wait-for-device")) {
Josh Gao6a7e5732016-02-24 15:16:17 -08001137 return 1;
1138 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001139 }
1140
Josh Gaoc2705962019-01-23 15:36:42 -08001141 return read_and_dump(fd.get(), use_shell_protocol, callback);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001142}
1143
Josh Gaob39e4152017-08-16 16:57:01 -07001144static int logcat(int argc, const char** argv) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001145 char* log_tags = getenv("ANDROID_LOG_TAGS");
1146 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001147
David Pursell22fc5e92015-09-30 13:35:42 -07001148 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001149
Jeff Sharkey824d1062014-06-10 11:31:24 -07001150 if (!strcmp(argv[0], "longcat")) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001151 cmd += " -v long";
Christopher Tate7b9b5162011-11-30 13:00:33 -08001152 }
1153
Elliott Hughese4b64792015-04-17 20:11:08 -07001154 --argc;
1155 ++argv;
Elliott Hughes170b5682015-04-17 10:59:34 -07001156 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001157 cmd += " " + escape_arg(*argv++);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001158 }
1159
Elliott Hughes8fa33512018-06-14 10:46:05 -07001160 return send_shell_command(cmd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001161}
1162
Josh Gao90228a62019-04-25 14:04:57 -07001163static void write_zeros(int bytes, borrowed_fd fd) {
Christopher Tatee0e9f562016-07-06 13:22:22 -07001164 int old_stdin_mode = -1;
1165 int old_stdout_mode = -1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001166 std::vector<char> buf(bytes);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001167
Josh Gao90228a62019-04-25 14:04:57 -07001168 D("write_zeros(%d) -> %d", bytes, fd.get());
Christopher Tatee0e9f562016-07-06 13:22:22 -07001169
Josh Gao90228a62019-04-25 14:04:57 -07001170 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001171
1172 if (fd == STDOUT_FILENO) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001173 fwrite(buf.data(), 1, bytes, stdout);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001174 fflush(stdout);
1175 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001176 adb_write(fd, buf.data(), bytes);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001177 }
1178
Josh Gao90228a62019-04-25 14:04:57 -07001179 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001180
1181 D("write_zeros() finished");
Christopher Tatee0e9f562016-07-06 13:22:22 -07001182}
1183
Dan Albertf30d73c2015-02-25 17:51:28 -08001184static int backup(int argc, const char** argv) {
Al Suttonb6326c72019-05-09 16:14:05 +00001185 fprintf(stdout, "WARNING: adb backup is deprecated and may be removed in a future release\n");
1186
Elliott Hughes1c1f7dc2015-08-21 20:31:31 -07001187 const char* filename = "backup.ab";
Christopher Tate73779122011-04-21 12:53:28 -07001188
Christopher Tatefba22972011-06-01 17:56:23 -07001189 /* find, extract, and use any -f argument */
Elliott Hughese4b64792015-04-17 20:11:08 -07001190 for (int i = 1; i < argc; i++) {
Christopher Tatefba22972011-06-01 17:56:23 -07001191 if (!strcmp("-f", argv[i])) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001192 if (i == argc - 1) error_exit("backup -f passed with no filename");
Christopher Tatefba22972011-06-01 17:56:23 -07001193 filename = argv[i+1];
Elliott Hughese4b64792015-04-17 20:11:08 -07001194 for (int j = i+2; j <= argc; ) {
Christopher Tatefba22972011-06-01 17:56:23 -07001195 argv[i++] = argv[j++];
1196 }
1197 argc -= 2;
Yi Kong86e67182018-07-13 18:15:16 -07001198 argv[argc] = nullptr;
Christopher Tatefba22972011-06-01 17:56:23 -07001199 }
Christopher Tate73779122011-04-21 12:53:28 -07001200 }
1201
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001202 // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
1203 // a list of packages is required.
Elliott Hughes0119a912018-10-22 17:02:51 -07001204 if (argc < 2) error_exit("backup either needs a list of packages or -all/-shared");
Christopher Tatecf4f16a2011-08-22 17:12:08 -07001205
Christopher Tate1e9f2392011-12-08 19:04:34 -08001206 adb_unlink(filename);
Josh Gaoc2705962019-01-23 15:36:42 -08001207 unique_fd outFd(adb_creat(filename, 0640));
Christopher Tate73779122011-04-21 12:53:28 -07001208 if (outFd < 0) {
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001209 fprintf(stderr, "adb: backup unable to create file '%s': %s\n", filename, strerror(errno));
1210 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001211 }
1212
Elliott Hughese4b64792015-04-17 20:11:08 -07001213 std::string cmd = "backup:";
1214 --argc;
1215 ++argv;
1216 while (argc-- > 0) {
1217 cmd += " " + escape_arg(*argv++);
Christopher Tate73779122011-04-21 12:53:28 -07001218 }
1219
Yabin Cui815ad882015-09-02 17:44:28 -07001220 D("backup. filename=%s cmd=%s", filename, cmd.c_str());
Elliott Hughes04a98c22015-04-29 08:35:59 -07001221 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001222 unique_fd fd(adb_connect(cmd, &error));
Christopher Tate73779122011-04-21 12:53:28 -07001223 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001224 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001225 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001226 }
1227
Elliott Hughes65bc2272017-04-18 14:34:16 -07001228 fprintf(stdout, "Now unlock your device and confirm the backup operation...\n");
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001229 fflush(stdout);
1230
Josh Gaoc2705962019-01-23 15:36:42 -08001231 copy_to_file(fd.get(), outFd.get());
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001232 return EXIT_SUCCESS;
Christopher Tate73779122011-04-21 12:53:28 -07001233}
1234
Dan Albertf30d73c2015-02-25 17:51:28 -08001235static int restore(int argc, const char** argv) {
Al Suttonb6326c72019-05-09 16:14:05 +00001236 fprintf(stdout, "WARNING: adb restore is deprecated and may be removed in a future release\n");
1237
Piyush Mehrotra7647b662023-02-24 16:40:38 +00001238 if (argc < 2) {
1239 error_exit("usage: adb restore FILENAME [ARG]...");
1240 }
Christopher Tatecf5379b2011-05-17 15:52:54 -07001241
Elliott Hughes04a98c22015-04-29 08:35:59 -07001242 const char* filename = argv[1];
Josh Gaoc2705962019-01-23 15:36:42 -08001243 unique_fd tarFd(adb_open(filename, O_RDONLY));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001244 if (tarFd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001245 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001246 return -1;
1247 }
1248
Piyush Mehrotra7647b662023-02-24 16:40:38 +00001249 std::string cmd = "restore:";
1250 argc -= 2;
1251 argv += 2;
1252 while (argc-- > 0) {
1253 cmd += " " + escape_arg(*argv++);
1254 }
1255
1256 D("restore. filename=%s cmd=%s", filename, cmd.c_str());
1257
Elliott Hughes04a98c22015-04-29 08:35:59 -07001258 std::string error;
Piyush Mehrotra7647b662023-02-24 16:40:38 +00001259 unique_fd fd(adb_connect(cmd, &error));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001260 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001261 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
Christopher Tatecf5379b2011-05-17 15:52:54 -07001262 return -1;
1263 }
1264
Elliott Hughes65bc2272017-04-18 14:34:16 -07001265 fprintf(stdout, "Now unlock your device and confirm the restore operation.\n");
1266 fflush(stdout);
1267
Josh Gaoc2705962019-01-23 15:36:42 -08001268 copy_to_file(tarFd.get(), fd.get());
Christopher Tatecf5379b2011-05-17 15:52:54 -07001269
Christopher Tatee0e9f562016-07-06 13:22:22 -07001270 // Provide an in-band EOD marker in case the archive file is malformed
Josh Gaoc2705962019-01-23 15:36:42 -08001271 write_zeros(512 * 2, fd);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001272
Josh Gao95230e82016-03-04 15:51:03 -08001273 // Wait until the other side finishes, or it'll get sent SIGHUP.
Josh Gaoc2705962019-01-23 15:36:42 -08001274 copy_to_file(fd.get(), STDOUT_FILENO);
Christopher Tatecf5379b2011-05-17 15:52:54 -07001275 return 0;
1276}
1277
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001278static CompressionType parse_compression_type(const std::string& str, bool allow_numbers) {
1279 if (allow_numbers) {
1280 if (str == "0") {
1281 return CompressionType::None;
1282 } else if (str == "1") {
1283 return CompressionType::Any;
1284 }
1285 }
1286
1287 if (str == "any") {
1288 return CompressionType::Any;
1289 } else if (str == "none") {
1290 return CompressionType::None;
1291 }
1292
1293 if (str == "brotli") {
1294 return CompressionType::Brotli;
Josh Gaofb386cc2020-03-26 22:02:03 -07001295 } else if (str == "lz4") {
1296 return CompressionType::LZ4;
Josh Gaobdebc9b2020-05-27 17:52:52 -07001297 } else if (str == "zstd") {
1298 return CompressionType::Zstd;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001299 }
1300
1301 error_exit("unexpected compression type %s", str.c_str());
1302}
1303
Dan Albert8449e062017-05-18 22:56:48 -07001304static void parse_push_pull_args(const char** arg, int narg, std::vector<const char*>* srcs,
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001305 const char** dst, bool* copy_attrs, bool* sync,
Josh Gao8a410a02020-03-30 23:25:16 -07001306 CompressionType* compression, bool* dry_run) {
Josh Gao5d093b22015-10-30 16:57:19 -07001307 *copy_attrs = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001308 if (const char* adb_compression = getenv("ADB_COMPRESSION")) {
1309 *compression = parse_compression_type(adb_compression, true);
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001310 }
Mark Lindner9f9d1452014-03-11 17:55:59 -07001311
Josh Gao5d093b22015-10-30 16:57:19 -07001312 srcs->clear();
1313 bool ignore_flags = false;
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001314 while (narg > 0) {
Josh Gao5d093b22015-10-30 16:57:19 -07001315 if (ignore_flags || *arg[0] != '-') {
1316 srcs->push_back(*arg);
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001317 } else {
Josh Gao5d093b22015-10-30 16:57:19 -07001318 if (!strcmp(*arg, "-p")) {
1319 // Silently ignore for backwards compatibility.
1320 } else if (!strcmp(*arg, "-a")) {
1321 *copy_attrs = true;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001322 } else if (!strcmp(*arg, "-z")) {
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001323 if (narg < 2) {
1324 error_exit("-z requires an argument");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001325 }
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001326 *compression = parse_compression_type(*++arg, false);
1327 --narg;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001328 } else if (!strcmp(*arg, "-Z")) {
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001329 *compression = CompressionType::None;
Josh Gao8a410a02020-03-30 23:25:16 -07001330 } else if (dry_run && !strcmp(*arg, "-n")) {
1331 *dry_run = true;
Dan Albert8449e062017-05-18 22:56:48 -07001332 } else if (!strcmp(*arg, "--sync")) {
1333 if (sync != nullptr) {
1334 *sync = true;
1335 }
Josh Gao5d093b22015-10-30 16:57:19 -07001336 } else if (!strcmp(*arg, "--")) {
1337 ignore_flags = true;
1338 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001339 error_exit("unrecognized option '%s'", *arg);
Josh Gao5d093b22015-10-30 16:57:19 -07001340 }
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001341 }
Mark Lindner9f9d1452014-03-11 17:55:59 -07001342 ++arg;
1343 --narg;
1344 }
1345
Josh Gao5d093b22015-10-30 16:57:19 -07001346 if (srcs->size() > 1) {
1347 *dst = srcs->back();
1348 srcs->pop_back();
Mark Lindner9f9d1452014-03-11 17:55:59 -07001349 }
1350}
1351
Shukang Zhou420ad552020-02-13 17:01:39 -08001352static int adb_connect_command(const std::string& command, TransportId* transport,
1353 StandardStreamsCallbackInterface* callback) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001354 std::string error;
Josh Gao67209db2019-03-14 15:38:02 -07001355 unique_fd fd(adb_connect(transport, command, &error));
Elliott Hughesdabb9742015-05-07 23:37:40 -07001356 if (fd < 0) {
1357 fprintf(stderr, "error: %s\n", error.c_str());
1358 return 1;
Tao Bao0db67642015-03-29 11:22:34 -07001359 }
Shukang Zhou420ad552020-02-13 17:01:39 -08001360 read_and_dump(fd, false, callback);
Elliott Hughesdabb9742015-05-07 23:37:40 -07001361 return 0;
Tao Bao0db67642015-03-29 11:22:34 -07001362}
1363
Shukang Zhou420ad552020-02-13 17:01:39 -08001364static int adb_connect_command(const std::string& command, TransportId* transport = nullptr) {
1365 return adb_connect_command(command, transport, &DEFAULT_STANDARD_STREAMS_CALLBACK);
1366}
1367
1368// A class that prints out human readable form of the protobuf message for "track-app" service
1369// (received in binary format).
1370class TrackAppStreamsCallback : public DefaultStandardStreamsCallback {
1371 public:
1372 TrackAppStreamsCallback() : DefaultStandardStreamsCallback(nullptr, nullptr) {}
1373
1374 // Assume the buffer contains at least 4 bytes of valid data.
Lee Shombertb796cd52022-03-22 12:19:06 -07001375 bool OnStdout(const char* buffer, size_t length) override {
1376 if (length < 4) return true; // Unexpected length received. Do nothing.
Shukang Zhou420ad552020-02-13 17:01:39 -08001377
1378 adb::proto::AppProcesses binary_proto;
1379 // The first 4 bytes are the length of remaining content in hexadecimal format.
1380 binary_proto.ParseFromString(std::string(buffer + 4, length - 4));
1381 char summary[24]; // The following string includes digits and 16 fixed characters.
1382 int written = snprintf(summary, sizeof(summary), "Process count: %d\n",
1383 binary_proto.process_size());
Lee Shombertb796cd52022-03-22 12:19:06 -07001384 if (!OnStream(nullptr, stdout, summary, written, false)) {
1385 return false;
1386 }
Shukang Zhou420ad552020-02-13 17:01:39 -08001387
1388 std::string string_proto;
1389 google::protobuf::TextFormat::PrintToString(binary_proto, &string_proto);
Lee Shombertb796cd52022-03-22 12:19:06 -07001390 return OnStream(nullptr, stdout, string_proto.data(), string_proto.length(), false);
Shukang Zhou420ad552020-02-13 17:01:39 -08001391 }
1392
1393 private:
1394 DISALLOW_COPY_AND_ASSIGN(TrackAppStreamsCallback);
1395};
1396
Josh Gao7b438fa2018-11-16 14:47:59 -08001397static int adb_connect_command_bidirectional(const std::string& command) {
1398 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001399 unique_fd fd(adb_connect(command, &error));
Josh Gao7b438fa2018-11-16 14:47:59 -08001400 if (fd < 0) {
1401 fprintf(stderr, "error: %s\n", error.c_str());
1402 return 1;
1403 }
1404
1405 static constexpr auto forward = [](int src, int sink, bool exit_on_end) {
1406 char buf[4096];
1407 while (true) {
1408 int rc = adb_read(src, buf, sizeof(buf));
1409 if (rc == 0) {
1410 if (exit_on_end) {
1411 exit(0);
1412 } else {
1413 adb_shutdown(sink, SHUT_WR);
1414 }
1415 return;
1416 } else if (rc < 0) {
1417 perror_exit("read failed");
1418 }
1419 if (!WriteFdExactly(sink, buf, rc)) {
1420 perror_exit("write failed");
1421 }
1422 }
1423 };
1424
Josh Gaoc2705962019-01-23 15:36:42 -08001425 std::thread read(forward, fd.get(), STDOUT_FILENO, true);
1426 std::thread write(forward, STDIN_FILENO, fd.get(), false);
Josh Gao7b438fa2018-11-16 14:47:59 -08001427 read.join();
1428 write.join();
Josh Gao7b438fa2018-11-16 14:47:59 -08001429 return 0;
1430}
1431
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07001432const std::optional<FeatureSet>& adb_get_feature_set_or_die(void) {
1433 std::string error;
1434 const std::optional<FeatureSet>& features = adb_get_feature_set(&error);
1435 if (!features) {
1436 error_exit("%s", error.c_str());
1437 }
1438 return features;
1439}
1440
Shaju Mathew3b481e52021-10-28 00:14:04 -07001441// Helper function to handle processing of shell service commands:
Elliott Hughes18056092022-02-18 10:16:38 -08001442// remount, disable/enable-verity. There's only one "feature",
1443// but they were all moved from adbd to external binaries in the
1444// same release.
1445static int process_remount_or_verity_service(const int argc, const char** argv) {
1446 auto&& features = adb_get_feature_set_or_die();
1447 if (CanUseFeature(*features, kFeatureRemountShell)) {
Shaju Mathew3b481e52021-10-28 00:14:04 -07001448 std::vector<const char*> args = {"shell"};
1449 args.insert(args.cend(), argv, argv + argc);
1450 return adb_shell_noinput(args.size(), args.data());
1451 } else if (argc > 1) {
1452 auto command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
1453 return adb_connect_command(command);
1454 } else {
1455 return adb_connect_command(std::string(argv[0]) + ":");
1456 }
1457}
1458
Elliott Hughesda945812015-04-29 12:28:13 -07001459static int adb_query_command(const std::string& command) {
1460 std::string result;
1461 std::string error;
1462 if (!adb_query(command, &result, &error)) {
1463 fprintf(stderr, "error: %s\n", error.c_str());
1464 return 1;
1465 }
1466 printf("%s\n", result.c_str());
1467 return 0;
1468}
1469
Spencer Lowe98825e2015-09-07 16:20:13 -07001470// Disallow stdin, stdout, and stderr.
1471static bool _is_valid_ack_reply_fd(const int ack_reply_fd) {
1472#ifdef _WIN32
1473 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
1474 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) &&
1475 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) &&
1476 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle);
1477#else
1478 return ack_reply_fd > 2;
1479#endif
1480}
1481
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07001482static bool _is_valid_os_fd(int fd) {
Songchun Fandaf826a2020-03-09 11:33:44 -07001483 // Disallow invalid FDs and stdin/out/err as well.
1484 if (fd < 3) {
1485 return false;
1486 }
1487#ifdef _WIN32
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07001488 auto handle = (HANDLE)fd;
Songchun Fandaf826a2020-03-09 11:33:44 -07001489 DWORD info = 0;
1490 if (GetHandleInformation(handle, &info) == 0) {
1491 return false;
1492 }
1493#else
1494 int flags = fcntl(fd, F_GETFD);
1495 if (flags == -1) {
1496 return false;
1497 }
1498#endif
1499 return true;
1500}
1501
Elliott Hughes02e33782016-10-19 14:47:11 -07001502int adb_commandline(int argc, const char** argv) {
Josh Gao4007ab72018-08-10 14:23:43 -07001503 bool no_daemon = false;
1504 bool is_daemon = false;
1505 bool is_server = false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001506 int r;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001507 TransportType transport_type = kTransportAny;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001508 int ack_reply_fd = -1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001509
Elliott Hughes4919c172015-11-18 18:07:48 -08001510#if !defined(_WIN32)
1511 // We'd rather have EPIPE than SIGPIPE.
1512 signal(SIGPIPE, SIG_IGN);
1513#endif
1514
Josh Gaobb4f8602016-08-25 16:00:22 -07001515 const char* server_host_str = nullptr;
1516 const char* server_port_str = nullptr;
1517 const char* server_socket_str = nullptr;
Vince Harron5703eb32021-11-12 12:40:58 -08001518 const char* one_device_str = nullptr;
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001519
Elliott Hughes67943d12015-10-07 14:55:10 -07001520 // We need to check for -d and -e before we look at $ANDROID_SERIAL.
1521 const char* serial = nullptr;
Josh Gaob39e4152017-08-16 16:57:01 -07001522 TransportId transport_id = 0;
Elliott Hughes67943d12015-10-07 14:55:10 -07001523
Riley Andrews03b4b372014-12-05 17:37:24 -08001524 while (argc > 0) {
Josh Gao67209db2019-03-14 15:38:02 -07001525 if (!strcmp(argv[0], "server")) {
Josh Gao4007ab72018-08-10 14:23:43 -07001526 is_server = true;
Josh Gao67209db2019-03-14 15:38:02 -07001527 } else if (!strcmp(argv[0], "nodaemon")) {
Josh Gao4007ab72018-08-10 14:23:43 -07001528 no_daemon = true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001529 } else if (!strcmp(argv[0], "fork-server")) {
1530 /* this is a special flag used only when the ADB client launches the ADB Server */
Josh Gao4007ab72018-08-10 14:23:43 -07001531 is_daemon = true;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001532 } else if (!strcmp(argv[0], "--reply-fd")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001533 if (argc < 2) error_exit("--reply-fd requires an argument");
Siva Velusamya55dbd82015-08-07 10:10:29 -07001534 const char* reply_fd_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001535 --argc;
1536 ++argv;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001537 ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
Spencer Lowe98825e2015-09-07 16:20:13 -07001538 if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001539 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001540 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001541 }
Vince Harron5703eb32021-11-12 12:40:58 -08001542 } else if (!strcmp(argv[0], "--one-device")) {
1543 if (argc < 2) error_exit("--one-device requires an argument");
1544 one_device_str = argv[1];
1545 --argc;
1546 ++argv;
Josh Gaob39e4152017-08-16 16:57:01 -07001547 } else if (!strncmp(argv[0], "-s", 2)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001548 if (isdigit(argv[0][2])) {
1549 serial = argv[0] + 2;
1550 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001551 if (argc < 2 || argv[0][2] != '\0') error_exit("-s requires an argument");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001552 serial = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001553 --argc;
1554 ++argv;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001555 }
Josh Gaob39e4152017-08-16 16:57:01 -07001556 } else if (!strncmp(argv[0], "-t", 2)) {
1557 const char* id;
1558 if (isdigit(argv[0][2])) {
1559 id = argv[0] + 2;
1560 } else {
Josh Gao5531e492021-10-18 16:38:13 -07001561 if (argc < 2 || argv[0][2] != '\0') error_exit("-t requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001562 id = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001563 --argc;
1564 ++argv;
Josh Gaob39e4152017-08-16 16:57:01 -07001565 }
1566 transport_id = strtoll(id, const_cast<char**>(&id), 10);
1567 if (*id != '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001568 error_exit("invalid transport id");
Josh Gaob39e4152017-08-16 16:57:01 -07001569 }
Josh Gao67209db2019-03-14 15:38:02 -07001570 } else if (!strcmp(argv[0], "-d")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001571 transport_type = kTransportUsb;
Josh Gao67209db2019-03-14 15:38:02 -07001572 } else if (!strcmp(argv[0], "-e")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001573 transport_type = kTransportLocal;
Josh Gao67209db2019-03-14 15:38:02 -07001574 } else if (!strcmp(argv[0], "-a")) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001575 gListenAll = 1;
Riley Andrews03b4b372014-12-05 17:37:24 -08001576 } else if (!strncmp(argv[0], "-H", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001577 if (argv[0][2] == '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001578 if (argc < 2) error_exit("-H requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001579 server_host_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001580 --argc;
1581 ++argv;
Matt Gumbel411775c2012-11-14 10:16:17 -08001582 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001583 server_host_str = argv[0] + 2;
Matt Gumbel411775c2012-11-14 10:16:17 -08001584 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001585 } else if (!strncmp(argv[0], "-P", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001586 if (argv[0][2] == '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001587 if (argc < 2) error_exit("-P requires an argument");
Matt Gumbel411775c2012-11-14 10:16:17 -08001588 server_port_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001589 --argc;
1590 ++argv;
Matt Gumbel411775c2012-11-14 10:16:17 -08001591 } else {
1592 server_port_str = argv[0] + 2;
1593 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001594 } else if (!strcmp(argv[0], "-L")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001595 if (argc < 2) error_exit("-L requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001596 server_socket_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001597 --argc;
1598 ++argv;
Lee Shombertb796cd52022-03-22 12:19:06 -07001599 } else if (strcmp(argv[0], "--exit-on-write-error") == 0) {
1600 DEFAULT_STANDARD_STREAMS_CALLBACK.ReturnErrors(true);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001601 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001602 /* out of recognized modifiers and flags */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001603 break;
1604 }
Vince Harron5703eb32021-11-12 12:40:58 -08001605 --argc;
1606 ++argv;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001607 }
1608
Josh Gaobb4f8602016-08-25 16:00:22 -07001609 if ((server_host_str || server_port_str) && server_socket_str) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001610 error_exit("-L is incompatible with -H or -P");
Josh Gaobb4f8602016-08-25 16:00:22 -07001611 }
1612
1613 // If -L, -H, or -P are specified, ignore environment variables.
1614 // Otherwise, prefer ADB_SERVER_SOCKET over ANDROID_ADB_SERVER_ADDRESS/PORT.
Tao Wucaedcb52016-09-16 13:01:24 -07001615 if (!server_host_str && !server_port_str && !server_socket_str) {
1616 server_socket_str = getenv("ADB_SERVER_SOCKET");
Josh Gaobb4f8602016-08-25 16:00:22 -07001617 }
1618
1619 if (!server_socket_str) {
1620 // tcp:1234 and tcp:localhost:1234 are different with -a, so don't default to localhost
1621 server_host_str = server_host_str ? server_host_str : getenv("ANDROID_ADB_SERVER_ADDRESS");
1622
Tao Wucaedcb52016-09-16 13:01:24 -07001623 int server_port = DEFAULT_ADB_PORT;
Josh Gaobb4f8602016-08-25 16:00:22 -07001624 server_port_str = server_port_str ? server_port_str : getenv("ANDROID_ADB_SERVER_PORT");
Tao Wucaedcb52016-09-16 13:01:24 -07001625 if (server_port_str && strlen(server_port_str) > 0) {
1626 if (!android::base::ParseInt(server_port_str, &server_port, 1, 65535)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001627 error_exit(
1628 "$ANDROID_ADB_SERVER_PORT must be a positive number less than 65535: "
1629 "got \"%s\"",
1630 server_port_str);
Tao Wucaedcb52016-09-16 13:01:24 -07001631 }
1632 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001633
1634 int rc;
1635 char* temp;
1636 if (server_host_str) {
Tao Wucaedcb52016-09-16 13:01:24 -07001637 rc = asprintf(&temp, "tcp:%s:%d", server_host_str, server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001638 } else {
Tao Wucaedcb52016-09-16 13:01:24 -07001639 rc = asprintf(&temp, "tcp:%d", server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001640 }
1641 if (rc < 0) {
Elliott Hughese64126b2018-10-19 13:59:44 -07001642 LOG(FATAL) << "failed to allocate server socket specification";
Josh Gaobb4f8602016-08-25 16:00:22 -07001643 }
1644 server_socket_str = temp;
1645 }
1646
Elliott Hughesde7776a2021-12-16 10:49:06 -08001647 bool server_start =
1648 is_daemon || is_server || (argc > 0 && strcmp(argv[0], "start-server") == 0);
Vince Harron5703eb32021-11-12 12:40:58 -08001649 if (one_device_str && !server_start) {
1650 error_exit("--one-device is only allowed when starting a server.");
1651 }
1652
1653 adb_set_one_device(one_device_str);
Josh Gaobb4f8602016-08-25 16:00:22 -07001654 adb_set_socket_spec(server_socket_str);
1655
Elliott Hughes67943d12015-10-07 14:55:10 -07001656 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1657 if (transport_type == kTransportAny && serial == nullptr) {
1658 serial = getenv("ANDROID_SERIAL");
1659 }
1660
Josh Gaob39e4152017-08-16 16:57:01 -07001661 adb_set_transport(transport_type, serial, transport_id);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001662
David 'Digit' Turner6826db62011-01-31 14:23:56 +01001663 if (is_server) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001664 if (no_daemon || is_daemon) {
Spencer Lowb28812f2015-08-08 15:07:07 -07001665 if (is_daemon && (ack_reply_fd == -1)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001666 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001667 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001668 }
Vince Harron5703eb32021-11-12 12:40:58 -08001669 r = adb_server_main(is_daemon, server_socket_str, one_device_str, ack_reply_fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001670 } else {
Vince Harron5703eb32021-11-12 12:40:58 -08001671 r = launch_server(server_socket_str, one_device_str);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001672 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001673 if (r) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001674 fprintf(stderr,"* could not start server *\n");
1675 }
1676 return r;
1677 }
1678
Riley Andrews03b4b372014-12-05 17:37:24 -08001679 if (argc == 0) {
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001680 help();
1681 return 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001682 }
1683
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001684 /* handle wait-for-* prefix */
1685 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001686 const char* service = argv[0];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001687
Josh Gaob39e4152017-08-16 16:57:01 -07001688 if (!wait_for_device(service)) {
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001689 return 1;
1690 }
1691
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001692 // Allow a command to be run after wait-for-device,
1693 // e.g. 'adb wait-for-device shell'.
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001694 if (argc == 1) {
1695 return 0;
1696 }
1697
1698 /* Fall through */
Vince Harron5703eb32021-11-12 12:40:58 -08001699 --argc;
1700 ++argv;
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001701 }
1702
1703 /* adb_connect() commands */
Riley Andrews03b4b372014-12-05 17:37:24 -08001704 if (!strcmp(argv[0], "devices")) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001705 const char *listopt;
Elliott Hughesda945812015-04-29 12:28:13 -07001706 if (argc < 2) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001707 listopt = "";
Elliott Hughesda945812015-04-29 12:28:13 -07001708 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001709 listopt = argv[1];
Elliott Hughesda945812015-04-29 12:28:13 -07001710 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001711 error_exit("adb devices [-l]");
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001712 }
Elliott Hughesda945812015-04-29 12:28:13 -07001713
1714 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
Josh Gao67209db2019-03-14 15:38:02 -07001715 std::string error;
1716 if (!adb_check_server_version(&error)) {
1717 error_exit("failed to check server version: %s", error.c_str());
1718 }
Elliott Hughesda945812015-04-29 12:28:13 -07001719 printf("List of devices attached\n");
1720 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001721 } else if (!strcmp(argv[0], "transport-id")) {
1722 TransportId transport_id;
1723 std::string error;
1724 unique_fd fd(adb_connect(&transport_id, "host:features", &error, true));
1725 if (fd == -1) {
1726 error_exit("%s", error.c_str());
1727 }
1728 printf("%" PRIu64 "\n", transport_id);
1729 return 0;
1730 } else if (!strcmp(argv[0], "connect")) {
Elliott Hughesa5d09032020-01-08 10:02:43 -08001731 if (argc != 2) error_exit("usage: adb connect HOST[:PORT]");
Elliott Hughesda945812015-04-29 12:28:13 -07001732
1733 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1734 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001735 } else if (!strcmp(argv[0], "disconnect")) {
Elliott Hughes14d673e2019-07-30 13:51:03 -07001736 if (argc > 2) error_exit("usage: adb disconnect [HOST[:PORT]]");
Elliott Hughesda945812015-04-29 12:28:13 -07001737
1738 std::string query = android::base::StringPrintf("host:disconnect:%s",
1739 (argc == 2) ? argv[1] : "");
1740 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001741 } else if (!strcmp(argv[0], "abb")) {
1742 return adb_abb(argc, argv);
Joshua Duong290ccb52019-11-20 14:18:43 -08001743 } else if (!strcmp(argv[0], "pair")) {
Joshua Duong64979d02020-05-05 10:46:17 -07001744 if (argc < 2 || argc > 3) error_exit("usage: adb pair HOST[:PORT] [PAIRING CODE]");
Joshua Duong290ccb52019-11-20 14:18:43 -08001745
1746 std::string password;
Joshua Duong64979d02020-05-05 10:46:17 -07001747 if (argc == 2) {
1748 printf("Enter pairing code: ");
1749 fflush(stdout);
1750 if (!std::getline(std::cin, password) || password.empty()) {
1751 error_exit("No pairing code provided");
1752 }
1753 } else {
1754 password = argv[2];
Joshua Duong290ccb52019-11-20 14:18:43 -08001755 }
1756 std::string query =
1757 android::base::StringPrintf("host:pair:%s:%s", password.c_str(), argv[1]);
1758
1759 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001760 } else if (!strcmp(argv[0], "emu")) {
Spencer Low7dc759f2015-05-06 16:13:42 -07001761 return adb_send_emulator_command(argc, argv, serial);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001762 } else if (!strcmp(argv[0], "shell")) {
Josh Gao91d53b52016-01-31 19:12:26 -08001763 return adb_shell(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001764 } else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001765 int exec_in = !strcmp(argv[0], "exec-in");
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001766
Elliott Hughes0119a912018-10-22 17:02:51 -07001767 if (argc < 2) error_exit("usage: adb %s command", argv[0]);
Zach Riggle328870b2016-04-14 17:18:04 -04001768
Elliott Hughes170b5682015-04-17 10:59:34 -07001769 std::string cmd = "exec:";
1770 cmd += argv[1];
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001771 argc -= 2;
1772 argv += 2;
1773 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001774 cmd += " " + escape_arg(*argv++);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001775 }
1776
Elliott Hughes04a98c22015-04-29 08:35:59 -07001777 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001778 unique_fd fd(adb_connect(cmd, &error));
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001779 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001780 fprintf(stderr, "error: %s\n", error.c_str());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001781 return -1;
1782 }
1783
1784 if (exec_in) {
Josh Gaoc2705962019-01-23 15:36:42 -08001785 copy_to_file(STDIN_FILENO, fd.get());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001786 } else {
Josh Gaoc2705962019-01-23 15:36:42 -08001787 copy_to_file(fd.get(), STDOUT_FILENO);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001788 }
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001789 return 0;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001790 } else if (!strcmp(argv[0], "kill-server")) {
Josh Gaoee356a72017-05-08 18:37:17 -07001791 return adb_kill_server() ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001792 } else if (!strcmp(argv[0], "sideload")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001793 if (argc != 2) error_exit("sideload requires an argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001794 if (adb_sideload_install(argv[1], false /* rescue_mode */)) {
Doug Zongker6b217ed2012-01-09 14:54:53 -08001795 return 1;
1796 } else {
1797 return 0;
1798 }
Tao Baoe23e6c72019-04-07 23:24:03 -07001799 } else if (!strcmp(argv[0], "rescue")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001800 // adb rescue getprop
Tao Baoe23e6c72019-04-07 23:24:03 -07001801 // adb rescue getprop <prop>
1802 // adb rescue install <filename>
xunchang8829d152019-04-22 23:14:28 -07001803 // adb rescue wipe userdata
Tao Bao1b11c232019-06-04 14:37:06 -07001804 if (argc < 2) error_exit("rescue requires at least one argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001805 if (!strcmp(argv[1], "getprop")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001806 if (argc == 2) {
1807 return adb_connect_command("rescue-getprop:");
1808 }
1809 if (argc == 3) {
1810 return adb_connect_command(
1811 android::base::StringPrintf("rescue-getprop:%s", argv[2]));
1812 }
1813 error_exit("invalid rescue getprop arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001814 } else if (!strcmp(argv[1], "install")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001815 if (argc != 3) error_exit("rescue install requires two arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001816 if (adb_sideload_install(argv[2], true /* rescue_mode */) != 0) {
1817 return 1;
1818 }
Tao Bao1b11c232019-06-04 14:37:06 -07001819 } else if (!strcmp(argv[1], "wipe")) {
1820 if (argc != 3 || strcmp(argv[2], "userdata") != 0) {
1821 error_exit("invalid rescue wipe arguments");
1822 }
xunchang8829d152019-04-22 23:14:28 -07001823 return adb_wipe_devices();
Tao Baoe23e6c72019-04-07 23:24:03 -07001824 } else {
1825 error_exit("invalid rescue argument");
1826 }
1827 return 0;
Elliott Hughesfa085be2017-08-23 15:42:28 -07001828 } else if (!strcmp(argv[0], "tcpip")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001829 if (argc != 2) error_exit("tcpip requires an argument");
Elliott Hughesfa085be2017-08-23 15:42:28 -07001830 int port;
1831 if (!android::base::ParseInt(argv[1], &port, 1, 65535)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001832 error_exit("tcpip: invalid port: %s", argv[1]);
Elliott Hughesfa085be2017-08-23 15:42:28 -07001833 }
1834 return adb_connect_command(android::base::StringPrintf("tcpip:%d", port));
Shaju Mathew3b481e52021-10-28 00:14:04 -07001835 } else if (!strcmp(argv[0], "remount") || !strcmp(argv[0], "disable-verity") ||
1836 !strcmp(argv[0], "enable-verity")) {
Elliott Hughes18056092022-02-18 10:16:38 -08001837 return process_remount_or_verity_service(argc, argv);
Shaju Mathew3b481e52021-10-28 00:14:04 -07001838 } else if (!strcmp(argv[0], "reboot") || !strcmp(argv[0], "reboot-bootloader") ||
1839 !strcmp(argv[0], "reboot-fastboot") || !strcmp(argv[0], "usb")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001840 std::string command;
Tao Bao0db67642015-03-29 11:22:34 -07001841 if (!strcmp(argv[0], "reboot-bootloader")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001842 command = "reboot:bootloader";
Mark Salyzynd6420432018-08-29 10:44:33 -07001843 } else if (!strcmp(argv[0], "reboot-fastboot")) {
1844 command = "reboot:fastboot";
Tao Bao0db67642015-03-29 11:22:34 -07001845 } else if (argc > 1) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001846 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
Tao Bao0db67642015-03-29 11:22:34 -07001847 } else {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001848 command = android::base::StringPrintf("%s:", argv[0]);
The Android Open Source Project9c753402009-03-13 13:04:37 -07001849 }
Tao Bao0db67642015-03-29 11:22:34 -07001850 return adb_connect_command(command);
Josh Gaod1d03392016-03-04 15:16:18 -08001851 } else if (!strcmp(argv[0], "root") || !strcmp(argv[0], "unroot")) {
1852 return adb_root(argv[0]) ? 0 : 1;
1853 } else if (!strcmp(argv[0], "bugreport")) {
Felipe Leme042c3512016-07-19 17:07:22 -07001854 Bugreport bugreport;
Josh Gaob39e4152017-08-16 16:57:01 -07001855 return bugreport.DoIt(argc, argv);
Felipe Lemeb6447032016-04-01 17:43:27 -07001856 } else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001857 bool reverse = !strcmp(argv[0], "reverse");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001858 --argc;
Elliott Hughes0119a912018-10-22 17:02:51 -07001859 if (argc < 1) error_exit("%s requires an argument", argv[0]);
Josh Gao596f63b2018-07-31 15:36:03 -07001860 ++argv;
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001861
1862 // Determine the <host-prefix> for this command.
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001863 std::string host_prefix;
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001864 if (reverse) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001865 host_prefix = "reverse:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001866 } else {
Josh Gaoed00ae12019-08-06 16:43:34 -07001867 host_prefix = "host:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001868 }
1869
Elliott Hughese64126b2018-10-19 13:59:44 -07001870 std::string cmd, error_message;
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001871 if (strcmp(argv[0], "--list") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001872 if (argc != 1) error_exit("--list doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001873 return adb_query_command(host_prefix + "list-forward");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001874 } else if (strcmp(argv[0], "--remove-all") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001875 if (argc != 1) error_exit("--remove-all doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001876 cmd = "killforward-all";
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001877 } else if (strcmp(argv[0], "--remove") == 0) {
1878 // forward --remove <local>
Elliott Hughes0119a912018-10-22 17:02:51 -07001879 if (argc != 2) error_exit("--remove requires an argument");
Josh Gaoed00ae12019-08-06 16:43:34 -07001880 cmd = std::string("killforward:") + argv[1];
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001881 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1882 // forward --no-rebind <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001883 if (argc != 3) error_exit("--no-rebind takes two arguments");
Elliott Hughese64126b2018-10-19 13:59:44 -07001884 if (forward_targets_are_valid(argv[1], argv[2], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001885 cmd = std::string("forward:norebind:") + argv[1] + ";" + argv[2];
David Pursell19d0c232016-04-07 11:25:48 -07001886 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001887 } else {
1888 // forward <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001889 if (argc != 2) error_exit("forward takes two arguments");
Elliott Hughese64126b2018-10-19 13:59:44 -07001890 if (forward_targets_are_valid(argv[0], argv[1], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001891 cmd = std::string("forward:") + argv[0] + ";" + argv[1];
David Pursell19d0c232016-04-07 11:25:48 -07001892 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001893 }
1894
Elliott Hughese64126b2018-10-19 13:59:44 -07001895 if (!error_message.empty()) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001896 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001897 }
1898
Josh Gaoed00ae12019-08-06 16:43:34 -07001899 unique_fd fd(adb_connect(nullptr, host_prefix + cmd, &error_message, true));
Josh Gaoc2705962019-01-23 15:36:42 -08001900 if (fd < 0 || !adb_status(fd.get(), &error_message)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001901 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001902 }
1903
1904 // Server or device may optionally return a resolved TCP port number.
1905 std::string resolved_port;
Elliott Hughese64126b2018-10-19 13:59:44 -07001906 if (ReadProtocolString(fd, &resolved_port, &error_message) && !resolved_port.empty()) {
David Pursell19d0c232016-04-07 11:25:48 -07001907 printf("%s\n", resolved_port.c_str());
1908 }
1909
1910 ReadOrderlyShutdown(fd);
1911 return 0;
Joshua Duonge22e1612020-03-31 10:58:50 -07001912 } else if (!strcmp(argv[0], "mdns")) {
1913 --argc;
1914 if (argc < 1) error_exit("mdns requires an argument");
1915 ++argv;
1916
1917 std::string error;
1918 if (!adb_check_server_version(&error)) {
1919 error_exit("failed to check server version: %s", error.c_str());
1920 }
1921
1922 std::string query = "host:mdns:";
1923 if (!strcmp(argv[0], "check")) {
1924 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1925 query += "check";
Joshua Duong5f63d112020-03-31 08:39:24 -07001926 } else if (!strcmp(argv[0], "services")) {
1927 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1928 query += "services";
1929 printf("List of discovered mdns services\n");
Joshua Duonge22e1612020-03-31 10:58:50 -07001930 } else {
1931 error_exit("unknown mdns command [%s]", argv[0]);
1932 }
1933
1934 return adb_query_command(query);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001935 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001936 /* do_sync_*() commands */
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001937 else if (!strcmp(argv[0], "ls")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001938 if (argc != 2) error_exit("ls requires an argument");
Elliott Hughesb628cb12015-08-03 10:38:08 -07001939 return do_sync_ls(argv[1]) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001940 } else if (!strcmp(argv[0], "push")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001941 bool copy_attrs = false;
Dan Albert8449e062017-05-18 22:56:48 -07001942 bool sync = false;
Josh Gao8a410a02020-03-30 23:25:16 -07001943 bool dry_run = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001944 CompressionType compression = CompressionType::Any;
Josh Gao5d093b22015-10-30 16:57:19 -07001945 std::vector<const char*> srcs;
1946 const char* dst = nullptr;
Mark Lindner9f9d1452014-03-11 17:55:59 -07001947
Josh Gao8a410a02020-03-30 23:25:16 -07001948 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, &sync, &compression,
1949 &dry_run);
shaju1a0f9152022-10-25 14:54:37 -07001950 if (srcs.empty() || !dst) {
1951 error_exit("push requires <source> and <destination> arguments");
1952 }
1953
Josh Gao8a410a02020-03-30 23:25:16 -07001954 return do_sync_push(srcs, dst, sync, compression, dry_run) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001955 } else if (!strcmp(argv[0], "pull")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001956 bool copy_attrs = false;
Snild Dolkow30e74ac2020-09-23 09:31:50 +02001957 CompressionType compression = CompressionType::None;
Josh Gao5d093b22015-10-30 16:57:19 -07001958 std::vector<const char*> srcs;
1959 const char* dst = ".";
Mark Lindner9f9d1452014-03-11 17:55:59 -07001960
Josh Gao8a410a02020-03-30 23:25:16 -07001961 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, nullptr, &compression,
1962 nullptr);
Elliott Hughes0119a912018-10-22 17:02:51 -07001963 if (srcs.empty()) error_exit("pull requires an argument");
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001964 return do_sync_pull(srcs, dst, copy_attrs, compression) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001965 } else if (!strcmp(argv[0], "install")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001966 if (argc < 2) error_exit("install requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001967 return install_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001968 } else if (!strcmp(argv[0], "install-multiple")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001969 if (argc < 2) error_exit("install-multiple requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001970 return install_multiple_app(argc, argv);
Patrick Baumann810ee9b2018-10-09 10:45:03 -07001971 } else if (!strcmp(argv[0], "install-multi-package")) {
Mohammad Samiul Islamed2e8732019-05-29 15:00:00 +01001972 if (argc < 2) error_exit("install-multi-package requires an argument");
Patrick Baumann810ee9b2018-10-09 10:45:03 -07001973 return install_multi_package(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001974 } else if (!strcmp(argv[0], "uninstall")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001975 if (argc < 2) error_exit("uninstall requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001976 return uninstall_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001977 } else if (!strcmp(argv[0], "sync")) {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001978 std::string src;
Elliott Hughes38104452015-04-17 13:57:15 -07001979 bool list_only = false;
Josh Gao8a410a02020-03-30 23:25:16 -07001980 bool dry_run = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001981 CompressionType compression = CompressionType::Any;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001982
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001983 if (const char* adb_compression = getenv("ADB_COMPRESSION"); adb_compression) {
1984 compression = parse_compression_type(adb_compression, true);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001985 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001986
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001987 int opt;
Josh Gao8a410a02020-03-30 23:25:16 -07001988 while ((opt = getopt(argc, const_cast<char**>(argv), "lnz:Z")) != -1) {
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001989 switch (opt) {
1990 case 'l':
1991 list_only = true;
1992 break;
Josh Gao8a410a02020-03-30 23:25:16 -07001993 case 'n':
1994 dry_run = true;
1995 break;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001996 case 'z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001997 compression = parse_compression_type(optarg, false);
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001998 break;
1999 case 'Z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002000 compression = CompressionType::None;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002001 break;
2002 default:
Josh Gao8a410a02020-03-30 23:25:16 -07002003 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002004 }
2005 }
2006
2007 if (optind == argc) {
2008 src = "all";
2009 } else if (optind + 1 == argc) {
2010 src = argv[optind];
2011 } else {
Josh Gao8a410a02020-03-30 23:25:16 -07002012 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002013 }
2014
Justin Yunb0c201c2019-06-26 09:18:03 +09002015 std::vector<std::string> partitions{"data", "odm", "oem", "product",
2016 "system", "system_ext", "vendor"};
Elliott Hughes145ac022018-04-03 10:54:39 -07002017 bool found = false;
2018 for (const auto& partition : partitions) {
2019 if (src == "all" || src == partition) {
2020 std::string src_dir{product_file(partition)};
2021 if (!directory_exists(src_dir)) continue;
2022 found = true;
Josh Gao8a410a02020-03-30 23:25:16 -07002023 if (!do_sync_sync(src_dir, "/" + partition, list_only, compression, dry_run)) {
2024 return 1;
2025 }
Elliott Hughes145ac022018-04-03 10:54:39 -07002026 }
Elliott Hughes38104452015-04-17 13:57:15 -07002027 }
Elliott Hughes0119a912018-10-22 17:02:51 -07002028 if (!found) error_exit("don't know how to sync %s partition", src.c_str());
Elliott Hughese64126b2018-10-19 13:59:44 -07002029 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002030 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002031 /* passthrough commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002032 else if (!strcmp(argv[0], "get-state") || !strcmp(argv[0], "get-serialno") ||
2033 !strcmp(argv[0], "get-devpath")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002034 return adb_query_command(format_host_command(argv[0]));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002035 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002036 /* other commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002037 else if (!strcmp(argv[0], "logcat") || !strcmp(argv[0], "lolcat") ||
2038 !strcmp(argv[0], "longcat")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002039 return logcat(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002040 } else if (!strcmp(argv[0], "start-server")) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07002041 std::string error;
Spencer Low85ee64b2015-08-11 17:05:02 -07002042 const int result = adb_connect("host:start-server", &error);
2043 if (result < 0) {
2044 fprintf(stderr, "error: %s\n", error.c_str());
2045 }
2046 return result;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002047 } else if (!strcmp(argv[0], "backup")) {
Christopher Tate73779122011-04-21 12:53:28 -07002048 return backup(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002049 } else if (!strcmp(argv[0], "restore")) {
Christopher Tatecf5379b2011-05-17 15:52:54 -07002050 return restore(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002051 } else if (!strcmp(argv[0], "keygen")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002052 if (argc != 2) error_exit("keygen requires an argument");
Yabin Cui19bec5b2015-09-22 15:52:57 -07002053 // Always print key generation information for keygen command.
2054 adb_trace_enable(AUTH);
Nick Kralevich6183c962014-11-13 15:17:29 -08002055 return adb_auth_keygen(argv[1]);
Josh Gao13102c32018-11-15 17:45:46 -08002056 } else if (!strcmp(argv[0], "pubkey")) {
2057 if (argc != 2) error_exit("pubkey requires an argument");
2058 return adb_auth_pubkey(argv[1]);
2059 } else if (!strcmp(argv[0], "jdwp")) {
Tao Bao0db67642015-03-29 11:22:34 -07002060 return adb_connect_command("jdwp");
Josh Gao13102c32018-11-15 17:45:46 -08002061 } else if (!strcmp(argv[0], "track-jdwp")) {
Josh Gao39d01bb2016-05-13 18:18:23 -07002062 return adb_connect_command("track-jdwp");
Shukang Zhou420ad552020-02-13 17:01:39 -08002063 } else if (!strcmp(argv[0], "track-app")) {
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07002064 auto&& features = adb_get_feature_set_or_die();
Josh Gao291733b2020-04-16 19:34:43 -07002065 if (!CanUseFeature(*features, kFeatureTrackApp)) {
Shukang Zhou420ad552020-02-13 17:01:39 -08002066 error_exit("track-app is not supported by the device");
2067 }
2068 TrackAppStreamsCallback callback;
2069 return adb_connect_command("track-app", nullptr, &callback);
Josh Gao13102c32018-11-15 17:45:46 -08002070 } else if (!strcmp(argv[0], "track-devices")) {
Elliott Hughes3d792f42019-07-31 14:13:57 -07002071 if (argc > 2 || (argc == 2 && strcmp(argv[1], "-l"))) {
2072 error_exit("usage: adb track-devices [-l]");
2073 }
2074 return adb_connect_command(argc == 2 ? "host:track-devices-l" : "host:track-devices");
Josh Gaobf5167c2018-06-18 14:51:56 -07002075 } else if (!strcmp(argv[0], "raw")) {
2076 if (argc != 2) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002077 error_exit("usage: adb raw SERVICE");
Josh Gaobf5167c2018-06-18 14:51:56 -07002078 }
Josh Gao7b438fa2018-11-16 14:47:59 -08002079 return adb_connect_command_bidirectional(argv[1]);
Josh Gao39d01bb2016-05-13 18:18:23 -07002080 }
2081
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002082 /* "adb /?" is a common idiom under Windows */
Elliott Hughes97e74bb2017-02-06 16:20:30 -08002083 else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002084 help();
2085 return 0;
Josh Gao13102c32018-11-15 17:45:46 -08002086 } else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
Elliott Hughesb9f01642015-08-12 08:32:10 -07002087 fprintf(stdout, "%s", adb_version().c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002088 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002089 } else if (!strcmp(argv[0], "features")) {
David Pursella07dbad2015-09-22 10:43:08 -07002090 // Only list the features common to both the adb client and the device.
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07002091 auto&& features = adb_get_feature_set_or_die();
David Pursell9650d862016-01-21 19:56:50 -08002092
Josh Gao291733b2020-04-16 19:34:43 -07002093 for (const std::string& name : *features) {
2094 if (CanUseFeature(*features, name)) {
David Pursella07dbad2015-09-22 10:43:08 -07002095 printf("%s\n", name.c_str());
2096 }
2097 }
2098 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002099 } else if (!strcmp(argv[0], "host-features")) {
2100 return adb_query_command("host:host-features");
Yabin Cuid78ed222016-04-05 13:50:44 -07002101 } else if (!strcmp(argv[0], "reconnect")) {
2102 if (argc == 1) {
Josh Gaob39e4152017-08-16 16:57:01 -07002103 return adb_query_command(format_host_command(argv[0]));
Josh Gao4e562502016-10-27 14:01:08 -07002104 } else if (argc == 2) {
2105 if (!strcmp(argv[1], "device")) {
2106 std::string err;
2107 adb_connect("reconnect", &err);
2108 return 0;
2109 } else if (!strcmp(argv[1], "offline")) {
2110 std::string err;
2111 return adb_query_command("host:reconnect-offline");
2112 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07002113 error_exit("usage: adb reconnect [device|offline]");
Josh Gao4e562502016-10-27 14:01:08 -07002114 }
Yabin Cuid78ed222016-04-05 13:50:44 -07002115 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002116 } else if (!strcmp(argv[0], "inc-server")) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002117 if (argc < 4) {
2118#ifdef _WIN32
2119 error_exit("usage: adb inc-server CONNECTION_HANDLE OUTPUT_HANDLE FILE1 FILE2 ...");
2120#else
2121 error_exit("usage: adb inc-server CONNECTION_FD OUTPUT_FD FILE1 FILE2 ...");
2122#endif
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002123 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002124 int connection_fd = atoi(argv[1]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002125 if (!_is_valid_os_fd(connection_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002126 error_exit("Invalid connection_fd number given: %d", connection_fd);
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002127 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002128
2129 connection_fd = adb_register_socket(connection_fd);
2130 close_on_exec(connection_fd);
2131
2132 int output_fd = atoi(argv[2]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002133 if (!_is_valid_os_fd(output_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002134 error_exit("Invalid output_fd number given: %d", output_fd);
2135 }
2136 output_fd = adb_register_socket(output_fd);
2137 close_on_exec(output_fd);
2138 return incremental::serve(connection_fd, output_fd, argc - 3, argv + 3);
Josh Gao8e7c9722021-06-17 04:19:45 -07002139 } else if (!strcmp(argv[0], "attach") || !strcmp(argv[0], "detach")) {
2140 const char* service = strcmp(argv[0], "attach") == 0 ? "host:attach" : "host:detach";
2141 std::string result;
2142 std::string error;
2143 if (!adb_query(service, &result, &error, true)) {
2144 error_exit("failed to %s: %s", argv[0], error.c_str());
2145 }
2146 printf("%s\n", result.c_str());
2147 return 0;
Dan Albert996c12e2015-05-20 18:58:41 -07002148 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002149
Elliott Hughes0119a912018-10-22 17:02:51 -07002150 error_exit("unknown command %s", argv[0]);
Elliott Hughese64126b2018-10-19 13:59:44 -07002151 __builtin_unreachable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002152}