blob: c07be21077cce4cab15d09817046e9d236b62040 [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"
Ryan Prichardc36807b2023-06-21 22:08:16 -070071#include "socket_spec.h"
Josh Gao70267e42016-11-15 18:55:47 -080072#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080073
Felipe Leme60192aa2016-07-26 12:14:39 -070074DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
75
Elliott Hughes145ac022018-04-03 10:54:39 -070076static std::string product_file(const std::string& file) {
Elliott Hughes314db002017-05-01 11:04:31 -070077 const char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
78 if (ANDROID_PRODUCT_OUT == nullptr) {
Elliott Hughes0119a912018-10-22 17:02:51 -070079 error_exit("product directory not specified; set $ANDROID_PRODUCT_OUT");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080080 }
Elliott Hughes145ac022018-04-03 10:54:39 -070081 return std::string{ANDROID_PRODUCT_OUT} + OS_PATH_SEPARATOR_STR + file;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080082}
83
Elliott Hughes38104452015-04-17 13:57:15 -070084static void help() {
Elliott Hughes687f8b42016-09-28 15:25:47 -070085 fprintf(stdout, "%s\n", adb_version().c_str());
Felipe Lemee4893a22016-07-29 17:57:00 -070086 // clang-format off
Elliott Hughes687f8b42016-09-28 15:25:47 -070087 fprintf(stdout,
88 "global options:\n"
Vince Harron5703eb32021-11-12 12:40:58 -080089 " -a listen on all network interfaces, not just localhost\n"
90 " -d use USB device (error if multiple devices connected)\n"
91 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
92 " -s SERIAL use device with given serial (overrides $ANDROID_SERIAL)\n"
93 " -t ID use device with given transport id\n"
94 " -H name of adb server host [default=localhost]\n"
95 " -P port of adb server [default=5037]\n"
96 " -L SOCKET listen on given socket for adb server"
97 " [default=tcp:localhost:5037]\n"
98 " --one-device SERIAL|USB only allowed with 'start-server' or 'server nodaemon', server"
99 " will only connect to one USB device, specified by a serial number or USB device"
100 " address.\n"
Lee Shombertb796cd52022-03-22 12:19:06 -0700101 " --exit-on-write-error exit if stdout is closed\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800102 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700103 "general commands:\n"
104 " devices [-l] list connected devices (-l for long output)\n"
105 " help show this help message\n"
106 " version show version num\n"
Elliott Hughes52746b02015-06-12 14:26:29 -0700107 "\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800108 "networking:\n"
Joshua Duong290ccb52019-11-20 14:18:43 -0800109 " connect HOST[:PORT] connect to a device via TCP/IP [default port=5555]\n"
110 " disconnect [HOST[:PORT]]\n"
111 " disconnect from given TCP/IP device [default port=5555], or all\n"
Joshua Duong64979d02020-05-05 10:46:17 -0700112 " pair HOST[:PORT] [PAIRING CODE]\n"
113 " pair with a device for secure TCP/IP communication\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700114 " forward --list list all forward socket connections\n"
115 " forward [--no-rebind] LOCAL REMOTE\n"
116 " forward socket connection using:\n"
117 " tcp:<port> (<local> may be \"tcp:0\" to pick any open port)\n"
118 " localabstract:<unix domain socket name>\n"
119 " localreserved:<unix domain socket name>\n"
120 " localfilesystem:<unix domain socket name>\n"
Shaju Mathew93c8e3c2022-07-27 08:19:01 +0000121 " dev:<character device name>\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700122 " jdwp:<process pid> (remote only)\n"
Andrew Walbranebf09dd2021-03-03 18:06:12 +0000123 " vsock:<CID>:<port> (remote only)\n"
Daniel Colascione3e124692019-11-13 17:49:37 -0800124 " acceptfd:<fd> (listen only)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700125 " forward --remove LOCAL remove specific forward socket connection\n"
126 " forward --remove-all remove all forward socket connections\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700127 " reverse --list list all reverse socket connections from device\n"
128 " reverse [--no-rebind] REMOTE LOCAL\n"
129 " reverse socket connection using:\n"
130 " tcp:<port> (<remote> may be \"tcp:0\" to pick any open port)\n"
131 " localabstract:<unix domain socket name>\n"
132 " localreserved:<unix domain socket name>\n"
133 " localfilesystem:<unix domain socket name>\n"
134 " reverse --remove REMOTE remove specific reverse socket connection\n"
135 " reverse --remove-all remove all reverse socket connections from device\n"
Joshua Duonge22e1612020-03-31 10:58:50 -0700136 " mdns check check if mdns discovery is available\n"
Joshua Duong5f63d112020-03-31 08:39:24 -0700137 " mdns services list all discovered services\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800138 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700139 "file transfer:\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700140 " push [--sync] [-z ALGORITHM] [-Z] LOCAL... REMOTE\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700141 " copy local files/directories to device\n"
Fergus Hendersonb683bd62024-02-26 09:09:52 +0000142 " --sync: only push files that have different timestamps on the host than the device\n"
Josh Gao8a410a02020-03-30 23:25:16 -0700143 " -n: dry run: push files to device without storing to the filesystem\n"
Elliott Hughes09988782022-02-23 15:33:15 -0800144 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800145 " -Z: disable compression\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700146 " pull [-a] [-z ALGORITHM] [-Z] REMOTE... LOCAL\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700147 " copy files/dirs from device\n"
148 " -a: preserve file timestamp and mode\n"
Elliott Hughes09988782022-02-23 15:33:15 -0800149 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800150 " -Z: disable compression\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700151 " sync [-l] [-z ALGORITHM] [-Z] [all|data|odm|oem|product|system|system_ext|vendor]\n"
Elliott Hughes314db002017-05-01 11:04:31 -0700152 " sync a local build from $ANDROID_PRODUCT_OUT to the device (default all)\n"
Josh Gao8a410a02020-03-30 23:25:16 -0700153 " -n: dry run: push files to device without storing to the filesystem\n"
Elliott Hughesc4b9b972019-07-30 10:32:53 -0700154 " -l: list files that would be copied, but don't copy them\n"
Elliott Hughes09988782022-02-23 15:33:15 -0800155 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800156 " -Z: disable compression\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800157 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700158 "shell:\n"
159 " shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]\n"
160 " run remote shell command (interactive shell if no command given)\n"
161 " -e: choose escape character, or \"none\"; default '~'\n"
162 " -n: don't read from stdin\n"
Elliott Hughes63cb1812019-12-13 16:43:10 -0800163 " -T: disable pty allocation\n"
164 " -t: allocate a pty if on a tty (-tt: force pty allocation)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700165 " -x: disable remote exit codes and stdout/stderr separation\n"
166 " emu COMMAND run emulator console command\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800167 "\n"
Elliott Hughesf8a41042019-01-11 13:50:05 -0800168 "app installation (see also `adb shell cmd package help`):\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700169 " install [-lrtsdg] [--instant] PACKAGE\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700170 " push a single package to the device and install it\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700171 " install-multiple [-lrtsdpg] [--instant] PACKAGE...\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700172 " push multiple APKs to the device for a single package and install them\n"
173 " install-multi-package [-lrtsdpg] [--instant] PACKAGE...\n"
174 " push one or more packages to the device and install them atomically\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700175 " -r: replace existing application\n"
176 " -t: allow test packages\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700177 " -d: allow version code downgrade (debuggable packages only)\n"
178 " -p: partial application install (install-multiple only)\n"
179 " -g: grant all runtime permissions\n"
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700180 " --abi ABI: override platform's default ABI\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700181 " --instant: cause the app to be installed as an ephemeral install app\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000182 " --no-streaming: always push APK to device and invoke Package Manager as separate steps\n"
183 " --streaming: force streaming APK directly into Package Manager\n"
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000184 " --fastdeploy: use fast deploy\n"
185 " --no-fastdeploy: prevent use of fast deploy\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000186 " --force-agent: force update of deployment agent when using fast deploy\n"
187 " --date-check-agent: update deployment agent when local version is newer and using fast deploy\n"
188 " --version-check-agent: update deployment agent when local version has different version code and using fast deploy\n"
189#ifndef _WIN32
190 " --local-agent: locate agent files from local source build (instead of SDK location)\n"
191#endif
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700192 " (See also `adb shell pm help` for more options.)\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000193 //TODO--installlog <filename>
Elliott Hughes687f8b42016-09-28 15:25:47 -0700194 " uninstall [-k] PACKAGE\n"
195 " remove this app package from the device\n"
196 " '-k': keep the data and cache directories\n"
197 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700198 "debugging:\n"
199 " bugreport [PATH]\n"
200 " write bugreport to given PATH [default=bugreport.zip];\n"
201 " if PATH is a directory, the bug report is saved in that directory.\n"
202 " devices that don't support zipped bug reports output to stdout.\n"
203 " jdwp list pids of processes hosting a JDWP transport\n"
204 " logcat show device log (logcat --help for more)\n"
205 "\n"
206 "security:\n"
207 " disable-verity disable dm-verity checking on userdebug builds\n"
208 " enable-verity re-enable dm-verity checking on userdebug builds\n"
209 " keygen FILE\n"
210 " generate adb public/private key; private key stored in FILE,\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700211 "\n"
212 "scripting:\n"
Elliott Hughes3657e9d2020-03-10 16:57:47 -0700213 " wait-for[-TRANSPORT]-STATE...\n"
214 " wait for device to be in a given state\n"
Tao Bao9d6eca52019-04-07 23:24:03 -0700215 " STATE: device, recovery, rescue, sideload, bootloader, or disconnect\n"
Josh Gaob32f5ac2019-02-22 14:01:36 -0800216 " TRANSPORT: usb, local, or any [default=any]\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700217 " get-state print offline | bootloader | device\n"
218 " get-serialno print <serial-number>\n"
219 " get-devpath print <device-path>\n"
David Anderson63b8a452018-11-21 13:43:22 -0800220 " remount [-R]\n"
221 " remount partitions read-write. if a reboot is required, -R will\n"
222 " will automatically reboot the device.\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700223 " reboot [bootloader|recovery|sideload|sideload-auto-reboot]\n"
224 " reboot the device; defaults to booting system image but\n"
225 " supports bootloader and recovery too. sideload reboots\n"
226 " into recovery and automatically starts sideload mode,\n"
227 " sideload-auto-reboot is the same but reboots after sideloading.\n"
228 " sideload OTAPACKAGE sideload the given full OTA package\n"
229 " root restart adbd with root permissions\n"
230 " unroot restart adbd without root permissions\n"
bohua49faa82018-10-24 10:38:33 -0700231 " usb restart adbd listening on USB\n"
232 " tcpip PORT restart adbd listening on TCP on PORT\n"
Tim1b29ed32010-02-16 20:18:29 +0000233 "\n"
Yabin Cuid78ed222016-04-05 13:50:44 -0700234 "internal debugging:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700235 " start-server ensure that there is a server running\n"
236 " kill-server kill the server if it is running\n"
237 " reconnect kick connection from host side to force reconnect\n"
238 " reconnect device kick connection from device side to force reconnect\n"
Yabin Cui3cf1b362017-03-10 16:01:01 -0800239 " reconnect offline reset offline/unauthorized devices to force reconnect\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700240 "\n"
Josh Gao8e7c9722021-06-17 04:19:45 -0700241 "usb:\n"
242 " attach attach a detached USB device\n"
243 " detach detach from a USB device to allow use by other processes\n"
244 ""
Elliott Hughes52746b02015-06-12 14:26:29 -0700245 "environment variables:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700246 " $ADB_TRACE\n"
Fabien Sanglarda3544292023-07-21 20:24:20 +0000247 " comma/space separated list of debug info to log:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700248 " all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp\n"
249 " $ADB_VENDOR_KEYS colon-separated list of keys (files or directories)\n"
250 " $ANDROID_SERIAL serial number to connect to (see -s)\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000251 " $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help)\n"
252 " $ADB_LOCAL_TRANSPORT_MAX_PORT max emulator scan port (default 5585, 16 emus)\n"
Joshua Duong2ed15ac2020-04-23 09:46:12 -0700253 " $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 +0000254 "\n"
Chirayu Desaieaae4ff2023-09-29 03:16:07 +0530255 "Online documentation: https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md\n"
Fabien Sanglardb75cb862022-12-15 01:54:17 +0000256 "\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000257 );
Felipe Lemee4893a22016-07-29 17:57:00 -0700258 // clang-format on
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800259}
260
Yabin Cui6704a3c2014-11-17 14:48:25 -0800261#if defined(_WIN32)
262
Elliott Hughes6a096932015-04-16 16:47:02 -0700263// Implemented in sysdeps_win32.cpp.
Elliott Hughesa8265792015-11-03 11:18:40 -0800264void stdin_raw_init();
265void stdin_raw_restore();
Yabin Cui6704a3c2014-11-17 14:48:25 -0800266
267#else
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100268static termios g_saved_terminal_state;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800269
Elliott Hughesa8265792015-11-03 11:18:40 -0800270static void stdin_raw_init() {
271 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800272
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100273 termios tio;
Elliott Hughesa8265792015-11-03 11:18:40 -0800274 if (tcgetattr(STDIN_FILENO, &tio)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800275
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100276 cfmakeraw(&tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800277
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100278 // No timeout but request at least one character per read.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800279 tio.c_cc[VTIME] = 0;
280 tio.c_cc[VMIN] = 1;
281
Elliott Hughesa8265792015-11-03 11:18:40 -0800282 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800283}
284
Elliott Hughesa8265792015-11-03 11:18:40 -0800285static void stdin_raw_restore() {
286 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800287}
288#endif
289
Lee Shombertb796cd52022-03-22 12:19:06 -0700290int read_and_dump_protocol(borrowed_fd fd, StandardStreamsCallbackInterface* callback) {
Josh Gaofa64cc22024-01-22 14:42:37 -0800291 // OpenSSH returns 255 on unexpected disconnection.
292 int exit_code = 255;
Lee Shombertb796cd52022-03-22 12:19:06 -0700293 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")) {
Ryan Prichardc36807b2023-06-21 22:08:16 -07001575 gListenAll = true;
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 }
Fabien Sanglard5295bfd2023-11-15 12:17:42 -08001646 VLOG(ADB) << "Using server socket: " << server_socket_str;
Josh Gaobb4f8602016-08-25 16:00:22 -07001647
Elliott Hughesde7776a2021-12-16 10:49:06 -08001648 bool server_start =
1649 is_daemon || is_server || (argc > 0 && strcmp(argv[0], "start-server") == 0);
Vince Harron5703eb32021-11-12 12:40:58 -08001650 if (one_device_str && !server_start) {
1651 error_exit("--one-device is only allowed when starting a server.");
1652 }
1653
1654 adb_set_one_device(one_device_str);
Josh Gaobb4f8602016-08-25 16:00:22 -07001655 adb_set_socket_spec(server_socket_str);
1656
Elliott Hughes67943d12015-10-07 14:55:10 -07001657 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1658 if (transport_type == kTransportAny && serial == nullptr) {
1659 serial = getenv("ANDROID_SERIAL");
1660 }
1661
Josh Gaob39e4152017-08-16 16:57:01 -07001662 adb_set_transport(transport_type, serial, transport_id);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001663
David 'Digit' Turner6826db62011-01-31 14:23:56 +01001664 if (is_server) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001665 if (no_daemon || is_daemon) {
Spencer Lowb28812f2015-08-08 15:07:07 -07001666 if (is_daemon && (ack_reply_fd == -1)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001667 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001668 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001669 }
Vince Harron5703eb32021-11-12 12:40:58 -08001670 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 -08001671 } else {
Vince Harron5703eb32021-11-12 12:40:58 -08001672 r = launch_server(server_socket_str, one_device_str);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001673 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001674 if (r) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001675 fprintf(stderr,"* could not start server *\n");
1676 }
1677 return r;
1678 }
1679
Riley Andrews03b4b372014-12-05 17:37:24 -08001680 if (argc == 0) {
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001681 help();
1682 return 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001683 }
1684
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001685 /* handle wait-for-* prefix */
1686 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001687 const char* service = argv[0];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001688
Josh Gaob39e4152017-08-16 16:57:01 -07001689 if (!wait_for_device(service)) {
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001690 return 1;
1691 }
1692
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001693 // Allow a command to be run after wait-for-device,
1694 // e.g. 'adb wait-for-device shell'.
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001695 if (argc == 1) {
1696 return 0;
1697 }
1698
1699 /* Fall through */
Vince Harron5703eb32021-11-12 12:40:58 -08001700 --argc;
1701 ++argv;
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001702 }
1703
1704 /* adb_connect() commands */
Riley Andrews03b4b372014-12-05 17:37:24 -08001705 if (!strcmp(argv[0], "devices")) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001706 const char *listopt;
Elliott Hughesda945812015-04-29 12:28:13 -07001707 if (argc < 2) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001708 listopt = "";
Elliott Hughesda945812015-04-29 12:28:13 -07001709 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001710 listopt = argv[1];
Elliott Hughesda945812015-04-29 12:28:13 -07001711 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001712 error_exit("adb devices [-l]");
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001713 }
Elliott Hughesda945812015-04-29 12:28:13 -07001714
1715 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
Josh Gao67209db2019-03-14 15:38:02 -07001716 std::string error;
1717 if (!adb_check_server_version(&error)) {
1718 error_exit("failed to check server version: %s", error.c_str());
1719 }
Elliott Hughesda945812015-04-29 12:28:13 -07001720 printf("List of devices attached\n");
1721 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001722 } else if (!strcmp(argv[0], "transport-id")) {
1723 TransportId transport_id;
1724 std::string error;
1725 unique_fd fd(adb_connect(&transport_id, "host:features", &error, true));
1726 if (fd == -1) {
1727 error_exit("%s", error.c_str());
1728 }
1729 printf("%" PRIu64 "\n", transport_id);
1730 return 0;
1731 } else if (!strcmp(argv[0], "connect")) {
Elliott Hughesa5d09032020-01-08 10:02:43 -08001732 if (argc != 2) error_exit("usage: adb connect HOST[:PORT]");
Elliott Hughesda945812015-04-29 12:28:13 -07001733
1734 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1735 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001736 } else if (!strcmp(argv[0], "disconnect")) {
Elliott Hughes14d673e2019-07-30 13:51:03 -07001737 if (argc > 2) error_exit("usage: adb disconnect [HOST[:PORT]]");
Elliott Hughesda945812015-04-29 12:28:13 -07001738
1739 std::string query = android::base::StringPrintf("host:disconnect:%s",
1740 (argc == 2) ? argv[1] : "");
1741 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001742 } else if (!strcmp(argv[0], "abb")) {
1743 return adb_abb(argc, argv);
Joshua Duong290ccb52019-11-20 14:18:43 -08001744 } else if (!strcmp(argv[0], "pair")) {
Joshua Duong64979d02020-05-05 10:46:17 -07001745 if (argc < 2 || argc > 3) error_exit("usage: adb pair HOST[:PORT] [PAIRING CODE]");
Joshua Duong290ccb52019-11-20 14:18:43 -08001746
1747 std::string password;
Joshua Duong64979d02020-05-05 10:46:17 -07001748 if (argc == 2) {
1749 printf("Enter pairing code: ");
1750 fflush(stdout);
1751 if (!std::getline(std::cin, password) || password.empty()) {
1752 error_exit("No pairing code provided");
1753 }
1754 } else {
1755 password = argv[2];
Joshua Duong290ccb52019-11-20 14:18:43 -08001756 }
1757 std::string query =
1758 android::base::StringPrintf("host:pair:%s:%s", password.c_str(), argv[1]);
1759
1760 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001761 } else if (!strcmp(argv[0], "emu")) {
Spencer Low7dc759f2015-05-06 16:13:42 -07001762 return adb_send_emulator_command(argc, argv, serial);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001763 } else if (!strcmp(argv[0], "shell")) {
Josh Gao91d53b52016-01-31 19:12:26 -08001764 return adb_shell(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001765 } else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001766 int exec_in = !strcmp(argv[0], "exec-in");
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001767
Elliott Hughes0119a912018-10-22 17:02:51 -07001768 if (argc < 2) error_exit("usage: adb %s command", argv[0]);
Zach Riggle328870b2016-04-14 17:18:04 -04001769
Elliott Hughes170b5682015-04-17 10:59:34 -07001770 std::string cmd = "exec:";
1771 cmd += argv[1];
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001772 argc -= 2;
1773 argv += 2;
1774 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001775 cmd += " " + escape_arg(*argv++);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001776 }
1777
Elliott Hughes04a98c22015-04-29 08:35:59 -07001778 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001779 unique_fd fd(adb_connect(cmd, &error));
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001780 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001781 fprintf(stderr, "error: %s\n", error.c_str());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001782 return -1;
1783 }
1784
1785 if (exec_in) {
Josh Gaoc2705962019-01-23 15:36:42 -08001786 copy_to_file(STDIN_FILENO, fd.get());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001787 } else {
Josh Gaoc2705962019-01-23 15:36:42 -08001788 copy_to_file(fd.get(), STDOUT_FILENO);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001789 }
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001790 return 0;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001791 } else if (!strcmp(argv[0], "kill-server")) {
Josh Gaoee356a72017-05-08 18:37:17 -07001792 return adb_kill_server() ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001793 } else if (!strcmp(argv[0], "sideload")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001794 if (argc != 2) error_exit("sideload requires an argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001795 if (adb_sideload_install(argv[1], false /* rescue_mode */)) {
Doug Zongker6b217ed2012-01-09 14:54:53 -08001796 return 1;
1797 } else {
1798 return 0;
1799 }
Tao Baoe23e6c72019-04-07 23:24:03 -07001800 } else if (!strcmp(argv[0], "rescue")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001801 // adb rescue getprop
Tao Baoe23e6c72019-04-07 23:24:03 -07001802 // adb rescue getprop <prop>
1803 // adb rescue install <filename>
xunchang8829d152019-04-22 23:14:28 -07001804 // adb rescue wipe userdata
Tao Bao1b11c232019-06-04 14:37:06 -07001805 if (argc < 2) error_exit("rescue requires at least one argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001806 if (!strcmp(argv[1], "getprop")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001807 if (argc == 2) {
1808 return adb_connect_command("rescue-getprop:");
1809 }
1810 if (argc == 3) {
1811 return adb_connect_command(
1812 android::base::StringPrintf("rescue-getprop:%s", argv[2]));
1813 }
1814 error_exit("invalid rescue getprop arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001815 } else if (!strcmp(argv[1], "install")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001816 if (argc != 3) error_exit("rescue install requires two arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001817 if (adb_sideload_install(argv[2], true /* rescue_mode */) != 0) {
1818 return 1;
1819 }
Tao Bao1b11c232019-06-04 14:37:06 -07001820 } else if (!strcmp(argv[1], "wipe")) {
1821 if (argc != 3 || strcmp(argv[2], "userdata") != 0) {
1822 error_exit("invalid rescue wipe arguments");
1823 }
xunchang8829d152019-04-22 23:14:28 -07001824 return adb_wipe_devices();
Tao Baoe23e6c72019-04-07 23:24:03 -07001825 } else {
1826 error_exit("invalid rescue argument");
1827 }
1828 return 0;
Elliott Hughesfa085be2017-08-23 15:42:28 -07001829 } else if (!strcmp(argv[0], "tcpip")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001830 if (argc != 2) error_exit("tcpip requires an argument");
Elliott Hughesfa085be2017-08-23 15:42:28 -07001831 int port;
1832 if (!android::base::ParseInt(argv[1], &port, 1, 65535)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001833 error_exit("tcpip: invalid port: %s", argv[1]);
Elliott Hughesfa085be2017-08-23 15:42:28 -07001834 }
1835 return adb_connect_command(android::base::StringPrintf("tcpip:%d", port));
Shaju Mathew3b481e52021-10-28 00:14:04 -07001836 } else if (!strcmp(argv[0], "remount") || !strcmp(argv[0], "disable-verity") ||
1837 !strcmp(argv[0], "enable-verity")) {
Elliott Hughes18056092022-02-18 10:16:38 -08001838 return process_remount_or_verity_service(argc, argv);
Shaju Mathew3b481e52021-10-28 00:14:04 -07001839 } else if (!strcmp(argv[0], "reboot") || !strcmp(argv[0], "reboot-bootloader") ||
1840 !strcmp(argv[0], "reboot-fastboot") || !strcmp(argv[0], "usb")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001841 std::string command;
Tao Bao0db67642015-03-29 11:22:34 -07001842 if (!strcmp(argv[0], "reboot-bootloader")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001843 command = "reboot:bootloader";
Mark Salyzynd6420432018-08-29 10:44:33 -07001844 } else if (!strcmp(argv[0], "reboot-fastboot")) {
1845 command = "reboot:fastboot";
Tao Bao0db67642015-03-29 11:22:34 -07001846 } else if (argc > 1) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001847 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
Tao Bao0db67642015-03-29 11:22:34 -07001848 } else {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001849 command = android::base::StringPrintf("%s:", argv[0]);
The Android Open Source Project9c753402009-03-13 13:04:37 -07001850 }
Tao Bao0db67642015-03-29 11:22:34 -07001851 return adb_connect_command(command);
Josh Gaod1d03392016-03-04 15:16:18 -08001852 } else if (!strcmp(argv[0], "root") || !strcmp(argv[0], "unroot")) {
1853 return adb_root(argv[0]) ? 0 : 1;
1854 } else if (!strcmp(argv[0], "bugreport")) {
Felipe Leme042c3512016-07-19 17:07:22 -07001855 Bugreport bugreport;
Josh Gaob39e4152017-08-16 16:57:01 -07001856 return bugreport.DoIt(argc, argv);
Felipe Lemeb6447032016-04-01 17:43:27 -07001857 } else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001858 bool reverse = !strcmp(argv[0], "reverse");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001859 --argc;
Elliott Hughes0119a912018-10-22 17:02:51 -07001860 if (argc < 1) error_exit("%s requires an argument", argv[0]);
Josh Gao596f63b2018-07-31 15:36:03 -07001861 ++argv;
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001862
1863 // Determine the <host-prefix> for this command.
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001864 std::string host_prefix;
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001865 if (reverse) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001866 host_prefix = "reverse:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001867 } else {
Josh Gaoed00ae12019-08-06 16:43:34 -07001868 host_prefix = "host:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001869 }
1870
Elliott Hughese64126b2018-10-19 13:59:44 -07001871 std::string cmd, error_message;
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001872 if (strcmp(argv[0], "--list") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001873 if (argc != 1) error_exit("--list doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001874 return adb_query_command(host_prefix + "list-forward");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001875 } else if (strcmp(argv[0], "--remove-all") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001876 if (argc != 1) error_exit("--remove-all doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001877 cmd = "killforward-all";
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001878 } else if (strcmp(argv[0], "--remove") == 0) {
1879 // forward --remove <local>
Elliott Hughes0119a912018-10-22 17:02:51 -07001880 if (argc != 2) error_exit("--remove requires an argument");
Josh Gaoed00ae12019-08-06 16:43:34 -07001881 cmd = std::string("killforward:") + argv[1];
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001882 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1883 // forward --no-rebind <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001884 if (argc != 3) error_exit("--no-rebind takes two arguments");
Elliott Hughese64126b2018-10-19 13:59:44 -07001885 if (forward_targets_are_valid(argv[1], argv[2], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001886 cmd = std::string("forward:norebind:") + argv[1] + ";" + argv[2];
David Pursell19d0c232016-04-07 11:25:48 -07001887 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001888 } else {
1889 // forward <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001890 if (argc != 2) error_exit("forward takes two arguments");
Elliott Hughese64126b2018-10-19 13:59:44 -07001891 if (forward_targets_are_valid(argv[0], argv[1], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001892 cmd = std::string("forward:") + argv[0] + ";" + argv[1];
David Pursell19d0c232016-04-07 11:25:48 -07001893 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001894 }
1895
Elliott Hughese64126b2018-10-19 13:59:44 -07001896 if (!error_message.empty()) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001897 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001898 }
1899
Josh Gaoed00ae12019-08-06 16:43:34 -07001900 unique_fd fd(adb_connect(nullptr, host_prefix + cmd, &error_message, true));
Josh Gaoc2705962019-01-23 15:36:42 -08001901 if (fd < 0 || !adb_status(fd.get(), &error_message)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001902 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001903 }
1904
1905 // Server or device may optionally return a resolved TCP port number.
1906 std::string resolved_port;
Elliott Hughese64126b2018-10-19 13:59:44 -07001907 if (ReadProtocolString(fd, &resolved_port, &error_message) && !resolved_port.empty()) {
David Pursell19d0c232016-04-07 11:25:48 -07001908 printf("%s\n", resolved_port.c_str());
1909 }
1910
1911 ReadOrderlyShutdown(fd);
1912 return 0;
Joshua Duonge22e1612020-03-31 10:58:50 -07001913 } else if (!strcmp(argv[0], "mdns")) {
1914 --argc;
1915 if (argc < 1) error_exit("mdns requires an argument");
1916 ++argv;
1917
1918 std::string error;
1919 if (!adb_check_server_version(&error)) {
1920 error_exit("failed to check server version: %s", error.c_str());
1921 }
1922
1923 std::string query = "host:mdns:";
1924 if (!strcmp(argv[0], "check")) {
1925 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1926 query += "check";
Joshua Duong5f63d112020-03-31 08:39:24 -07001927 } else if (!strcmp(argv[0], "services")) {
1928 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1929 query += "services";
1930 printf("List of discovered mdns services\n");
Joshua Duonge22e1612020-03-31 10:58:50 -07001931 } else {
1932 error_exit("unknown mdns command [%s]", argv[0]);
1933 }
1934
1935 return adb_query_command(query);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001936 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001937 /* do_sync_*() commands */
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001938 else if (!strcmp(argv[0], "ls")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001939 if (argc != 2) error_exit("ls requires an argument");
Elliott Hughesb628cb12015-08-03 10:38:08 -07001940 return do_sync_ls(argv[1]) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001941 } else if (!strcmp(argv[0], "push")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001942 bool copy_attrs = false;
Dan Albert8449e062017-05-18 22:56:48 -07001943 bool sync = false;
Josh Gao8a410a02020-03-30 23:25:16 -07001944 bool dry_run = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001945 CompressionType compression = CompressionType::Any;
Josh Gao5d093b22015-10-30 16:57:19 -07001946 std::vector<const char*> srcs;
1947 const char* dst = nullptr;
Mark Lindner9f9d1452014-03-11 17:55:59 -07001948
Josh Gao8a410a02020-03-30 23:25:16 -07001949 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, &sync, &compression,
1950 &dry_run);
shaju1a0f9152022-10-25 14:54:37 -07001951 if (srcs.empty() || !dst) {
1952 error_exit("push requires <source> and <destination> arguments");
1953 }
1954
Josh Gao8a410a02020-03-30 23:25:16 -07001955 return do_sync_push(srcs, dst, sync, compression, dry_run) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001956 } else if (!strcmp(argv[0], "pull")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001957 bool copy_attrs = false;
Snild Dolkow30e74ac2020-09-23 09:31:50 +02001958 CompressionType compression = CompressionType::None;
Josh Gao5d093b22015-10-30 16:57:19 -07001959 std::vector<const char*> srcs;
1960 const char* dst = ".";
Mark Lindner9f9d1452014-03-11 17:55:59 -07001961
Josh Gao8a410a02020-03-30 23:25:16 -07001962 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, nullptr, &compression,
1963 nullptr);
Elliott Hughes0119a912018-10-22 17:02:51 -07001964 if (srcs.empty()) error_exit("pull requires an argument");
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001965 return do_sync_pull(srcs, dst, copy_attrs, compression) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001966 } else if (!strcmp(argv[0], "install")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001967 if (argc < 2) error_exit("install requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001968 return install_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001969 } else if (!strcmp(argv[0], "install-multiple")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001970 if (argc < 2) error_exit("install-multiple requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001971 return install_multiple_app(argc, argv);
Patrick Baumann810ee9b2018-10-09 10:45:03 -07001972 } else if (!strcmp(argv[0], "install-multi-package")) {
Mohammad Samiul Islamed2e8732019-05-29 15:00:00 +01001973 if (argc < 2) error_exit("install-multi-package requires an argument");
Patrick Baumann810ee9b2018-10-09 10:45:03 -07001974 return install_multi_package(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001975 } else if (!strcmp(argv[0], "uninstall")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001976 if (argc < 2) error_exit("uninstall requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001977 return uninstall_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001978 } else if (!strcmp(argv[0], "sync")) {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001979 std::string src;
Elliott Hughes38104452015-04-17 13:57:15 -07001980 bool list_only = false;
Josh Gao8a410a02020-03-30 23:25:16 -07001981 bool dry_run = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001982 CompressionType compression = CompressionType::Any;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001983
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001984 if (const char* adb_compression = getenv("ADB_COMPRESSION"); adb_compression) {
1985 compression = parse_compression_type(adb_compression, true);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001986 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001987
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001988 int opt;
Josh Gao8a410a02020-03-30 23:25:16 -07001989 while ((opt = getopt(argc, const_cast<char**>(argv), "lnz:Z")) != -1) {
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001990 switch (opt) {
1991 case 'l':
1992 list_only = true;
1993 break;
Josh Gao8a410a02020-03-30 23:25:16 -07001994 case 'n':
1995 dry_run = true;
1996 break;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001997 case 'z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001998 compression = parse_compression_type(optarg, false);
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001999 break;
2000 case 'Z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002001 compression = CompressionType::None;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002002 break;
2003 default:
Josh Gao8a410a02020-03-30 23:25:16 -07002004 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002005 }
2006 }
2007
2008 if (optind == argc) {
2009 src = "all";
2010 } else if (optind + 1 == argc) {
2011 src = argv[optind];
2012 } else {
Josh Gao8a410a02020-03-30 23:25:16 -07002013 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002014 }
2015
Justin Yunb0c201c2019-06-26 09:18:03 +09002016 std::vector<std::string> partitions{"data", "odm", "oem", "product",
2017 "system", "system_ext", "vendor"};
Elliott Hughes145ac022018-04-03 10:54:39 -07002018 bool found = false;
2019 for (const auto& partition : partitions) {
2020 if (src == "all" || src == partition) {
2021 std::string src_dir{product_file(partition)};
2022 if (!directory_exists(src_dir)) continue;
2023 found = true;
Josh Gao8a410a02020-03-30 23:25:16 -07002024 if (!do_sync_sync(src_dir, "/" + partition, list_only, compression, dry_run)) {
2025 return 1;
2026 }
Elliott Hughes145ac022018-04-03 10:54:39 -07002027 }
Elliott Hughes38104452015-04-17 13:57:15 -07002028 }
Elliott Hughes0119a912018-10-22 17:02:51 -07002029 if (!found) error_exit("don't know how to sync %s partition", src.c_str());
Elliott Hughese64126b2018-10-19 13:59:44 -07002030 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002031 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002032 /* passthrough commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002033 else if (!strcmp(argv[0], "get-state") || !strcmp(argv[0], "get-serialno") ||
2034 !strcmp(argv[0], "get-devpath")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002035 return adb_query_command(format_host_command(argv[0]));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002036 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002037 /* other commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002038 else if (!strcmp(argv[0], "logcat") || !strcmp(argv[0], "lolcat") ||
2039 !strcmp(argv[0], "longcat")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002040 return logcat(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002041 } else if (!strcmp(argv[0], "start-server")) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07002042 std::string error;
Spencer Low85ee64b2015-08-11 17:05:02 -07002043 const int result = adb_connect("host:start-server", &error);
2044 if (result < 0) {
2045 fprintf(stderr, "error: %s\n", error.c_str());
2046 }
2047 return result;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002048 } else if (!strcmp(argv[0], "backup")) {
Christopher Tate73779122011-04-21 12:53:28 -07002049 return backup(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002050 } else if (!strcmp(argv[0], "restore")) {
Christopher Tatecf5379b2011-05-17 15:52:54 -07002051 return restore(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002052 } else if (!strcmp(argv[0], "keygen")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002053 if (argc != 2) error_exit("keygen requires an argument");
Yabin Cui19bec5b2015-09-22 15:52:57 -07002054 // Always print key generation information for keygen command.
2055 adb_trace_enable(AUTH);
Nick Kralevich6183c962014-11-13 15:17:29 -08002056 return adb_auth_keygen(argv[1]);
Josh Gao13102c32018-11-15 17:45:46 -08002057 } else if (!strcmp(argv[0], "pubkey")) {
2058 if (argc != 2) error_exit("pubkey requires an argument");
2059 return adb_auth_pubkey(argv[1]);
2060 } else if (!strcmp(argv[0], "jdwp")) {
Tao Bao0db67642015-03-29 11:22:34 -07002061 return adb_connect_command("jdwp");
Josh Gao13102c32018-11-15 17:45:46 -08002062 } else if (!strcmp(argv[0], "track-jdwp")) {
Josh Gao39d01bb2016-05-13 18:18:23 -07002063 return adb_connect_command("track-jdwp");
Shukang Zhou420ad552020-02-13 17:01:39 -08002064 } else if (!strcmp(argv[0], "track-app")) {
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07002065 auto&& features = adb_get_feature_set_or_die();
Josh Gao291733b2020-04-16 19:34:43 -07002066 if (!CanUseFeature(*features, kFeatureTrackApp)) {
Shukang Zhou420ad552020-02-13 17:01:39 -08002067 error_exit("track-app is not supported by the device");
2068 }
2069 TrackAppStreamsCallback callback;
2070 return adb_connect_command("track-app", nullptr, &callback);
Josh Gao13102c32018-11-15 17:45:46 -08002071 } else if (!strcmp(argv[0], "track-devices")) {
Fabien Sanglard3d155b62023-11-30 14:52:40 -08002072 const char* listopt;
2073 if (argc < 2) {
2074 listopt = "";
2075 } else {
2076 if (!strcmp(argv[1], "-l")) {
2077 listopt = argv[1];
2078 } else if (!strcmp(argv[1], "--proto-text")) {
2079 listopt = "-proto-text";
2080 } else if (!strcmp(argv[1], "--proto-binary")) {
2081 listopt = "-proto-binary";
2082 } else {
2083 error_exit("usage: adb track-devices [-l][--proto-text][--proto-binary]");
2084 }
Elliott Hughes3d792f42019-07-31 14:13:57 -07002085 }
Fabien Sanglard3d155b62023-11-30 14:52:40 -08002086 std::string query = android::base::StringPrintf("host:track-devices%s", listopt);
2087 return adb_connect_command(query);
Josh Gaobf5167c2018-06-18 14:51:56 -07002088 } else if (!strcmp(argv[0], "raw")) {
2089 if (argc != 2) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002090 error_exit("usage: adb raw SERVICE");
Josh Gaobf5167c2018-06-18 14:51:56 -07002091 }
Josh Gao7b438fa2018-11-16 14:47:59 -08002092 return adb_connect_command_bidirectional(argv[1]);
Josh Gao39d01bb2016-05-13 18:18:23 -07002093 }
2094
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002095 /* "adb /?" is a common idiom under Windows */
Elliott Hughes97e74bb2017-02-06 16:20:30 -08002096 else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002097 help();
2098 return 0;
Josh Gao13102c32018-11-15 17:45:46 -08002099 } else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
Elliott Hughesb9f01642015-08-12 08:32:10 -07002100 fprintf(stdout, "%s", adb_version().c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002101 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002102 } else if (!strcmp(argv[0], "features")) {
David Pursella07dbad2015-09-22 10:43:08 -07002103 // Only list the features common to both the adb client and the device.
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07002104 auto&& features = adb_get_feature_set_or_die();
David Pursell9650d862016-01-21 19:56:50 -08002105
Josh Gao291733b2020-04-16 19:34:43 -07002106 for (const std::string& name : *features) {
2107 if (CanUseFeature(*features, name)) {
David Pursella07dbad2015-09-22 10:43:08 -07002108 printf("%s\n", name.c_str());
2109 }
2110 }
2111 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002112 } else if (!strcmp(argv[0], "host-features")) {
2113 return adb_query_command("host:host-features");
Yabin Cuid78ed222016-04-05 13:50:44 -07002114 } else if (!strcmp(argv[0], "reconnect")) {
2115 if (argc == 1) {
Josh Gaob39e4152017-08-16 16:57:01 -07002116 return adb_query_command(format_host_command(argv[0]));
Josh Gao4e562502016-10-27 14:01:08 -07002117 } else if (argc == 2) {
2118 if (!strcmp(argv[1], "device")) {
2119 std::string err;
2120 adb_connect("reconnect", &err);
2121 return 0;
2122 } else if (!strcmp(argv[1], "offline")) {
2123 std::string err;
2124 return adb_query_command("host:reconnect-offline");
2125 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07002126 error_exit("usage: adb reconnect [device|offline]");
Josh Gao4e562502016-10-27 14:01:08 -07002127 }
Yabin Cuid78ed222016-04-05 13:50:44 -07002128 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002129 } else if (!strcmp(argv[0], "inc-server")) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002130 if (argc < 4) {
2131#ifdef _WIN32
2132 error_exit("usage: adb inc-server CONNECTION_HANDLE OUTPUT_HANDLE FILE1 FILE2 ...");
2133#else
2134 error_exit("usage: adb inc-server CONNECTION_FD OUTPUT_FD FILE1 FILE2 ...");
2135#endif
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002136 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002137 int connection_fd = atoi(argv[1]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002138 if (!_is_valid_os_fd(connection_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002139 error_exit("Invalid connection_fd number given: %d", connection_fd);
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002140 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002141
2142 connection_fd = adb_register_socket(connection_fd);
2143 close_on_exec(connection_fd);
2144
2145 int output_fd = atoi(argv[2]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002146 if (!_is_valid_os_fd(output_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002147 error_exit("Invalid output_fd number given: %d", output_fd);
2148 }
2149 output_fd = adb_register_socket(output_fd);
2150 close_on_exec(output_fd);
2151 return incremental::serve(connection_fd, output_fd, argc - 3, argv + 3);
Josh Gao8e7c9722021-06-17 04:19:45 -07002152 } else if (!strcmp(argv[0], "attach") || !strcmp(argv[0], "detach")) {
2153 const char* service = strcmp(argv[0], "attach") == 0 ? "host:attach" : "host:detach";
2154 std::string result;
2155 std::string error;
2156 if (!adb_query(service, &result, &error, true)) {
2157 error_exit("failed to %s: %s", argv[0], error.c_str());
2158 }
2159 printf("%s\n", result.c_str());
2160 return 0;
Dan Albert996c12e2015-05-20 18:58:41 -07002161 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002162
Elliott Hughes0119a912018-10-22 17:02:51 -07002163 error_exit("unknown command %s", argv[0]);
Elliott Hughese64126b2018-10-19 13:59:44 -07002164 __builtin_unreachable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002165}