blob: 0caf9e253a8b27d50febff59adb49f13698c729d [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)
Josh Gaof344ecf2015-10-23 15:03:31 -070047#include <signal.h>
Elliott Hughes4c5e8042015-11-04 13:07:47 -080048#include <sys/ioctl.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080049#include <termios.h>
Dan Albertb302d122015-02-24 15:51:19 -080050#include <unistd.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080051#endif
52
Shukang Zhou420ad552020-02-13 17:01:39 -080053#include <google/protobuf/text_format.h>
54
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080055#include "adb.h"
Nick Kralevich6183c962014-11-13 15:17:29 -080056#include "adb_auth.h"
Dan Albert66a91b02015-02-24 21:26:58 -080057#include "adb_client.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000058#include "adb_install.h"
Dan Albert66a91b02015-02-24 21:26:58 -080059#include "adb_io.h"
Josh Gaoea7457b2016-08-30 15:39:25 -070060#include "adb_unique_fd.h"
Elliott Hughes38104452015-04-17 13:57:15 -070061#include "adb_utils.h"
Shukang Zhou420ad552020-02-13 17:01:39 -080062#include "app_processes.pb.h"
Felipe Leme042c3512016-07-19 17:07:22 -070063#include "bugreport.h"
Josh Gaoc7b74592018-07-25 15:55:25 -070064#include "client/file_sync_client.h"
Felipe Leme042c3512016-07-19 17:07:22 -070065#include "commandline.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000066#include "fastdeploy.h"
Alex Buynytskyy175ce292020-02-13 06:52:04 -080067#include "incremental_server.h"
David Pursell22fc5e92015-09-30 13:35:42 -070068#include "services.h"
Josh Gao076b5ba2018-07-25 16:07:26 -070069#include "shell_protocol.h"
Josh Gao70267e42016-11-15 18:55:47 -080070#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080071
Matt Gumbel411775c2012-11-14 10:16:17 -080072extern int gListenAll;
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"
89 " -a listen on all network interfaces, not just localhost\n"
90 " -d use USB device (error if multiple devices connected)\n"
Elliott Hughes2d821142017-01-13 16:58:25 -080091 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
Elliott Hughes314db002017-05-01 11:04:31 -070092 " -s SERIAL use device with given serial (overrides $ANDROID_SERIAL)\n"
Josh Gaob39e4152017-08-16 16:57:01 -070093 " -t ID use device with given transport id\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -070094 " -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 [default=tcp:localhost:5037]\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080097 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -070098 "general commands:\n"
99 " devices [-l] list connected devices (-l for long output)\n"
100 " help show this help message\n"
101 " version show version num\n"
Elliott Hughes52746b02015-06-12 14:26:29 -0700102 "\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800103 "networking:\n"
Joshua Duong290ccb52019-11-20 14:18:43 -0800104 " connect HOST[:PORT] connect to a device via TCP/IP [default port=5555]\n"
105 " disconnect [HOST[:PORT]]\n"
106 " disconnect from given TCP/IP device [default port=5555], or all\n"
Joshua Duong64979d02020-05-05 10:46:17 -0700107 " pair HOST[:PORT] [PAIRING CODE]\n"
108 " pair with a device for secure TCP/IP communication\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700109 " forward --list list all forward socket connections\n"
110 " forward [--no-rebind] LOCAL REMOTE\n"
111 " forward socket connection using:\n"
112 " tcp:<port> (<local> may be \"tcp:0\" to pick any open port)\n"
113 " localabstract:<unix domain socket name>\n"
114 " localreserved:<unix domain socket name>\n"
115 " localfilesystem:<unix domain socket name>\n"
116 " dev:<character device name>\n"
117 " jdwp:<process pid> (remote only)\n"
Andrew Walbranebf09dd2021-03-03 18:06:12 +0000118 " vsock:<CID>:<port> (remote only)\n"
Daniel Colascione3e124692019-11-13 17:49:37 -0800119 " acceptfd:<fd> (listen only)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700120 " forward --remove LOCAL remove specific forward socket connection\n"
121 " forward --remove-all remove all forward socket connections\n"
122 " ppp TTY [PARAMETER...] run PPP over USB\n"
123 " reverse --list list all reverse socket connections from device\n"
124 " reverse [--no-rebind] REMOTE LOCAL\n"
125 " reverse socket connection using:\n"
126 " tcp:<port> (<remote> may be \"tcp:0\" to pick any open port)\n"
127 " localabstract:<unix domain socket name>\n"
128 " localreserved:<unix domain socket name>\n"
129 " localfilesystem:<unix domain socket name>\n"
130 " reverse --remove REMOTE remove specific reverse socket connection\n"
131 " reverse --remove-all remove all reverse socket connections from device\n"
Joshua Duonge22e1612020-03-31 10:58:50 -0700132 " mdns check check if mdns discovery is available\n"
Joshua Duong5f63d112020-03-31 08:39:24 -0700133 " mdns services list all discovered services\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800134 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700135 "file transfer:\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700136 " push [--sync] [-z ALGORITHM] [-Z] LOCAL... REMOTE\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700137 " copy local files/directories to device\n"
Dan Albert8449e062017-05-18 22:56:48 -0700138 " --sync: only push files that are newer on the host than the device\n"
Josh Gao8a410a02020-03-30 23:25:16 -0700139 " -n: dry run: push files to device without storing to the filesystem\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700140 " -z: enable compression with a specified algorithm (any, none, brotli)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800141 " -Z: disable compression\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700142 " pull [-a] [-z ALGORITHM] [-Z] REMOTE... LOCAL\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700143 " copy files/dirs from device\n"
144 " -a: preserve file timestamp and mode\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700145 " -z: enable compression with a specified algorithm (any, none, brotli)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800146 " -Z: disable compression\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700147 " sync [-l] [-z ALGORITHM] [-Z] [all|data|odm|oem|product|system|system_ext|vendor]\n"
Elliott Hughes314db002017-05-01 11:04:31 -0700148 " sync a local build from $ANDROID_PRODUCT_OUT to the device (default all)\n"
Josh Gao8a410a02020-03-30 23:25:16 -0700149 " -n: dry run: push files to device without storing to the filesystem\n"
Elliott Hughesc4b9b972019-07-30 10:32:53 -0700150 " -l: list files that would be copied, but don't copy them\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700151 " -z: enable compression with a specified algorithm (any, none, brotli)\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800152 " -Z: disable compression\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800153 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700154 "shell:\n"
155 " shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]\n"
156 " run remote shell command (interactive shell if no command given)\n"
157 " -e: choose escape character, or \"none\"; default '~'\n"
158 " -n: don't read from stdin\n"
Elliott Hughes63cb1812019-12-13 16:43:10 -0800159 " -T: disable pty allocation\n"
160 " -t: allocate a pty if on a tty (-tt: force pty allocation)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700161 " -x: disable remote exit codes and stdout/stderr separation\n"
162 " emu COMMAND run emulator console command\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800163 "\n"
Elliott Hughesf8a41042019-01-11 13:50:05 -0800164 "app installation (see also `adb shell cmd package help`):\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700165 " install [-lrtsdg] [--instant] PACKAGE\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700166 " push a single package to the device and install it\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700167 " install-multiple [-lrtsdpg] [--instant] PACKAGE...\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700168 " push multiple APKs to the device for a single package and install them\n"
169 " install-multi-package [-lrtsdpg] [--instant] PACKAGE...\n"
170 " push one or more packages to the device and install them atomically\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700171 " -r: replace existing application\n"
172 " -t: allow test packages\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700173 " -d: allow version code downgrade (debuggable packages only)\n"
174 " -p: partial application install (install-multiple only)\n"
175 " -g: grant all runtime permissions\n"
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700176 " --abi ABI: override platform's default ABI\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700177 " --instant: cause the app to be installed as an ephemeral install app\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000178 " --no-streaming: always push APK to device and invoke Package Manager as separate steps\n"
179 " --streaming: force streaming APK directly into Package Manager\n"
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000180 " --fastdeploy: use fast deploy\n"
181 " --no-fastdeploy: prevent use of fast deploy\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000182 " --force-agent: force update of deployment agent when using fast deploy\n"
183 " --date-check-agent: update deployment agent when local version is newer and using fast deploy\n"
184 " --version-check-agent: update deployment agent when local version has different version code and using fast deploy\n"
185#ifndef _WIN32
186 " --local-agent: locate agent files from local source build (instead of SDK location)\n"
187#endif
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700188 " (See also `adb shell pm help` for more options.)\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000189 //TODO--installlog <filename>
Elliott Hughes687f8b42016-09-28 15:25:47 -0700190 " uninstall [-k] PACKAGE\n"
191 " remove this app package from the device\n"
192 " '-k': keep the data and cache directories\n"
193 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700194 "debugging:\n"
195 " bugreport [PATH]\n"
196 " write bugreport to given PATH [default=bugreport.zip];\n"
197 " if PATH is a directory, the bug report is saved in that directory.\n"
198 " devices that don't support zipped bug reports output to stdout.\n"
199 " jdwp list pids of processes hosting a JDWP transport\n"
200 " logcat show device log (logcat --help for more)\n"
201 "\n"
202 "security:\n"
203 " disable-verity disable dm-verity checking on userdebug builds\n"
204 " enable-verity re-enable dm-verity checking on userdebug builds\n"
205 " keygen FILE\n"
206 " generate adb public/private key; private key stored in FILE,\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700207 "\n"
208 "scripting:\n"
Elliott Hughes3657e9d2020-03-10 16:57:47 -0700209 " wait-for[-TRANSPORT]-STATE...\n"
210 " wait for device to be in a given state\n"
Tao Bao9d6eca52019-04-07 23:24:03 -0700211 " STATE: device, recovery, rescue, sideload, bootloader, or disconnect\n"
Josh Gaob32f5ac2019-02-22 14:01:36 -0800212 " TRANSPORT: usb, local, or any [default=any]\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700213 " get-state print offline | bootloader | device\n"
214 " get-serialno print <serial-number>\n"
215 " get-devpath print <device-path>\n"
David Anderson63b8a452018-11-21 13:43:22 -0800216 " remount [-R]\n"
217 " remount partitions read-write. if a reboot is required, -R will\n"
218 " will automatically reboot the device.\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700219 " reboot [bootloader|recovery|sideload|sideload-auto-reboot]\n"
220 " reboot the device; defaults to booting system image but\n"
221 " supports bootloader and recovery too. sideload reboots\n"
222 " into recovery and automatically starts sideload mode,\n"
223 " sideload-auto-reboot is the same but reboots after sideloading.\n"
224 " sideload OTAPACKAGE sideload the given full OTA package\n"
225 " root restart adbd with root permissions\n"
226 " unroot restart adbd without root permissions\n"
bohua49faa82018-10-24 10:38:33 -0700227 " usb restart adbd listening on USB\n"
228 " tcpip PORT restart adbd listening on TCP on PORT\n"
Tim1b29ed32010-02-16 20:18:29 +0000229 "\n"
Yabin Cuid78ed222016-04-05 13:50:44 -0700230 "internal debugging:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700231 " start-server ensure that there is a server running\n"
232 " kill-server kill the server if it is running\n"
233 " reconnect kick connection from host side to force reconnect\n"
234 " reconnect device kick connection from device side to force reconnect\n"
Yabin Cui3cf1b362017-03-10 16:01:01 -0800235 " reconnect offline reset offline/unauthorized devices to force reconnect\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700236 "\n"
Elliott Hughes52746b02015-06-12 14:26:29 -0700237 "environment variables:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700238 " $ADB_TRACE\n"
239 " comma-separated list of debug info to log:\n"
240 " all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp\n"
241 " $ADB_VENDOR_KEYS colon-separated list of keys (files or directories)\n"
242 " $ANDROID_SERIAL serial number to connect to (see -s)\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000243 " $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help)\n"
244 " $ADB_LOCAL_TRANSPORT_MAX_PORT max emulator scan port (default 5585, 16 emus)\n"
Joshua Duong2ed15ac2020-04-23 09:46:12 -0700245 " $ADB_MDNS_AUTO_CONNECT comma-separated list of mdns services to allow auto-connect (default adb-tls-connect)\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000246 );
Felipe Lemee4893a22016-07-29 17:57:00 -0700247 // clang-format on
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800248}
249
Yabin Cui6704a3c2014-11-17 14:48:25 -0800250#if defined(_WIN32)
251
Elliott Hughes6a096932015-04-16 16:47:02 -0700252// Implemented in sysdeps_win32.cpp.
Elliott Hughesa8265792015-11-03 11:18:40 -0800253void stdin_raw_init();
254void stdin_raw_restore();
Yabin Cui6704a3c2014-11-17 14:48:25 -0800255
256#else
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100257static termios g_saved_terminal_state;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800258
Elliott Hughesa8265792015-11-03 11:18:40 -0800259static void stdin_raw_init() {
260 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800261
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100262 termios tio;
Elliott Hughesa8265792015-11-03 11:18:40 -0800263 if (tcgetattr(STDIN_FILENO, &tio)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800264
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100265 cfmakeraw(&tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800266
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100267 // No timeout but request at least one character per read.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800268 tio.c_cc[VTIME] = 0;
269 tio.c_cc[VMIN] = 1;
270
Elliott Hughesa8265792015-11-03 11:18:40 -0800271 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800272}
273
Elliott Hughesa8265792015-11-03 11:18:40 -0800274static void stdin_raw_restore() {
275 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800276}
277#endif
278
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700279int read_and_dump(borrowed_fd fd, bool use_shell_protocol,
280 StandardStreamsCallbackInterface* callback) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700281 int exit_code = 0;
Felipe Leme5ad50902016-06-06 16:05:36 -0700282 if (fd < 0) return exit_code;
283
David Pursell8a5a5aa2015-09-08 17:17:02 -0700284 std::unique_ptr<ShellProtocol> protocol;
285 int length = 0;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700286
287 char raw_buffer[BUFSIZ];
288 char* buffer_ptr = raw_buffer;
289 if (use_shell_protocol) {
Josh Gaof2a988c2018-03-07 16:51:08 -0800290 protocol = std::make_unique<ShellProtocol>(fd);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700291 if (!protocol) {
292 LOG(ERROR) << "failed to allocate memory for ShellProtocol object";
293 return 1;
294 }
295 buffer_ptr = protocol->data();
296 }
297
Felipe Leme5ad50902016-06-06 16:05:36 -0700298 while (true) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700299 if (use_shell_protocol) {
300 if (!protocol->Read()) {
301 break;
302 }
Felipe Leme60192aa2016-07-26 12:14:39 -0700303 length = protocol->data_length();
David Pursell8a5a5aa2015-09-08 17:17:02 -0700304 switch (protocol->id()) {
305 case ShellProtocol::kIdStdout:
Felipe Leme60192aa2016-07-26 12:14:39 -0700306 callback->OnStdout(buffer_ptr, length);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700307 break;
308 case ShellProtocol::kIdStderr:
Felipe Leme60192aa2016-07-26 12:14:39 -0700309 callback->OnStderr(buffer_ptr, length);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700310 break;
311 case ShellProtocol::kIdExit:
Josh Gaod2fbd5c2019-03-15 14:49:25 -0700312 // data() returns a char* which doesn't have defined signedness.
313 // Cast to uint8_t to prevent 255 from being sign extended to INT_MIN,
314 // which doesn't get truncated on Windows.
315 exit_code = static_cast<uint8_t>(protocol->data()[0]);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700316 continue;
317 default:
318 continue;
319 }
320 length = protocol->data_length();
321 } else {
Josh Gao90228a62019-04-25 14:04:57 -0700322 D("read_and_dump(): pre adb_read(fd=%d)", fd.get());
David Pursell8a5a5aa2015-09-08 17:17:02 -0700323 length = adb_read(fd, raw_buffer, sizeof(raw_buffer));
Josh Gao90228a62019-04-25 14:04:57 -0700324 D("read_and_dump(): post adb_read(fd=%d): length=%d", fd.get(), length);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700325 if (length <= 0) {
326 break;
327 }
Felipe Leme60192aa2016-07-26 12:14:39 -0700328 callback->OnStdout(buffer_ptr, length);
Felipe Lemeb6447032016-04-01 17:43:27 -0700329 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800330 }
David Pursell8a5a5aa2015-09-08 17:17:02 -0700331
Felipe Leme60192aa2016-07-26 12:14:39 -0700332 return callback->Done(exit_code);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800333}
334
Christopher Tatee0e9f562016-07-06 13:22:22 -0700335static void stdinout_raw_prologue(int inFd, int outFd, int& old_stdin_mode, int& old_stdout_mode) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700336 if (inFd == STDIN_FILENO) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800337 stdin_raw_init();
Spencer Lowe7af2d32015-05-22 16:48:31 -0700338#ifdef _WIN32
339 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY);
340 if (old_stdin_mode == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700341 PLOG(FATAL) << "could not set stdin to binary";
Spencer Lowe7af2d32015-05-22 16:48:31 -0700342 }
343#endif
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700344 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800345
Spencer Lowe7af2d32015-05-22 16:48:31 -0700346#ifdef _WIN32
347 if (outFd == STDOUT_FILENO) {
348 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY);
349 if (old_stdout_mode == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700350 PLOG(FATAL) << "could not set stdout to binary";
Spencer Lowe7af2d32015-05-22 16:48:31 -0700351 }
352 }
353#endif
Christopher Tatee0e9f562016-07-06 13:22:22 -0700354}
355
356static void stdinout_raw_epilogue(int inFd, int outFd, int old_stdin_mode, int old_stdout_mode) {
357 if (inFd == STDIN_FILENO) {
358 stdin_raw_restore();
359#ifdef _WIN32
360 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700361 PLOG(FATAL) << "could not restore stdin mode";
Christopher Tatee0e9f562016-07-06 13:22:22 -0700362 }
363#endif
364 }
365
366#ifdef _WIN32
367 if (outFd == STDOUT_FILENO) {
368 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700369 PLOG(FATAL) << "could not restore stdout mode";
Christopher Tatee0e9f562016-07-06 13:22:22 -0700370 }
371 }
372#endif
373}
374
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800375bool copy_to_file(int inFd, int outFd) {
376 bool result = true;
Yurii Zubrytskyie59c1bd2019-06-27 13:47:34 -0700377 std::vector<char> buf(64 * 1024);
Christopher Tatee0e9f562016-07-06 13:22:22 -0700378 int len;
379 long total = 0;
380 int old_stdin_mode = -1;
381 int old_stdout_mode = -1;
382
383 D("copy_to_file(%d -> %d)", inFd, outFd);
384
385 stdinout_raw_prologue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowe7af2d32015-05-22 16:48:31 -0700386
Elliott Hughes7cf35752015-04-17 17:03:59 -0700387 while (true) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700388 if (inFd == STDIN_FILENO) {
Elliott Hughesc3462f42018-09-05 12:13:11 -0700389 len = unix_read(inFd, buf.data(), buf.size());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700390 } else {
Elliott Hughesc3462f42018-09-05 12:13:11 -0700391 len = adb_read(inFd, buf.data(), buf.size());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700392 }
Christopher Tate73779122011-04-21 12:53:28 -0700393 if (len == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700394 D("copy_to_file() : read 0 bytes; exiting");
Christopher Tate73779122011-04-21 12:53:28 -0700395 break;
396 }
397 if (len < 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700398 D("copy_to_file(): read failed: %s", strerror(errno));
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800399 result = false;
Christopher Tate73779122011-04-21 12:53:28 -0700400 break;
401 }
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700402 if (outFd == STDOUT_FILENO) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700403 fwrite(buf.data(), 1, len, stdout);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700404 fflush(stdout);
405 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700406 adb_write(outFd, buf.data(), len);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700407 }
Christopher Tatefba22972011-06-01 17:56:23 -0700408 total += len;
Christopher Tate73779122011-04-21 12:53:28 -0700409 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800410
Christopher Tatee0e9f562016-07-06 13:22:22 -0700411 stdinout_raw_epilogue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowe7af2d32015-05-22 16:48:31 -0700412
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800413 D("copy_to_file() finished with %s after %lu bytes", result ? "success" : "failure", total);
414 return result;
Christopher Tate73779122011-04-21 12:53:28 -0700415}
416
Elliott Hughesa8265792015-11-03 11:18:40 -0800417static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800418 // Old devices can't handle window size changes.
419 if (shell == nullptr) return;
420
Spencer Low55441402015-11-07 17:34:39 -0800421#if defined(_WIN32)
422 struct winsize {
423 unsigned short ws_row;
424 unsigned short ws_col;
425 unsigned short ws_xpixel;
426 unsigned short ws_ypixel;
427 };
428#endif
429
Elliott Hughesa8265792015-11-03 11:18:40 -0800430 winsize ws;
Spencer Low55441402015-11-07 17:34:39 -0800431
432#if defined(_WIN32)
433 // If stdout is redirected to a non-console, we won't be able to get the
434 // console size, but that makes sense.
435 const intptr_t intptr_handle = _get_osfhandle(STDOUT_FILENO);
436 if (intptr_handle == -1) return;
437
438 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
439
440 CONSOLE_SCREEN_BUFFER_INFO info;
441 memset(&info, 0, sizeof(info));
442 if (!GetConsoleScreenBufferInfo(handle, &info)) return;
443
444 memset(&ws, 0, sizeof(ws));
445 // The number of visible rows, excluding offscreen scroll-back rows which are in info.dwSize.Y.
446 ws.ws_row = info.srWindow.Bottom - info.srWindow.Top + 1;
447 // If the user has disabled "Wrap text output on resize", they can make the screen buffer wider
448 // than the window, in which case we should use the width of the buffer.
449 ws.ws_col = info.dwSize.X;
450#else
Elliott Hughesa8265792015-11-03 11:18:40 -0800451 if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
Spencer Low55441402015-11-07 17:34:39 -0800452#endif
Elliott Hughesa8265792015-11-03 11:18:40 -0800453
454 // Send the new window size as human-readable ASCII for debugging convenience.
455 size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
456 ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
457 shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
Elliott Hughesa8265792015-11-03 11:18:40 -0800458}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800459
David Pursell8a5a5aa2015-09-08 17:17:02 -0700460// Used to pass multiple values to the stdin read thread.
461struct StdinReadArgs {
462 int stdin_fd, write_fd;
David Pursell3fe11f62015-10-06 15:30:03 -0700463 bool raw_stdin;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700464 std::unique_ptr<ShellProtocol> protocol;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800465 char escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700466};
467
David Pursell8a5a5aa2015-09-08 17:17:02 -0700468// Loops to read from stdin and push the data to the given FD.
469// The argument should be a pointer to a StdinReadArgs object. This function
470// will take ownership of the object and delete it when finished.
Josh Gao382ea6e2016-02-12 14:31:15 -0800471static void stdin_read_thread_loop(void* x) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700472 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800473
Elliott Hughesa8265792015-11-03 11:18:40 -0800474#if !defined(_WIN32)
475 // Mask SIGTTIN in case we're in a backgrounded process.
Josh Gaof344ecf2015-10-23 15:03:31 -0700476 sigset_t sigset;
477 sigemptyset(&sigset);
478 sigaddset(&sigset, SIGTTIN);
479 pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
480#endif
481
Spencer Low55441402015-11-07 17:34:39 -0800482#if defined(_WIN32)
483 // _get_interesting_input_record_uncached() causes unix_read_interruptible()
484 // to return -1 with errno == EINTR if the window size changes.
485#else
Elliott Hughesa8265792015-11-03 11:18:40 -0800486 // Unblock SIGWINCH for this thread, so our read(2) below will be
487 // interrupted if the window size changes.
488 sigset_t mask;
489 sigemptyset(&mask);
490 sigaddset(&mask, SIGWINCH);
491 pthread_sigmask(SIG_UNBLOCK, &mask, nullptr);
492#endif
493
494 // Set up the initial window size.
495 send_window_size_change(args->stdin_fd, args->protocol);
496
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800497 char raw_buffer[BUFSIZ];
David Pursell8a5a5aa2015-09-08 17:17:02 -0700498 char* buffer_ptr = raw_buffer;
499 size_t buffer_size = sizeof(raw_buffer);
Elliott Hughesa8265792015-11-03 11:18:40 -0800500 if (args->protocol != nullptr) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700501 buffer_ptr = args->protocol->data();
502 buffer_size = args->protocol->data_capacity();
503 }
504
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800505 // If we need to parse escape sequences, make life easy.
506 if (args->raw_stdin && args->escape_char != '\0') {
507 buffer_size = 1;
508 }
509
510 enum EscapeState { kMidFlow, kStartOfLine, kInEscape };
511 EscapeState state = kStartOfLine;
512
Elliott Hughesb628cb12015-08-03 10:38:08 -0700513 while (true) {
Spencer Low55441402015-11-07 17:34:39 -0800514 // Use unix_read_interruptible() rather than adb_read() for stdin.
515 D("stdin_read_thread_loop(): pre unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
516 int r = unix_read_interruptible(args->stdin_fd, buffer_ptr,
517 buffer_size);
Elliott Hughesa8265792015-11-03 11:18:40 -0800518 if (r == -1 && errno == EINTR) {
519 send_window_size_change(args->stdin_fd, args->protocol);
520 continue;
521 }
Spencer Low55441402015-11-07 17:34:39 -0800522 D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
David Pursell3fe11f62015-10-06 15:30:03 -0700523 if (r <= 0) {
524 // Only devices using the shell protocol know to close subprocess
525 // stdin. For older devices we want to just leave the connection
526 // open, otherwise an unpredictable amount of return data could
527 // be lost due to the FD closing before all data has been received.
528 if (args->protocol) {
529 args->protocol->Write(ShellProtocol::kIdCloseStdin, 0);
530 }
531 break;
532 }
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800533 // If we made stdin raw, check input for escape sequences. In
David Pursell3fe11f62015-10-06 15:30:03 -0700534 // this situation signals like Ctrl+C are sent remotely rather than
535 // interpreted locally so this provides an emergency out if the remote
536 // process starts ignoring the signal. SSH also does this, see the
537 // "escape characters" section on the ssh man page for more info.
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800538 if (args->raw_stdin && args->escape_char != '\0') {
539 char ch = buffer_ptr[0];
540 if (ch == args->escape_char) {
541 if (state == kStartOfLine) {
542 state = kInEscape;
543 // Swallow the escape character.
544 continue;
545 } else {
546 state = kMidFlow;
547 }
548 } else {
549 if (state == kInEscape) {
550 if (ch == '.') {
551 fprintf(stderr,"\r\n[ disconnected ]\r\n");
Elliott Hughesa8265792015-11-03 11:18:40 -0800552 stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700553 exit(0);
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800554 } else {
555 // We swallowed an escape character that wasn't part of
556 // a valid escape sequence; time to cough it up.
557 buffer_ptr[0] = args->escape_char;
558 buffer_ptr[1] = ch;
559 ++r;
David Pursell3fe11f62015-10-06 15:30:03 -0700560 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800561 }
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800562 state = (ch == '\n' || ch == '\r') ? kStartOfLine : kMidFlow;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800563 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800564 }
David Pursell8a5a5aa2015-09-08 17:17:02 -0700565 if (args->protocol) {
566 if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) {
567 break;
568 }
569 } else {
570 if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) {
571 break;
572 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800573 }
574 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800575}
576
David Pursell3fe11f62015-10-06 15:30:03 -0700577// Returns a shell service string with the indicated arguments and command.
578static std::string ShellServiceString(bool use_shell_protocol,
579 const std::string& type_arg,
580 const std::string& command) {
581 std::vector<std::string> args;
582 if (use_shell_protocol) {
583 args.push_back(kShellServiceArgShellProtocol);
Elliott Hughes401847e2015-11-18 12:45:48 -0800584
585 const char* terminal_type = getenv("TERM");
586 if (terminal_type != nullptr) {
587 args.push_back(std::string("TERM=") + terminal_type);
588 }
David Pursell3fe11f62015-10-06 15:30:03 -0700589 }
590 if (!type_arg.empty()) {
591 args.push_back(type_arg);
592 }
593
594 // Shell service string can look like: shell[,arg1,arg2,...]:[command].
595 return android::base::StringPrintf("shell%s%s:%s",
596 args.empty() ? "" : ",",
597 android::base::Join(args, ',').c_str(),
598 command.c_str());
599}
600
601// Connects to a shell on the device and read/writes data.
602//
603// Note: currently this function doesn't properly clean up resources; the
604// FD connected to the adb server is never closed and the stdin read thread
605// may never exit.
606//
607// On success returns the remote exit code if |use_shell_protocol| is true,
608// 0 otherwise. On failure returns 1.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800609static int RemoteShell(bool use_shell_protocol, const std::string& type_arg, char escape_char,
610 bool empty_command, const std::string& service_string) {
Josh Gao05012022017-06-16 15:34:34 -0700611 // Old devices can't handle a service string that's longer than MAX_PAYLOAD_V1.
612 // Use |use_shell_protocol| to determine whether to allow a command longer than that.
613 if (service_string.size() > MAX_PAYLOAD_V1 && !use_shell_protocol) {
614 fprintf(stderr, "error: shell command too long\n");
615 return 1;
616 }
617
David Pursell3fe11f62015-10-06 15:30:03 -0700618 // Make local stdin raw if the device allocates a PTY, which happens if:
619 // 1. We are explicitly asking for a PTY shell, or
620 // 2. We don't specify shell type and are starting an interactive session.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800621 bool raw_stdin = (type_arg == kShellServiceArgPty || (type_arg.empty() && empty_command));
David Pursell3fe11f62015-10-06 15:30:03 -0700622
Elliott Hughes04a98c22015-04-29 08:35:59 -0700623 std::string error;
David Pursella07dbad2015-09-22 10:43:08 -0700624 int fd = adb_connect(service_string, &error);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700625 if (fd < 0) {
626 fprintf(stderr,"error: %s\n", error.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800627 return 1;
628 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800629
David Pursell8a5a5aa2015-09-08 17:17:02 -0700630 StdinReadArgs* args = new StdinReadArgs;
631 if (!args) {
632 LOG(ERROR) << "couldn't allocate StdinReadArgs object";
Elliott Hughesd0269c92015-04-21 19:39:52 -0700633 return 1;
634 }
David Pursell3fe11f62015-10-06 15:30:03 -0700635 args->stdin_fd = STDIN_FILENO;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700636 args->write_fd = fd;
David Pursell3fe11f62015-10-06 15:30:03 -0700637 args->raw_stdin = raw_stdin;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800638 args->escape_char = escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700639 if (use_shell_protocol) {
Josh Gaof2a988c2018-03-07 16:51:08 -0800640 args->protocol = std::make_unique<ShellProtocol>(args->write_fd);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700641 }
Elliott Hughesd0269c92015-04-21 19:39:52 -0700642
Elliott Hughesa8265792015-11-03 11:18:40 -0800643 if (raw_stdin) stdin_raw_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800644
Elliott Hughesa8265792015-11-03 11:18:40 -0800645#if !defined(_WIN32)
646 // Ensure our process is notified if the local window size changes.
647 // We use sigaction(2) to ensure that the SA_RESTART flag is not set,
648 // because the whole reason we're sending signals is to unblock the read(2)!
649 // That also means we don't need to do anything in the signal handler:
650 // the side effect of delivering the signal is all we need.
651 struct sigaction sa;
652 memset(&sa, 0, sizeof(sa));
653 sa.sa_handler = [](int) {};
654 sa.sa_flags = 0;
655 sigaction(SIGWINCH, &sa, nullptr);
656
657 // Now block SIGWINCH in this thread (the main thread) and all threads spawned
658 // from it. The stdin read thread will unblock this signal to ensure that it's
659 // the thread that receives the signal.
660 sigset_t mask;
661 sigemptyset(&mask);
662 sigaddset(&mask, SIGWINCH);
663 pthread_sigmask(SIG_BLOCK, &mask, nullptr);
664#endif
665
666 // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
Josh Gao0f3312a2017-04-12 17:00:49 -0700667 std::thread(stdin_read_thread_loop, args).detach();
668 int exit_code = read_and_dump(fd, use_shell_protocol);
Elliott Hughesf2517142015-05-05 13:41:21 -0700669
Elliott Hughesa8265792015-11-03 11:18:40 -0800670 // TODO: properly exit stdin_read_thread_loop and close |fd|.
David Pursell3fe11f62015-10-06 15:30:03 -0700671
Elliott Hughesa8265792015-11-03 11:18:40 -0800672 // TODO: we should probably install signal handlers for this.
673 // TODO: can we use atexit? even on Windows?
674 if (raw_stdin) stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700675
David Pursell8a5a5aa2015-09-08 17:17:02 -0700676 return exit_code;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800677}
678
Josh Gao91d53b52016-01-31 19:12:26 -0800679static int adb_shell(int argc, const char** argv) {
Josh Gao291733b2020-04-16 19:34:43 -0700680 std::string error;
681 auto&& features = adb_get_feature_set(&error);
682 if (!features) {
683 error_exit("%s", error.c_str());
David Pursell9650d862016-01-21 19:56:50 -0800684 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800685
Elliott Hughes02e33782016-10-19 14:47:11 -0700686 enum PtyAllocationMode { kPtyAuto, kPtyNo, kPtyYes, kPtyDefinitely };
687
688 // Defaults.
Josh Gao291733b2020-04-16 19:34:43 -0700689 char escape_char = '~'; // -e
690 bool use_shell_protocol = CanUseFeature(*features, kFeatureShell2); // -x
Elliott Hughes02e33782016-10-19 14:47:11 -0700691 PtyAllocationMode tty = use_shell_protocol ? kPtyAuto : kPtyDefinitely; // -t/-T
Elliott Hughesda945812015-04-29 12:28:13 -0700692
Elliott Hughesa8265792015-11-03 11:18:40 -0800693 // Parse shell-specific command-line options.
Elliott Hughes02e33782016-10-19 14:47:11 -0700694 argv[0] = "adb shell"; // So getopt(3) error messages start "adb shell".
Huihong Luo323874f2017-08-17 15:23:08 -0700695#ifdef _WIN32
696 // fixes "adb shell -l" crash on Windows, b/37284906
697 __argv = const_cast<char**>(argv);
698#endif
Elliott Hughes02e33782016-10-19 14:47:11 -0700699 optind = 1; // argv[0] is always "shell", so set `optind` appropriately.
700 int opt;
701 while ((opt = getopt(argc, const_cast<char**>(argv), "+e:ntTx")) != -1) {
702 switch (opt) {
703 case 'e':
704 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
Elliott Hughes0119a912018-10-22 17:02:51 -0700705 error_exit("-e requires a single-character argument or 'none'");
Elliott Hughes02e33782016-10-19 14:47:11 -0700706 }
707 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
708 break;
709 case 'n':
710 close_stdin();
711 break;
712 case 'x':
713 // This option basically asks for historical behavior, so set options that
714 // correspond to the historical defaults. This is slightly weird in that -Tx
715 // is fine (because we'll undo the -T) but -xT isn't, but that does seem to
716 // be our least worst choice...
717 use_shell_protocol = false;
718 tty = kPtyDefinitely;
719 escape_char = '~';
720 break;
721 case 't':
722 // Like ssh, -t arguments are cumulative so that multiple -t's
723 // are needed to force a PTY.
724 tty = (tty >= kPtyYes) ? kPtyDefinitely : kPtyYes;
725 break;
726 case 'T':
727 tty = kPtyNo;
728 break;
729 default:
730 // getopt(3) already printed an error message for us.
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800731 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800732 }
Elliott Hughesda945812015-04-29 12:28:13 -0700733 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800734
Elliott Hughes02e33782016-10-19 14:47:11 -0700735 bool is_interactive = (optind == argc);
David Pursell182dc322016-01-27 16:07:52 -0800736
Elliott Hughes02e33782016-10-19 14:47:11 -0700737 std::string shell_type_arg = kShellServiceArgPty;
738 if (tty == kPtyNo) {
739 shell_type_arg = kShellServiceArgRaw;
740 } else if (tty == kPtyAuto) {
741 // If stdin isn't a TTY, default to a raw shell; this lets
742 // things like `adb shell < my_script.sh` work as expected.
743 // Non-interactive shells should also not have a pty.
744 if (!unix_isatty(STDIN_FILENO) || !is_interactive) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800745 shell_type_arg = kShellServiceArgRaw;
Elliott Hughes02e33782016-10-19 14:47:11 -0700746 }
747 } else if (tty == kPtyYes) {
748 // A single -t arg isn't enough to override implicit -T.
749 if (!unix_isatty(STDIN_FILENO)) {
750 fprintf(stderr,
751 "Remote PTY will not be allocated because stdin is not a terminal.\n"
752 "Use multiple -t options to force remote PTY allocation.\n");
753 shell_type_arg = kShellServiceArgRaw;
754 }
755 }
756
757 D("shell -e 0x%x t=%d use_shell_protocol=%s shell_type_arg=%s\n",
758 escape_char, tty,
759 use_shell_protocol ? "true" : "false",
760 (shell_type_arg == kShellServiceArgPty) ? "pty" : "raw");
761
762 // Raw mode is only supported when talking to a new device *and* using the shell protocol.
763 if (!use_shell_protocol) {
764 if (shell_type_arg != kShellServiceArgPty) {
765 fprintf(stderr, "error: %s only supports allocating a pty\n",
Josh Gao291733b2020-04-16 19:34:43 -0700766 !CanUseFeature(*features, kFeatureShell2) ? "device" : "-x");
Elliott Hughes02e33782016-10-19 14:47:11 -0700767 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800768 } else {
Elliott Hughes02e33782016-10-19 14:47:11 -0700769 // If we're not using the shell protocol, the type argument must be empty.
770 shell_type_arg = "";
Elliott Hughesa8265792015-11-03 11:18:40 -0800771 }
David Purselle570b982015-09-14 15:33:50 -0700772 }
Elliott Hughesa8265792015-11-03 11:18:40 -0800773
774 std::string command;
Elliott Hughes02e33782016-10-19 14:47:11 -0700775 if (optind < argc) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800776 // We don't escape here, just like ssh(1). http://b/20564385.
Elliott Hughes02e33782016-10-19 14:47:11 -0700777 command = android::base::Join(std::vector<const char*>(argv + optind, argv + argc), ' ');
Elliott Hughesa8265792015-11-03 11:18:40 -0800778 }
779
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800780 std::string service_string = ShellServiceString(use_shell_protocol, shell_type_arg, command);
781 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command.empty(),
782 service_string);
783}
784
785static int adb_abb(int argc, const char** argv) {
Josh Gao291733b2020-04-16 19:34:43 -0700786 std::string error;
787 auto&& features = adb_get_feature_set(&error);
788 if (!features) {
789 error_exit("%s", error.c_str());
Alex Buynytskyye1fa8142019-01-17 13:13:56 -0800790 return 1;
791 }
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
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001014/**
1015 * Run ppp in "notty" mode against a resource listed as the first parameter
1016 * eg:
1017 *
1018 * ppp dev:/dev/omap_csmi_tty0 <ppp options>
1019 *
1020 */
Elliott Hughes38104452015-04-17 13:57:15 -07001021static int ppp(int argc, const char** argv) {
Yabin Cui2fa43212014-11-11 09:24:11 -08001022#if defined(_WIN32)
Elliott Hughes0119a912018-10-22 17:02:51 -07001023 error_exit("adb %s not implemented on Win32", argv[0]);
Elliott Hughese64126b2018-10-19 13:59:44 -07001024 __builtin_unreachable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001025#else
Elliott Hughes0119a912018-10-22 17:02:51 -07001026 if (argc < 2) error_exit("usage: adb %s <adb service name> [ppp opts]", argv[0]);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001027
Dan Albertf30d73c2015-02-25 17:51:28 -08001028 const char* adb_service_name = argv[1];
Elliott Hughese64126b2018-10-19 13:59:44 -07001029 std::string error_message;
1030 int fd = adb_connect(adb_service_name, &error_message);
Elliott Hughes04a98c22015-04-29 08:35:59 -07001031 if (fd < 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001032 error_exit("could not open adb service %s: %s", adb_service_name, error_message.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001033 }
1034
Elliott Hughes04a98c22015-04-29 08:35:59 -07001035 pid_t pid = fork();
Elliott Hughese64126b2018-10-19 13:59:44 -07001036 if (pid == -1) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001037 perror_exit("fork failed");
Elliott Hughese64126b2018-10-19 13:59:44 -07001038 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001039
Elliott Hughese64126b2018-10-19 13:59:44 -07001040 if (pid == 0) {
1041 // child side
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001042 int i;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001043
1044 // copy args
Elliott Hughese64126b2018-10-19 13:59:44 -07001045 const char** ppp_args = (const char**)alloca(sizeof(char*) * argc + 1);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001046 ppp_args[0] = "pppd";
1047 for (i = 2 ; i < argc ; i++) {
1048 //argv[2] and beyond become ppp_args[1] and beyond
1049 ppp_args[i - 1] = argv[i];
1050 }
Yi Kong86e67182018-07-13 18:15:16 -07001051 ppp_args[i-1] = nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001052
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001053 dup2(fd, STDIN_FILENO);
1054 dup2(fd, STDOUT_FILENO);
1055 adb_close(STDERR_FILENO);
1056 adb_close(fd);
1057
Elliott Hughese64126b2018-10-19 13:59:44 -07001058 execvp("pppd", (char* const*)ppp_args);
Elliott Hughes0119a912018-10-22 17:02:51 -07001059 perror_exit("exec pppd failed");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001060 }
Elliott Hughese64126b2018-10-19 13:59:44 -07001061
1062 // parent side
1063 adb_close(fd);
1064 return 0;
Yabin Cui2fa43212014-11-11 09:24:11 -08001065#endif /* !defined(_WIN32) */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001066}
1067
Josh Gao4ce212e2019-03-11 15:39:44 -07001068static bool wait_for_device(const char* service,
1069 std::optional<std::chrono::milliseconds> timeout = std::nullopt) {
Josh Gao63cede32016-04-13 12:14:16 -07001070 std::vector<std::string> components = android::base::Split(service, "-");
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001071 if (components.size() < 3) {
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001072 fprintf(stderr, "adb: couldn't parse 'wait-for' command: %s\n", service);
1073 return false;
1074 }
1075
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001076 // If the first thing after "wait-for-" wasn't a TRANSPORT, insert whatever
1077 // the current transport implies.
1078 if (components[2] != "usb" && components[2] != "local" && components[2] != "any") {
1079 TransportType t;
1080 adb_get_transport(&t, nullptr, nullptr);
Josh Gao63cede32016-04-13 12:14:16 -07001081 auto it = components.begin() + 2;
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001082 if (t == kTransportUsb) {
Josh Gao63cede32016-04-13 12:14:16 -07001083 components.insert(it, "usb");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001084 } else if (t == kTransportLocal) {
Josh Gao63cede32016-04-13 12:14:16 -07001085 components.insert(it, "local");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001086 } else {
Josh Gao63cede32016-04-13 12:14:16 -07001087 components.insert(it, "any");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001088 }
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001089 }
1090
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001091 // Stitch it back together and send it over...
Josh Gaob39e4152017-08-16 16:57:01 -07001092 std::string cmd = format_host_command(android::base::Join(components, "-").c_str());
Josh Gao4ce212e2019-03-11 15:39:44 -07001093 if (timeout) {
1094 std::thread([timeout]() {
1095 std::this_thread::sleep_for(*timeout);
1096 fprintf(stderr, "timeout expired while waiting for device\n");
1097 _exit(1);
1098 }).detach();
1099 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001100 return adb_command(cmd);
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001101}
1102
Josh Gaod1d03392016-03-04 15:16:18 -08001103static bool adb_root(const char* command) {
1104 std::string error;
Josh Gaod1d03392016-03-04 15:16:18 -08001105
Josh Gaoff707d32019-02-22 15:20:27 -08001106 TransportId transport_id;
1107 unique_fd fd(adb_connect(&transport_id, android::base::StringPrintf("%s:", command), &error));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001108 if (fd < 0) {
Josh Gaod1d03392016-03-04 15:16:18 -08001109 fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
1110 return false;
1111 }
1112
1113 // Figure out whether we actually did anything.
1114 char buf[256];
1115 char* cur = buf;
1116 ssize_t bytes_left = sizeof(buf);
1117 while (bytes_left > 0) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001118 ssize_t bytes_read = adb_read(fd, cur, bytes_left);
Josh Gaod1d03392016-03-04 15:16:18 -08001119 if (bytes_read == 0) {
1120 break;
1121 } else if (bytes_read < 0) {
1122 fprintf(stderr, "adb: error while reading for %s: %s\n", command, strerror(errno));
1123 return false;
1124 }
1125 cur += bytes_read;
1126 bytes_left -= bytes_read;
1127 }
1128
1129 if (bytes_left == 0) {
1130 fprintf(stderr, "adb: unexpected output length for %s\n", command);
1131 return false;
1132 }
1133
Junyong Sun88dd2462020-01-15 16:34:58 +08001134 fwrite(buf, 1, sizeof(buf) - bytes_left, stdout);
Josh Gaod1d03392016-03-04 15:16:18 -08001135 fflush(stdout);
Josh Gaod1d03392016-03-04 15:16:18 -08001136 if (cur != buf && strstr(buf, "restarting") == nullptr) {
1137 return true;
1138 }
1139
Josh Gaoff707d32019-02-22 15:20:27 -08001140 // Wait for the device to go away.
Josh Gao4ce212e2019-03-11 15:39:44 -07001141 TransportType previous_type;
1142 const char* previous_serial;
1143 TransportId previous_id;
1144 adb_get_transport(&previous_type, &previous_serial, &previous_id);
1145
Josh Gaoff707d32019-02-22 15:20:27 -08001146 adb_set_transport(kTransportAny, nullptr, transport_id);
1147 wait_for_device("wait-for-disconnect");
Josh Gao4ce212e2019-03-11 15:39:44 -07001148
1149 // Wait for the device to come back.
1150 // If we were using a specific transport ID, there's nothing we can wait for.
1151 if (previous_id == 0) {
1152 adb_set_transport(previous_type, previous_serial, 0);
Josh Gao04ef6962020-10-15 18:32:55 -07001153 wait_for_device("wait-for-device", 12000ms);
Josh Gao4ce212e2019-03-11 15:39:44 -07001154 }
1155
Josh Gaod3d9cbf2016-06-16 14:00:09 -07001156 return true;
Josh Gaod1d03392016-03-04 15:16:18 -08001157}
1158
Josh Gaob39e4152017-08-16 16:57:01 -07001159int send_shell_command(const std::string& command, bool disable_shell_protocol,
1160 StandardStreamsCallbackInterface* callback) {
Josh Gaoc2705962019-01-23 15:36:42 -08001161 unique_fd fd;
David Pursell9650d862016-01-21 19:56:50 -08001162 bool use_shell_protocol = false;
1163
Elliott Hughes170b5682015-04-17 10:59:34 -07001164 while (true) {
David Pursell9650d862016-01-21 19:56:50 -08001165 bool attempt_connection = true;
1166
Felipe Leme60192aa2016-07-26 12:14:39 -07001167 // Use shell protocol if it's supported and the caller doesn't explicitly
1168 // disable it.
David Pursell9650d862016-01-21 19:56:50 -08001169 if (!disable_shell_protocol) {
Josh Gao291733b2020-04-16 19:34:43 -07001170 auto&& features = adb_get_feature_set(nullptr);
1171 if (features) {
1172 use_shell_protocol = CanUseFeature(*features, kFeatureShell2);
David Pursell9650d862016-01-21 19:56:50 -08001173 } else {
1174 // Device was unreachable.
1175 attempt_connection = false;
1176 }
Elliott Hughes04a98c22015-04-29 08:35:59 -07001177 }
David Pursell9650d862016-01-21 19:56:50 -08001178
1179 if (attempt_connection) {
1180 std::string error;
1181 std::string service_string = ShellServiceString(use_shell_protocol, "", command);
1182
Josh Gaoc2705962019-01-23 15:36:42 -08001183 fd.reset(adb_connect(service_string, &error));
David Pursell9650d862016-01-21 19:56:50 -08001184 if (fd >= 0) {
1185 break;
1186 }
1187 }
1188
Felipe Leme60192aa2016-07-26 12:14:39 -07001189 fprintf(stderr, "- waiting for device -\n");
Josh Gaob39e4152017-08-16 16:57:01 -07001190 if (!wait_for_device("wait-for-device")) {
Josh Gao6a7e5732016-02-24 15:16:17 -08001191 return 1;
1192 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001193 }
1194
Josh Gaoc2705962019-01-23 15:36:42 -08001195 return read_and_dump(fd.get(), use_shell_protocol, callback);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001196}
1197
Josh Gaob39e4152017-08-16 16:57:01 -07001198static int logcat(int argc, const char** argv) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001199 char* log_tags = getenv("ANDROID_LOG_TAGS");
1200 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001201
David Pursell22fc5e92015-09-30 13:35:42 -07001202 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001203
Jeff Sharkey824d1062014-06-10 11:31:24 -07001204 if (!strcmp(argv[0], "longcat")) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001205 cmd += " -v long";
Christopher Tate7b9b5162011-11-30 13:00:33 -08001206 }
1207
Elliott Hughese4b64792015-04-17 20:11:08 -07001208 --argc;
1209 ++argv;
Elliott Hughes170b5682015-04-17 10:59:34 -07001210 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001211 cmd += " " + escape_arg(*argv++);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001212 }
1213
Elliott Hughes8fa33512018-06-14 10:46:05 -07001214 return send_shell_command(cmd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001215}
1216
Josh Gao90228a62019-04-25 14:04:57 -07001217static void write_zeros(int bytes, borrowed_fd fd) {
Christopher Tatee0e9f562016-07-06 13:22:22 -07001218 int old_stdin_mode = -1;
1219 int old_stdout_mode = -1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001220 std::vector<char> buf(bytes);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001221
Josh Gao90228a62019-04-25 14:04:57 -07001222 D("write_zeros(%d) -> %d", bytes, fd.get());
Christopher Tatee0e9f562016-07-06 13:22:22 -07001223
Josh Gao90228a62019-04-25 14:04:57 -07001224 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001225
1226 if (fd == STDOUT_FILENO) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001227 fwrite(buf.data(), 1, bytes, stdout);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001228 fflush(stdout);
1229 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001230 adb_write(fd, buf.data(), bytes);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001231 }
1232
Josh Gao90228a62019-04-25 14:04:57 -07001233 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001234
1235 D("write_zeros() finished");
Christopher Tatee0e9f562016-07-06 13:22:22 -07001236}
1237
Dan Albertf30d73c2015-02-25 17:51:28 -08001238static int backup(int argc, const char** argv) {
Al Suttonb6326c72019-05-09 16:14:05 +00001239 fprintf(stdout, "WARNING: adb backup is deprecated and may be removed in a future release\n");
1240
Elliott Hughes1c1f7dc2015-08-21 20:31:31 -07001241 const char* filename = "backup.ab";
Christopher Tate73779122011-04-21 12:53:28 -07001242
Christopher Tatefba22972011-06-01 17:56:23 -07001243 /* find, extract, and use any -f argument */
Elliott Hughese4b64792015-04-17 20:11:08 -07001244 for (int i = 1; i < argc; i++) {
Christopher Tatefba22972011-06-01 17:56:23 -07001245 if (!strcmp("-f", argv[i])) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001246 if (i == argc - 1) error_exit("backup -f passed with no filename");
Christopher Tatefba22972011-06-01 17:56:23 -07001247 filename = argv[i+1];
Elliott Hughese4b64792015-04-17 20:11:08 -07001248 for (int j = i+2; j <= argc; ) {
Christopher Tatefba22972011-06-01 17:56:23 -07001249 argv[i++] = argv[j++];
1250 }
1251 argc -= 2;
Yi Kong86e67182018-07-13 18:15:16 -07001252 argv[argc] = nullptr;
Christopher Tatefba22972011-06-01 17:56:23 -07001253 }
Christopher Tate73779122011-04-21 12:53:28 -07001254 }
1255
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001256 // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
1257 // a list of packages is required.
Elliott Hughes0119a912018-10-22 17:02:51 -07001258 if (argc < 2) error_exit("backup either needs a list of packages or -all/-shared");
Christopher Tatecf4f16a2011-08-22 17:12:08 -07001259
Christopher Tate1e9f2392011-12-08 19:04:34 -08001260 adb_unlink(filename);
Josh Gaoc2705962019-01-23 15:36:42 -08001261 unique_fd outFd(adb_creat(filename, 0640));
Christopher Tate73779122011-04-21 12:53:28 -07001262 if (outFd < 0) {
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001263 fprintf(stderr, "adb: backup unable to create file '%s': %s\n", filename, strerror(errno));
1264 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001265 }
1266
Elliott Hughese4b64792015-04-17 20:11:08 -07001267 std::string cmd = "backup:";
1268 --argc;
1269 ++argv;
1270 while (argc-- > 0) {
1271 cmd += " " + escape_arg(*argv++);
Christopher Tate73779122011-04-21 12:53:28 -07001272 }
1273
Yabin Cui815ad882015-09-02 17:44:28 -07001274 D("backup. filename=%s cmd=%s", filename, cmd.c_str());
Elliott Hughes04a98c22015-04-29 08:35:59 -07001275 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001276 unique_fd fd(adb_connect(cmd, &error));
Christopher Tate73779122011-04-21 12:53:28 -07001277 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001278 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001279 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001280 }
1281
Elliott Hughes65bc2272017-04-18 14:34:16 -07001282 fprintf(stdout, "Now unlock your device and confirm the backup operation...\n");
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001283 fflush(stdout);
1284
Josh Gaoc2705962019-01-23 15:36:42 -08001285 copy_to_file(fd.get(), outFd.get());
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001286 return EXIT_SUCCESS;
Christopher Tate73779122011-04-21 12:53:28 -07001287}
1288
Dan Albertf30d73c2015-02-25 17:51:28 -08001289static int restore(int argc, const char** argv) {
Al Suttonb6326c72019-05-09 16:14:05 +00001290 fprintf(stdout, "WARNING: adb restore is deprecated and may be removed in a future release\n");
1291
Elliott Hughes0119a912018-10-22 17:02:51 -07001292 if (argc != 2) error_exit("restore requires an argument");
Christopher Tatecf5379b2011-05-17 15:52:54 -07001293
Elliott Hughes04a98c22015-04-29 08:35:59 -07001294 const char* filename = argv[1];
Josh Gaoc2705962019-01-23 15:36:42 -08001295 unique_fd tarFd(adb_open(filename, O_RDONLY));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001296 if (tarFd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001297 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001298 return -1;
1299 }
1300
Elliott Hughes04a98c22015-04-29 08:35:59 -07001301 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001302 unique_fd fd(adb_connect("restore:", &error));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001303 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001304 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
Christopher Tatecf5379b2011-05-17 15:52:54 -07001305 return -1;
1306 }
1307
Elliott Hughes65bc2272017-04-18 14:34:16 -07001308 fprintf(stdout, "Now unlock your device and confirm the restore operation.\n");
1309 fflush(stdout);
1310
Josh Gaoc2705962019-01-23 15:36:42 -08001311 copy_to_file(tarFd.get(), fd.get());
Christopher Tatecf5379b2011-05-17 15:52:54 -07001312
Christopher Tatee0e9f562016-07-06 13:22:22 -07001313 // Provide an in-band EOD marker in case the archive file is malformed
Josh Gaoc2705962019-01-23 15:36:42 -08001314 write_zeros(512 * 2, fd);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001315
Josh Gao95230e82016-03-04 15:51:03 -08001316 // Wait until the other side finishes, or it'll get sent SIGHUP.
Josh Gaoc2705962019-01-23 15:36:42 -08001317 copy_to_file(fd.get(), STDOUT_FILENO);
Christopher Tatecf5379b2011-05-17 15:52:54 -07001318 return 0;
1319}
1320
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001321static CompressionType parse_compression_type(const std::string& str, bool allow_numbers) {
1322 if (allow_numbers) {
1323 if (str == "0") {
1324 return CompressionType::None;
1325 } else if (str == "1") {
1326 return CompressionType::Any;
1327 }
1328 }
1329
1330 if (str == "any") {
1331 return CompressionType::Any;
1332 } else if (str == "none") {
1333 return CompressionType::None;
1334 }
1335
1336 if (str == "brotli") {
1337 return CompressionType::Brotli;
Josh Gaofb386cc2020-03-26 22:02:03 -07001338 } else if (str == "lz4") {
1339 return CompressionType::LZ4;
Josh Gaobdebc9b2020-05-27 17:52:52 -07001340 } else if (str == "zstd") {
1341 return CompressionType::Zstd;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001342 }
1343
1344 error_exit("unexpected compression type %s", str.c_str());
1345}
1346
Dan Albert8449e062017-05-18 22:56:48 -07001347static void parse_push_pull_args(const char** arg, int narg, std::vector<const char*>* srcs,
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001348 const char** dst, bool* copy_attrs, bool* sync,
Josh Gao8a410a02020-03-30 23:25:16 -07001349 CompressionType* compression, bool* dry_run) {
Josh Gao5d093b22015-10-30 16:57:19 -07001350 *copy_attrs = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001351 if (const char* adb_compression = getenv("ADB_COMPRESSION")) {
1352 *compression = parse_compression_type(adb_compression, true);
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001353 }
Mark Lindner9f9d1452014-03-11 17:55:59 -07001354
Josh Gao5d093b22015-10-30 16:57:19 -07001355 srcs->clear();
1356 bool ignore_flags = false;
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001357 while (narg > 0) {
Josh Gao5d093b22015-10-30 16:57:19 -07001358 if (ignore_flags || *arg[0] != '-') {
1359 srcs->push_back(*arg);
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001360 } else {
Josh Gao5d093b22015-10-30 16:57:19 -07001361 if (!strcmp(*arg, "-p")) {
1362 // Silently ignore for backwards compatibility.
1363 } else if (!strcmp(*arg, "-a")) {
1364 *copy_attrs = true;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001365 } else if (!strcmp(*arg, "-z")) {
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001366 if (narg < 2) {
1367 error_exit("-z requires an argument");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001368 }
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001369 *compression = parse_compression_type(*++arg, false);
1370 --narg;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001371 } else if (!strcmp(*arg, "-Z")) {
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001372 *compression = CompressionType::None;
Josh Gao8a410a02020-03-30 23:25:16 -07001373 } else if (dry_run && !strcmp(*arg, "-n")) {
1374 *dry_run = true;
Dan Albert8449e062017-05-18 22:56:48 -07001375 } else if (!strcmp(*arg, "--sync")) {
1376 if (sync != nullptr) {
1377 *sync = true;
1378 }
Josh Gao5d093b22015-10-30 16:57:19 -07001379 } else if (!strcmp(*arg, "--")) {
1380 ignore_flags = true;
1381 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001382 error_exit("unrecognized option '%s'", *arg);
Josh Gao5d093b22015-10-30 16:57:19 -07001383 }
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001384 }
Mark Lindner9f9d1452014-03-11 17:55:59 -07001385 ++arg;
1386 --narg;
1387 }
1388
Josh Gao5d093b22015-10-30 16:57:19 -07001389 if (srcs->size() > 1) {
1390 *dst = srcs->back();
1391 srcs->pop_back();
Mark Lindner9f9d1452014-03-11 17:55:59 -07001392 }
1393}
1394
Shukang Zhou420ad552020-02-13 17:01:39 -08001395static int adb_connect_command(const std::string& command, TransportId* transport,
1396 StandardStreamsCallbackInterface* callback) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001397 std::string error;
Josh Gao67209db2019-03-14 15:38:02 -07001398 unique_fd fd(adb_connect(transport, command, &error));
Elliott Hughesdabb9742015-05-07 23:37:40 -07001399 if (fd < 0) {
1400 fprintf(stderr, "error: %s\n", error.c_str());
1401 return 1;
Tao Bao0db67642015-03-29 11:22:34 -07001402 }
Shukang Zhou420ad552020-02-13 17:01:39 -08001403 read_and_dump(fd, false, callback);
Elliott Hughesdabb9742015-05-07 23:37:40 -07001404 return 0;
Tao Bao0db67642015-03-29 11:22:34 -07001405}
1406
Shukang Zhou420ad552020-02-13 17:01:39 -08001407static int adb_connect_command(const std::string& command, TransportId* transport = nullptr) {
1408 return adb_connect_command(command, transport, &DEFAULT_STANDARD_STREAMS_CALLBACK);
1409}
1410
1411// A class that prints out human readable form of the protobuf message for "track-app" service
1412// (received in binary format).
1413class TrackAppStreamsCallback : public DefaultStandardStreamsCallback {
1414 public:
1415 TrackAppStreamsCallback() : DefaultStandardStreamsCallback(nullptr, nullptr) {}
1416
1417 // Assume the buffer contains at least 4 bytes of valid data.
1418 void OnStdout(const char* buffer, int length) override {
1419 if (length < 4) return; // Unexpected length received. Do nothing.
1420
1421 adb::proto::AppProcesses binary_proto;
1422 // The first 4 bytes are the length of remaining content in hexadecimal format.
1423 binary_proto.ParseFromString(std::string(buffer + 4, length - 4));
1424 char summary[24]; // The following string includes digits and 16 fixed characters.
1425 int written = snprintf(summary, sizeof(summary), "Process count: %d\n",
1426 binary_proto.process_size());
1427 OnStream(nullptr, stdout, summary, written);
1428
1429 std::string string_proto;
1430 google::protobuf::TextFormat::PrintToString(binary_proto, &string_proto);
1431 OnStream(nullptr, stdout, string_proto.data(), string_proto.length());
1432 }
1433
1434 private:
1435 DISALLOW_COPY_AND_ASSIGN(TrackAppStreamsCallback);
1436};
1437
Josh Gao7b438fa2018-11-16 14:47:59 -08001438static int adb_connect_command_bidirectional(const std::string& command) {
1439 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001440 unique_fd fd(adb_connect(command, &error));
Josh Gao7b438fa2018-11-16 14:47:59 -08001441 if (fd < 0) {
1442 fprintf(stderr, "error: %s\n", error.c_str());
1443 return 1;
1444 }
1445
1446 static constexpr auto forward = [](int src, int sink, bool exit_on_end) {
1447 char buf[4096];
1448 while (true) {
1449 int rc = adb_read(src, buf, sizeof(buf));
1450 if (rc == 0) {
1451 if (exit_on_end) {
1452 exit(0);
1453 } else {
1454 adb_shutdown(sink, SHUT_WR);
1455 }
1456 return;
1457 } else if (rc < 0) {
1458 perror_exit("read failed");
1459 }
1460 if (!WriteFdExactly(sink, buf, rc)) {
1461 perror_exit("write failed");
1462 }
1463 }
1464 };
1465
Josh Gaoc2705962019-01-23 15:36:42 -08001466 std::thread read(forward, fd.get(), STDOUT_FILENO, true);
1467 std::thread write(forward, STDIN_FILENO, fd.get(), false);
Josh Gao7b438fa2018-11-16 14:47:59 -08001468 read.join();
1469 write.join();
Josh Gao7b438fa2018-11-16 14:47:59 -08001470 return 0;
1471}
1472
Elliott Hughesda945812015-04-29 12:28:13 -07001473static int adb_query_command(const std::string& command) {
1474 std::string result;
1475 std::string error;
1476 if (!adb_query(command, &result, &error)) {
1477 fprintf(stderr, "error: %s\n", error.c_str());
1478 return 1;
1479 }
1480 printf("%s\n", result.c_str());
1481 return 0;
1482}
1483
Spencer Lowe98825e2015-09-07 16:20:13 -07001484// Disallow stdin, stdout, and stderr.
1485static bool _is_valid_ack_reply_fd(const int ack_reply_fd) {
1486#ifdef _WIN32
1487 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
1488 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) &&
1489 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) &&
1490 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle);
1491#else
1492 return ack_reply_fd > 2;
1493#endif
1494}
1495
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07001496static bool _is_valid_os_fd(int fd) {
Songchun Fandaf826a2020-03-09 11:33:44 -07001497 // Disallow invalid FDs and stdin/out/err as well.
1498 if (fd < 3) {
1499 return false;
1500 }
1501#ifdef _WIN32
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07001502 auto handle = (HANDLE)fd;
Songchun Fandaf826a2020-03-09 11:33:44 -07001503 DWORD info = 0;
1504 if (GetHandleInformation(handle, &info) == 0) {
1505 return false;
1506 }
1507#else
1508 int flags = fcntl(fd, F_GETFD);
1509 if (flags == -1) {
1510 return false;
1511 }
1512#endif
1513 return true;
1514}
1515
Elliott Hughes02e33782016-10-19 14:47:11 -07001516int adb_commandline(int argc, const char** argv) {
Josh Gao4007ab72018-08-10 14:23:43 -07001517 bool no_daemon = false;
1518 bool is_daemon = false;
1519 bool is_server = false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001520 int r;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001521 TransportType transport_type = kTransportAny;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001522 int ack_reply_fd = -1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001523
Elliott Hughes4919c172015-11-18 18:07:48 -08001524#if !defined(_WIN32)
1525 // We'd rather have EPIPE than SIGPIPE.
1526 signal(SIGPIPE, SIG_IGN);
1527#endif
1528
Josh Gaobb4f8602016-08-25 16:00:22 -07001529 const char* server_host_str = nullptr;
1530 const char* server_port_str = nullptr;
1531 const char* server_socket_str = nullptr;
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001532
Elliott Hughes67943d12015-10-07 14:55:10 -07001533 // We need to check for -d and -e before we look at $ANDROID_SERIAL.
1534 const char* serial = nullptr;
Josh Gaob39e4152017-08-16 16:57:01 -07001535 TransportId transport_id = 0;
Elliott Hughes67943d12015-10-07 14:55:10 -07001536
Riley Andrews03b4b372014-12-05 17:37:24 -08001537 while (argc > 0) {
Josh Gao67209db2019-03-14 15:38:02 -07001538 if (!strcmp(argv[0], "server")) {
Josh Gao4007ab72018-08-10 14:23:43 -07001539 is_server = true;
Josh Gao67209db2019-03-14 15:38:02 -07001540 } else if (!strcmp(argv[0], "nodaemon")) {
Josh Gao4007ab72018-08-10 14:23:43 -07001541 no_daemon = true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001542 } else if (!strcmp(argv[0], "fork-server")) {
1543 /* this is a special flag used only when the ADB client launches the ADB Server */
Josh Gao4007ab72018-08-10 14:23:43 -07001544 is_daemon = true;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001545 } else if (!strcmp(argv[0], "--reply-fd")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001546 if (argc < 2) error_exit("--reply-fd requires an argument");
Siva Velusamya55dbd82015-08-07 10:10:29 -07001547 const char* reply_fd_str = argv[1];
1548 argc--;
1549 argv++;
1550 ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
Spencer Lowe98825e2015-09-07 16:20:13 -07001551 if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001552 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001553 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001554 }
Josh Gaob39e4152017-08-16 16:57:01 -07001555 } else if (!strncmp(argv[0], "-s", 2)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001556 if (isdigit(argv[0][2])) {
1557 serial = argv[0] + 2;
1558 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001559 if (argc < 2 || argv[0][2] != '\0') error_exit("-s requires an argument");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001560 serial = argv[1];
1561 argc--;
1562 argv++;
1563 }
Josh Gaob39e4152017-08-16 16:57:01 -07001564 } else if (!strncmp(argv[0], "-t", 2)) {
1565 const char* id;
1566 if (isdigit(argv[0][2])) {
1567 id = argv[0] + 2;
1568 } else {
1569 id = argv[1];
1570 argc--;
1571 argv++;
1572 }
1573 transport_id = strtoll(id, const_cast<char**>(&id), 10);
1574 if (*id != '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001575 error_exit("invalid transport id");
Josh Gaob39e4152017-08-16 16:57:01 -07001576 }
Josh Gao67209db2019-03-14 15:38:02 -07001577 } else if (!strcmp(argv[0], "-d")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001578 transport_type = kTransportUsb;
Josh Gao67209db2019-03-14 15:38:02 -07001579 } else if (!strcmp(argv[0], "-e")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001580 transport_type = kTransportLocal;
Josh Gao67209db2019-03-14 15:38:02 -07001581 } else if (!strcmp(argv[0], "-a")) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001582 gListenAll = 1;
Riley Andrews03b4b372014-12-05 17:37:24 -08001583 } else if (!strncmp(argv[0], "-H", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001584 if (argv[0][2] == '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001585 if (argc < 2) error_exit("-H requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001586 server_host_str = argv[1];
Matt Gumbel411775c2012-11-14 10:16:17 -08001587 argc--;
1588 argv++;
1589 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001590 server_host_str = argv[0] + 2;
Matt Gumbel411775c2012-11-14 10:16:17 -08001591 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001592 } else if (!strncmp(argv[0], "-P", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001593 if (argv[0][2] == '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001594 if (argc < 2) error_exit("-P requires an argument");
Matt Gumbel411775c2012-11-14 10:16:17 -08001595 server_port_str = argv[1];
1596 argc--;
1597 argv++;
1598 } else {
1599 server_port_str = argv[0] + 2;
1600 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001601 } else if (!strcmp(argv[0], "-L")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001602 if (argc < 2) error_exit("-L requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001603 server_socket_str = argv[1];
1604 argc--;
1605 argv++;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001606 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001607 /* out of recognized modifiers and flags */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001608 break;
1609 }
1610 argc--;
1611 argv++;
1612 }
1613
Josh Gaobb4f8602016-08-25 16:00:22 -07001614 if ((server_host_str || server_port_str) && server_socket_str) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001615 error_exit("-L is incompatible with -H or -P");
Josh Gaobb4f8602016-08-25 16:00:22 -07001616 }
1617
1618 // If -L, -H, or -P are specified, ignore environment variables.
1619 // Otherwise, prefer ADB_SERVER_SOCKET over ANDROID_ADB_SERVER_ADDRESS/PORT.
Tao Wucaedcb52016-09-16 13:01:24 -07001620 if (!server_host_str && !server_port_str && !server_socket_str) {
1621 server_socket_str = getenv("ADB_SERVER_SOCKET");
Josh Gaobb4f8602016-08-25 16:00:22 -07001622 }
1623
1624 if (!server_socket_str) {
1625 // tcp:1234 and tcp:localhost:1234 are different with -a, so don't default to localhost
1626 server_host_str = server_host_str ? server_host_str : getenv("ANDROID_ADB_SERVER_ADDRESS");
1627
Tao Wucaedcb52016-09-16 13:01:24 -07001628 int server_port = DEFAULT_ADB_PORT;
Josh Gaobb4f8602016-08-25 16:00:22 -07001629 server_port_str = server_port_str ? server_port_str : getenv("ANDROID_ADB_SERVER_PORT");
Tao Wucaedcb52016-09-16 13:01:24 -07001630 if (server_port_str && strlen(server_port_str) > 0) {
1631 if (!android::base::ParseInt(server_port_str, &server_port, 1, 65535)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001632 error_exit(
1633 "$ANDROID_ADB_SERVER_PORT must be a positive number less than 65535: "
1634 "got \"%s\"",
1635 server_port_str);
Tao Wucaedcb52016-09-16 13:01:24 -07001636 }
1637 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001638
1639 int rc;
1640 char* temp;
1641 if (server_host_str) {
Tao Wucaedcb52016-09-16 13:01:24 -07001642 rc = asprintf(&temp, "tcp:%s:%d", server_host_str, server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001643 } else {
Tao Wucaedcb52016-09-16 13:01:24 -07001644 rc = asprintf(&temp, "tcp:%d", server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001645 }
1646 if (rc < 0) {
Elliott Hughese64126b2018-10-19 13:59:44 -07001647 LOG(FATAL) << "failed to allocate server socket specification";
Josh Gaobb4f8602016-08-25 16:00:22 -07001648 }
1649 server_socket_str = temp;
1650 }
1651
1652 adb_set_socket_spec(server_socket_str);
1653
Elliott Hughes67943d12015-10-07 14:55:10 -07001654 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1655 if (transport_type == kTransportAny && serial == nullptr) {
1656 serial = getenv("ANDROID_SERIAL");
1657 }
1658
Josh Gaob39e4152017-08-16 16:57:01 -07001659 adb_set_transport(transport_type, serial, transport_id);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001660
David 'Digit' Turner6826db62011-01-31 14:23:56 +01001661 if (is_server) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001662 if (no_daemon || is_daemon) {
Spencer Lowb28812f2015-08-08 15:07:07 -07001663 if (is_daemon && (ack_reply_fd == -1)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001664 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001665 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001666 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001667 r = adb_server_main(is_daemon, server_socket_str, ack_reply_fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001668 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001669 r = launch_server(server_socket_str);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001670 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001671 if (r) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001672 fprintf(stderr,"* could not start server *\n");
1673 }
1674 return r;
1675 }
1676
Riley Andrews03b4b372014-12-05 17:37:24 -08001677 if (argc == 0) {
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001678 help();
1679 return 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001680 }
1681
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001682 /* handle wait-for-* prefix */
1683 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001684 const char* service = argv[0];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001685
Josh Gaob39e4152017-08-16 16:57:01 -07001686 if (!wait_for_device(service)) {
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001687 return 1;
1688 }
1689
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001690 // Allow a command to be run after wait-for-device,
1691 // e.g. 'adb wait-for-device shell'.
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001692 if (argc == 1) {
1693 return 0;
1694 }
1695
1696 /* Fall through */
1697 argc--;
1698 argv++;
1699 }
1700
1701 /* adb_connect() commands */
Riley Andrews03b4b372014-12-05 17:37:24 -08001702 if (!strcmp(argv[0], "devices")) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001703 const char *listopt;
Elliott Hughesda945812015-04-29 12:28:13 -07001704 if (argc < 2) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001705 listopt = "";
Elliott Hughesda945812015-04-29 12:28:13 -07001706 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001707 listopt = argv[1];
Elliott Hughesda945812015-04-29 12:28:13 -07001708 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001709 error_exit("adb devices [-l]");
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001710 }
Elliott Hughesda945812015-04-29 12:28:13 -07001711
1712 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
Josh Gao67209db2019-03-14 15:38:02 -07001713 std::string error;
1714 if (!adb_check_server_version(&error)) {
1715 error_exit("failed to check server version: %s", error.c_str());
1716 }
Elliott Hughesda945812015-04-29 12:28:13 -07001717 printf("List of devices attached\n");
1718 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001719 } else if (!strcmp(argv[0], "transport-id")) {
1720 TransportId transport_id;
1721 std::string error;
1722 unique_fd fd(adb_connect(&transport_id, "host:features", &error, true));
1723 if (fd == -1) {
1724 error_exit("%s", error.c_str());
1725 }
1726 printf("%" PRIu64 "\n", transport_id);
1727 return 0;
1728 } else if (!strcmp(argv[0], "connect")) {
Elliott Hughesa5d09032020-01-08 10:02:43 -08001729 if (argc != 2) error_exit("usage: adb connect HOST[:PORT]");
Elliott Hughesda945812015-04-29 12:28:13 -07001730
1731 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1732 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001733 } else if (!strcmp(argv[0], "disconnect")) {
Elliott Hughes14d673e2019-07-30 13:51:03 -07001734 if (argc > 2) error_exit("usage: adb disconnect [HOST[:PORT]]");
Elliott Hughesda945812015-04-29 12:28:13 -07001735
1736 std::string query = android::base::StringPrintf("host:disconnect:%s",
1737 (argc == 2) ? argv[1] : "");
1738 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001739 } else if (!strcmp(argv[0], "abb")) {
1740 return adb_abb(argc, argv);
Joshua Duong290ccb52019-11-20 14:18:43 -08001741 } else if (!strcmp(argv[0], "pair")) {
Joshua Duong64979d02020-05-05 10:46:17 -07001742 if (argc < 2 || argc > 3) error_exit("usage: adb pair HOST[:PORT] [PAIRING CODE]");
Joshua Duong290ccb52019-11-20 14:18:43 -08001743
1744 std::string password;
Joshua Duong64979d02020-05-05 10:46:17 -07001745 if (argc == 2) {
1746 printf("Enter pairing code: ");
1747 fflush(stdout);
1748 if (!std::getline(std::cin, password) || password.empty()) {
1749 error_exit("No pairing code provided");
1750 }
1751 } else {
1752 password = argv[2];
Joshua Duong290ccb52019-11-20 14:18:43 -08001753 }
1754 std::string query =
1755 android::base::StringPrintf("host:pair:%s:%s", password.c_str(), argv[1]);
1756
1757 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001758 } else if (!strcmp(argv[0], "emu")) {
Spencer Low7dc759f2015-05-06 16:13:42 -07001759 return adb_send_emulator_command(argc, argv, serial);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001760 } else if (!strcmp(argv[0], "shell")) {
Josh Gao91d53b52016-01-31 19:12:26 -08001761 return adb_shell(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001762 } else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001763 int exec_in = !strcmp(argv[0], "exec-in");
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001764
Elliott Hughes0119a912018-10-22 17:02:51 -07001765 if (argc < 2) error_exit("usage: adb %s command", argv[0]);
Zach Riggle328870b2016-04-14 17:18:04 -04001766
Elliott Hughes170b5682015-04-17 10:59:34 -07001767 std::string cmd = "exec:";
1768 cmd += argv[1];
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001769 argc -= 2;
1770 argv += 2;
1771 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001772 cmd += " " + escape_arg(*argv++);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001773 }
1774
Elliott Hughes04a98c22015-04-29 08:35:59 -07001775 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001776 unique_fd fd(adb_connect(cmd, &error));
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001777 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001778 fprintf(stderr, "error: %s\n", error.c_str());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001779 return -1;
1780 }
1781
1782 if (exec_in) {
Josh Gaoc2705962019-01-23 15:36:42 -08001783 copy_to_file(STDIN_FILENO, fd.get());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001784 } else {
Josh Gaoc2705962019-01-23 15:36:42 -08001785 copy_to_file(fd.get(), STDOUT_FILENO);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001786 }
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001787 return 0;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001788 } else if (!strcmp(argv[0], "kill-server")) {
Josh Gaoee356a72017-05-08 18:37:17 -07001789 return adb_kill_server() ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001790 } else if (!strcmp(argv[0], "sideload")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001791 if (argc != 2) error_exit("sideload requires an argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001792 if (adb_sideload_install(argv[1], false /* rescue_mode */)) {
Doug Zongker6b217ed2012-01-09 14:54:53 -08001793 return 1;
1794 } else {
1795 return 0;
1796 }
Tao Baoe23e6c72019-04-07 23:24:03 -07001797 } else if (!strcmp(argv[0], "rescue")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001798 // adb rescue getprop
Tao Baoe23e6c72019-04-07 23:24:03 -07001799 // adb rescue getprop <prop>
1800 // adb rescue install <filename>
xunchang8829d152019-04-22 23:14:28 -07001801 // adb rescue wipe userdata
Tao Bao1b11c232019-06-04 14:37:06 -07001802 if (argc < 2) error_exit("rescue requires at least one argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001803 if (!strcmp(argv[1], "getprop")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001804 if (argc == 2) {
1805 return adb_connect_command("rescue-getprop:");
1806 }
1807 if (argc == 3) {
1808 return adb_connect_command(
1809 android::base::StringPrintf("rescue-getprop:%s", argv[2]));
1810 }
1811 error_exit("invalid rescue getprop arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001812 } else if (!strcmp(argv[1], "install")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001813 if (argc != 3) error_exit("rescue install requires two arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001814 if (adb_sideload_install(argv[2], true /* rescue_mode */) != 0) {
1815 return 1;
1816 }
Tao Bao1b11c232019-06-04 14:37:06 -07001817 } else if (!strcmp(argv[1], "wipe")) {
1818 if (argc != 3 || strcmp(argv[2], "userdata") != 0) {
1819 error_exit("invalid rescue wipe arguments");
1820 }
xunchang8829d152019-04-22 23:14:28 -07001821 return adb_wipe_devices();
Tao Baoe23e6c72019-04-07 23:24:03 -07001822 } else {
1823 error_exit("invalid rescue argument");
1824 }
1825 return 0;
Elliott Hughesfa085be2017-08-23 15:42:28 -07001826 } else if (!strcmp(argv[0], "tcpip")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001827 if (argc != 2) error_exit("tcpip requires an argument");
Elliott Hughesfa085be2017-08-23 15:42:28 -07001828 int port;
1829 if (!android::base::ParseInt(argv[1], &port, 1, 65535)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001830 error_exit("tcpip: invalid port: %s", argv[1]);
Elliott Hughesfa085be2017-08-23 15:42:28 -07001831 }
1832 return adb_connect_command(android::base::StringPrintf("tcpip:%d", port));
Josh Gaof764d572019-07-11 14:15:32 -07001833 } else if (!strcmp(argv[0], "remount")) {
Josh Gao291733b2020-04-16 19:34:43 -07001834 std::string error;
1835 auto&& features = adb_get_feature_set(&error);
1836 if (!features) {
1837 error_exit("%s", error.c_str());
Josh Gaof764d572019-07-11 14:15:32 -07001838 }
1839
Josh Gao291733b2020-04-16 19:34:43 -07001840 if (CanUseFeature(*features, kFeatureRemountShell)) {
Mark Salyzyne39eb9b2019-09-17 08:01:15 -07001841 std::vector<const char*> args = {"shell"};
1842 args.insert(args.cend(), argv, argv + argc);
Josh Gaofff240a2020-01-08 12:39:52 -08001843 return adb_shell_noinput(args.size(), args.data());
Mark Salyzyne39eb9b2019-09-17 08:01:15 -07001844 } else if (argc > 1) {
1845 auto command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
1846 return adb_connect_command(command);
Josh Gaof764d572019-07-11 14:15:32 -07001847 } else {
1848 return adb_connect_command("remount:");
1849 }
Elliott Hughesd94e8ba2015-07-21 16:13:40 -07001850 }
Mark Salyzynd6420432018-08-29 10:44:33 -07001851 // clang-format off
Josh Gaof764d572019-07-11 14:15:32 -07001852 else if (!strcmp(argv[0], "reboot") ||
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001853 !strcmp(argv[0], "reboot-bootloader") ||
Mark Salyzynd6420432018-08-29 10:44:33 -07001854 !strcmp(argv[0], "reboot-fastboot") ||
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001855 !strcmp(argv[0], "usb") ||
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001856 !strcmp(argv[0], "disable-verity") ||
1857 !strcmp(argv[0], "enable-verity")) {
Mark Salyzynd6420432018-08-29 10:44:33 -07001858 // clang-format on
Elliott Hughesdabb9742015-05-07 23:37:40 -07001859 std::string command;
Tao Bao0db67642015-03-29 11:22:34 -07001860 if (!strcmp(argv[0], "reboot-bootloader")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001861 command = "reboot:bootloader";
Mark Salyzynd6420432018-08-29 10:44:33 -07001862 } else if (!strcmp(argv[0], "reboot-fastboot")) {
1863 command = "reboot:fastboot";
Tao Bao0db67642015-03-29 11:22:34 -07001864 } else if (argc > 1) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001865 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
Tao Bao0db67642015-03-29 11:22:34 -07001866 } else {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001867 command = android::base::StringPrintf("%s:", argv[0]);
The Android Open Source Project9c753402009-03-13 13:04:37 -07001868 }
Tao Bao0db67642015-03-29 11:22:34 -07001869 return adb_connect_command(command);
Josh Gaod1d03392016-03-04 15:16:18 -08001870 } else if (!strcmp(argv[0], "root") || !strcmp(argv[0], "unroot")) {
1871 return adb_root(argv[0]) ? 0 : 1;
1872 } else if (!strcmp(argv[0], "bugreport")) {
Felipe Leme042c3512016-07-19 17:07:22 -07001873 Bugreport bugreport;
Josh Gaob39e4152017-08-16 16:57:01 -07001874 return bugreport.DoIt(argc, argv);
Felipe Lemeb6447032016-04-01 17:43:27 -07001875 } else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001876 bool reverse = !strcmp(argv[0], "reverse");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001877 --argc;
Elliott Hughes0119a912018-10-22 17:02:51 -07001878 if (argc < 1) error_exit("%s requires an argument", argv[0]);
Josh Gao596f63b2018-07-31 15:36:03 -07001879 ++argv;
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001880
1881 // Determine the <host-prefix> for this command.
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001882 std::string host_prefix;
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001883 if (reverse) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001884 host_prefix = "reverse:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001885 } else {
Josh Gaoed00ae12019-08-06 16:43:34 -07001886 host_prefix = "host:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001887 }
1888
Elliott Hughese64126b2018-10-19 13:59:44 -07001889 std::string cmd, error_message;
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001890 if (strcmp(argv[0], "--list") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001891 if (argc != 1) error_exit("--list doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001892 return adb_query_command(host_prefix + "list-forward");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001893 } else if (strcmp(argv[0], "--remove-all") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001894 if (argc != 1) error_exit("--remove-all doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001895 cmd = "killforward-all";
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001896 } else if (strcmp(argv[0], "--remove") == 0) {
1897 // forward --remove <local>
Elliott Hughes0119a912018-10-22 17:02:51 -07001898 if (argc != 2) error_exit("--remove requires an argument");
Josh Gaoed00ae12019-08-06 16:43:34 -07001899 cmd = std::string("killforward:") + argv[1];
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001900 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1901 // forward --no-rebind <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001902 if (argc != 3) error_exit("--no-rebind takes two arguments");
Elliott Hughese64126b2018-10-19 13:59:44 -07001903 if (forward_targets_are_valid(argv[1], argv[2], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001904 cmd = std::string("forward:norebind:") + argv[1] + ";" + argv[2];
David Pursell19d0c232016-04-07 11:25:48 -07001905 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001906 } else {
1907 // forward <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001908 if (argc != 2) error_exit("forward takes two arguments");
Elliott Hughese64126b2018-10-19 13:59:44 -07001909 if (forward_targets_are_valid(argv[0], argv[1], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001910 cmd = std::string("forward:") + argv[0] + ";" + argv[1];
David Pursell19d0c232016-04-07 11:25:48 -07001911 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001912 }
1913
Elliott Hughese64126b2018-10-19 13:59:44 -07001914 if (!error_message.empty()) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001915 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001916 }
1917
Josh Gaoed00ae12019-08-06 16:43:34 -07001918 unique_fd fd(adb_connect(nullptr, host_prefix + cmd, &error_message, true));
Josh Gaoc2705962019-01-23 15:36:42 -08001919 if (fd < 0 || !adb_status(fd.get(), &error_message)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001920 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001921 }
1922
1923 // Server or device may optionally return a resolved TCP port number.
1924 std::string resolved_port;
Elliott Hughese64126b2018-10-19 13:59:44 -07001925 if (ReadProtocolString(fd, &resolved_port, &error_message) && !resolved_port.empty()) {
David Pursell19d0c232016-04-07 11:25:48 -07001926 printf("%s\n", resolved_port.c_str());
1927 }
1928
1929 ReadOrderlyShutdown(fd);
1930 return 0;
Joshua Duonge22e1612020-03-31 10:58:50 -07001931 } else if (!strcmp(argv[0], "mdns")) {
1932 --argc;
1933 if (argc < 1) error_exit("mdns requires an argument");
1934 ++argv;
1935
1936 std::string error;
1937 if (!adb_check_server_version(&error)) {
1938 error_exit("failed to check server version: %s", error.c_str());
1939 }
1940
1941 std::string query = "host:mdns:";
1942 if (!strcmp(argv[0], "check")) {
1943 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1944 query += "check";
Joshua Duong5f63d112020-03-31 08:39:24 -07001945 } else if (!strcmp(argv[0], "services")) {
1946 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1947 query += "services";
1948 printf("List of discovered mdns services\n");
Joshua Duonge22e1612020-03-31 10:58:50 -07001949 } else {
1950 error_exit("unknown mdns command [%s]", argv[0]);
1951 }
1952
1953 return adb_query_command(query);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001954 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001955 /* do_sync_*() commands */
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001956 else if (!strcmp(argv[0], "ls")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001957 if (argc != 2) error_exit("ls requires an argument");
Elliott Hughesb628cb12015-08-03 10:38:08 -07001958 return do_sync_ls(argv[1]) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001959 } else if (!strcmp(argv[0], "push")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001960 bool copy_attrs = false;
Dan Albert8449e062017-05-18 22:56:48 -07001961 bool sync = false;
Josh Gao8a410a02020-03-30 23:25:16 -07001962 bool dry_run = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001963 CompressionType compression = CompressionType::Any;
Josh Gao5d093b22015-10-30 16:57:19 -07001964 std::vector<const char*> srcs;
1965 const char* dst = nullptr;
Mark Lindner9f9d1452014-03-11 17:55:59 -07001966
Josh Gao8a410a02020-03-30 23:25:16 -07001967 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, &sync, &compression,
1968 &dry_run);
Elliott Hughes0119a912018-10-22 17:02:51 -07001969 if (srcs.empty() || !dst) error_exit("push requires an argument");
Josh Gao8a410a02020-03-30 23:25:16 -07001970 return do_sync_push(srcs, dst, sync, compression, dry_run) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001971 } else if (!strcmp(argv[0], "pull")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001972 bool copy_attrs = false;
Snild Dolkow30e74ac2020-09-23 09:31:50 +02001973 CompressionType compression = CompressionType::None;
Josh Gao5d093b22015-10-30 16:57:19 -07001974 std::vector<const char*> srcs;
1975 const char* dst = ".";
Mark Lindner9f9d1452014-03-11 17:55:59 -07001976
Josh Gao8a410a02020-03-30 23:25:16 -07001977 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, nullptr, &compression,
1978 nullptr);
Elliott Hughes0119a912018-10-22 17:02:51 -07001979 if (srcs.empty()) error_exit("pull requires an argument");
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001980 return do_sync_pull(srcs, dst, copy_attrs, compression) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001981 } else if (!strcmp(argv[0], "install")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001982 if (argc < 2) error_exit("install requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001983 return install_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001984 } else if (!strcmp(argv[0], "install-multiple")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001985 if (argc < 2) error_exit("install-multiple requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001986 return install_multiple_app(argc, argv);
Patrick Baumann810ee9b2018-10-09 10:45:03 -07001987 } else if (!strcmp(argv[0], "install-multi-package")) {
Mohammad Samiul Islamed2e8732019-05-29 15:00:00 +01001988 if (argc < 2) error_exit("install-multi-package requires an argument");
Patrick Baumann810ee9b2018-10-09 10:45:03 -07001989 return install_multi_package(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001990 } else if (!strcmp(argv[0], "uninstall")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001991 if (argc < 2) error_exit("uninstall requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001992 return uninstall_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001993 } else if (!strcmp(argv[0], "sync")) {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07001994 std::string src;
Elliott Hughes38104452015-04-17 13:57:15 -07001995 bool list_only = false;
Josh Gao8a410a02020-03-30 23:25:16 -07001996 bool dry_run = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001997 CompressionType compression = CompressionType::Any;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001998
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001999 if (const char* adb_compression = getenv("ADB_COMPRESSION"); adb_compression) {
2000 compression = parse_compression_type(adb_compression, true);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002001 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002002
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002003 int opt;
Josh Gao8a410a02020-03-30 23:25:16 -07002004 while ((opt = getopt(argc, const_cast<char**>(argv), "lnz:Z")) != -1) {
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002005 switch (opt) {
2006 case 'l':
2007 list_only = true;
2008 break;
Josh Gao8a410a02020-03-30 23:25:16 -07002009 case 'n':
2010 dry_run = true;
2011 break;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002012 case 'z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002013 compression = parse_compression_type(optarg, false);
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002014 break;
2015 case 'Z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002016 compression = CompressionType::None;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002017 break;
2018 default:
Josh Gao8a410a02020-03-30 23:25:16 -07002019 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002020 }
2021 }
2022
2023 if (optind == argc) {
2024 src = "all";
2025 } else if (optind + 1 == argc) {
2026 src = argv[optind];
2027 } else {
Josh Gao8a410a02020-03-30 23:25:16 -07002028 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002029 }
2030
Justin Yunb0c201c2019-06-26 09:18:03 +09002031 std::vector<std::string> partitions{"data", "odm", "oem", "product",
2032 "system", "system_ext", "vendor"};
Elliott Hughes145ac022018-04-03 10:54:39 -07002033 bool found = false;
2034 for (const auto& partition : partitions) {
2035 if (src == "all" || src == partition) {
2036 std::string src_dir{product_file(partition)};
2037 if (!directory_exists(src_dir)) continue;
2038 found = true;
Josh Gao8a410a02020-03-30 23:25:16 -07002039 if (!do_sync_sync(src_dir, "/" + partition, list_only, compression, dry_run)) {
2040 return 1;
2041 }
Elliott Hughes145ac022018-04-03 10:54:39 -07002042 }
Elliott Hughes38104452015-04-17 13:57:15 -07002043 }
Elliott Hughes0119a912018-10-22 17:02:51 -07002044 if (!found) error_exit("don't know how to sync %s partition", src.c_str());
Elliott Hughese64126b2018-10-19 13:59:44 -07002045 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002046 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002047 /* passthrough commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002048 else if (!strcmp(argv[0], "get-state") || !strcmp(argv[0], "get-serialno") ||
2049 !strcmp(argv[0], "get-devpath")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002050 return adb_query_command(format_host_command(argv[0]));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002051 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002052 /* other commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002053 else if (!strcmp(argv[0], "logcat") || !strcmp(argv[0], "lolcat") ||
2054 !strcmp(argv[0], "longcat")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002055 return logcat(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002056 } else if (!strcmp(argv[0], "ppp")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002057 return ppp(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002058 } else if (!strcmp(argv[0], "start-server")) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07002059 std::string error;
Spencer Low85ee64b2015-08-11 17:05:02 -07002060 const int result = adb_connect("host:start-server", &error);
2061 if (result < 0) {
2062 fprintf(stderr, "error: %s\n", error.c_str());
2063 }
2064 return result;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002065 } else if (!strcmp(argv[0], "backup")) {
Christopher Tate73779122011-04-21 12:53:28 -07002066 return backup(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002067 } else if (!strcmp(argv[0], "restore")) {
Christopher Tatecf5379b2011-05-17 15:52:54 -07002068 return restore(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002069 } else if (!strcmp(argv[0], "keygen")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002070 if (argc != 2) error_exit("keygen requires an argument");
Yabin Cui19bec5b2015-09-22 15:52:57 -07002071 // Always print key generation information for keygen command.
2072 adb_trace_enable(AUTH);
Nick Kralevich6183c962014-11-13 15:17:29 -08002073 return adb_auth_keygen(argv[1]);
Josh Gao13102c32018-11-15 17:45:46 -08002074 } else if (!strcmp(argv[0], "pubkey")) {
2075 if (argc != 2) error_exit("pubkey requires an argument");
2076 return adb_auth_pubkey(argv[1]);
2077 } else if (!strcmp(argv[0], "jdwp")) {
Tao Bao0db67642015-03-29 11:22:34 -07002078 return adb_connect_command("jdwp");
Josh Gao13102c32018-11-15 17:45:46 -08002079 } else if (!strcmp(argv[0], "track-jdwp")) {
Josh Gao39d01bb2016-05-13 18:18:23 -07002080 return adb_connect_command("track-jdwp");
Shukang Zhou420ad552020-02-13 17:01:39 -08002081 } else if (!strcmp(argv[0], "track-app")) {
Josh Gao291733b2020-04-16 19:34:43 -07002082 std::string error;
2083 auto&& features = adb_get_feature_set(&error);
2084 if (!features) {
2085 error_exit("%s", error.c_str());
Shukang Zhou420ad552020-02-13 17:01:39 -08002086 }
Josh Gao291733b2020-04-16 19:34:43 -07002087 if (!CanUseFeature(*features, kFeatureTrackApp)) {
Shukang Zhou420ad552020-02-13 17:01:39 -08002088 error_exit("track-app is not supported by the device");
2089 }
2090 TrackAppStreamsCallback callback;
2091 return adb_connect_command("track-app", nullptr, &callback);
Josh Gao13102c32018-11-15 17:45:46 -08002092 } else if (!strcmp(argv[0], "track-devices")) {
Elliott Hughes3d792f42019-07-31 14:13:57 -07002093 if (argc > 2 || (argc == 2 && strcmp(argv[1], "-l"))) {
2094 error_exit("usage: adb track-devices [-l]");
2095 }
2096 return adb_connect_command(argc == 2 ? "host:track-devices-l" : "host:track-devices");
Josh Gaobf5167c2018-06-18 14:51:56 -07002097 } else if (!strcmp(argv[0], "raw")) {
2098 if (argc != 2) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002099 error_exit("usage: adb raw SERVICE");
Josh Gaobf5167c2018-06-18 14:51:56 -07002100 }
Josh Gao7b438fa2018-11-16 14:47:59 -08002101 return adb_connect_command_bidirectional(argv[1]);
Josh Gao39d01bb2016-05-13 18:18:23 -07002102 }
2103
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002104 /* "adb /?" is a common idiom under Windows */
Elliott Hughes97e74bb2017-02-06 16:20:30 -08002105 else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002106 help();
2107 return 0;
Josh Gao13102c32018-11-15 17:45:46 -08002108 } else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
Elliott Hughesb9f01642015-08-12 08:32:10 -07002109 fprintf(stdout, "%s", adb_version().c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002110 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002111 } else if (!strcmp(argv[0], "features")) {
David Pursella07dbad2015-09-22 10:43:08 -07002112 // Only list the features common to both the adb client and the device.
Josh Gao291733b2020-04-16 19:34:43 -07002113 std::string error;
2114 auto&& features = adb_get_feature_set(&error);
2115 if (!features) {
2116 error_exit("%s", error.c_str());
David Pursell9650d862016-01-21 19:56:50 -08002117 }
2118
Josh Gao291733b2020-04-16 19:34:43 -07002119 for (const std::string& name : *features) {
2120 if (CanUseFeature(*features, name)) {
David Pursella07dbad2015-09-22 10:43:08 -07002121 printf("%s\n", name.c_str());
2122 }
2123 }
2124 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002125 } else if (!strcmp(argv[0], "host-features")) {
2126 return adb_query_command("host:host-features");
Yabin Cuid78ed222016-04-05 13:50:44 -07002127 } else if (!strcmp(argv[0], "reconnect")) {
2128 if (argc == 1) {
Josh Gaob39e4152017-08-16 16:57:01 -07002129 return adb_query_command(format_host_command(argv[0]));
Josh Gao4e562502016-10-27 14:01:08 -07002130 } else if (argc == 2) {
2131 if (!strcmp(argv[1], "device")) {
2132 std::string err;
2133 adb_connect("reconnect", &err);
2134 return 0;
2135 } else if (!strcmp(argv[1], "offline")) {
2136 std::string err;
2137 return adb_query_command("host:reconnect-offline");
2138 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07002139 error_exit("usage: adb reconnect [device|offline]");
Josh Gao4e562502016-10-27 14:01:08 -07002140 }
Yabin Cuid78ed222016-04-05 13:50:44 -07002141 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002142 } else if (!strcmp(argv[0], "inc-server")) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002143 if (argc < 4) {
2144#ifdef _WIN32
2145 error_exit("usage: adb inc-server CONNECTION_HANDLE OUTPUT_HANDLE FILE1 FILE2 ...");
2146#else
2147 error_exit("usage: adb inc-server CONNECTION_FD OUTPUT_FD FILE1 FILE2 ...");
2148#endif
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002149 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002150 int connection_fd = atoi(argv[1]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002151 if (!_is_valid_os_fd(connection_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002152 error_exit("Invalid connection_fd number given: %d", connection_fd);
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002153 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002154
2155 connection_fd = adb_register_socket(connection_fd);
2156 close_on_exec(connection_fd);
2157
2158 int output_fd = atoi(argv[2]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002159 if (!_is_valid_os_fd(output_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002160 error_exit("Invalid output_fd number given: %d", output_fd);
2161 }
2162 output_fd = adb_register_socket(output_fd);
2163 close_on_exec(output_fd);
2164 return incremental::serve(connection_fd, output_fd, argc - 3, argv + 3);
Dan Albert996c12e2015-05-20 18:58:41 -07002165 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002166
Elliott Hughes0119a912018-10-22 17:02:51 -07002167 error_exit("unknown command %s", argv[0]);
Elliott Hughese64126b2018-10-19 13:59:44 -07002168 __builtin_unreachable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002169}