blob: 6620836f69084f1e2853e71d8d03fc040b63ae34 [file] [log] [blame]
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG ADB
Dan Albertdb6fe642015-03-19 15:21:08 -070018
19#include "sysdeps.h"
20
Dan Albertb302d122015-02-24 15:51:19 -080021#include <assert.h>
22#include <ctype.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080023#include <errno.h>
Elliott Hughesd1a5b2b2015-04-17 14:07:52 -070024#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080025#include <limits.h>
26#include <stdarg.h>
Dan Albertb302d122015-02-24 15:51:19 -080027#include <stdint.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080031#include <sys/stat.h>
Dan Albertb302d122015-02-24 15:51:19 -080032#include <sys/types.h>
Joshua Duong290ccb52019-11-20 14:18:43 -080033#include <iostream>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080034
David Pursell8a5a5aa2015-09-08 17:17:02 -070035#include <memory>
Elliott Hughes170b5682015-04-17 10:59:34 -070036#include <string>
Elliott Hughes73925982016-11-15 12:37:32 -080037#include <thread>
Josh Gao5d093b22015-10-30 16:57:19 -070038#include <vector>
Elliott Hughes170b5682015-04-17 10:59:34 -070039
Elliott Hughese0a6e2a2016-05-26 22:43:19 -070040#include <android-base/file.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080041#include <android-base/logging.h>
Tao Wucaedcb52016-09-16 13:01:24 -070042#include <android-base/parseint.h>
Elliott Hughesf55ead92015-12-04 22:00:26 -080043#include <android-base/stringprintf.h>
44#include <android-base/strings.h>
Elliott Hughes170b5682015-04-17 10:59:34 -070045
Yabin Cui6704a3c2014-11-17 14:48:25 -080046#if !defined(_WIN32)
Elliott Hughes4c5e8042015-11-04 13:07:47 -080047#include <sys/ioctl.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080048#include <termios.h>
Lee Shombertb796cd52022-03-22 12:19:06 -070049#else
50#define _POSIX
51#include <signal.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080052#endif
53
Shukang Zhou420ad552020-02-13 17:01:39 -080054#include <google/protobuf/text_format.h>
55
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080056#include "adb.h"
Nick Kralevich6183c962014-11-13 15:17:29 -080057#include "adb_auth.h"
Dan Albert66a91b02015-02-24 21:26:58 -080058#include "adb_client.h"
Fabien Sanglard05789412024-05-30 23:00:18 -070059#include "adb_host.pb.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000060#include "adb_install.h"
Dan Albert66a91b02015-02-24 21:26:58 -080061#include "adb_io.h"
Josh Gaoea7457b2016-08-30 15:39:25 -070062#include "adb_unique_fd.h"
Elliott Hughes38104452015-04-17 13:57:15 -070063#include "adb_utils.h"
Shukang Zhou420ad552020-02-13 17:01:39 -080064#include "app_processes.pb.h"
Felipe Leme042c3512016-07-19 17:07:22 -070065#include "bugreport.h"
Josh Gaoc7b74592018-07-25 15:55:25 -070066#include "client/file_sync_client.h"
Felipe Leme042c3512016-07-19 17:07:22 -070067#include "commandline.h"
Idries Hamadi1ecee442018-01-29 16:30:36 +000068#include "fastdeploy.h"
Alex Buynytskyy175ce292020-02-13 06:52:04 -080069#include "incremental_server.h"
David Pursell22fc5e92015-09-30 13:35:42 -070070#include "services.h"
Josh Gao076b5ba2018-07-25 16:07:26 -070071#include "shell_protocol.h"
Ryan Prichardc36807b2023-06-21 22:08:16 -070072#include "socket_spec.h"
Josh Gao70267e42016-11-15 18:55:47 -080073#include "sysdeps/chrono.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080074
Felipe Leme60192aa2016-07-26 12:14:39 -070075DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
76
Elliott Hughes145ac022018-04-03 10:54:39 -070077static std::string product_file(const std::string& file) {
Elliott Hughes314db002017-05-01 11:04:31 -070078 const char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
79 if (ANDROID_PRODUCT_OUT == nullptr) {
Elliott Hughes0119a912018-10-22 17:02:51 -070080 error_exit("product directory not specified; set $ANDROID_PRODUCT_OUT");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080081 }
Elliott Hughes145ac022018-04-03 10:54:39 -070082 return std::string{ANDROID_PRODUCT_OUT} + OS_PATH_SEPARATOR_STR + file;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080083}
84
Elliott Hughes38104452015-04-17 13:57:15 -070085static void help() {
Elliott Hughes687f8b42016-09-28 15:25:47 -070086 fprintf(stdout, "%s\n", adb_version().c_str());
Felipe Lemee4893a22016-07-29 17:57:00 -070087 // clang-format off
Elliott Hughes687f8b42016-09-28 15:25:47 -070088 fprintf(stdout,
89 "global options:\n"
Vince Harron5703eb32021-11-12 12:40:58 -080090 " -a listen on all network interfaces, not just localhost\n"
91 " -d use USB device (error if multiple devices connected)\n"
92 " -e use TCP/IP device (error if multiple TCP/IP devices available)\n"
93 " -s SERIAL use device with given serial (overrides $ANDROID_SERIAL)\n"
94 " -t ID use device with given transport id\n"
95 " -H name of adb server host [default=localhost]\n"
96 " -P port of adb server [default=5037]\n"
97 " -L SOCKET listen on given socket for adb server"
98 " [default=tcp:localhost:5037]\n"
99 " --one-device SERIAL|USB only allowed with 'start-server' or 'server nodaemon', server"
100 " will only connect to one USB device, specified by a serial number or USB device"
101 " address.\n"
Lee Shombertb796cd52022-03-22 12:19:06 -0700102 " --exit-on-write-error exit if stdout is closed\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800103 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700104 "general commands:\n"
105 " devices [-l] list connected devices (-l for long output)\n"
106 " help show this help message\n"
107 " version show version num\n"
Elliott Hughes52746b02015-06-12 14:26:29 -0700108 "\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800109 "networking:\n"
Joshua Duong290ccb52019-11-20 14:18:43 -0800110 " connect HOST[:PORT] connect to a device via TCP/IP [default port=5555]\n"
111 " disconnect [HOST[:PORT]]\n"
112 " disconnect from given TCP/IP device [default port=5555], or all\n"
Joshua Duong64979d02020-05-05 10:46:17 -0700113 " pair HOST[:PORT] [PAIRING CODE]\n"
114 " pair with a device for secure TCP/IP communication\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700115 " forward --list list all forward socket connections\n"
116 " forward [--no-rebind] LOCAL REMOTE\n"
117 " forward socket connection using:\n"
118 " tcp:<port> (<local> may be \"tcp:0\" to pick any open port)\n"
119 " localabstract:<unix domain socket name>\n"
120 " localreserved:<unix domain socket name>\n"
121 " localfilesystem:<unix domain socket name>\n"
Shaju Mathew93c8e3c2022-07-27 08:19:01 +0000122 " dev:<character device name>\n"
Octavian Purdila4b4421d2024-04-03 23:13:14 -0700123 " dev-raw:<character device name> (open device in raw mode)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700124 " jdwp:<process pid> (remote only)\n"
Andrew Walbranebf09dd2021-03-03 18:06:12 +0000125 " vsock:<CID>:<port> (remote only)\n"
Daniel Colascione3e124692019-11-13 17:49:37 -0800126 " acceptfd:<fd> (listen only)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700127 " forward --remove LOCAL remove specific forward socket connection\n"
128 " forward --remove-all remove all forward socket connections\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700129 " reverse --list list all reverse socket connections from device\n"
130 " reverse [--no-rebind] REMOTE LOCAL\n"
131 " reverse socket connection using:\n"
132 " tcp:<port> (<remote> may be \"tcp:0\" to pick any open port)\n"
133 " localabstract:<unix domain socket name>\n"
134 " localreserved:<unix domain socket name>\n"
135 " localfilesystem:<unix domain socket name>\n"
136 " reverse --remove REMOTE remove specific reverse socket connection\n"
137 " reverse --remove-all remove all reverse socket connections from device\n"
Joshua Duonge22e1612020-03-31 10:58:50 -0700138 " mdns check check if mdns discovery is available\n"
Joshua Duong5f63d112020-03-31 08:39:24 -0700139 " mdns services list all discovered services\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800140 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700141 "file transfer:\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700142 " push [--sync] [-z ALGORITHM] [-Z] LOCAL... REMOTE\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700143 " copy local files/directories to device\n"
Josh Gao8a410a02020-03-30 23:25:16 -0700144 " -n: dry run: push files to device without storing to the filesystem\n"
Peter Collingbournea41eb3d2024-03-28 20:05:07 -0700145 " -q: suppress progress messages\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800146 " -Z: disable compression\n"
Peter Collingbournea41eb3d2024-03-28 20:05:07 -0700147 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
148 " --sync: only push files that have different timestamps on the host than the device\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700149 " pull [-a] [-z ALGORITHM] [-Z] REMOTE... LOCAL\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700150 " copy files/dirs from device\n"
151 " -a: preserve file timestamp and mode\n"
Peter Collingbournea41eb3d2024-03-28 20:05:07 -0700152 " -q: suppress progress messages\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800153 " -Z: disable compression\n"
Peter Collingbournea41eb3d2024-03-28 20:05:07 -0700154 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
Josh Gaobfcd8ff2020-03-26 19:33:25 -0700155 " sync [-l] [-z ALGORITHM] [-Z] [all|data|odm|oem|product|system|system_ext|vendor]\n"
Elliott Hughes314db002017-05-01 11:04:31 -0700156 " sync a local build from $ANDROID_PRODUCT_OUT to the device (default all)\n"
Elliott Hughesc4b9b972019-07-30 10:32:53 -0700157 " -l: list files that would be copied, but don't copy them\n"
Peter Collingbournea41eb3d2024-03-28 20:05:07 -0700158 " -n: dry run: push files to device without storing to the filesystem\n"
159 " -q: suppress progress messages\n"
Josh Gao2f0f9eb2020-03-04 19:34:08 -0800160 " -Z: disable compression\n"
Peter Collingbournea41eb3d2024-03-28 20:05:07 -0700161 " -z: enable compression with a specified algorithm (any/none/brotli/lz4/zstd)\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800162 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700163 "shell:\n"
164 " shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]\n"
165 " run remote shell command (interactive shell if no command given)\n"
166 " -e: choose escape character, or \"none\"; default '~'\n"
167 " -n: don't read from stdin\n"
Elliott Hughes63cb1812019-12-13 16:43:10 -0800168 " -T: disable pty allocation\n"
169 " -t: allocate a pty if on a tty (-tt: force pty allocation)\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700170 " -x: disable remote exit codes and stdout/stderr separation\n"
171 " emu COMMAND run emulator console command\n"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800172 "\n"
Elliott Hughesf8a41042019-01-11 13:50:05 -0800173 "app installation (see also `adb shell cmd package help`):\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700174 " install [-lrtsdg] [--instant] PACKAGE\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700175 " push a single package to the device and install it\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700176 " install-multiple [-lrtsdpg] [--instant] PACKAGE...\n"
Patrick Baumann810ee9b2018-10-09 10:45:03 -0700177 " push multiple APKs to the device for a single package and install them\n"
178 " install-multi-package [-lrtsdpg] [--instant] PACKAGE...\n"
179 " push one or more packages to the device and install them atomically\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700180 " -r: replace existing application\n"
181 " -t: allow test packages\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700182 " -d: allow version code downgrade (debuggable packages only)\n"
183 " -p: partial application install (install-multiple only)\n"
184 " -g: grant all runtime permissions\n"
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700185 " --abi ABI: override platform's default ABI\n"
Felipe Leme30a3c5a2018-05-08 18:40:18 -0700186 " --instant: cause the app to be installed as an ephemeral install app\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000187 " --no-streaming: always push APK to device and invoke Package Manager as separate steps\n"
188 " --streaming: force streaming APK directly into Package Manager\n"
Henry Daitxe4cc4d92018-12-12 10:40:57 +0000189 " --fastdeploy: use fast deploy\n"
190 " --no-fastdeploy: prevent use of fast deploy\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000191 " --force-agent: force update of deployment agent when using fast deploy\n"
192 " --date-check-agent: update deployment agent when local version is newer and using fast deploy\n"
193 " --version-check-agent: update deployment agent when local version has different version code and using fast deploy\n"
194#ifndef _WIN32
195 " --local-agent: locate agent files from local source build (instead of SDK location)\n"
196#endif
Elliott Hughes9b2458a2019-08-02 17:09:30 -0700197 " (See also `adb shell pm help` for more options.)\n"
Idries Hamadi1ecee442018-01-29 16:30:36 +0000198 //TODO--installlog <filename>
Elliott Hughes687f8b42016-09-28 15:25:47 -0700199 " uninstall [-k] PACKAGE\n"
200 " remove this app package from the device\n"
201 " '-k': keep the data and cache directories\n"
202 "\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700203 "debugging:\n"
204 " bugreport [PATH]\n"
205 " write bugreport to given PATH [default=bugreport.zip];\n"
206 " if PATH is a directory, the bug report is saved in that directory.\n"
207 " devices that don't support zipped bug reports output to stdout.\n"
208 " jdwp list pids of processes hosting a JDWP transport\n"
209 " logcat show device log (logcat --help for more)\n"
210 "\n"
211 "security:\n"
212 " disable-verity disable dm-verity checking on userdebug builds\n"
213 " enable-verity re-enable dm-verity checking on userdebug builds\n"
214 " keygen FILE\n"
215 " generate adb public/private key; private key stored in FILE,\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700216 "\n"
217 "scripting:\n"
Elliott Hughes3657e9d2020-03-10 16:57:47 -0700218 " wait-for[-TRANSPORT]-STATE...\n"
219 " wait for device to be in a given state\n"
Tao Bao9d6eca52019-04-07 23:24:03 -0700220 " STATE: device, recovery, rescue, sideload, bootloader, or disconnect\n"
Josh Gaob32f5ac2019-02-22 14:01:36 -0800221 " TRANSPORT: usb, local, or any [default=any]\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700222 " get-state print offline | bootloader | device\n"
223 " get-serialno print <serial-number>\n"
224 " get-devpath print <device-path>\n"
David Anderson63b8a452018-11-21 13:43:22 -0800225 " remount [-R]\n"
226 " remount partitions read-write. if a reboot is required, -R will\n"
227 " will automatically reboot the device.\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700228 " reboot [bootloader|recovery|sideload|sideload-auto-reboot]\n"
229 " reboot the device; defaults to booting system image but\n"
230 " supports bootloader and recovery too. sideload reboots\n"
231 " into recovery and automatically starts sideload mode,\n"
232 " sideload-auto-reboot is the same but reboots after sideloading.\n"
233 " sideload OTAPACKAGE sideload the given full OTA package\n"
234 " root restart adbd with root permissions\n"
235 " unroot restart adbd without root permissions\n"
bohua49faa82018-10-24 10:38:33 -0700236 " usb restart adbd listening on USB\n"
237 " tcpip PORT restart adbd listening on TCP on PORT\n"
Tim1b29ed32010-02-16 20:18:29 +0000238 "\n"
Yabin Cuid78ed222016-04-05 13:50:44 -0700239 "internal debugging:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700240 " start-server ensure that there is a server running\n"
241 " kill-server kill the server if it is running\n"
242 " reconnect kick connection from host side to force reconnect\n"
243 " reconnect device kick connection from device side to force reconnect\n"
Yabin Cui3cf1b362017-03-10 16:01:01 -0800244 " reconnect offline reset offline/unauthorized devices to force reconnect\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700245 "\n"
Josh Gao8e7c9722021-06-17 04:19:45 -0700246 "usb:\n"
247 " attach attach a detached USB device\n"
248 " detach detach from a USB device to allow use by other processes\n"
249 ""
Elliott Hughes52746b02015-06-12 14:26:29 -0700250 "environment variables:\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700251 " $ADB_TRACE\n"
Fabien Sanglarda3544292023-07-21 20:24:20 +0000252 " comma/space separated list of debug info to log:\n"
Jaewan Kim7abc3dc2024-06-11 12:09:34 +0000253 " all,adb,sockets,packets,rwx,usb,sync,sysdeps,transport,jdwp,services,auth,fdevent,shell,incremental\n"
Elliott Hughes687f8b42016-09-28 15:25:47 -0700254 " $ADB_VENDOR_KEYS colon-separated list of keys (files or directories)\n"
255 " $ANDROID_SERIAL serial number to connect to (see -s)\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000256 " $ANDROID_LOG_TAGS tags to be used by logcat (see logcat --help)\n"
257 " $ADB_LOCAL_TRANSPORT_MAX_PORT max emulator scan port (default 5585, 16 emus)\n"
Joshua Duong2ed15ac2020-04-23 09:46:12 -0700258 " $ADB_MDNS_AUTO_CONNECT comma-separated list of mdns services to allow auto-connect (default adb-tls-connect)\n"
Fabien Sanglardb75cb862022-12-15 01:54:17 +0000259 "\n"
Chirayu Desaieaae4ff2023-09-29 03:16:07 +0530260 "Online documentation: https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md\n"
Fabien Sanglardb75cb862022-12-15 01:54:17 +0000261 "\n"
Tim Baverstock96ee6b12019-02-08 16:27:16 +0000262 );
Felipe Lemee4893a22016-07-29 17:57:00 -0700263 // clang-format on
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800264}
265
Yabin Cui6704a3c2014-11-17 14:48:25 -0800266#if defined(_WIN32)
267
Elliott Hughes6a096932015-04-16 16:47:02 -0700268// Implemented in sysdeps_win32.cpp.
Elliott Hughesa8265792015-11-03 11:18:40 -0800269void stdin_raw_init();
270void stdin_raw_restore();
Yabin Cui6704a3c2014-11-17 14:48:25 -0800271
272#else
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100273static termios g_saved_terminal_state;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800274
Elliott Hughesa8265792015-11-03 11:18:40 -0800275static void stdin_raw_init() {
276 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800277
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100278 termios tio;
Elliott Hughesa8265792015-11-03 11:18:40 -0800279 if (tcgetattr(STDIN_FILENO, &tio)) return;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800280
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100281 cfmakeraw(&tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800282
Alistair Buxton7c5dcbb2013-03-01 22:16:41 +0100283 // No timeout but request at least one character per read.
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800284 tio.c_cc[VTIME] = 0;
285 tio.c_cc[VMIN] = 1;
286
Elliott Hughesa8265792015-11-03 11:18:40 -0800287 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800288}
289
Elliott Hughesa8265792015-11-03 11:18:40 -0800290static void stdin_raw_restore() {
291 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800292}
293#endif
294
Lee Shombertb796cd52022-03-22 12:19:06 -0700295int read_and_dump_protocol(borrowed_fd fd, StandardStreamsCallbackInterface* callback) {
Josh Gaofa64cc22024-01-22 14:42:37 -0800296 // OpenSSH returns 255 on unexpected disconnection.
297 int exit_code = 255;
Lee Shombertb796cd52022-03-22 12:19:06 -0700298 std::unique_ptr<ShellProtocol> protocol = std::make_unique<ShellProtocol>(fd);
299 if (!protocol) {
300 LOG(ERROR) << "failed to allocate memory for ShellProtocol object";
301 return 1;
302 }
303 while (protocol->Read()) {
304 if (protocol->id() == ShellProtocol::kIdStdout) {
305 if (!callback->OnStdout(protocol->data(), protocol->data_length())) {
306 exit_code = SIGPIPE + 128;
307 break;
308 }
309 } else if (protocol->id() == ShellProtocol::kIdStderr) {
310 if (!callback->OnStderr(protocol->data(), protocol->data_length())) {
311 exit_code = SIGPIPE + 128;
312 break;
313 }
314 } else if (protocol->id() == ShellProtocol::kIdExit) {
315 // data() returns a char* which doesn't have defined signedness.
316 // Cast to uint8_t to prevent 255 from being sign extended to INT_MIN,
317 // which doesn't get truncated on Windows.
318 exit_code = static_cast<uint8_t>(protocol->data()[0]);
319 }
320 }
321 return exit_code;
322}
323
Alex Buynytskyy1af550e2019-09-16 12:10:54 -0700324int read_and_dump(borrowed_fd fd, bool use_shell_protocol,
325 StandardStreamsCallbackInterface* callback) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700326 int exit_code = 0;
Felipe Leme5ad50902016-06-06 16:05:36 -0700327 if (fd < 0) return exit_code;
328
David Pursell8a5a5aa2015-09-08 17:17:02 -0700329 if (use_shell_protocol) {
Lee Shombertb796cd52022-03-22 12:19:06 -0700330 exit_code = read_and_dump_protocol(fd, callback);
331 } else {
332 char raw_buffer[BUFSIZ];
333 char* buffer_ptr = raw_buffer;
334 while (true) {
335 D("read_and_dump(): pre adb_read(fd=%d)", fd.get());
336 int length = adb_read(fd, raw_buffer, sizeof(raw_buffer));
337 D("read_and_dump(): post adb_read(fd=%d): length=%d", fd.get(), length);
338 if (length <= 0) {
339 break;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700340 }
Lee Shombertb796cd52022-03-22 12:19:06 -0700341 if (!callback->OnStdout(buffer_ptr, length)) {
342 break;
Felipe Lemeb6447032016-04-01 17:43:27 -0700343 }
Lee Shombertb796cd52022-03-22 12:19:06 -0700344 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800345 }
David Pursell8a5a5aa2015-09-08 17:17:02 -0700346
Felipe Leme60192aa2016-07-26 12:14:39 -0700347 return callback->Done(exit_code);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800348}
349
Christopher Tatee0e9f562016-07-06 13:22:22 -0700350static void stdinout_raw_prologue(int inFd, int outFd, int& old_stdin_mode, int& old_stdout_mode) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700351 if (inFd == STDIN_FILENO) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800352 stdin_raw_init();
Spencer Lowe7af2d32015-05-22 16:48:31 -0700353#ifdef _WIN32
354 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY);
355 if (old_stdin_mode == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700356 PLOG(FATAL) << "could not set stdin to binary";
Spencer Lowe7af2d32015-05-22 16:48:31 -0700357 }
358#endif
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700359 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800360
Spencer Lowe7af2d32015-05-22 16:48:31 -0700361#ifdef _WIN32
362 if (outFd == STDOUT_FILENO) {
363 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY);
364 if (old_stdout_mode == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700365 PLOG(FATAL) << "could not set stdout to binary";
Spencer Lowe7af2d32015-05-22 16:48:31 -0700366 }
367 }
368#endif
Christopher Tatee0e9f562016-07-06 13:22:22 -0700369}
370
371static void stdinout_raw_epilogue(int inFd, int outFd, int old_stdin_mode, int old_stdout_mode) {
372 if (inFd == STDIN_FILENO) {
373 stdin_raw_restore();
374#ifdef _WIN32
375 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700376 PLOG(FATAL) << "could not restore stdin mode";
Christopher Tatee0e9f562016-07-06 13:22:22 -0700377 }
378#endif
379 }
380
381#ifdef _WIN32
382 if (outFd == STDOUT_FILENO) {
383 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) {
Elliott Hughese64126b2018-10-19 13:59:44 -0700384 PLOG(FATAL) << "could not restore stdout mode";
Christopher Tatee0e9f562016-07-06 13:22:22 -0700385 }
386 }
387#endif
388}
389
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800390bool copy_to_file(int inFd, int outFd) {
391 bool result = true;
Yurii Zubrytskyie59c1bd2019-06-27 13:47:34 -0700392 std::vector<char> buf(64 * 1024);
Christopher Tatee0e9f562016-07-06 13:22:22 -0700393 int len;
394 long total = 0;
395 int old_stdin_mode = -1;
396 int old_stdout_mode = -1;
397
398 D("copy_to_file(%d -> %d)", inFd, outFd);
399
400 stdinout_raw_prologue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowe7af2d32015-05-22 16:48:31 -0700401
Elliott Hughes7cf35752015-04-17 17:03:59 -0700402 while (true) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700403 if (inFd == STDIN_FILENO) {
Elliott Hughesc3462f42018-09-05 12:13:11 -0700404 len = unix_read(inFd, buf.data(), buf.size());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700405 } else {
Elliott Hughesc3462f42018-09-05 12:13:11 -0700406 len = adb_read(inFd, buf.data(), buf.size());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700407 }
Christopher Tate73779122011-04-21 12:53:28 -0700408 if (len == 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700409 D("copy_to_file() : read 0 bytes; exiting");
Christopher Tate73779122011-04-21 12:53:28 -0700410 break;
411 }
412 if (len < 0) {
Yabin Cui815ad882015-09-02 17:44:28 -0700413 D("copy_to_file(): read failed: %s", strerror(errno));
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800414 result = false;
Christopher Tate73779122011-04-21 12:53:28 -0700415 break;
416 }
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700417 if (outFd == STDOUT_FILENO) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700418 fwrite(buf.data(), 1, len, stdout);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700419 fflush(stdout);
420 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -0700421 adb_write(outFd, buf.data(), len);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -0700422 }
Christopher Tatefba22972011-06-01 17:56:23 -0700423 total += len;
Christopher Tate73779122011-04-21 12:53:28 -0700424 }
Yabin Cui6704a3c2014-11-17 14:48:25 -0800425
Christopher Tatee0e9f562016-07-06 13:22:22 -0700426 stdinout_raw_epilogue(inFd, outFd, old_stdin_mode, old_stdout_mode);
Spencer Lowe7af2d32015-05-22 16:48:31 -0700427
Josh Gaod7f1d0b2019-12-03 16:05:54 -0800428 D("copy_to_file() finished with %s after %lu bytes", result ? "success" : "failure", total);
429 return result;
Christopher Tate73779122011-04-21 12:53:28 -0700430}
431
Elliott Hughesa8265792015-11-03 11:18:40 -0800432static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800433 // Old devices can't handle window size changes.
434 if (shell == nullptr) return;
435
Spencer Low55441402015-11-07 17:34:39 -0800436#if defined(_WIN32)
437 struct winsize {
438 unsigned short ws_row;
439 unsigned short ws_col;
440 unsigned short ws_xpixel;
441 unsigned short ws_ypixel;
442 };
443#endif
444
Elliott Hughesa8265792015-11-03 11:18:40 -0800445 winsize ws;
Spencer Low55441402015-11-07 17:34:39 -0800446
447#if defined(_WIN32)
448 // If stdout is redirected to a non-console, we won't be able to get the
449 // console size, but that makes sense.
450 const intptr_t intptr_handle = _get_osfhandle(STDOUT_FILENO);
451 if (intptr_handle == -1) return;
452
453 const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
454
455 CONSOLE_SCREEN_BUFFER_INFO info;
456 memset(&info, 0, sizeof(info));
457 if (!GetConsoleScreenBufferInfo(handle, &info)) return;
458
459 memset(&ws, 0, sizeof(ws));
460 // The number of visible rows, excluding offscreen scroll-back rows which are in info.dwSize.Y.
461 ws.ws_row = info.srWindow.Bottom - info.srWindow.Top + 1;
462 // If the user has disabled "Wrap text output on resize", they can make the screen buffer wider
463 // than the window, in which case we should use the width of the buffer.
464 ws.ws_col = info.dwSize.X;
465#else
Elliott Hughesa8265792015-11-03 11:18:40 -0800466 if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
Spencer Low55441402015-11-07 17:34:39 -0800467#endif
Elliott Hughesa8265792015-11-03 11:18:40 -0800468
469 // Send the new window size as human-readable ASCII for debugging convenience.
470 size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
471 ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
472 shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
Elliott Hughesa8265792015-11-03 11:18:40 -0800473}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800474
David Pursell8a5a5aa2015-09-08 17:17:02 -0700475// Used to pass multiple values to the stdin read thread.
476struct StdinReadArgs {
477 int stdin_fd, write_fd;
David Pursell3fe11f62015-10-06 15:30:03 -0700478 bool raw_stdin;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700479 std::unique_ptr<ShellProtocol> protocol;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800480 char escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700481};
482
David Pursell8a5a5aa2015-09-08 17:17:02 -0700483// Loops to read from stdin and push the data to the given FD.
484// The argument should be a pointer to a StdinReadArgs object. This function
485// will take ownership of the object and delete it when finished.
Josh Gao382ea6e2016-02-12 14:31:15 -0800486static void stdin_read_thread_loop(void* x) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700487 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800488
Elliott Hughesa8265792015-11-03 11:18:40 -0800489#if !defined(_WIN32)
490 // Mask SIGTTIN in case we're in a backgrounded process.
Josh Gaof344ecf2015-10-23 15:03:31 -0700491 sigset_t sigset;
492 sigemptyset(&sigset);
493 sigaddset(&sigset, SIGTTIN);
494 pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
495#endif
496
Spencer Low55441402015-11-07 17:34:39 -0800497#if defined(_WIN32)
498 // _get_interesting_input_record_uncached() causes unix_read_interruptible()
499 // to return -1 with errno == EINTR if the window size changes.
500#else
Elliott Hughesa8265792015-11-03 11:18:40 -0800501 // Unblock SIGWINCH for this thread, so our read(2) below will be
502 // interrupted if the window size changes.
503 sigset_t mask;
504 sigemptyset(&mask);
505 sigaddset(&mask, SIGWINCH);
506 pthread_sigmask(SIG_UNBLOCK, &mask, nullptr);
507#endif
508
509 // Set up the initial window size.
510 send_window_size_change(args->stdin_fd, args->protocol);
511
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800512 char raw_buffer[BUFSIZ];
David Pursell8a5a5aa2015-09-08 17:17:02 -0700513 char* buffer_ptr = raw_buffer;
514 size_t buffer_size = sizeof(raw_buffer);
Elliott Hughesa8265792015-11-03 11:18:40 -0800515 if (args->protocol != nullptr) {
David Pursell8a5a5aa2015-09-08 17:17:02 -0700516 buffer_ptr = args->protocol->data();
517 buffer_size = args->protocol->data_capacity();
518 }
519
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800520 // If we need to parse escape sequences, make life easy.
521 if (args->raw_stdin && args->escape_char != '\0') {
522 buffer_size = 1;
523 }
524
525 enum EscapeState { kMidFlow, kStartOfLine, kInEscape };
526 EscapeState state = kStartOfLine;
527
Elliott Hughesb628cb12015-08-03 10:38:08 -0700528 while (true) {
Spencer Low55441402015-11-07 17:34:39 -0800529 // Use unix_read_interruptible() rather than adb_read() for stdin.
530 D("stdin_read_thread_loop(): pre unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
531 int r = unix_read_interruptible(args->stdin_fd, buffer_ptr,
532 buffer_size);
Elliott Hughesa8265792015-11-03 11:18:40 -0800533 if (r == -1 && errno == EINTR) {
534 send_window_size_change(args->stdin_fd, args->protocol);
535 continue;
536 }
Spencer Low55441402015-11-07 17:34:39 -0800537 D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
David Pursell3fe11f62015-10-06 15:30:03 -0700538 if (r <= 0) {
539 // Only devices using the shell protocol know to close subprocess
540 // stdin. For older devices we want to just leave the connection
541 // open, otherwise an unpredictable amount of return data could
542 // be lost due to the FD closing before all data has been received.
543 if (args->protocol) {
544 args->protocol->Write(ShellProtocol::kIdCloseStdin, 0);
545 }
546 break;
547 }
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800548 // If we made stdin raw, check input for escape sequences. In
David Pursell3fe11f62015-10-06 15:30:03 -0700549 // this situation signals like Ctrl+C are sent remotely rather than
550 // interpreted locally so this provides an emergency out if the remote
551 // process starts ignoring the signal. SSH also does this, see the
552 // "escape characters" section on the ssh man page for more info.
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800553 if (args->raw_stdin && args->escape_char != '\0') {
554 char ch = buffer_ptr[0];
555 if (ch == args->escape_char) {
556 if (state == kStartOfLine) {
557 state = kInEscape;
558 // Swallow the escape character.
559 continue;
560 } else {
561 state = kMidFlow;
562 }
563 } else {
564 if (state == kInEscape) {
565 if (ch == '.') {
566 fprintf(stderr,"\r\n[ disconnected ]\r\n");
Elliott Hughesa8265792015-11-03 11:18:40 -0800567 stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700568 exit(0);
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800569 } else {
570 // We swallowed an escape character that wasn't part of
571 // a valid escape sequence; time to cough it up.
572 buffer_ptr[0] = args->escape_char;
573 buffer_ptr[1] = ch;
574 ++r;
David Pursell3fe11f62015-10-06 15:30:03 -0700575 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800576 }
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800577 state = (ch == '\n' || ch == '\r') ? kStartOfLine : kMidFlow;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800578 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800579 }
David Pursell8a5a5aa2015-09-08 17:17:02 -0700580 if (args->protocol) {
581 if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) {
582 break;
583 }
584 } else {
585 if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) {
586 break;
587 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800588 }
589 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800590}
591
David Pursell3fe11f62015-10-06 15:30:03 -0700592// Returns a shell service string with the indicated arguments and command.
593static std::string ShellServiceString(bool use_shell_protocol,
594 const std::string& type_arg,
595 const std::string& command) {
596 std::vector<std::string> args;
597 if (use_shell_protocol) {
598 args.push_back(kShellServiceArgShellProtocol);
Elliott Hughes401847e2015-11-18 12:45:48 -0800599
600 const char* terminal_type = getenv("TERM");
601 if (terminal_type != nullptr) {
602 args.push_back(std::string("TERM=") + terminal_type);
603 }
David Pursell3fe11f62015-10-06 15:30:03 -0700604 }
605 if (!type_arg.empty()) {
606 args.push_back(type_arg);
607 }
608
609 // Shell service string can look like: shell[,arg1,arg2,...]:[command].
610 return android::base::StringPrintf("shell%s%s:%s",
611 args.empty() ? "" : ",",
612 android::base::Join(args, ',').c_str(),
613 command.c_str());
614}
615
616// Connects to a shell on the device and read/writes data.
617//
618// Note: currently this function doesn't properly clean up resources; the
619// FD connected to the adb server is never closed and the stdin read thread
620// may never exit.
621//
622// On success returns the remote exit code if |use_shell_protocol| is true,
623// 0 otherwise. On failure returns 1.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800624static int RemoteShell(bool use_shell_protocol, const std::string& type_arg, char escape_char,
625 bool empty_command, const std::string& service_string) {
Josh Gao05012022017-06-16 15:34:34 -0700626 // Old devices can't handle a service string that's longer than MAX_PAYLOAD_V1.
627 // Use |use_shell_protocol| to determine whether to allow a command longer than that.
628 if (service_string.size() > MAX_PAYLOAD_V1 && !use_shell_protocol) {
629 fprintf(stderr, "error: shell command too long\n");
630 return 1;
631 }
632
David Pursell3fe11f62015-10-06 15:30:03 -0700633 // Make local stdin raw if the device allocates a PTY, which happens if:
634 // 1. We are explicitly asking for a PTY shell, or
635 // 2. We don't specify shell type and are starting an interactive session.
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800636 bool raw_stdin = (type_arg == kShellServiceArgPty || (type_arg.empty() && empty_command));
David Pursell3fe11f62015-10-06 15:30:03 -0700637
Elliott Hughes04a98c22015-04-29 08:35:59 -0700638 std::string error;
David Pursella07dbad2015-09-22 10:43:08 -0700639 int fd = adb_connect(service_string, &error);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700640 if (fd < 0) {
641 fprintf(stderr,"error: %s\n", error.c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800642 return 1;
643 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800644
David Pursell8a5a5aa2015-09-08 17:17:02 -0700645 StdinReadArgs* args = new StdinReadArgs;
646 if (!args) {
647 LOG(ERROR) << "couldn't allocate StdinReadArgs object";
Elliott Hughesd0269c92015-04-21 19:39:52 -0700648 return 1;
649 }
David Pursell3fe11f62015-10-06 15:30:03 -0700650 args->stdin_fd = STDIN_FILENO;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700651 args->write_fd = fd;
David Pursell3fe11f62015-10-06 15:30:03 -0700652 args->raw_stdin = raw_stdin;
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800653 args->escape_char = escape_char;
David Pursell8a5a5aa2015-09-08 17:17:02 -0700654 if (use_shell_protocol) {
Josh Gaof2a988c2018-03-07 16:51:08 -0800655 args->protocol = std::make_unique<ShellProtocol>(args->write_fd);
David Pursell8a5a5aa2015-09-08 17:17:02 -0700656 }
Elliott Hughesd0269c92015-04-21 19:39:52 -0700657
Elliott Hughesa8265792015-11-03 11:18:40 -0800658 if (raw_stdin) stdin_raw_init();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800659
Elliott Hughesa8265792015-11-03 11:18:40 -0800660#if !defined(_WIN32)
661 // Ensure our process is notified if the local window size changes.
662 // We use sigaction(2) to ensure that the SA_RESTART flag is not set,
663 // because the whole reason we're sending signals is to unblock the read(2)!
664 // That also means we don't need to do anything in the signal handler:
665 // the side effect of delivering the signal is all we need.
666 struct sigaction sa;
667 memset(&sa, 0, sizeof(sa));
668 sa.sa_handler = [](int) {};
669 sa.sa_flags = 0;
670 sigaction(SIGWINCH, &sa, nullptr);
671
672 // Now block SIGWINCH in this thread (the main thread) and all threads spawned
673 // from it. The stdin read thread will unblock this signal to ensure that it's
674 // the thread that receives the signal.
675 sigset_t mask;
676 sigemptyset(&mask);
677 sigaddset(&mask, SIGWINCH);
678 pthread_sigmask(SIG_BLOCK, &mask, nullptr);
679#endif
680
681 // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
Josh Gao0f3312a2017-04-12 17:00:49 -0700682 std::thread(stdin_read_thread_loop, args).detach();
683 int exit_code = read_and_dump(fd, use_shell_protocol);
Elliott Hughesf2517142015-05-05 13:41:21 -0700684
Elliott Hughesa8265792015-11-03 11:18:40 -0800685 // TODO: properly exit stdin_read_thread_loop and close |fd|.
David Pursell3fe11f62015-10-06 15:30:03 -0700686
Elliott Hughesa8265792015-11-03 11:18:40 -0800687 // TODO: we should probably install signal handlers for this.
688 // TODO: can we use atexit? even on Windows?
689 if (raw_stdin) stdin_raw_restore();
David Pursell3fe11f62015-10-06 15:30:03 -0700690
David Pursell8a5a5aa2015-09-08 17:17:02 -0700691 return exit_code;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800692}
693
Josh Gao91d53b52016-01-31 19:12:26 -0800694static int adb_shell(int argc, const char** argv) {
Elliott Hughes02e33782016-10-19 14:47:11 -0700695 enum PtyAllocationMode { kPtyAuto, kPtyNo, kPtyYes, kPtyDefinitely };
696
697 // Defaults.
Josh Gao291733b2020-04-16 19:34:43 -0700698 char escape_char = '~'; // -e
Shaju Mathewbf7da1c2021-10-30 13:47:11 -0700699 auto&& features = adb_get_feature_set_or_die();
Josh Gao291733b2020-04-16 19:34:43 -0700700 bool use_shell_protocol = CanUseFeature(*features, kFeatureShell2); // -x
Elliott Hughes02e33782016-10-19 14:47:11 -0700701 PtyAllocationMode tty = use_shell_protocol ? kPtyAuto : kPtyDefinitely; // -t/-T
Elliott Hughesda945812015-04-29 12:28:13 -0700702
Elliott Hughesa8265792015-11-03 11:18:40 -0800703 // Parse shell-specific command-line options.
Elliott Hughes02e33782016-10-19 14:47:11 -0700704 argv[0] = "adb shell"; // So getopt(3) error messages start "adb shell".
Huihong Luo323874f2017-08-17 15:23:08 -0700705#ifdef _WIN32
706 // fixes "adb shell -l" crash on Windows, b/37284906
707 __argv = const_cast<char**>(argv);
708#endif
Elliott Hughes02e33782016-10-19 14:47:11 -0700709 optind = 1; // argv[0] is always "shell", so set `optind` appropriately.
710 int opt;
711 while ((opt = getopt(argc, const_cast<char**>(argv), "+e:ntTx")) != -1) {
712 switch (opt) {
713 case 'e':
714 if (!(strlen(optarg) == 1 || strcmp(optarg, "none") == 0)) {
Elliott Hughes0119a912018-10-22 17:02:51 -0700715 error_exit("-e requires a single-character argument or 'none'");
Elliott Hughes02e33782016-10-19 14:47:11 -0700716 }
717 escape_char = (strcmp(optarg, "none") == 0) ? 0 : optarg[0];
718 break;
719 case 'n':
720 close_stdin();
721 break;
722 case 'x':
723 // This option basically asks for historical behavior, so set options that
724 // correspond to the historical defaults. This is slightly weird in that -Tx
725 // is fine (because we'll undo the -T) but -xT isn't, but that does seem to
726 // be our least worst choice...
727 use_shell_protocol = false;
728 tty = kPtyDefinitely;
729 escape_char = '~';
730 break;
731 case 't':
732 // Like ssh, -t arguments are cumulative so that multiple -t's
733 // are needed to force a PTY.
734 tty = (tty >= kPtyYes) ? kPtyDefinitely : kPtyYes;
735 break;
736 case 'T':
737 tty = kPtyNo;
738 break;
739 default:
740 // getopt(3) already printed an error message for us.
Elliott Hughes4cf6f102015-11-04 13:36:32 -0800741 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800742 }
Elliott Hughesda945812015-04-29 12:28:13 -0700743 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800744
Elliott Hughes02e33782016-10-19 14:47:11 -0700745 bool is_interactive = (optind == argc);
David Pursell182dc322016-01-27 16:07:52 -0800746
Elliott Hughes02e33782016-10-19 14:47:11 -0700747 std::string shell_type_arg = kShellServiceArgPty;
748 if (tty == kPtyNo) {
749 shell_type_arg = kShellServiceArgRaw;
750 } else if (tty == kPtyAuto) {
751 // If stdin isn't a TTY, default to a raw shell; this lets
752 // things like `adb shell < my_script.sh` work as expected.
753 // Non-interactive shells should also not have a pty.
754 if (!unix_isatty(STDIN_FILENO) || !is_interactive) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800755 shell_type_arg = kShellServiceArgRaw;
Elliott Hughes02e33782016-10-19 14:47:11 -0700756 }
757 } else if (tty == kPtyYes) {
758 // A single -t arg isn't enough to override implicit -T.
759 if (!unix_isatty(STDIN_FILENO)) {
760 fprintf(stderr,
761 "Remote PTY will not be allocated because stdin is not a terminal.\n"
762 "Use multiple -t options to force remote PTY allocation.\n");
763 shell_type_arg = kShellServiceArgRaw;
764 }
765 }
766
767 D("shell -e 0x%x t=%d use_shell_protocol=%s shell_type_arg=%s\n",
768 escape_char, tty,
769 use_shell_protocol ? "true" : "false",
770 (shell_type_arg == kShellServiceArgPty) ? "pty" : "raw");
771
772 // Raw mode is only supported when talking to a new device *and* using the shell protocol.
773 if (!use_shell_protocol) {
774 if (shell_type_arg != kShellServiceArgPty) {
775 fprintf(stderr, "error: %s only supports allocating a pty\n",
Josh Gao291733b2020-04-16 19:34:43 -0700776 !CanUseFeature(*features, kFeatureShell2) ? "device" : "-x");
Elliott Hughes02e33782016-10-19 14:47:11 -0700777 return 1;
Elliott Hughesa8265792015-11-03 11:18:40 -0800778 } else {
Elliott Hughes02e33782016-10-19 14:47:11 -0700779 // If we're not using the shell protocol, the type argument must be empty.
780 shell_type_arg = "";
Elliott Hughesa8265792015-11-03 11:18:40 -0800781 }
David Purselle570b982015-09-14 15:33:50 -0700782 }
Elliott Hughesa8265792015-11-03 11:18:40 -0800783
784 std::string command;
Elliott Hughes02e33782016-10-19 14:47:11 -0700785 if (optind < argc) {
Elliott Hughesa8265792015-11-03 11:18:40 -0800786 // We don't escape here, just like ssh(1). http://b/20564385.
Elliott Hughes02e33782016-10-19 14:47:11 -0700787 command = android::base::Join(std::vector<const char*>(argv + optind, argv + argc), ' ');
Elliott Hughesa8265792015-11-03 11:18:40 -0800788 }
789
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800790 std::string service_string = ShellServiceString(use_shell_protocol, shell_type_arg, command);
791 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command.empty(),
792 service_string);
793}
794
795static int adb_abb(int argc, const char** argv) {
Shaju Mathewbf7da1c2021-10-30 13:47:11 -0700796 auto&& features = adb_get_feature_set_or_die();
Josh Gao291733b2020-04-16 19:34:43 -0700797 if (!CanUseFeature(*features, kFeatureAbb)) {
Alex Buynytskyye1fa8142019-01-17 13:13:56 -0800798 error_exit("abb is not supported by the device");
799 }
800
Alex Buynytskyyee1221d2019-06-27 10:33:54 -0700801 optind = 1; // argv[0] is always "abb", so set `optind` appropriately.
802
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800803 // Defaults.
804 constexpr char escape_char = '~'; // -e
805 constexpr bool use_shell_protocol = true;
806 constexpr auto shell_type_arg = kShellServiceArgRaw;
807 constexpr bool empty_command = false;
808
Alex Buynytskyyee1221d2019-06-27 10:33:54 -0700809 std::vector<const char*> args(argv + optind, argv + argc);
810 std::string service_string = "abb:" + android::base::Join(args, ABB_ARG_DELIMETER);
Alex Buynytskyyef34f012018-12-12 10:48:50 -0800811
812 D("abb -e 0x%x [%*.s]\n", escape_char, static_cast<int>(service_string.size()),
813 service_string.data());
814
815 return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, empty_command,
816 service_string);
David Purselle570b982015-09-14 15:33:50 -0700817}
818
Josh Gaofff240a2020-01-08 12:39:52 -0800819static int adb_shell_noinput(int argc, const char** argv) {
820#if !defined(_WIN32)
821 unique_fd fd(adb_open("/dev/null", O_RDONLY));
822 CHECK_NE(STDIN_FILENO, fd.get());
823 dup2(fd.get(), STDIN_FILENO);
824#endif
825 return adb_shell(argc, argv);
826}
827
Elliott Hughes9548e562017-05-02 14:31:59 -0700828static int adb_sideload_legacy(const char* filename, int in_fd, int size) {
Elliott Hughes04a98c22015-04-29 08:35:59 -0700829 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -0800830 unique_fd out_fd(adb_connect(android::base::StringPrintf("sideload:%d", size), &error));
Elliott Hughes9548e562017-05-02 14:31:59 -0700831 if (out_fd < 0) {
832 fprintf(stderr, "adb: pre-KitKat sideload connection failed: %s\n", error.c_str());
Doug Zongker6b217ed2012-01-09 14:54:53 -0800833 return -1;
834 }
835
836 int opt = CHUNK_SIZE;
Elliott Hughes9548e562017-05-02 14:31:59 -0700837 opt = adb_setsockopt(out_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
Doug Zongker6b217ed2012-01-09 14:54:53 -0800838
Elliott Hughes9548e562017-05-02 14:31:59 -0700839 char buf[CHUNK_SIZE];
840 int total = size;
841 while (size > 0) {
842 unsigned xfer = (size > CHUNK_SIZE) ? CHUNK_SIZE : size;
843 if (!ReadFdExactly(in_fd, buf, xfer)) {
844 fprintf(stderr, "adb: failed to read data from %s: %s\n", filename, strerror(errno));
Doug Zongker6b217ed2012-01-09 14:54:53 -0800845 return -1;
846 }
Elliott Hughes9548e562017-05-02 14:31:59 -0700847 if (!WriteFdExactly(out_fd, buf, xfer)) {
848 std::string error;
849 adb_status(out_fd, &error);
850 fprintf(stderr, "adb: failed to write data: %s\n", error.c_str());
Elliott Hughes9548e562017-05-02 14:31:59 -0700851 return -1;
852 }
853 size -= xfer;
854 printf("sending: '%s' %4d%% \r", filename, (int)(100LL - ((100LL * size) / (total))));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700855 fflush(stdout);
Doug Zongker6b217ed2012-01-09 14:54:53 -0800856 }
Elliott Hughes96038eb2017-03-21 17:14:18 -0700857 printf("\n");
Doug Zongker6b217ed2012-01-09 14:54:53 -0800858
Elliott Hughes9548e562017-05-02 14:31:59 -0700859 if (!adb_status(out_fd, &error)) {
860 fprintf(stderr, "adb: error response: %s\n", error.c_str());
Doug Zongker6b217ed2012-01-09 14:54:53 -0800861 return -1;
862 }
863
Doug Zongker6b217ed2012-01-09 14:54:53 -0800864 return 0;
865}
866
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700867#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE)
868
Tao Baoe23e6c72019-04-07 23:24:03 -0700869// Connects to the sideload / rescue service on the device (served by minadbd) and sends over the
870// data in an OTA package.
871//
872// It uses a simple protocol as follows.
873//
874// - The connect message includes the total number of bytes in the file and a block size chosen by
875// us.
876//
877// - The other side sends the desired block number as eight decimal digits (e.g. "00000023" for
878// block 23). Blocks are numbered from zero.
879//
880// - We send back the data of the requested block. The last block is likely to be partial; when the
881// last block is requested we only send the part of the block that exists, it's not padded up to
882// the block size.
883//
884// - When the other side sends "DONEDONE" or "FAILFAIL" instead of a block number, we have done all
885// the data transfer.
886//
887static int adb_sideload_install(const char* filename, bool rescue_mode) {
Elliott Hughes65bc2272017-04-18 14:34:16 -0700888 // TODO: use a LinePrinter instead...
Elliott Hughes96038eb2017-03-21 17:14:18 -0700889 struct stat sb;
890 if (stat(filename, &sb) == -1) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700891 fprintf(stderr, "adb: failed to stat file %s: %s\n", filename, strerror(errno));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700892 return -1;
893 }
894 unique_fd package_fd(adb_open(filename, O_RDONLY));
895 if (package_fd == -1) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700896 fprintf(stderr, "adb: failed to open file %s: %s\n", filename, strerror(errno));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700897 return -1;
898 }
899
Tao Baoe23e6c72019-04-07 23:24:03 -0700900 std::string service = android::base::StringPrintf(
901 "%s:%" PRId64 ":%d", rescue_mode ? "rescue-install" : "sideload-host",
902 static_cast<int64_t>(sb.st_size), SIDELOAD_HOST_BLOCK_SIZE);
Elliott Hughes04a98c22015-04-29 08:35:59 -0700903 std::string error;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700904 unique_fd device_fd(adb_connect(service, &error));
905 if (device_fd < 0) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700906 fprintf(stderr, "adb: sideload connection failed: %s\n", error.c_str());
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700907
Tao Baoe23e6c72019-04-07 23:24:03 -0700908 if (rescue_mode) {
909 return -1;
910 }
911
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700912 // If this is a small enough package, maybe this is an older device that doesn't
913 // support sideload-host. Try falling back to the older (<= K) sideload method.
914 if (sb.st_size > INT_MAX) {
915 return -1;
916 }
Elliott Hughes9548e562017-05-02 14:31:59 -0700917 fprintf(stderr, "adb: trying pre-KitKat sideload method...\n");
Josh Gao90228a62019-04-25 14:04:57 -0700918 return adb_sideload_legacy(filename, package_fd.get(), static_cast<int>(sb.st_size));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700919 }
920
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700921 int opt = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughes96038eb2017-03-21 17:14:18 -0700922 adb_setsockopt(device_fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
923
924 char buf[SIDELOAD_HOST_BLOCK_SIZE];
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700925
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700926 int64_t xfer = 0;
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700927 int last_percent = -1;
Elliott Hughes7cf35752015-04-17 17:03:59 -0700928 while (true) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700929 if (!ReadFdExactly(device_fd, buf, 8)) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700930 fprintf(stderr, "adb: failed to read command: %s\n", strerror(errno));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700931 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700932 }
Elliott Hughesda945812015-04-29 12:28:13 -0700933 buf[8] = '\0';
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700934
xunchang8829d152019-04-22 23:14:28 -0700935 if (strcmp(kMinadbdServicesExitSuccess, buf) == 0 ||
936 strcmp(kMinadbdServicesExitFailure, buf) == 0) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700937 printf("\rTotal xfer: %.2fx%*s\n",
Elliott Hughes96038eb2017-03-21 17:14:18 -0700938 static_cast<double>(xfer) / (sb.st_size ? sb.st_size : 1),
939 static_cast<int>(strlen(filename) + 10), "");
xunchang8829d152019-04-22 23:14:28 -0700940 if (strcmp(kMinadbdServicesExitFailure, buf) == 0) {
Tao Baoe23e6c72019-04-07 23:24:03 -0700941 return 1;
942 }
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700943 return 0;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700944 }
945
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700946 int64_t block = strtoll(buf, nullptr, 10);
947 int64_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
948 if (offset >= static_cast<int64_t>(sb.st_size)) {
949 fprintf(stderr,
950 "adb: failed to read block %" PRId64 " at offset %" PRId64 ", past end %" PRId64
951 "\n",
952 block, offset, static_cast<int64_t>(sb.st_size));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700953 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700954 }
Elliott Hughes96038eb2017-03-21 17:14:18 -0700955
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700956 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700957 if ((offset + SIDELOAD_HOST_BLOCK_SIZE) > static_cast<int64_t>(sb.st_size)) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700958 to_write = sb.st_size - offset;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700959 }
960
Elliott Hughes9dcbc212018-09-20 13:59:49 -0700961 if (adb_lseek(package_fd, offset, SEEK_SET) != offset) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700962 fprintf(stderr, "adb: failed to seek to package block: %s\n", strerror(errno));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700963 return -1;
964 }
965 if (!ReadFdExactly(package_fd, buf, to_write)) {
Elliott Hughes9548e562017-05-02 14:31:59 -0700966 fprintf(stderr, "adb: failed to read package block: %s\n", strerror(errno));
Elliott Hughes96038eb2017-03-21 17:14:18 -0700967 return -1;
968 }
969
970 if (!WriteFdExactly(device_fd, buf, to_write)) {
971 adb_status(device_fd, &error);
Elliott Hughes9548e562017-05-02 14:31:59 -0700972 fprintf(stderr, "adb: failed to write data '%s' *\n", error.c_str());
Elliott Hughese0a6e2a2016-05-26 22:43:19 -0700973 return -1;
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700974 }
975 xfer += to_write;
976
977 // For normal OTA packages, we expect to transfer every byte
978 // twice, plus a bit of overhead (one read during
979 // verification, one read of each byte for installation, plus
980 // extra access to things like the zip central directory).
981 // This estimate of the completion becomes 100% when we've
982 // transferred ~2.13 (=100/47) times the package size.
Elliott Hughes96038eb2017-03-21 17:14:18 -0700983 int percent = static_cast<int>(xfer * 47LL / (sb.st_size ? sb.st_size : 1));
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700984 if (percent != last_percent) {
Elliott Hughes96038eb2017-03-21 17:14:18 -0700985 printf("\rserving: '%s' (~%d%%) ", filename, percent);
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700986 fflush(stdout);
987 last_percent = percent;
988 }
989 }
Doug Zongkerbcad29f2014-06-26 15:35:36 -0700990}
991
xunchang8829d152019-04-22 23:14:28 -0700992static int adb_wipe_devices() {
993 auto wipe_devices_message_size = strlen(kMinadbdServicesExitSuccess);
994 std::string error;
995 unique_fd fd(adb_connect(
996 android::base::StringPrintf("rescue-wipe:userdata:%zu", wipe_devices_message_size),
997 &error));
998 if (fd < 0) {
999 fprintf(stderr, "adb: wipe device connection failed: %s\n", error.c_str());
1000 return 1;
1001 }
1002
1003 std::string message(wipe_devices_message_size, '\0');
1004 if (!ReadFdExactly(fd, message.data(), wipe_devices_message_size)) {
1005 fprintf(stderr, "adb: failed to read wipe result: %s\n", strerror(errno));
1006 return 1;
1007 }
1008
1009 if (message == kMinadbdServicesExitSuccess) {
1010 return 0;
1011 }
1012
1013 if (message != kMinadbdServicesExitFailure) {
1014 fprintf(stderr, "adb: got unexpected message from rescue wipe %s\n", message.c_str());
1015 }
1016 return 1;
1017}
1018
Josh Gao4ce212e2019-03-11 15:39:44 -07001019static bool wait_for_device(const char* service,
1020 std::optional<std::chrono::milliseconds> timeout = std::nullopt) {
Josh Gao63cede32016-04-13 12:14:16 -07001021 std::vector<std::string> components = android::base::Split(service, "-");
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001022 if (components.size() < 3) {
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001023 fprintf(stderr, "adb: couldn't parse 'wait-for' command: %s\n", service);
1024 return false;
1025 }
1026
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001027 // If the first thing after "wait-for-" wasn't a TRANSPORT, insert whatever
1028 // the current transport implies.
1029 if (components[2] != "usb" && components[2] != "local" && components[2] != "any") {
1030 TransportType t;
1031 adb_get_transport(&t, nullptr, nullptr);
Josh Gao63cede32016-04-13 12:14:16 -07001032 auto it = components.begin() + 2;
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001033 if (t == kTransportUsb) {
Josh Gao63cede32016-04-13 12:14:16 -07001034 components.insert(it, "usb");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001035 } else if (t == kTransportLocal) {
Josh Gao63cede32016-04-13 12:14:16 -07001036 components.insert(it, "local");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001037 } else {
Josh Gao63cede32016-04-13 12:14:16 -07001038 components.insert(it, "any");
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001039 }
Leo Sartre6cd9bc32015-11-27 18:56:48 +01001040 }
1041
Elliott Hughes3657e9d2020-03-10 16:57:47 -07001042 // Stitch it back together and send it over...
Josh Gaob39e4152017-08-16 16:57:01 -07001043 std::string cmd = format_host_command(android::base::Join(components, "-").c_str());
Josh Gao4ce212e2019-03-11 15:39:44 -07001044 if (timeout) {
1045 std::thread([timeout]() {
1046 std::this_thread::sleep_for(*timeout);
1047 fprintf(stderr, "timeout expired while waiting for device\n");
1048 _exit(1);
1049 }).detach();
1050 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001051 return adb_command(cmd);
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001052}
1053
Josh Gaod1d03392016-03-04 15:16:18 -08001054static bool adb_root(const char* command) {
1055 std::string error;
Josh Gaod1d03392016-03-04 15:16:18 -08001056
Josh Gaoff707d32019-02-22 15:20:27 -08001057 TransportId transport_id;
1058 unique_fd fd(adb_connect(&transport_id, android::base::StringPrintf("%s:", command), &error));
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001059 if (fd < 0) {
Josh Gaod1d03392016-03-04 15:16:18 -08001060 fprintf(stderr, "adb: unable to connect for %s: %s\n", command, error.c_str());
1061 return false;
1062 }
1063
1064 // Figure out whether we actually did anything.
1065 char buf[256];
1066 char* cur = buf;
1067 ssize_t bytes_left = sizeof(buf);
1068 while (bytes_left > 0) {
Elliott Hughese0a6e2a2016-05-26 22:43:19 -07001069 ssize_t bytes_read = adb_read(fd, cur, bytes_left);
Josh Gaod1d03392016-03-04 15:16:18 -08001070 if (bytes_read == 0) {
1071 break;
1072 } else if (bytes_read < 0) {
1073 fprintf(stderr, "adb: error while reading for %s: %s\n", command, strerror(errno));
1074 return false;
1075 }
1076 cur += bytes_read;
1077 bytes_left -= bytes_read;
1078 }
1079
1080 if (bytes_left == 0) {
1081 fprintf(stderr, "adb: unexpected output length for %s\n", command);
1082 return false;
1083 }
1084
Junyong Sun88dd2462020-01-15 16:34:58 +08001085 fwrite(buf, 1, sizeof(buf) - bytes_left, stdout);
Josh Gaod1d03392016-03-04 15:16:18 -08001086 fflush(stdout);
Josh Gaod1d03392016-03-04 15:16:18 -08001087 if (cur != buf && strstr(buf, "restarting") == nullptr) {
1088 return true;
1089 }
1090
Josh Gaoff707d32019-02-22 15:20:27 -08001091 // Wait for the device to go away.
Josh Gao4ce212e2019-03-11 15:39:44 -07001092 TransportType previous_type;
1093 const char* previous_serial;
1094 TransportId previous_id;
1095 adb_get_transport(&previous_type, &previous_serial, &previous_id);
1096
Josh Gaoff707d32019-02-22 15:20:27 -08001097 adb_set_transport(kTransportAny, nullptr, transport_id);
1098 wait_for_device("wait-for-disconnect");
Josh Gao4ce212e2019-03-11 15:39:44 -07001099
1100 // Wait for the device to come back.
1101 // If we were using a specific transport ID, there's nothing we can wait for.
1102 if (previous_id == 0) {
1103 adb_set_transport(previous_type, previous_serial, 0);
Josh Gao04ef6962020-10-15 18:32:55 -07001104 wait_for_device("wait-for-device", 12000ms);
Josh Gao4ce212e2019-03-11 15:39:44 -07001105 }
1106
Josh Gaod3d9cbf2016-06-16 14:00:09 -07001107 return true;
Josh Gaod1d03392016-03-04 15:16:18 -08001108}
1109
Josh Gaob39e4152017-08-16 16:57:01 -07001110int send_shell_command(const std::string& command, bool disable_shell_protocol,
1111 StandardStreamsCallbackInterface* callback) {
Josh Gaoc2705962019-01-23 15:36:42 -08001112 unique_fd fd;
David Pursell9650d862016-01-21 19:56:50 -08001113 bool use_shell_protocol = false;
1114
Elliott Hughes170b5682015-04-17 10:59:34 -07001115 while (true) {
David Pursell9650d862016-01-21 19:56:50 -08001116 bool attempt_connection = true;
1117
Felipe Leme60192aa2016-07-26 12:14:39 -07001118 // Use shell protocol if it's supported and the caller doesn't explicitly
1119 // disable it.
David Pursell9650d862016-01-21 19:56:50 -08001120 if (!disable_shell_protocol) {
Josh Gao291733b2020-04-16 19:34:43 -07001121 auto&& features = adb_get_feature_set(nullptr);
1122 if (features) {
1123 use_shell_protocol = CanUseFeature(*features, kFeatureShell2);
David Pursell9650d862016-01-21 19:56:50 -08001124 } else {
1125 // Device was unreachable.
1126 attempt_connection = false;
1127 }
Elliott Hughes04a98c22015-04-29 08:35:59 -07001128 }
David Pursell9650d862016-01-21 19:56:50 -08001129
1130 if (attempt_connection) {
1131 std::string error;
1132 std::string service_string = ShellServiceString(use_shell_protocol, "", command);
1133
Josh Gaoc2705962019-01-23 15:36:42 -08001134 fd.reset(adb_connect(service_string, &error));
David Pursell9650d862016-01-21 19:56:50 -08001135 if (fd >= 0) {
1136 break;
1137 }
1138 }
1139
Felipe Leme60192aa2016-07-26 12:14:39 -07001140 fprintf(stderr, "- waiting for device -\n");
Josh Gaob39e4152017-08-16 16:57:01 -07001141 if (!wait_for_device("wait-for-device")) {
Josh Gao6a7e5732016-02-24 15:16:17 -08001142 return 1;
1143 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001144 }
1145
Josh Gaoc2705962019-01-23 15:36:42 -08001146 return read_and_dump(fd.get(), use_shell_protocol, callback);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001147}
1148
Josh Gaob39e4152017-08-16 16:57:01 -07001149static int logcat(int argc, const char** argv) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001150 char* log_tags = getenv("ANDROID_LOG_TAGS");
1151 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001152
David Pursell22fc5e92015-09-30 13:35:42 -07001153 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001154
Jeff Sharkey824d1062014-06-10 11:31:24 -07001155 if (!strcmp(argv[0], "longcat")) {
Elliott Hughes170b5682015-04-17 10:59:34 -07001156 cmd += " -v long";
Christopher Tate7b9b5162011-11-30 13:00:33 -08001157 }
1158
Elliott Hughese4b64792015-04-17 20:11:08 -07001159 --argc;
1160 ++argv;
Elliott Hughes170b5682015-04-17 10:59:34 -07001161 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001162 cmd += " " + escape_arg(*argv++);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001163 }
1164
Elliott Hughes8fa33512018-06-14 10:46:05 -07001165 return send_shell_command(cmd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001166}
1167
Josh Gao90228a62019-04-25 14:04:57 -07001168static void write_zeros(int bytes, borrowed_fd fd) {
Christopher Tatee0e9f562016-07-06 13:22:22 -07001169 int old_stdin_mode = -1;
1170 int old_stdout_mode = -1;
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001171 std::vector<char> buf(bytes);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001172
Josh Gao90228a62019-04-25 14:04:57 -07001173 D("write_zeros(%d) -> %d", bytes, fd.get());
Christopher Tatee0e9f562016-07-06 13:22:22 -07001174
Josh Gao90228a62019-04-25 14:04:57 -07001175 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001176
1177 if (fd == STDOUT_FILENO) {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001178 fwrite(buf.data(), 1, bytes, stdout);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001179 fflush(stdout);
1180 } else {
Luis Hector Chavezb4edbdf2018-07-18 21:18:27 -07001181 adb_write(fd, buf.data(), bytes);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001182 }
1183
Josh Gao90228a62019-04-25 14:04:57 -07001184 stdinout_raw_prologue(-1, fd.get(), old_stdin_mode, old_stdout_mode);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001185
1186 D("write_zeros() finished");
Christopher Tatee0e9f562016-07-06 13:22:22 -07001187}
1188
Dan Albertf30d73c2015-02-25 17:51:28 -08001189static int backup(int argc, const char** argv) {
Al Suttonb6326c72019-05-09 16:14:05 +00001190 fprintf(stdout, "WARNING: adb backup is deprecated and may be removed in a future release\n");
1191
Elliott Hughes1c1f7dc2015-08-21 20:31:31 -07001192 const char* filename = "backup.ab";
Christopher Tate73779122011-04-21 12:53:28 -07001193
Christopher Tatefba22972011-06-01 17:56:23 -07001194 /* find, extract, and use any -f argument */
Elliott Hughese4b64792015-04-17 20:11:08 -07001195 for (int i = 1; i < argc; i++) {
Christopher Tatefba22972011-06-01 17:56:23 -07001196 if (!strcmp("-f", argv[i])) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001197 if (i == argc - 1) error_exit("backup -f passed with no filename");
Christopher Tatefba22972011-06-01 17:56:23 -07001198 filename = argv[i+1];
Elliott Hughese4b64792015-04-17 20:11:08 -07001199 for (int j = i+2; j <= argc; ) {
Christopher Tatefba22972011-06-01 17:56:23 -07001200 argv[i++] = argv[j++];
1201 }
1202 argc -= 2;
Yi Kong86e67182018-07-13 18:15:16 -07001203 argv[argc] = nullptr;
Christopher Tatefba22972011-06-01 17:56:23 -07001204 }
Christopher Tate73779122011-04-21 12:53:28 -07001205 }
1206
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001207 // Bare "adb backup" or "adb backup -f filename" are not valid invocations ---
1208 // a list of packages is required.
Elliott Hughes0119a912018-10-22 17:02:51 -07001209 if (argc < 2) error_exit("backup either needs a list of packages or -all/-shared");
Christopher Tatecf4f16a2011-08-22 17:12:08 -07001210
Christopher Tate1e9f2392011-12-08 19:04:34 -08001211 adb_unlink(filename);
Josh Gaoc2705962019-01-23 15:36:42 -08001212 unique_fd outFd(adb_creat(filename, 0640));
Christopher Tate73779122011-04-21 12:53:28 -07001213 if (outFd < 0) {
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001214 fprintf(stderr, "adb: backup unable to create file '%s': %s\n", filename, strerror(errno));
1215 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001216 }
1217
Elliott Hughese4b64792015-04-17 20:11:08 -07001218 std::string cmd = "backup:";
1219 --argc;
1220 ++argv;
1221 while (argc-- > 0) {
1222 cmd += " " + escape_arg(*argv++);
Christopher Tate73779122011-04-21 12:53:28 -07001223 }
1224
Yabin Cui815ad882015-09-02 17:44:28 -07001225 D("backup. filename=%s cmd=%s", filename, cmd.c_str());
Elliott Hughes04a98c22015-04-29 08:35:59 -07001226 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001227 unique_fd fd(adb_connect(cmd, &error));
Christopher Tate73779122011-04-21 12:53:28 -07001228 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001229 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001230 return EXIT_FAILURE;
Christopher Tate73779122011-04-21 12:53:28 -07001231 }
1232
Elliott Hughes65bc2272017-04-18 14:34:16 -07001233 fprintf(stdout, "Now unlock your device and confirm the backup operation...\n");
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001234 fflush(stdout);
1235
Josh Gaoc2705962019-01-23 15:36:42 -08001236 copy_to_file(fd.get(), outFd.get());
Elliott Hughes9406f7e2015-11-13 11:04:10 -08001237 return EXIT_SUCCESS;
Christopher Tate73779122011-04-21 12:53:28 -07001238}
1239
Dan Albertf30d73c2015-02-25 17:51:28 -08001240static int restore(int argc, const char** argv) {
Al Suttonb6326c72019-05-09 16:14:05 +00001241 fprintf(stdout, "WARNING: adb restore is deprecated and may be removed in a future release\n");
1242
Piyush Mehrotra7647b662023-02-24 16:40:38 +00001243 if (argc < 2) {
1244 error_exit("usage: adb restore FILENAME [ARG]...");
1245 }
Christopher Tatecf5379b2011-05-17 15:52:54 -07001246
Elliott Hughes04a98c22015-04-29 08:35:59 -07001247 const char* filename = argv[1];
Josh Gaoc2705962019-01-23 15:36:42 -08001248 unique_fd tarFd(adb_open(filename, O_RDONLY));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001249 if (tarFd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001250 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001251 return -1;
1252 }
1253
Piyush Mehrotra7647b662023-02-24 16:40:38 +00001254 std::string cmd = "restore:";
1255 argc -= 2;
1256 argv += 2;
1257 while (argc-- > 0) {
1258 cmd += " " + escape_arg(*argv++);
1259 }
1260
1261 D("restore. filename=%s cmd=%s", filename, cmd.c_str());
1262
Elliott Hughes04a98c22015-04-29 08:35:59 -07001263 std::string error;
Piyush Mehrotra7647b662023-02-24 16:40:38 +00001264 unique_fd fd(adb_connect(cmd, &error));
Christopher Tatecf5379b2011-05-17 15:52:54 -07001265 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001266 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
Christopher Tatecf5379b2011-05-17 15:52:54 -07001267 return -1;
1268 }
1269
Elliott Hughes65bc2272017-04-18 14:34:16 -07001270 fprintf(stdout, "Now unlock your device and confirm the restore operation.\n");
1271 fflush(stdout);
1272
Josh Gaoc2705962019-01-23 15:36:42 -08001273 copy_to_file(tarFd.get(), fd.get());
Christopher Tatecf5379b2011-05-17 15:52:54 -07001274
Christopher Tatee0e9f562016-07-06 13:22:22 -07001275 // Provide an in-band EOD marker in case the archive file is malformed
Josh Gaoc2705962019-01-23 15:36:42 -08001276 write_zeros(512 * 2, fd);
Christopher Tatee0e9f562016-07-06 13:22:22 -07001277
Josh Gao95230e82016-03-04 15:51:03 -08001278 // Wait until the other side finishes, or it'll get sent SIGHUP.
Josh Gaoc2705962019-01-23 15:36:42 -08001279 copy_to_file(fd.get(), STDOUT_FILENO);
Christopher Tatecf5379b2011-05-17 15:52:54 -07001280 return 0;
1281}
1282
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001283static CompressionType parse_compression_type(const std::string& str, bool allow_numbers) {
1284 if (allow_numbers) {
1285 if (str == "0") {
1286 return CompressionType::None;
1287 } else if (str == "1") {
1288 return CompressionType::Any;
1289 }
1290 }
1291
1292 if (str == "any") {
1293 return CompressionType::Any;
1294 } else if (str == "none") {
1295 return CompressionType::None;
1296 }
1297
1298 if (str == "brotli") {
1299 return CompressionType::Brotli;
Josh Gaofb386cc2020-03-26 22:02:03 -07001300 } else if (str == "lz4") {
1301 return CompressionType::LZ4;
Josh Gaobdebc9b2020-05-27 17:52:52 -07001302 } else if (str == "zstd") {
1303 return CompressionType::Zstd;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001304 }
1305
1306 error_exit("unexpected compression type %s", str.c_str());
1307}
1308
Dan Albert8449e062017-05-18 22:56:48 -07001309static void parse_push_pull_args(const char** arg, int narg, std::vector<const char*>* srcs,
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07001310 const char** dst, bool* copy_attrs, bool* sync, bool* quiet,
Josh Gao8a410a02020-03-30 23:25:16 -07001311 CompressionType* compression, bool* dry_run) {
Josh Gao5d093b22015-10-30 16:57:19 -07001312 *copy_attrs = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001313 if (const char* adb_compression = getenv("ADB_COMPRESSION")) {
1314 *compression = parse_compression_type(adb_compression, true);
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001315 }
Mark Lindner9f9d1452014-03-11 17:55:59 -07001316
Josh Gao5d093b22015-10-30 16:57:19 -07001317 srcs->clear();
1318 bool ignore_flags = false;
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001319 while (narg > 0) {
Josh Gao5d093b22015-10-30 16:57:19 -07001320 if (ignore_flags || *arg[0] != '-') {
1321 srcs->push_back(*arg);
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001322 } else {
Josh Gao5d093b22015-10-30 16:57:19 -07001323 if (!strcmp(*arg, "-p")) {
1324 // Silently ignore for backwards compatibility.
1325 } else if (!strcmp(*arg, "-a")) {
1326 *copy_attrs = true;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001327 } else if (!strcmp(*arg, "-z")) {
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001328 if (narg < 2) {
1329 error_exit("-z requires an argument");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001330 }
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001331 *compression = parse_compression_type(*++arg, false);
1332 --narg;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08001333 } else if (!strcmp(*arg, "-Z")) {
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001334 *compression = CompressionType::None;
Josh Gao8a410a02020-03-30 23:25:16 -07001335 } else if (dry_run && !strcmp(*arg, "-n")) {
1336 *dry_run = true;
Dan Albert8449e062017-05-18 22:56:48 -07001337 } else if (!strcmp(*arg, "--sync")) {
1338 if (sync != nullptr) {
1339 *sync = true;
1340 }
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07001341 } else if (!strcmp(*arg, "-q")) {
1342 *quiet = true;
Josh Gao5d093b22015-10-30 16:57:19 -07001343 } else if (!strcmp(*arg, "--")) {
1344 ignore_flags = true;
1345 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001346 error_exit("unrecognized option '%s'", *arg);
Josh Gao5d093b22015-10-30 16:57:19 -07001347 }
Lajos Molnar4e23e3c2013-04-19 12:41:09 -07001348 }
Mark Lindner9f9d1452014-03-11 17:55:59 -07001349 ++arg;
1350 --narg;
1351 }
1352
Josh Gao5d093b22015-10-30 16:57:19 -07001353 if (srcs->size() > 1) {
1354 *dst = srcs->back();
1355 srcs->pop_back();
Mark Lindner9f9d1452014-03-11 17:55:59 -07001356 }
1357}
1358
Shukang Zhou420ad552020-02-13 17:01:39 -08001359static int adb_connect_command(const std::string& command, TransportId* transport,
1360 StandardStreamsCallbackInterface* callback) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001361 std::string error;
Josh Gao67209db2019-03-14 15:38:02 -07001362 unique_fd fd(adb_connect(transport, command, &error));
Elliott Hughesdabb9742015-05-07 23:37:40 -07001363 if (fd < 0) {
1364 fprintf(stderr, "error: %s\n", error.c_str());
1365 return 1;
Tao Bao0db67642015-03-29 11:22:34 -07001366 }
Shukang Zhou420ad552020-02-13 17:01:39 -08001367 read_and_dump(fd, false, callback);
Elliott Hughesdabb9742015-05-07 23:37:40 -07001368 return 0;
Tao Bao0db67642015-03-29 11:22:34 -07001369}
1370
Shukang Zhou420ad552020-02-13 17:01:39 -08001371static int adb_connect_command(const std::string& command, TransportId* transport = nullptr) {
1372 return adb_connect_command(command, transport, &DEFAULT_STANDARD_STREAMS_CALLBACK);
1373}
1374
Fabien Sanglard05789412024-05-30 23:00:18 -07001375// A class to convert server status binary protobuf to text protobuf.
1376class AdbServerStateStreamsCallback : public DefaultStandardStreamsCallback {
1377 public:
1378 AdbServerStateStreamsCallback() : DefaultStandardStreamsCallback(nullptr, nullptr) {}
1379
1380 bool OnStdout(const char* buffer, size_t length) override {
1381 return OnStream(&output_, nullptr, buffer, length, false);
1382 }
1383
1384 int Done(int status) {
1385 if (output_.size() < 4) {
Fabien Sanglard4112c112024-06-29 00:15:44 -07001386 return OnStream(nullptr, stdout, output_.data(), output_.length(), false);
Fabien Sanglard05789412024-05-30 23:00:18 -07001387 }
1388
1389 // Skip the 4-hex prefix
1390 std::string binary_proto_bytes{output_.substr(4)};
1391
1392 ::adb::proto::AdbServerStatus binary_proto;
1393 binary_proto.ParseFromString(binary_proto_bytes);
1394
1395 std::string string_proto;
1396 google::protobuf::TextFormat::PrintToString(binary_proto, &string_proto);
1397
1398 return OnStream(nullptr, stdout, string_proto.data(), string_proto.length(), false);
1399 }
1400
1401 private:
1402 std::string output_;
1403 DISALLOW_COPY_AND_ASSIGN(AdbServerStateStreamsCallback);
1404};
1405
Shukang Zhou420ad552020-02-13 17:01:39 -08001406// A class that prints out human readable form of the protobuf message for "track-app" service
1407// (received in binary format).
1408class TrackAppStreamsCallback : public DefaultStandardStreamsCallback {
1409 public:
1410 TrackAppStreamsCallback() : DefaultStandardStreamsCallback(nullptr, nullptr) {}
1411
1412 // Assume the buffer contains at least 4 bytes of valid data.
Lee Shombertb796cd52022-03-22 12:19:06 -07001413 bool OnStdout(const char* buffer, size_t length) override {
1414 if (length < 4) return true; // Unexpected length received. Do nothing.
Shukang Zhou420ad552020-02-13 17:01:39 -08001415
1416 adb::proto::AppProcesses binary_proto;
1417 // The first 4 bytes are the length of remaining content in hexadecimal format.
1418 binary_proto.ParseFromString(std::string(buffer + 4, length - 4));
1419 char summary[24]; // The following string includes digits and 16 fixed characters.
1420 int written = snprintf(summary, sizeof(summary), "Process count: %d\n",
1421 binary_proto.process_size());
Lee Shombertb796cd52022-03-22 12:19:06 -07001422 if (!OnStream(nullptr, stdout, summary, written, false)) {
1423 return false;
1424 }
Shukang Zhou420ad552020-02-13 17:01:39 -08001425
1426 std::string string_proto;
1427 google::protobuf::TextFormat::PrintToString(binary_proto, &string_proto);
Lee Shombertb796cd52022-03-22 12:19:06 -07001428 return OnStream(nullptr, stdout, string_proto.data(), string_proto.length(), false);
Shukang Zhou420ad552020-02-13 17:01:39 -08001429 }
1430
1431 private:
1432 DISALLOW_COPY_AND_ASSIGN(TrackAppStreamsCallback);
1433};
1434
Josh Gao7b438fa2018-11-16 14:47:59 -08001435static int adb_connect_command_bidirectional(const std::string& command) {
1436 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001437 unique_fd fd(adb_connect(command, &error));
Josh Gao7b438fa2018-11-16 14:47:59 -08001438 if (fd < 0) {
1439 fprintf(stderr, "error: %s\n", error.c_str());
1440 return 1;
1441 }
1442
1443 static constexpr auto forward = [](int src, int sink, bool exit_on_end) {
1444 char buf[4096];
1445 while (true) {
1446 int rc = adb_read(src, buf, sizeof(buf));
1447 if (rc == 0) {
1448 if (exit_on_end) {
1449 exit(0);
1450 } else {
1451 adb_shutdown(sink, SHUT_WR);
1452 }
1453 return;
1454 } else if (rc < 0) {
1455 perror_exit("read failed");
1456 }
1457 if (!WriteFdExactly(sink, buf, rc)) {
1458 perror_exit("write failed");
1459 }
1460 }
1461 };
1462
Josh Gaoc2705962019-01-23 15:36:42 -08001463 std::thread read(forward, fd.get(), STDOUT_FILENO, true);
1464 std::thread write(forward, STDIN_FILENO, fd.get(), false);
Josh Gao7b438fa2018-11-16 14:47:59 -08001465 read.join();
1466 write.join();
Josh Gao7b438fa2018-11-16 14:47:59 -08001467 return 0;
1468}
1469
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07001470const std::optional<FeatureSet>& adb_get_feature_set_or_die(void) {
1471 std::string error;
1472 const std::optional<FeatureSet>& features = adb_get_feature_set(&error);
1473 if (!features) {
1474 error_exit("%s", error.c_str());
1475 }
1476 return features;
1477}
1478
Shaju Mathew3b481e52021-10-28 00:14:04 -07001479// Helper function to handle processing of shell service commands:
Elliott Hughes18056092022-02-18 10:16:38 -08001480// remount, disable/enable-verity. There's only one "feature",
1481// but they were all moved from adbd to external binaries in the
1482// same release.
1483static int process_remount_or_verity_service(const int argc, const char** argv) {
1484 auto&& features = adb_get_feature_set_or_die();
1485 if (CanUseFeature(*features, kFeatureRemountShell)) {
Shaju Mathew3b481e52021-10-28 00:14:04 -07001486 std::vector<const char*> args = {"shell"};
1487 args.insert(args.cend(), argv, argv + argc);
1488 return adb_shell_noinput(args.size(), args.data());
1489 } else if (argc > 1) {
1490 auto command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
1491 return adb_connect_command(command);
1492 } else {
1493 return adb_connect_command(std::string(argv[0]) + ":");
1494 }
1495}
1496
Elliott Hughesda945812015-04-29 12:28:13 -07001497static int adb_query_command(const std::string& command) {
1498 std::string result;
1499 std::string error;
1500 if (!adb_query(command, &result, &error)) {
1501 fprintf(stderr, "error: %s\n", error.c_str());
1502 return 1;
1503 }
1504 printf("%s\n", result.c_str());
1505 return 0;
1506}
1507
Spencer Lowe98825e2015-09-07 16:20:13 -07001508// Disallow stdin, stdout, and stderr.
1509static bool _is_valid_ack_reply_fd(const int ack_reply_fd) {
1510#ifdef _WIN32
1511 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
1512 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) &&
1513 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) &&
1514 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle);
1515#else
1516 return ack_reply_fd > 2;
1517#endif
1518}
1519
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07001520static bool _is_valid_os_fd(int fd) {
Songchun Fandaf826a2020-03-09 11:33:44 -07001521 // Disallow invalid FDs and stdin/out/err as well.
1522 if (fd < 3) {
1523 return false;
1524 }
1525#ifdef _WIN32
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07001526 auto handle = (HANDLE)fd;
Songchun Fandaf826a2020-03-09 11:33:44 -07001527 DWORD info = 0;
1528 if (GetHandleInformation(handle, &info) == 0) {
1529 return false;
1530 }
1531#else
1532 int flags = fcntl(fd, F_GETFD);
1533 if (flags == -1) {
1534 return false;
1535 }
1536#endif
1537 return true;
1538}
1539
Octavian Purdila4b4421d2024-04-03 23:13:14 -07001540bool forward_dest_is_featured(const std::string& dest, std::string* error) {
1541 auto features = adb_get_feature_set_or_die();
1542
1543 if (android::base::StartsWith(dest, "dev-raw:")) {
1544 if (!CanUseFeature(*features, kFeatureDevRaw)) {
1545 *error = "dev-raw is not supported by the device";
1546 return false;
1547 }
1548 }
1549
1550 return true;
1551}
1552
Elliott Hughes02e33782016-10-19 14:47:11 -07001553int adb_commandline(int argc, const char** argv) {
Josh Gao4007ab72018-08-10 14:23:43 -07001554 bool no_daemon = false;
1555 bool is_daemon = false;
1556 bool is_server = false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001557 int r;
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001558 TransportType transport_type = kTransportAny;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001559 int ack_reply_fd = -1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001560
Elliott Hughes4919c172015-11-18 18:07:48 -08001561#if !defined(_WIN32)
1562 // We'd rather have EPIPE than SIGPIPE.
1563 signal(SIGPIPE, SIG_IGN);
1564#endif
1565
Josh Gaobb4f8602016-08-25 16:00:22 -07001566 const char* server_host_str = nullptr;
1567 const char* server_port_str = nullptr;
1568 const char* server_socket_str = nullptr;
Vince Harron5703eb32021-11-12 12:40:58 -08001569 const char* one_device_str = nullptr;
Stefan Hilzinger92ca4fa2010-04-19 12:21:12 +01001570
Elliott Hughes67943d12015-10-07 14:55:10 -07001571 // We need to check for -d and -e before we look at $ANDROID_SERIAL.
1572 const char* serial = nullptr;
Josh Gaob39e4152017-08-16 16:57:01 -07001573 TransportId transport_id = 0;
Elliott Hughes67943d12015-10-07 14:55:10 -07001574
Riley Andrews03b4b372014-12-05 17:37:24 -08001575 while (argc > 0) {
Josh Gao67209db2019-03-14 15:38:02 -07001576 if (!strcmp(argv[0], "server")) {
Josh Gao4007ab72018-08-10 14:23:43 -07001577 is_server = true;
Josh Gao67209db2019-03-14 15:38:02 -07001578 } else if (!strcmp(argv[0], "nodaemon")) {
Josh Gao4007ab72018-08-10 14:23:43 -07001579 no_daemon = true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001580 } else if (!strcmp(argv[0], "fork-server")) {
1581 /* this is a special flag used only when the ADB client launches the ADB Server */
Josh Gao4007ab72018-08-10 14:23:43 -07001582 is_daemon = true;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001583 } else if (!strcmp(argv[0], "--reply-fd")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001584 if (argc < 2) error_exit("--reply-fd requires an argument");
Siva Velusamya55dbd82015-08-07 10:10:29 -07001585 const char* reply_fd_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001586 --argc;
1587 ++argv;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001588 ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
Spencer Lowe98825e2015-09-07 16:20:13 -07001589 if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001590 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001591 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001592 }
Vince Harron5703eb32021-11-12 12:40:58 -08001593 } else if (!strcmp(argv[0], "--one-device")) {
1594 if (argc < 2) error_exit("--one-device requires an argument");
1595 one_device_str = argv[1];
1596 --argc;
1597 ++argv;
Josh Gaob39e4152017-08-16 16:57:01 -07001598 } else if (!strncmp(argv[0], "-s", 2)) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001599 if (isdigit(argv[0][2])) {
1600 serial = argv[0] + 2;
1601 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001602 if (argc < 2 || argv[0][2] != '\0') error_exit("-s requires an argument");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001603 serial = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001604 --argc;
1605 ++argv;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001606 }
Josh Gaob39e4152017-08-16 16:57:01 -07001607 } else if (!strncmp(argv[0], "-t", 2)) {
1608 const char* id;
1609 if (isdigit(argv[0][2])) {
1610 id = argv[0] + 2;
1611 } else {
Josh Gao5531e492021-10-18 16:38:13 -07001612 if (argc < 2 || argv[0][2] != '\0') error_exit("-t requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07001613 id = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001614 --argc;
1615 ++argv;
Josh Gaob39e4152017-08-16 16:57:01 -07001616 }
1617 transport_id = strtoll(id, const_cast<char**>(&id), 10);
1618 if (*id != '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001619 error_exit("invalid transport id");
Josh Gaob39e4152017-08-16 16:57:01 -07001620 }
Josh Gao67209db2019-03-14 15:38:02 -07001621 } else if (!strcmp(argv[0], "-d")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001622 transport_type = kTransportUsb;
Josh Gao67209db2019-03-14 15:38:02 -07001623 } else if (!strcmp(argv[0], "-e")) {
Elliott Hughes3aec2ba2015-05-05 13:10:43 -07001624 transport_type = kTransportLocal;
Josh Gao67209db2019-03-14 15:38:02 -07001625 } else if (!strcmp(argv[0], "-a")) {
Ryan Prichardc36807b2023-06-21 22:08:16 -07001626 gListenAll = true;
Riley Andrews03b4b372014-12-05 17:37:24 -08001627 } else if (!strncmp(argv[0], "-H", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001628 if (argv[0][2] == '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001629 if (argc < 2) error_exit("-H requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001630 server_host_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001631 --argc;
1632 ++argv;
Matt Gumbel411775c2012-11-14 10:16:17 -08001633 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001634 server_host_str = argv[0] + 2;
Matt Gumbel411775c2012-11-14 10:16:17 -08001635 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001636 } else if (!strncmp(argv[0], "-P", 2)) {
Matt Gumbel411775c2012-11-14 10:16:17 -08001637 if (argv[0][2] == '\0') {
Elliott Hughes0119a912018-10-22 17:02:51 -07001638 if (argc < 2) error_exit("-P requires an argument");
Matt Gumbel411775c2012-11-14 10:16:17 -08001639 server_port_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001640 --argc;
1641 ++argv;
Matt Gumbel411775c2012-11-14 10:16:17 -08001642 } else {
1643 server_port_str = argv[0] + 2;
1644 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001645 } else if (!strcmp(argv[0], "-L")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001646 if (argc < 2) error_exit("-L requires an argument");
Josh Gaobb4f8602016-08-25 16:00:22 -07001647 server_socket_str = argv[1];
Vince Harron5703eb32021-11-12 12:40:58 -08001648 --argc;
1649 ++argv;
Lee Shombertb796cd52022-03-22 12:19:06 -07001650 } else if (strcmp(argv[0], "--exit-on-write-error") == 0) {
1651 DEFAULT_STANDARD_STREAMS_CALLBACK.ReturnErrors(true);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001652 } else {
Josh Gaobb4f8602016-08-25 16:00:22 -07001653 /* out of recognized modifiers and flags */
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001654 break;
1655 }
Vince Harron5703eb32021-11-12 12:40:58 -08001656 --argc;
1657 ++argv;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001658 }
1659
Josh Gaobb4f8602016-08-25 16:00:22 -07001660 if ((server_host_str || server_port_str) && server_socket_str) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001661 error_exit("-L is incompatible with -H or -P");
Josh Gaobb4f8602016-08-25 16:00:22 -07001662 }
1663
1664 // If -L, -H, or -P are specified, ignore environment variables.
1665 // Otherwise, prefer ADB_SERVER_SOCKET over ANDROID_ADB_SERVER_ADDRESS/PORT.
Tao Wucaedcb52016-09-16 13:01:24 -07001666 if (!server_host_str && !server_port_str && !server_socket_str) {
1667 server_socket_str = getenv("ADB_SERVER_SOCKET");
Josh Gaobb4f8602016-08-25 16:00:22 -07001668 }
1669
1670 if (!server_socket_str) {
1671 // tcp:1234 and tcp:localhost:1234 are different with -a, so don't default to localhost
1672 server_host_str = server_host_str ? server_host_str : getenv("ANDROID_ADB_SERVER_ADDRESS");
1673
Tao Wucaedcb52016-09-16 13:01:24 -07001674 int server_port = DEFAULT_ADB_PORT;
Josh Gaobb4f8602016-08-25 16:00:22 -07001675 server_port_str = server_port_str ? server_port_str : getenv("ANDROID_ADB_SERVER_PORT");
Tao Wucaedcb52016-09-16 13:01:24 -07001676 if (server_port_str && strlen(server_port_str) > 0) {
1677 if (!android::base::ParseInt(server_port_str, &server_port, 1, 65535)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001678 error_exit(
1679 "$ANDROID_ADB_SERVER_PORT must be a positive number less than 65535: "
1680 "got \"%s\"",
1681 server_port_str);
Tao Wucaedcb52016-09-16 13:01:24 -07001682 }
1683 }
Josh Gaobb4f8602016-08-25 16:00:22 -07001684
1685 int rc;
1686 char* temp;
1687 if (server_host_str) {
Tao Wucaedcb52016-09-16 13:01:24 -07001688 rc = asprintf(&temp, "tcp:%s:%d", server_host_str, server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001689 } else {
Tao Wucaedcb52016-09-16 13:01:24 -07001690 rc = asprintf(&temp, "tcp:%d", server_port);
Josh Gaobb4f8602016-08-25 16:00:22 -07001691 }
1692 if (rc < 0) {
Elliott Hughese64126b2018-10-19 13:59:44 -07001693 LOG(FATAL) << "failed to allocate server socket specification";
Josh Gaobb4f8602016-08-25 16:00:22 -07001694 }
1695 server_socket_str = temp;
1696 }
Fabien Sanglard5295bfd2023-11-15 12:17:42 -08001697 VLOG(ADB) << "Using server socket: " << server_socket_str;
Josh Gaobb4f8602016-08-25 16:00:22 -07001698
Elliott Hughesde7776a2021-12-16 10:49:06 -08001699 bool server_start =
1700 is_daemon || is_server || (argc > 0 && strcmp(argv[0], "start-server") == 0);
Vince Harron5703eb32021-11-12 12:40:58 -08001701 if (one_device_str && !server_start) {
1702 error_exit("--one-device is only allowed when starting a server.");
1703 }
1704
1705 adb_set_one_device(one_device_str);
Josh Gaobb4f8602016-08-25 16:00:22 -07001706 adb_set_socket_spec(server_socket_str);
1707
Elliott Hughes67943d12015-10-07 14:55:10 -07001708 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1709 if (transport_type == kTransportAny && serial == nullptr) {
1710 serial = getenv("ANDROID_SERIAL");
1711 }
1712
Josh Gaob39e4152017-08-16 16:57:01 -07001713 adb_set_transport(transport_type, serial, transport_id);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001714
David 'Digit' Turner6826db62011-01-31 14:23:56 +01001715 if (is_server) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001716 if (no_daemon || is_daemon) {
Spencer Lowb28812f2015-08-08 15:07:07 -07001717 if (is_daemon && (ack_reply_fd == -1)) {
Siva Velusamya55dbd82015-08-07 10:10:29 -07001718 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001719 return 1;
Siva Velusamya55dbd82015-08-07 10:10:29 -07001720 }
Vince Harron5703eb32021-11-12 12:40:58 -08001721 r = adb_server_main(is_daemon, server_socket_str, one_device_str, ack_reply_fd);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001722 } else {
Vince Harron5703eb32021-11-12 12:40:58 -08001723 r = launch_server(server_socket_str, one_device_str);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001724 }
Riley Andrews03b4b372014-12-05 17:37:24 -08001725 if (r) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001726 fprintf(stderr,"* could not start server *\n");
1727 }
1728 return r;
1729 }
1730
Riley Andrews03b4b372014-12-05 17:37:24 -08001731 if (argc == 0) {
Elliott Hughes97e74bb2017-02-06 16:20:30 -08001732 help();
1733 return 1;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001734 }
1735
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001736 /* handle wait-for-* prefix */
1737 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001738 const char* service = argv[0];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001739
Josh Gaob39e4152017-08-16 16:57:01 -07001740 if (!wait_for_device(service)) {
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001741 return 1;
1742 }
1743
Elliott Hugheseaabdd62015-05-04 19:29:32 -07001744 // Allow a command to be run after wait-for-device,
1745 // e.g. 'adb wait-for-device shell'.
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001746 if (argc == 1) {
1747 return 0;
1748 }
1749
1750 /* Fall through */
Vince Harron5703eb32021-11-12 12:40:58 -08001751 --argc;
1752 ++argv;
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001753 }
1754
1755 /* adb_connect() commands */
Riley Andrews03b4b372014-12-05 17:37:24 -08001756 if (!strcmp(argv[0], "devices")) {
Dan Albertf30d73c2015-02-25 17:51:28 -08001757 const char *listopt;
Elliott Hughesda945812015-04-29 12:28:13 -07001758 if (argc < 2) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001759 listopt = "";
Elliott Hughesda945812015-04-29 12:28:13 -07001760 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001761 listopt = argv[1];
Elliott Hughesda945812015-04-29 12:28:13 -07001762 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07001763 error_exit("adb devices [-l]");
Scott Anderson6dfaf4b2012-04-20 11:21:14 -07001764 }
Elliott Hughesda945812015-04-29 12:28:13 -07001765
1766 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
Josh Gao67209db2019-03-14 15:38:02 -07001767 std::string error;
1768 if (!adb_check_server_version(&error)) {
1769 error_exit("failed to check server version: %s", error.c_str());
1770 }
Elliott Hughesda945812015-04-29 12:28:13 -07001771 printf("List of devices attached\n");
1772 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001773 } else if (!strcmp(argv[0], "transport-id")) {
1774 TransportId transport_id;
1775 std::string error;
1776 unique_fd fd(adb_connect(&transport_id, "host:features", &error, true));
1777 if (fd == -1) {
1778 error_exit("%s", error.c_str());
1779 }
1780 printf("%" PRIu64 "\n", transport_id);
1781 return 0;
1782 } else if (!strcmp(argv[0], "connect")) {
Elliott Hughesa5d09032020-01-08 10:02:43 -08001783 if (argc != 2) error_exit("usage: adb connect HOST[:PORT]");
Elliott Hughesda945812015-04-29 12:28:13 -07001784
1785 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1786 return adb_query_command(query);
Josh Gao5d3ef9b2020-05-04 19:23:45 -07001787 } else if (!strcmp(argv[0], "disconnect")) {
Elliott Hughes14d673e2019-07-30 13:51:03 -07001788 if (argc > 2) error_exit("usage: adb disconnect [HOST[:PORT]]");
Elliott Hughesda945812015-04-29 12:28:13 -07001789
1790 std::string query = android::base::StringPrintf("host:disconnect:%s",
1791 (argc == 2) ? argv[1] : "");
1792 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001793 } else if (!strcmp(argv[0], "abb")) {
1794 return adb_abb(argc, argv);
Joshua Duong290ccb52019-11-20 14:18:43 -08001795 } else if (!strcmp(argv[0], "pair")) {
Joshua Duong64979d02020-05-05 10:46:17 -07001796 if (argc < 2 || argc > 3) error_exit("usage: adb pair HOST[:PORT] [PAIRING CODE]");
Joshua Duong290ccb52019-11-20 14:18:43 -08001797
1798 std::string password;
Joshua Duong64979d02020-05-05 10:46:17 -07001799 if (argc == 2) {
1800 printf("Enter pairing code: ");
1801 fflush(stdout);
1802 if (!std::getline(std::cin, password) || password.empty()) {
1803 error_exit("No pairing code provided");
1804 }
1805 } else {
1806 password = argv[2];
Joshua Duong290ccb52019-11-20 14:18:43 -08001807 }
1808 std::string query =
1809 android::base::StringPrintf("host:pair:%s:%s", password.c_str(), argv[1]);
1810
1811 return adb_query_command(query);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001812 } else if (!strcmp(argv[0], "emu")) {
Spencer Low7dc759f2015-05-06 16:13:42 -07001813 return adb_send_emulator_command(argc, argv, serial);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001814 } else if (!strcmp(argv[0], "shell")) {
Josh Gao91d53b52016-01-31 19:12:26 -08001815 return adb_shell(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001816 } else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001817 int exec_in = !strcmp(argv[0], "exec-in");
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001818
Elliott Hughes0119a912018-10-22 17:02:51 -07001819 if (argc < 2) error_exit("usage: adb %s command", argv[0]);
Zach Riggle328870b2016-04-14 17:18:04 -04001820
Elliott Hughes170b5682015-04-17 10:59:34 -07001821 std::string cmd = "exec:";
1822 cmd += argv[1];
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001823 argc -= 2;
1824 argv += 2;
1825 while (argc-- > 0) {
Elliott Hughese4b64792015-04-17 20:11:08 -07001826 cmd += " " + escape_arg(*argv++);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001827 }
1828
Elliott Hughes04a98c22015-04-29 08:35:59 -07001829 std::string error;
Josh Gaoc2705962019-01-23 15:36:42 -08001830 unique_fd fd(adb_connect(cmd, &error));
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001831 if (fd < 0) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07001832 fprintf(stderr, "error: %s\n", error.c_str());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001833 return -1;
1834 }
1835
1836 if (exec_in) {
Josh Gaoc2705962019-01-23 15:36:42 -08001837 copy_to_file(STDIN_FILENO, fd.get());
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001838 } else {
Josh Gaoc2705962019-01-23 15:36:42 -08001839 copy_to_file(fd.get(), STDOUT_FILENO);
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001840 }
Jeff Sharkeyc52ec1a2014-05-26 18:30:43 -07001841 return 0;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001842 } else if (!strcmp(argv[0], "kill-server")) {
Josh Gaoee356a72017-05-08 18:37:17 -07001843 return adb_kill_server() ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001844 } else if (!strcmp(argv[0], "sideload")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001845 if (argc != 2) error_exit("sideload requires an argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001846 if (adb_sideload_install(argv[1], false /* rescue_mode */)) {
Doug Zongker6b217ed2012-01-09 14:54:53 -08001847 return 1;
1848 } else {
1849 return 0;
1850 }
Tao Baoe23e6c72019-04-07 23:24:03 -07001851 } else if (!strcmp(argv[0], "rescue")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001852 // adb rescue getprop
Tao Baoe23e6c72019-04-07 23:24:03 -07001853 // adb rescue getprop <prop>
1854 // adb rescue install <filename>
xunchang8829d152019-04-22 23:14:28 -07001855 // adb rescue wipe userdata
Tao Bao1b11c232019-06-04 14:37:06 -07001856 if (argc < 2) error_exit("rescue requires at least one argument");
Tao Baoe23e6c72019-04-07 23:24:03 -07001857 if (!strcmp(argv[1], "getprop")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001858 if (argc == 2) {
1859 return adb_connect_command("rescue-getprop:");
1860 }
1861 if (argc == 3) {
1862 return adb_connect_command(
1863 android::base::StringPrintf("rescue-getprop:%s", argv[2]));
1864 }
1865 error_exit("invalid rescue getprop arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001866 } else if (!strcmp(argv[1], "install")) {
Tao Bao1b11c232019-06-04 14:37:06 -07001867 if (argc != 3) error_exit("rescue install requires two arguments");
Tao Baoe23e6c72019-04-07 23:24:03 -07001868 if (adb_sideload_install(argv[2], true /* rescue_mode */) != 0) {
1869 return 1;
1870 }
Tao Bao1b11c232019-06-04 14:37:06 -07001871 } else if (!strcmp(argv[1], "wipe")) {
1872 if (argc != 3 || strcmp(argv[2], "userdata") != 0) {
1873 error_exit("invalid rescue wipe arguments");
1874 }
xunchang8829d152019-04-22 23:14:28 -07001875 return adb_wipe_devices();
Tao Baoe23e6c72019-04-07 23:24:03 -07001876 } else {
1877 error_exit("invalid rescue argument");
1878 }
1879 return 0;
Elliott Hughesfa085be2017-08-23 15:42:28 -07001880 } else if (!strcmp(argv[0], "tcpip")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001881 if (argc != 2) error_exit("tcpip requires an argument");
Elliott Hughesfa085be2017-08-23 15:42:28 -07001882 int port;
1883 if (!android::base::ParseInt(argv[1], &port, 1, 65535)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001884 error_exit("tcpip: invalid port: %s", argv[1]);
Elliott Hughesfa085be2017-08-23 15:42:28 -07001885 }
1886 return adb_connect_command(android::base::StringPrintf("tcpip:%d", port));
Shaju Mathew3b481e52021-10-28 00:14:04 -07001887 } else if (!strcmp(argv[0], "remount") || !strcmp(argv[0], "disable-verity") ||
1888 !strcmp(argv[0], "enable-verity")) {
Elliott Hughes18056092022-02-18 10:16:38 -08001889 return process_remount_or_verity_service(argc, argv);
Shaju Mathew3b481e52021-10-28 00:14:04 -07001890 } else if (!strcmp(argv[0], "reboot") || !strcmp(argv[0], "reboot-bootloader") ||
1891 !strcmp(argv[0], "reboot-fastboot") || !strcmp(argv[0], "usb")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001892 std::string command;
Tao Bao0db67642015-03-29 11:22:34 -07001893 if (!strcmp(argv[0], "reboot-bootloader")) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001894 command = "reboot:bootloader";
Mark Salyzynd6420432018-08-29 10:44:33 -07001895 } else if (!strcmp(argv[0], "reboot-fastboot")) {
1896 command = "reboot:fastboot";
Tao Bao0db67642015-03-29 11:22:34 -07001897 } else if (argc > 1) {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001898 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
Tao Bao0db67642015-03-29 11:22:34 -07001899 } else {
Elliott Hughesdabb9742015-05-07 23:37:40 -07001900 command = android::base::StringPrintf("%s:", argv[0]);
The Android Open Source Project9c753402009-03-13 13:04:37 -07001901 }
Tao Bao0db67642015-03-29 11:22:34 -07001902 return adb_connect_command(command);
Josh Gaod1d03392016-03-04 15:16:18 -08001903 } else if (!strcmp(argv[0], "root") || !strcmp(argv[0], "unroot")) {
1904 return adb_root(argv[0]) ? 0 : 1;
1905 } else if (!strcmp(argv[0], "bugreport")) {
Felipe Leme042c3512016-07-19 17:07:22 -07001906 Bugreport bugreport;
Josh Gaob39e4152017-08-16 16:57:01 -07001907 return bugreport.DoIt(argc, argv);
Felipe Lemeb6447032016-04-01 17:43:27 -07001908 } else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001909 bool reverse = !strcmp(argv[0], "reverse");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001910 --argc;
Elliott Hughes0119a912018-10-22 17:02:51 -07001911 if (argc < 1) error_exit("%s requires an argument", argv[0]);
Josh Gao596f63b2018-07-31 15:36:03 -07001912 ++argv;
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001913
1914 // Determine the <host-prefix> for this command.
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001915 std::string host_prefix;
David 'Digit' Turner963a4492013-03-21 21:07:42 +01001916 if (reverse) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001917 host_prefix = "reverse:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001918 } else {
Josh Gaoed00ae12019-08-06 16:43:34 -07001919 host_prefix = "host:";
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001920 }
1921
Elliott Hughese64126b2018-10-19 13:59:44 -07001922 std::string cmd, error_message;
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001923 if (strcmp(argv[0], "--list") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001924 if (argc != 1) error_exit("--list doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001925 return adb_query_command(host_prefix + "list-forward");
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001926 } else if (strcmp(argv[0], "--remove-all") == 0) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001927 if (argc != 1) error_exit("--remove-all doesn't take any arguments");
Josh Gaoed00ae12019-08-06 16:43:34 -07001928 cmd = "killforward-all";
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001929 } else if (strcmp(argv[0], "--remove") == 0) {
1930 // forward --remove <local>
Elliott Hughes0119a912018-10-22 17:02:51 -07001931 if (argc != 2) error_exit("--remove requires an argument");
Josh Gaoed00ae12019-08-06 16:43:34 -07001932 cmd = std::string("killforward:") + argv[1];
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001933 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1934 // forward --no-rebind <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001935 if (argc != 3) error_exit("--no-rebind takes two arguments");
Octavian Purdila4b4421d2024-04-03 23:13:14 -07001936 if (forward_targets_are_valid(argv[1], argv[2], &error_message) &&
1937 forward_dest_is_featured(argv[2], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001938 cmd = std::string("forward:norebind:") + argv[1] + ";" + argv[2];
David Pursell19d0c232016-04-07 11:25:48 -07001939 }
Elliott Hughesd98ca8a2015-05-29 17:55:19 -07001940 } else {
1941 // forward <local> <remote>
Elliott Hughes0119a912018-10-22 17:02:51 -07001942 if (argc != 2) error_exit("forward takes two arguments");
Octavian Purdila4b4421d2024-04-03 23:13:14 -07001943 if (forward_targets_are_valid(argv[0], argv[1], &error_message) &&
1944 forward_dest_is_featured(argv[1], &error_message)) {
Josh Gaoed00ae12019-08-06 16:43:34 -07001945 cmd = std::string("forward:") + argv[0] + ";" + argv[1];
David Pursell19d0c232016-04-07 11:25:48 -07001946 }
David 'Digit' Turner6c489802012-11-14 15:01:55 +01001947 }
1948
Elliott Hughese64126b2018-10-19 13:59:44 -07001949 if (!error_message.empty()) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001950 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001951 }
1952
Josh Gaoed00ae12019-08-06 16:43:34 -07001953 unique_fd fd(adb_connect(nullptr, host_prefix + cmd, &error_message, true));
Josh Gaoc2705962019-01-23 15:36:42 -08001954 if (fd < 0 || !adb_status(fd.get(), &error_message)) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001955 error_exit("error: %s", error_message.c_str());
David Pursell19d0c232016-04-07 11:25:48 -07001956 }
1957
1958 // Server or device may optionally return a resolved TCP port number.
1959 std::string resolved_port;
Elliott Hughese64126b2018-10-19 13:59:44 -07001960 if (ReadProtocolString(fd, &resolved_port, &error_message) && !resolved_port.empty()) {
David Pursell19d0c232016-04-07 11:25:48 -07001961 printf("%s\n", resolved_port.c_str());
1962 }
1963
1964 ReadOrderlyShutdown(fd);
1965 return 0;
Joshua Duonge22e1612020-03-31 10:58:50 -07001966 } else if (!strcmp(argv[0], "mdns")) {
1967 --argc;
1968 if (argc < 1) error_exit("mdns requires an argument");
1969 ++argv;
1970
1971 std::string error;
1972 if (!adb_check_server_version(&error)) {
1973 error_exit("failed to check server version: %s", error.c_str());
1974 }
1975
1976 std::string query = "host:mdns:";
1977 if (!strcmp(argv[0], "check")) {
1978 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1979 query += "check";
Joshua Duong5f63d112020-03-31 08:39:24 -07001980 } else if (!strcmp(argv[0], "services")) {
1981 if (argc != 1) error_exit("mdns %s doesn't take any arguments", argv[0]);
1982 query += "services";
1983 printf("List of discovered mdns services\n");
Joshua Duonge22e1612020-03-31 10:58:50 -07001984 } else {
1985 error_exit("unknown mdns command [%s]", argv[0]);
1986 }
1987
1988 return adb_query_command(query);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001989 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08001990 /* do_sync_*() commands */
Riley Andrewsfacb92d2014-12-05 17:32:46 -08001991 else if (!strcmp(argv[0], "ls")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07001992 if (argc != 2) error_exit("ls requires an argument");
Elliott Hughesb628cb12015-08-03 10:38:08 -07001993 return do_sync_ls(argv[1]) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08001994 } else if (!strcmp(argv[0], "push")) {
Josh Gao5d093b22015-10-30 16:57:19 -07001995 bool copy_attrs = false;
Dan Albert8449e062017-05-18 22:56:48 -07001996 bool sync = false;
Josh Gao8a410a02020-03-30 23:25:16 -07001997 bool dry_run = false;
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07001998 bool quiet = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07001999 CompressionType compression = CompressionType::Any;
Josh Gao5d093b22015-10-30 16:57:19 -07002000 std::vector<const char*> srcs;
2001 const char* dst = nullptr;
Mark Lindner9f9d1452014-03-11 17:55:59 -07002002
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002003 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, &sync, &quiet,
2004 &compression, &dry_run);
shaju1a0f9152022-10-25 14:54:37 -07002005 if (srcs.empty() || !dst) {
2006 error_exit("push requires <source> and <destination> arguments");
2007 }
2008
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002009 return do_sync_push(srcs, dst, sync, compression, dry_run, quiet) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002010 } else if (!strcmp(argv[0], "pull")) {
Josh Gao5d093b22015-10-30 16:57:19 -07002011 bool copy_attrs = false;
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002012 bool quiet = false;
Snild Dolkow30e74ac2020-09-23 09:31:50 +02002013 CompressionType compression = CompressionType::None;
Josh Gao5d093b22015-10-30 16:57:19 -07002014 std::vector<const char*> srcs;
2015 const char* dst = ".";
Mark Lindner9f9d1452014-03-11 17:55:59 -07002016
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002017 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs, nullptr, &quiet,
2018 &compression, nullptr);
Elliott Hughes0119a912018-10-22 17:02:51 -07002019 if (srcs.empty()) error_exit("pull requires an argument");
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002020 return do_sync_pull(srcs, dst, copy_attrs, compression, nullptr, quiet) ? 0 : 1;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002021 } else if (!strcmp(argv[0], "install")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002022 if (argc < 2) error_exit("install requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07002023 return install_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002024 } else if (!strcmp(argv[0], "install-multiple")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002025 if (argc < 2) error_exit("install-multiple requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07002026 return install_multiple_app(argc, argv);
Patrick Baumann810ee9b2018-10-09 10:45:03 -07002027 } else if (!strcmp(argv[0], "install-multi-package")) {
Mohammad Samiul Islamed2e8732019-05-29 15:00:00 +01002028 if (argc < 2) error_exit("install-multi-package requires an argument");
Patrick Baumann810ee9b2018-10-09 10:45:03 -07002029 return install_multi_package(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002030 } else if (!strcmp(argv[0], "uninstall")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002031 if (argc < 2) error_exit("uninstall requires an argument");
Josh Gaob39e4152017-08-16 16:57:01 -07002032 return uninstall_app(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002033 } else if (!strcmp(argv[0], "sync")) {
Elliott Hughesc5a12b22015-04-21 10:17:07 -07002034 std::string src;
Elliott Hughes38104452015-04-17 13:57:15 -07002035 bool list_only = false;
Josh Gao8a410a02020-03-30 23:25:16 -07002036 bool dry_run = false;
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002037 bool quiet = false;
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002038 CompressionType compression = CompressionType::Any;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002039
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002040 if (const char* adb_compression = getenv("ADB_COMPRESSION"); adb_compression) {
2041 compression = parse_compression_type(adb_compression, true);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002042 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002043
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002044 int opt;
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002045 while ((opt = getopt(argc, const_cast<char**>(argv), "lnz:Zq")) != -1) {
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002046 switch (opt) {
2047 case 'l':
2048 list_only = true;
2049 break;
Josh Gao8a410a02020-03-30 23:25:16 -07002050 case 'n':
2051 dry_run = true;
2052 break;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002053 case 'z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002054 compression = parse_compression_type(optarg, false);
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002055 break;
2056 case 'Z':
Josh Gaobfcd8ff2020-03-26 19:33:25 -07002057 compression = CompressionType::None;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002058 break;
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002059 case 'q':
2060 quiet = true;
2061 break;
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002062 default:
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002063 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [-q] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002064 }
2065 }
2066
2067 if (optind == argc) {
2068 src = "all";
2069 } else if (optind + 1 == argc) {
2070 src = argv[optind];
2071 } else {
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002072 error_exit("usage: adb sync [-l] [-n] [-z ALGORITHM] [-Z] [-q] [PARTITION]");
Josh Gao2f0f9eb2020-03-04 19:34:08 -08002073 }
2074
Justin Yunb0c201c2019-06-26 09:18:03 +09002075 std::vector<std::string> partitions{"data", "odm", "oem", "product",
2076 "system", "system_ext", "vendor"};
Elliott Hughes145ac022018-04-03 10:54:39 -07002077 bool found = false;
2078 for (const auto& partition : partitions) {
2079 if (src == "all" || src == partition) {
2080 std::string src_dir{product_file(partition)};
2081 if (!directory_exists(src_dir)) continue;
2082 found = true;
Peter Collingbournea41eb3d2024-03-28 20:05:07 -07002083 if (!do_sync_sync(src_dir, "/" + partition, list_only, compression, dry_run, quiet)) {
Josh Gao8a410a02020-03-30 23:25:16 -07002084 return 1;
2085 }
Elliott Hughes145ac022018-04-03 10:54:39 -07002086 }
Elliott Hughes38104452015-04-17 13:57:15 -07002087 }
Elliott Hughes0119a912018-10-22 17:02:51 -07002088 if (!found) error_exit("don't know how to sync %s partition", src.c_str());
Elliott Hughese64126b2018-10-19 13:59:44 -07002089 return 0;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002090 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002091 /* passthrough commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002092 else if (!strcmp(argv[0], "get-state") || !strcmp(argv[0], "get-serialno") ||
2093 !strcmp(argv[0], "get-devpath")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002094 return adb_query_command(format_host_command(argv[0]));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002095 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002096 /* other commands */
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002097 else if (!strcmp(argv[0], "logcat") || !strcmp(argv[0], "lolcat") ||
2098 !strcmp(argv[0], "longcat")) {
Josh Gaob39e4152017-08-16 16:57:01 -07002099 return logcat(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002100 } else if (!strcmp(argv[0], "start-server")) {
Elliott Hughes04a98c22015-04-29 08:35:59 -07002101 std::string error;
Spencer Low85ee64b2015-08-11 17:05:02 -07002102 const int result = adb_connect("host:start-server", &error);
2103 if (result < 0) {
2104 fprintf(stderr, "error: %s\n", error.c_str());
2105 }
2106 return result;
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002107 } else if (!strcmp(argv[0], "backup")) {
Christopher Tate73779122011-04-21 12:53:28 -07002108 return backup(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002109 } else if (!strcmp(argv[0], "restore")) {
Christopher Tatecf5379b2011-05-17 15:52:54 -07002110 return restore(argc, argv);
Alex Buynytskyyef34f012018-12-12 10:48:50 -08002111 } else if (!strcmp(argv[0], "keygen")) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002112 if (argc != 2) error_exit("keygen requires an argument");
Yabin Cui19bec5b2015-09-22 15:52:57 -07002113 // Always print key generation information for keygen command.
2114 adb_trace_enable(AUTH);
Nick Kralevich6183c962014-11-13 15:17:29 -08002115 return adb_auth_keygen(argv[1]);
Josh Gao13102c32018-11-15 17:45:46 -08002116 } else if (!strcmp(argv[0], "pubkey")) {
2117 if (argc != 2) error_exit("pubkey requires an argument");
2118 return adb_auth_pubkey(argv[1]);
2119 } else if (!strcmp(argv[0], "jdwp")) {
Tao Bao0db67642015-03-29 11:22:34 -07002120 return adb_connect_command("jdwp");
Josh Gao13102c32018-11-15 17:45:46 -08002121 } else if (!strcmp(argv[0], "track-jdwp")) {
Josh Gao39d01bb2016-05-13 18:18:23 -07002122 return adb_connect_command("track-jdwp");
Shukang Zhou420ad552020-02-13 17:01:39 -08002123 } else if (!strcmp(argv[0], "track-app")) {
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07002124 auto&& features = adb_get_feature_set_or_die();
Josh Gao291733b2020-04-16 19:34:43 -07002125 if (!CanUseFeature(*features, kFeatureTrackApp)) {
Shukang Zhou420ad552020-02-13 17:01:39 -08002126 error_exit("track-app is not supported by the device");
2127 }
2128 TrackAppStreamsCallback callback;
Fabien Sanglard15335e02024-03-05 21:33:44 +00002129 if (argc == 1) {
2130 return adb_connect_command("track-app", nullptr, &callback);
2131 } else if (argc == 2) {
2132 if (!strcmp(argv[1], "--proto-binary")) {
2133 return adb_connect_command("track-app");
2134 } else if (!strcmp(argv[1], "--proto-text")) {
2135 return adb_connect_command("track-app", nullptr, &callback);
2136 }
2137 } else {
2138 error_exit("usage: adb track-app [--proto-binary][--proto-text]");
2139 }
Josh Gao13102c32018-11-15 17:45:46 -08002140 } else if (!strcmp(argv[0], "track-devices")) {
Fabien Sanglard3d155b62023-11-30 14:52:40 -08002141 const char* listopt;
2142 if (argc < 2) {
2143 listopt = "";
2144 } else {
2145 if (!strcmp(argv[1], "-l")) {
2146 listopt = argv[1];
2147 } else if (!strcmp(argv[1], "--proto-text")) {
2148 listopt = "-proto-text";
2149 } else if (!strcmp(argv[1], "--proto-binary")) {
2150 listopt = "-proto-binary";
2151 } else {
2152 error_exit("usage: adb track-devices [-l][--proto-text][--proto-binary]");
2153 }
Elliott Hughes3d792f42019-07-31 14:13:57 -07002154 }
Fabien Sanglard3d155b62023-11-30 14:52:40 -08002155 std::string query = android::base::StringPrintf("host:track-devices%s", listopt);
2156 return adb_connect_command(query);
Josh Gaobf5167c2018-06-18 14:51:56 -07002157 } else if (!strcmp(argv[0], "raw")) {
2158 if (argc != 2) {
Elliott Hughes0119a912018-10-22 17:02:51 -07002159 error_exit("usage: adb raw SERVICE");
Josh Gaobf5167c2018-06-18 14:51:56 -07002160 }
Josh Gao7b438fa2018-11-16 14:47:59 -08002161 return adb_connect_command_bidirectional(argv[1]);
Josh Gao39d01bb2016-05-13 18:18:23 -07002162 }
2163
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002164 /* "adb /?" is a common idiom under Windows */
Elliott Hughes97e74bb2017-02-06 16:20:30 -08002165 else if (!strcmp(argv[0], "--help") || !strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002166 help();
2167 return 0;
Josh Gao13102c32018-11-15 17:45:46 -08002168 } else if (!strcmp(argv[0], "--version") || !strcmp(argv[0], "version")) {
Elliott Hughesb9f01642015-08-12 08:32:10 -07002169 fprintf(stdout, "%s", adb_version().c_str());
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002170 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002171 } else if (!strcmp(argv[0], "features")) {
David Pursella07dbad2015-09-22 10:43:08 -07002172 // Only list the features common to both the adb client and the device.
Shaju Mathewbf7da1c2021-10-30 13:47:11 -07002173 auto&& features = adb_get_feature_set_or_die();
David Pursell9650d862016-01-21 19:56:50 -08002174
Josh Gao291733b2020-04-16 19:34:43 -07002175 for (const std::string& name : *features) {
2176 if (CanUseFeature(*features, name)) {
David Pursella07dbad2015-09-22 10:43:08 -07002177 printf("%s\n", name.c_str());
2178 }
2179 }
2180 return 0;
Josh Gao210b63f2017-02-22 17:07:01 -08002181 } else if (!strcmp(argv[0], "host-features")) {
2182 return adb_query_command("host:host-features");
Yabin Cuid78ed222016-04-05 13:50:44 -07002183 } else if (!strcmp(argv[0], "reconnect")) {
2184 if (argc == 1) {
Josh Gaob39e4152017-08-16 16:57:01 -07002185 return adb_query_command(format_host_command(argv[0]));
Josh Gao4e562502016-10-27 14:01:08 -07002186 } else if (argc == 2) {
2187 if (!strcmp(argv[1], "device")) {
2188 std::string err;
2189 adb_connect("reconnect", &err);
2190 return 0;
2191 } else if (!strcmp(argv[1], "offline")) {
2192 std::string err;
2193 return adb_query_command("host:reconnect-offline");
2194 } else {
Elliott Hughes0119a912018-10-22 17:02:51 -07002195 error_exit("usage: adb reconnect [device|offline]");
Josh Gao4e562502016-10-27 14:01:08 -07002196 }
Yabin Cuid78ed222016-04-05 13:50:44 -07002197 }
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002198 } else if (!strcmp(argv[0], "inc-server")) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002199 if (argc < 4) {
2200#ifdef _WIN32
2201 error_exit("usage: adb inc-server CONNECTION_HANDLE OUTPUT_HANDLE FILE1 FILE2 ...");
2202#else
2203 error_exit("usage: adb inc-server CONNECTION_FD OUTPUT_FD FILE1 FILE2 ...");
2204#endif
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002205 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002206 int connection_fd = atoi(argv[1]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002207 if (!_is_valid_os_fd(connection_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002208 error_exit("Invalid connection_fd number given: %d", connection_fd);
Alex Buynytskyy175ce292020-02-13 06:52:04 -08002209 }
Songchun Fandaf826a2020-03-09 11:33:44 -07002210
2211 connection_fd = adb_register_socket(connection_fd);
2212 close_on_exec(connection_fd);
2213
2214 int output_fd = atoi(argv[2]);
Yurii Zubrytskyi745a8182020-03-18 15:49:45 -07002215 if (!_is_valid_os_fd(output_fd)) {
Songchun Fandaf826a2020-03-09 11:33:44 -07002216 error_exit("Invalid output_fd number given: %d", output_fd);
2217 }
2218 output_fd = adb_register_socket(output_fd);
2219 close_on_exec(output_fd);
2220 return incremental::serve(connection_fd, output_fd, argc - 3, argv + 3);
Josh Gao8e7c9722021-06-17 04:19:45 -07002221 } else if (!strcmp(argv[0], "attach") || !strcmp(argv[0], "detach")) {
2222 const char* service = strcmp(argv[0], "attach") == 0 ? "host:attach" : "host:detach";
2223 std::string result;
2224 std::string error;
2225 if (!adb_query(service, &result, &error, true)) {
2226 error_exit("failed to %s: %s", argv[0], error.c_str());
2227 }
2228 printf("%s\n", result.c_str());
2229 return 0;
Fabien Sanglard05789412024-05-30 23:00:18 -07002230 } else if (!strcmp(argv[0], "server-status")) {
2231 AdbServerStateStreamsCallback callback;
2232 return adb_connect_command("host:server-status", nullptr, &callback);
Dan Albert996c12e2015-05-20 18:58:41 -07002233 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002234
Elliott Hughes0119a912018-10-22 17:02:51 -07002235 error_exit("unknown command %s", argv[0]);
Elliott Hughese64126b2018-10-19 13:59:44 -07002236 __builtin_unreachable();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -08002237}