blob: 6970a18401880adb1edec7152a3d5ebdeaee420d [file] [log] [blame]
The Android Open Source Projectdd7bc332009-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 Cuiaed3c612015-09-22 15:52:57 -070017#define TRACE_TAG ADB
Dan Albert33134262015-03-19 15:21:08 -070018
19#include "sysdeps.h"
20
Dan Albert76649012015-02-24 15:51:19 -080021#include <assert.h>
22#include <ctype.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080023#include <errno.h>
Elliott Hughes2940ccf2015-04-17 14:07:52 -070024#include <inttypes.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080025#include <limits.h>
26#include <stdarg.h>
Dan Albert76649012015-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 Projectdd7bc332009-03-03 19:32:55 -080031#include <sys/stat.h>
Dan Albert76649012015-02-24 15:51:19 -080032#include <sys/types.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080033
David Pursell606835a2015-09-08 17:17:02 -070034#include <memory>
Elliott Hughes2baae3a2015-04-17 10:59:34 -070035#include <string>
Josh Gao05786772015-10-30 16:57:19 -070036#include <vector>
Elliott Hughes2baae3a2015-04-17 10:59:34 -070037
David Pursell606835a2015-09-08 17:17:02 -070038#include <base/logging.h>
Elliott Hughes2baae3a2015-04-17 10:59:34 -070039#include <base/stringprintf.h>
David Pursell4e2fd362015-09-22 10:43:08 -070040#include <base/strings.h>
Elliott Hughes2baae3a2015-04-17 10:59:34 -070041
Yabin Cuid325e862014-11-17 14:48:25 -080042#if !defined(_WIN32)
Josh Gao8dcdb572015-10-23 15:03:31 -070043#include <signal.h>
Elliott Hughes0fbf9612015-11-04 13:07:47 -080044#include <sys/ioctl.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080045#include <termios.h>
Dan Albert76649012015-02-24 15:51:19 -080046#include <unistd.h>
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080047#endif
48
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080049#include "adb.h"
Nick Kralevichbea3f9c2014-11-13 15:17:29 -080050#include "adb_auth.h"
Dan Albertcc731cc2015-02-24 21:26:58 -080051#include "adb_client.h"
52#include "adb_io.h"
Elliott Hughes58305772015-04-17 13:57:15 -070053#include "adb_utils.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080054#include "file_sync_service.h"
David Pursell70ef7b42015-09-30 13:35:42 -070055#include "services.h"
David Pursell606835a2015-09-08 17:17:02 -070056#include "shell_service.h"
57#include "transport.h"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080058
Elliott Hughes3bd73c12015-05-05 13:10:43 -070059static int install_app(TransportType t, const char* serial, int argc, const char** argv);
60static int install_multiple_app(TransportType t, const char* serial, int argc, const char** argv);
61static int uninstall_app(TransportType t, const char* serial, int argc, const char** argv);
Todd Kennedy6fa848a2015-11-03 16:53:08 -080062static int install_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
63static int uninstall_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080064
Elliott Hughes58305772015-04-17 13:57:15 -070065static std::string gProductOutPath;
Matt Gumbeld7b33082012-11-14 10:16:17 -080066extern int gListenAll;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080067
Elliott Hughes58305772015-04-17 13:57:15 -070068static std::string product_file(const char *extra) {
69 if (gProductOutPath.empty()) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080070 fprintf(stderr, "adb: Product directory not specified; "
71 "use -p or define ANDROID_PRODUCT_OUT\n");
72 exit(1);
73 }
74
Elliott Hughes58305772015-04-17 13:57:15 -070075 return android::base::StringPrintf("%s%s%s",
76 gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080077}
78
Elliott Hughes58305772015-04-17 13:57:15 -070079static void help() {
Elliott Hughes42ae2602015-08-12 08:32:10 -070080 fprintf(stderr, "%s\n", adb_version().c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080081 fprintf(stderr,
Matt Gumbeld7b33082012-11-14 10:16:17 -080082 " -a - directs adb to listen on all interfaces for a connection\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080083 " -d - directs command to the only connected USB device\n"
84 " returns an error if more than one USB device is present.\n"
85 " -e - directs command to the only running emulator.\n"
86 " returns an error if more than one emulator is running.\n"
Scott Andersone109d262012-04-20 11:21:14 -070087 " -s <specific device> - directs command to the device or emulator with the given\n"
Scott Anderson2ca3e6b2012-05-30 18:11:27 -070088 " serial number or qualifier. Overrides ANDROID_SERIAL\n"
Elliott Hughes31dbed72009-10-07 15:38:53 -070089 " environment variable.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080090 " -p <product name or path> - simple product name like 'sooner', or\n"
91 " a relative/absolute path to a product\n"
92 " out directory like 'out/target/product/sooner'.\n"
93 " If -p is not specified, the ANDROID_PRODUCT_OUT\n"
94 " environment variable is used, which must\n"
95 " be an absolute path.\n"
Matt Gumbeld7b33082012-11-14 10:16:17 -080096 " -H - Name of adb server host (default: localhost)\n"
97 " -P - Port of adb server (default: 5037)\n"
Scott Andersone109d262012-04-20 11:21:14 -070098 " devices [-l] - list all connected devices\n"
Scott Anderson2ca3e6b2012-05-30 18:11:27 -070099 " ('-l' will also list device qualifiers)\n"
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400100 " connect <host>[:<port>] - connect to a device via TCP/IP\n"
101 " Port 5555 is used by default if no port number is specified.\n"
102 " disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.\n"
103 " Port 5555 is used by default if no port number is specified.\n"
Bernhard Reutner-Fischer6715a432011-04-26 12:46:05 +0200104 " Using this command with no additional arguments\n"
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -0400105 " will disconnect from all connected TCP/IP devices.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800106 "\n"
107 "device commands:\n"
Josh Gao05786772015-10-30 16:57:19 -0700108 " adb push <local>... <remote>\n"
109 " - copy files/dirs to device\n"
110 " adb pull [-a] <remote>... <local>\n"
111 " - copy files/dirs from device\n"
112 " (-a preserves file timestamp and mode)\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800113 " adb sync [ <directory> ] - copy host->device only if changed\n"
Anthony Newnam705c9442010-02-22 08:36:49 -0600114 " (-l means list but don't copy)\n"
David Pursell70ef7b42015-09-30 13:35:42 -0700115 " adb shell [-Ttx] - run remote shell interactively\n"
116 " adb shell [-Ttx] <command> - run remote shell command\n"
David Pursell4e2fd362015-09-22 10:43:08 -0700117 " (-T disables PTY allocation)\n"
118 " (-t forces PTY allocation)\n"
David Pursell70ef7b42015-09-30 13:35:42 -0700119 " (-x disables remote exit codes and stdout/stderr separation)\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800120 " adb emu <command> - run emulator console command\n"
121 " adb logcat [ <filter-spec> ] - View device log\n"
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100122 " adb forward --list - list all forward socket connections.\n"
123 " the format is a list of lines with the following format:\n"
124 " <serial> \" \" <local> \" \" <remote> \"\\n\"\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800125 " adb forward <local> <remote> - forward socket connections\n"
126 " forward specs are one of: \n"
127 " tcp:<port>\n"
128 " localabstract:<unix domain socket name>\n"
129 " localreserved:<unix domain socket name>\n"
130 " localfilesystem:<unix domain socket name>\n"
131 " dev:<character device name>\n"
132 " jdwp:<process pid> (remote only)\n"
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +0100133 " adb forward --no-rebind <local> <remote>\n"
134 " - same as 'adb forward <local> <remote>' but fails\n"
135 " if <local> is already forwarded\n"
136 " adb forward --remove <local> - remove a specific forward socket connection\n"
137 " adb forward --remove-all - remove all forward socket connections\n"
David 'Digit' Turner25258692013-03-21 21:07:42 +0100138 " adb reverse --list - list all reverse socket connections from device\n"
139 " adb reverse <remote> <local> - reverse socket connections\n"
140 " reverse specs are one of:\n"
141 " tcp:<port>\n"
142 " localabstract:<unix domain socket name>\n"
143 " localreserved:<unix domain socket name>\n"
144 " localfilesystem:<unix domain socket name>\n"
Spencer Low587ea202015-11-02 17:34:49 -0800145 " adb reverse --no-rebind <remote> <local>\n"
David 'Digit' Turner25258692013-03-21 21:07:42 +0100146 " - same as 'adb reverse <remote> <local>' but fails\n"
147 " if <remote> is already reversed.\n"
148 " adb reverse --remove <remote>\n"
149 " - remove a specific reversed socket connection\n"
150 " adb reverse --remove-all - remove all reversed socket connections from device\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800151 " adb jdwp - list PIDs of processes hosting a JDWP transport\n"
Lorenzo Colitti0b3baac2015-05-28 12:03:44 +0900152 " adb install [-lrtsdg] <file>\n"
Svetoslav23d84072015-06-01 16:02:50 -0700153 " - push this package file to the device and install it\n"
154 " (-l: forward lock application)\n"
155 " (-r: replace existing application)\n"
156 " (-t: allow test packages)\n"
157 " (-s: install application on sdcard)\n"
158 " (-d: allow version code downgrade)\n"
159 " (-g: grant all runtime permissions)\n"
Lorenzo Colitti0b3baac2015-05-28 12:03:44 +0900160 " adb install-multiple [-lrtsdpg] <file...>\n"
Anonymous Coward4474ac42012-04-24 10:43:41 -0700161 " - push this package file to the device and install it\n"
Jeff Sharkey960df972014-06-09 17:30:57 -0700162 " (-l: forward lock application)\n"
163 " (-r: replace existing application)\n"
164 " (-t: allow test packages)\n"
165 " (-s: install application on sdcard)\n"
166 " (-d: allow version code downgrade)\n"
167 " (-p: partial application install)\n"
Lorenzo Colitti0b3baac2015-05-28 12:03:44 +0900168 " (-g: grant all runtime permissions)\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800169 " adb uninstall [-k] <package> - remove this app package from the device\n"
170 " ('-k' means keep the data and cache directories)\n"
171 " adb bugreport - return all information from the device\n"
172 " that should be included in a bug report.\n"
173 "\n"
Christopher Tate0c06eb52013-03-06 16:40:52 -0800174 " adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]\n"
Christopher Tate56885092011-10-03 18:27:01 -0700175 " - write an archive of the device's data to <file>.\n"
176 " If no -f option is supplied then the data is written\n"
177 " to \"backup.ab\" in the current directory.\n"
Christopher Tated2f54152011-04-21 12:53:28 -0700178 " (-apk|-noapk enable/disable backup of the .apks themselves\n"
Christopher Tatede034ec2011-08-09 17:05:29 -0700179 " in the archive; the default is noapk.)\n"
Christopher Tate0c06eb52013-03-06 16:40:52 -0800180 " (-obb|-noobb enable/disable backup of any installed apk expansion\n"
181 " (aka .obb) files associated with each application; the default\n"
182 " is noobb.)\n"
Christopher Tated2f54152011-04-21 12:53:28 -0700183 " (-shared|-noshared enable/disable backup of the device's\n"
184 " shared storage / SD card contents; the default is noshared.)\n"
185 " (-all means to back up all installed applications)\n"
Christopher Tate56885092011-10-03 18:27:01 -0700186 " (-system|-nosystem toggles whether -all automatically includes\n"
187 " system applications; the default is to include system apps)\n"
Christopher Tated2f54152011-04-21 12:53:28 -0700188 " (<packages...> is the list of applications to be backed up. If\n"
189 " the -all or -shared flags are passed, then the package\n"
Christopher Tate56885092011-10-03 18:27:01 -0700190 " list is optional. Applications explicitly given on the\n"
191 " command line will be included even if -nosystem would\n"
192 " ordinarily cause them to be omitted.)\n"
Christopher Tated2f54152011-04-21 12:53:28 -0700193 "\n"
Christopher Tatede034ec2011-08-09 17:05:29 -0700194 " adb restore <file> - restore device contents from the <file> backup archive\n"
Christopher Tate702967a2011-05-17 15:52:54 -0700195 "\n"
Paul Lawrence982089d2014-12-03 15:31:57 -0800196 " adb disable-verity - disable dm-verity checking on USERDEBUG builds\n"
197 " adb enable-verity - re-enable dm-verity checking on USERDEBUG builds\n"
Nick Kralevichbea3f9c2014-11-13 15:17:29 -0800198 " adb keygen <file> - generate adb public/private key. The private key is stored in <file>,\n"
199 " and the public key is stored in <file>.pub. Any existing files\n"
200 " are overwritten.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201 " adb help - show this help message\n"
202 " adb version - show version num\n"
203 "\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800204 "scripting:\n"
205 " adb wait-for-device - block until device is online\n"
206 " adb start-server - ensure that there is a server running\n"
207 " adb kill-server - kill the server if it is running\n"
208 " adb get-state - prints: offline | bootloader | device\n"
209 " adb get-serialno - prints: <serial-number>\n"
Scott Andersone109d262012-04-20 11:21:14 -0700210 " adb get-devpath - prints: <device-path>\n"
Elliott Hughesec7a6672015-03-16 21:58:32 +0000211 " adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write\n"
Tao Bao175b7bb2015-03-29 11:22:34 -0700212 " adb reboot [bootloader|recovery]\n"
213 " - reboots the device, optionally into the bootloader or recovery program.\n"
214 " adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).\n"
215 " adb reboot sideload-auto-reboot\n"
216 " - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.\n"
Elliott Hughes7e067cf2015-06-12 14:26:29 -0700217 " adb sideload <file> - sideloads the given package\n"
Mike Lockwoodff196702009-08-24 15:58:40 -0700218 " adb root - restarts the adbd daemon with root permissions\n"
Dan Pasanen98858812014-10-06 12:57:20 -0500219 " adb unroot - restarts the adbd daemon without root permissions\n"
Romain Guy311add42009-12-14 14:42:17 -0800220 " adb usb - restarts the adbd daemon listening on USB\n"
Paul Lawrenceec900bb2014-10-09 14:22:49 +0000221 " adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port\n"
Elliott Hughes7e067cf2015-06-12 14:26:29 -0700222 "\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800223 "networking:\n"
224 " adb ppp <tty> [parameters] - Run PPP over USB.\n"
Kenny Rootc9891992009-06-08 14:40:30 -0500225 " Note: you should not automatically start a PPP connection.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800226 " <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1\n"
227 " [parameters] - Eg. defaultroute debug dump local notty usepeerdns\n"
228 "\n"
229 "adb sync notes: adb sync [ <directory> ]\n"
230 " <localdir> can be interpreted in several ways:\n"
231 "\n"
Elliott Hughesec7a6672015-03-16 21:58:32 +0000232 " - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800233 "\n"
Elliott Hughesec7a6672015-03-16 21:58:32 +0000234 " - If it is \"system\", \"vendor\", \"oem\" or \"data\", only the corresponding partition\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800235 " is updated.\n"
Timcd643152010-02-16 20:18:29 +0000236 "\n"
Elliott Hughes7e067cf2015-06-12 14:26:29 -0700237 "environment variables:\n"
Timcd643152010-02-16 20:18:29 +0000238 " ADB_TRACE - Print debug information. A comma separated list of the following values\n"
239 " 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp\n"
240 " ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.\n"
241 " ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.\n"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800242 );
243}
244
Elliott Hughes58305772015-04-17 13:57:15 -0700245static int usage() {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800246 help();
247 return 1;
248}
249
Yabin Cuid325e862014-11-17 14:48:25 -0800250#if defined(_WIN32)
251
Elliott Hughesa2f2e562015-04-16 16:47:02 -0700252// Implemented in sysdeps_win32.cpp.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800253void stdin_raw_init();
254void stdin_raw_restore();
Yabin Cuid325e862014-11-17 14:48:25 -0800255
256#else
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100257static termios g_saved_terminal_state;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800259static void stdin_raw_init() {
260 if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800261
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100262 termios tio;
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800263 if (tcgetattr(STDIN_FILENO, &tio)) return;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800264
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100265 cfmakeraw(&tio);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800266
Alistair Buxtondfa09fd2013-03-01 22:16:41 +0100267 // No timeout but request at least one character per read.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800268 tio.c_cc[VTIME] = 0;
269 tio.c_cc[VMIN] = 1;
270
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800271 tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272}
273
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800274static void stdin_raw_restore() {
275 tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800276}
277#endif
278
David Pursell606835a2015-09-08 17:17:02 -0700279// Reads from |fd| and prints received data. If |use_shell_protocol| is true
280// this expects that incoming data will use the shell protocol, in which case
281// stdout/stderr are routed independently and the remote exit code will be
282// returned.
283static int read_and_dump(int fd, bool use_shell_protocol=false) {
284 int exit_code = 0;
285 std::unique_ptr<ShellProtocol> protocol;
286 int length = 0;
287 FILE* outfile = stdout;
288
289 char raw_buffer[BUFSIZ];
290 char* buffer_ptr = raw_buffer;
291 if (use_shell_protocol) {
292 protocol.reset(new ShellProtocol(fd));
293 if (!protocol) {
294 LOG(ERROR) << "failed to allocate memory for ShellProtocol object";
295 return 1;
296 }
297 buffer_ptr = protocol->data();
298 }
299
Elliott Hughes5677c232015-05-07 23:37:40 -0700300 while (fd >= 0) {
David Pursell606835a2015-09-08 17:17:02 -0700301 if (use_shell_protocol) {
302 if (!protocol->Read()) {
303 break;
304 }
305 switch (protocol->id()) {
306 case ShellProtocol::kIdStdout:
307 outfile = stdout;
308 break;
309 case ShellProtocol::kIdStderr:
310 outfile = stderr;
311 break;
312 case ShellProtocol::kIdExit:
313 exit_code = protocol->data()[0];
314 continue;
315 default:
316 continue;
317 }
318 length = protocol->data_length();
319 } else {
320 D("read_and_dump(): pre adb_read(fd=%d)", fd);
321 length = adb_read(fd, raw_buffer, sizeof(raw_buffer));
322 D("read_and_dump(): post adb_read(fd=%d): length=%d", fd, length);
323 if (length <= 0) {
324 break;
325 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800326 }
327
David Pursell606835a2015-09-08 17:17:02 -0700328 fwrite(buffer_ptr, 1, length, outfile);
329 fflush(outfile);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800330 }
David Pursell606835a2015-09-08 17:17:02 -0700331
332 return exit_code;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800333}
334
Jeff Sharkey960df972014-06-09 17:30:57 -0700335static void read_status_line(int fd, char* buf, size_t count)
336{
337 count--;
338 while (count > 0) {
339 int len = adb_read(fd, buf, count);
Elliott Hughes8fcd8bc2015-08-25 10:59:45 -0700340 if (len <= 0) {
Jeff Sharkey960df972014-06-09 17:30:57 -0700341 break;
342 }
343
344 buf += len;
345 count -= len;
346 }
347 *buf = '\0';
348}
349
Christopher Tated2f54152011-04-21 12:53:28 -0700350static void copy_to_file(int inFd, int outFd) {
Christopher Tate5b811fa2011-06-10 11:38:37 -0700351 const size_t BUFSIZE = 32 * 1024;
352 char* buf = (char*) malloc(BUFSIZE);
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700353 if (buf == nullptr) fatal("couldn't allocate buffer for copy_to_file");
Christopher Tated2f54152011-04-21 12:53:28 -0700354 int len;
Christopher Tatec9cd3b92011-06-01 17:56:23 -0700355 long total = 0;
Spencer Lowb7dfb792015-05-22 16:48:31 -0700356#ifdef _WIN32
357 int old_stdin_mode = -1;
358 int old_stdout_mode = -1;
359#endif
Christopher Tated2f54152011-04-21 12:53:28 -0700360
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700361 D("copy_to_file(%d -> %d)", inFd, outFd);
Yabin Cuid325e862014-11-17 14:48:25 -0800362
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700363 if (inFd == STDIN_FILENO) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800364 stdin_raw_init();
Spencer Lowb7dfb792015-05-22 16:48:31 -0700365#ifdef _WIN32
366 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY);
367 if (old_stdin_mode == -1) {
368 fatal_errno("could not set stdin to binary");
369 }
370#endif
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700371 }
Yabin Cuid325e862014-11-17 14:48:25 -0800372
Spencer Lowb7dfb792015-05-22 16:48:31 -0700373#ifdef _WIN32
374 if (outFd == STDOUT_FILENO) {
375 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY);
376 if (old_stdout_mode == -1) {
377 fatal_errno("could not set stdout to binary");
378 }
379 }
380#endif
381
Elliott Hughesa7090b92015-04-17 17:03:59 -0700382 while (true) {
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700383 if (inFd == STDIN_FILENO) {
384 len = unix_read(inFd, buf, BUFSIZE);
385 } else {
386 len = adb_read(inFd, buf, BUFSIZE);
387 }
Christopher Tated2f54152011-04-21 12:53:28 -0700388 if (len == 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700389 D("copy_to_file() : read 0 bytes; exiting");
Christopher Tated2f54152011-04-21 12:53:28 -0700390 break;
391 }
392 if (len < 0) {
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700393 D("copy_to_file(): read failed: %s", strerror(errno));
Christopher Tated2f54152011-04-21 12:53:28 -0700394 break;
395 }
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700396 if (outFd == STDOUT_FILENO) {
397 fwrite(buf, 1, len, stdout);
398 fflush(stdout);
399 } else {
400 adb_write(outFd, buf, len);
401 }
Christopher Tatec9cd3b92011-06-01 17:56:23 -0700402 total += len;
Christopher Tated2f54152011-04-21 12:53:28 -0700403 }
Yabin Cuid325e862014-11-17 14:48:25 -0800404
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700405 if (inFd == STDIN_FILENO) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800406 stdin_raw_restore();
Spencer Lowb7dfb792015-05-22 16:48:31 -0700407#ifdef _WIN32
408 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) {
409 fatal_errno("could not restore stdin mode");
410 }
411#endif
Jeff Sharkey5d9d4342014-05-26 18:30:43 -0700412 }
Yabin Cuid325e862014-11-17 14:48:25 -0800413
Spencer Lowb7dfb792015-05-22 16:48:31 -0700414#ifdef _WIN32
415 if (outFd == STDOUT_FILENO) {
416 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) {
417 fatal_errno("could not restore stdout mode");
418 }
419 }
420#endif
421
Yabin Cui7a3f8d62015-09-02 17:44:28 -0700422 D("copy_to_file() finished after %lu bytes", total);
Christopher Tate5b811fa2011-06-10 11:38:37 -0700423 free(buf);
Christopher Tated2f54152011-04-21 12:53:28 -0700424}
425
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800426static std::string format_host_command(const char* command,
427 TransportType type, const char* serial) {
428 if (serial) {
429 return android::base::StringPrintf("host-serial:%s:%s", serial, command);
430 }
431
432 const char* prefix = "host";
433 if (type == kTransportUsb) {
434 prefix = "host-usb";
435 } else if (type == kTransportLocal) {
436 prefix = "host-local";
437 }
438 return android::base::StringPrintf("%s:%s", prefix, command);
439}
440
441// Returns the FeatureSet for the indicated transport.
442static FeatureSet GetFeatureSet(TransportType transport_type, const char* serial) {
443 std::string result, error;
444 if (adb_query(format_host_command("features", transport_type, serial), &result, &error)) {
445 return StringToFeatureSet(result);
446 }
447 return FeatureSet();
448}
449
450static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
451#if !defined(_WIN32)
452 // Old devices can't handle window size changes.
453 if (shell == nullptr) return;
454
455 winsize ws;
456 if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
457
458 // Send the new window size as human-readable ASCII for debugging convenience.
459 size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
460 ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
461 shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
462#endif
463}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800464
David Pursell606835a2015-09-08 17:17:02 -0700465// Used to pass multiple values to the stdin read thread.
466struct StdinReadArgs {
467 int stdin_fd, write_fd;
David Pursell1ed57f02015-10-06 15:30:03 -0700468 bool raw_stdin;
David Pursell606835a2015-09-08 17:17:02 -0700469 std::unique_ptr<ShellProtocol> protocol;
470};
471
David Pursell606835a2015-09-08 17:17:02 -0700472// Loops to read from stdin and push the data to the given FD.
473// The argument should be a pointer to a StdinReadArgs object. This function
474// will take ownership of the object and delete it when finished.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800475static void* stdin_read_thread_loop(void* x) {
David Pursell606835a2015-09-08 17:17:02 -0700476 std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
477 int state = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800478
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800479#if !defined(_WIN32)
480 // Mask SIGTTIN in case we're in a backgrounded process.
Josh Gao8dcdb572015-10-23 15:03:31 -0700481 sigset_t sigset;
482 sigemptyset(&sigset);
483 sigaddset(&sigset, SIGTTIN);
484 pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
485#endif
486
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800487#if !defined(_WIN32)
488 // Unblock SIGWINCH for this thread, so our read(2) below will be
489 // interrupted if the window size changes.
490 sigset_t mask;
491 sigemptyset(&mask);
492 sigaddset(&mask, SIGWINCH);
493 pthread_sigmask(SIG_UNBLOCK, &mask, nullptr);
494#endif
495
496 // Set up the initial window size.
497 send_window_size_change(args->stdin_fd, args->protocol);
498
David Pursell606835a2015-09-08 17:17:02 -0700499 char raw_buffer[1024];
500 char* buffer_ptr = raw_buffer;
501 size_t buffer_size = sizeof(raw_buffer);
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800502 if (args->protocol != nullptr) {
David Pursell606835a2015-09-08 17:17:02 -0700503 buffer_ptr = args->protocol->data();
504 buffer_size = args->protocol->data_capacity();
505 }
506
Elliott Hughesaa245492015-08-03 10:38:08 -0700507 while (true) {
David Pursell606835a2015-09-08 17:17:02 -0700508 // Use unix_read() rather than adb_read() for stdin.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800509 D("stdin_read_thread_loop(): pre unix_read(fdi=%d,...)", args->stdin_fd);
510#if !defined(_WIN32)
511#undef read
512 int r = read(args->stdin_fd, buffer_ptr, buffer_size);
513 if (r == -1 && errno == EINTR) {
514 send_window_size_change(args->stdin_fd, args->protocol);
515 continue;
516 }
517#define read ___xxx_read
518#else
David Pursell606835a2015-09-08 17:17:02 -0700519 int r = unix_read(args->stdin_fd, buffer_ptr, buffer_size);
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800520#endif
521 D("stdin_read_thread_loop(): post unix_read(fdi=%d,...)", args->stdin_fd);
David Pursell1ed57f02015-10-06 15:30:03 -0700522 if (r <= 0) {
523 // Only devices using the shell protocol know to close subprocess
524 // stdin. For older devices we want to just leave the connection
525 // open, otherwise an unpredictable amount of return data could
526 // be lost due to the FD closing before all data has been received.
527 if (args->protocol) {
528 args->protocol->Write(ShellProtocol::kIdCloseStdin, 0);
529 }
530 break;
531 }
532 // If we made stdin raw, check input for the "~." escape sequence. In
533 // this situation signals like Ctrl+C are sent remotely rather than
534 // interpreted locally so this provides an emergency out if the remote
535 // process starts ignoring the signal. SSH also does this, see the
536 // "escape characters" section on the ssh man page for more info.
537 if (args->raw_stdin) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800538 for (int n = 0; n < r; n++) {
539 switch (buffer_ptr[n]) {
David Pursell1ed57f02015-10-06 15:30:03 -0700540 case '\n':
541 state = 1;
542 break;
543 case '\r':
544 state = 1;
545 break;
546 case '~':
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800547 if (state == 1) {
David Pursell08a27092015-10-20 14:19:36 -0700548 state++;
549 } else {
550 state = 0;
551 }
David Pursell1ed57f02015-10-06 15:30:03 -0700552 break;
553 case '.':
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800554 if (state == 2) {
555 fprintf(stderr,"\r\n* disconnect *\r\n");
556 stdin_raw_restore();
David Pursell1ed57f02015-10-06 15:30:03 -0700557 exit(0);
558 }
559 default:
560 state = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800561 }
562 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800563 }
David Pursell606835a2015-09-08 17:17:02 -0700564 if (args->protocol) {
565 if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) {
566 break;
567 }
568 } else {
569 if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) {
570 break;
571 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800572 }
573 }
David Pursell606835a2015-09-08 17:17:02 -0700574
575 return nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800576}
577
David Pursell1ed57f02015-10-06 15:30:03 -0700578// Returns a shell service string with the indicated arguments and command.
579static std::string ShellServiceString(bool use_shell_protocol,
580 const std::string& type_arg,
581 const std::string& command) {
582 std::vector<std::string> args;
583 if (use_shell_protocol) {
584 args.push_back(kShellServiceArgShellProtocol);
585 }
586 if (!type_arg.empty()) {
587 args.push_back(type_arg);
588 }
589
590 // Shell service string can look like: shell[,arg1,arg2,...]:[command].
591 return android::base::StringPrintf("shell%s%s:%s",
592 args.empty() ? "" : ",",
593 android::base::Join(args, ',').c_str(),
594 command.c_str());
595}
596
597// Connects to a shell on the device and read/writes data.
598//
599// Note: currently this function doesn't properly clean up resources; the
600// FD connected to the adb server is never closed and the stdin read thread
601// may never exit.
602//
603// On success returns the remote exit code if |use_shell_protocol| is true,
604// 0 otherwise. On failure returns 1.
605static int RemoteShell(bool use_shell_protocol, const std::string& type_arg,
606 const std::string& command) {
607 std::string service_string = ShellServiceString(use_shell_protocol,
608 type_arg, command);
609
610 // Make local stdin raw if the device allocates a PTY, which happens if:
611 // 1. We are explicitly asking for a PTY shell, or
612 // 2. We don't specify shell type and are starting an interactive session.
613 bool raw_stdin = (type_arg == kShellServiceArgPty ||
614 (type_arg.empty() && command.empty()));
615
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700616 std::string error;
David Pursell4e2fd362015-09-22 10:43:08 -0700617 int fd = adb_connect(service_string, &error);
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700618 if (fd < 0) {
619 fprintf(stderr,"error: %s\n", error.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800620 return 1;
621 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800622
David Pursell606835a2015-09-08 17:17:02 -0700623 StdinReadArgs* args = new StdinReadArgs;
624 if (!args) {
625 LOG(ERROR) << "couldn't allocate StdinReadArgs object";
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700626 return 1;
627 }
David Pursell1ed57f02015-10-06 15:30:03 -0700628 args->stdin_fd = STDIN_FILENO;
David Pursell606835a2015-09-08 17:17:02 -0700629 args->write_fd = fd;
David Pursell1ed57f02015-10-06 15:30:03 -0700630 args->raw_stdin = raw_stdin;
David Pursell606835a2015-09-08 17:17:02 -0700631 if (use_shell_protocol) {
632 args->protocol.reset(new ShellProtocol(args->write_fd));
633 }
Elliott Hughesdc3b4592015-04-21 19:39:52 -0700634
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800635 if (raw_stdin) stdin_raw_init();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800636
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800637#if !defined(_WIN32)
638 // Ensure our process is notified if the local window size changes.
639 // We use sigaction(2) to ensure that the SA_RESTART flag is not set,
640 // because the whole reason we're sending signals is to unblock the read(2)!
641 // That also means we don't need to do anything in the signal handler:
642 // the side effect of delivering the signal is all we need.
643 struct sigaction sa;
644 memset(&sa, 0, sizeof(sa));
645 sa.sa_handler = [](int) {};
646 sa.sa_flags = 0;
647 sigaction(SIGWINCH, &sa, nullptr);
648
649 // Now block SIGWINCH in this thread (the main thread) and all threads spawned
650 // from it. The stdin read thread will unblock this signal to ensure that it's
651 // the thread that receives the signal.
652 sigset_t mask;
653 sigemptyset(&mask);
654 sigaddset(&mask, SIGWINCH);
655 pthread_sigmask(SIG_BLOCK, &mask, nullptr);
656#endif
657
658 // TODO: combine read_and_dump with stdin_read_thread to make life simpler?
659 int exit_code = 1;
660 if (!adb_thread_create(stdin_read_thread_loop, args)) {
David Pursell606835a2015-09-08 17:17:02 -0700661 PLOG(ERROR) << "error starting stdin read thread";
David Pursell606835a2015-09-08 17:17:02 -0700662 delete args;
663 } else {
664 exit_code = read_and_dump(fd, use_shell_protocol);
665 }
Elliott Hughes9b0f3542015-05-05 13:41:21 -0700666
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800667 // TODO: properly exit stdin_read_thread_loop and close |fd|.
David Pursell1ed57f02015-10-06 15:30:03 -0700668
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800669 // TODO: we should probably install signal handlers for this.
670 // TODO: can we use atexit? even on Windows?
671 if (raw_stdin) stdin_raw_restore();
David Pursell1ed57f02015-10-06 15:30:03 -0700672
David Pursell606835a2015-09-08 17:17:02 -0700673 return exit_code;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800674}
675
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800676static int adb_shell(int argc, const char** argv,
677 TransportType transport_type, const char* serial) {
678 FeatureSet features = GetFeatureSet(transport_type, serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800679
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800680 bool use_shell_protocol = CanUseFeature(features, kFeatureShell2);
681 if (!use_shell_protocol) {
682 D("shell protocol not supported, using raw data transfer");
683 } else {
684 D("using shell protocol");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800685 }
Elliott Hughes6452a892015-04-29 12:28:13 -0700686
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800687 // Parse shell-specific command-line options.
688 // argv[0] is always "shell".
689 --argc;
690 ++argv;
691 int t_arg_count = 0;
692 while (argc) {
693 if (!strcmp(argv[0], "-T") || !strcmp(argv[0], "-t")) {
694 if (!CanUseFeature(features, kFeatureShell2)) {
695 fprintf(stderr, "error: target doesn't support PTY args -Tt\n");
696 return 1;
697 }
698 // Like ssh, -t arguments are cumulative so that multiple -t's
699 // are needed to force a PTY.
700 if (argv[0][1] == 't') {
701 ++t_arg_count;
702 } else {
703 t_arg_count = -1;
704 }
705 --argc;
706 ++argv;
707 } else if (!strcmp(argv[0], "-x")) {
708 use_shell_protocol = false;
709 --argc;
710 ++argv;
711 } else {
712 break;
713 }
Elliott Hughes6452a892015-04-29 12:28:13 -0700714 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800715
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800716 std::string shell_type_arg;
717 if (CanUseFeature(features, kFeatureShell2)) {
718 if (t_arg_count < 0) {
719 shell_type_arg = kShellServiceArgRaw;
720 } else if (t_arg_count == 0) {
721 // If stdin isn't a TTY, default to a raw shell; this lets
722 // things like `adb shell < my_script.sh` work as expected.
723 // Otherwise leave |shell_type_arg| blank which uses PTY for
724 // interactive shells and raw for non-interactive.
725 if (!unix_isatty(STDIN_FILENO)) {
726 shell_type_arg = kShellServiceArgRaw;
727 }
728 } else if (t_arg_count == 1) {
729 // A single -t arg isn't enough to override implicit -T.
730 if (!unix_isatty(STDIN_FILENO)) {
731 fprintf(stderr,
732 "Remote PTY will not be allocated because stdin is not a terminal.\n"
733 "Use multiple -t options to force remote PTY allocation.\n");
734 shell_type_arg = kShellServiceArgRaw;
735 } else {
736 shell_type_arg = kShellServiceArgPty;
737 }
738 } else {
739 shell_type_arg = kShellServiceArgPty;
740 }
David Pursell71c83122015-09-14 15:33:50 -0700741 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800742
743 std::string command;
744 if (argc) {
745 // We don't escape here, just like ssh(1). http://b/20564385.
746 command = android::base::Join(std::vector<const char*>(argv, argv + argc), ' ');
747 }
748
749 return RemoteShell(use_shell_protocol, shell_type_arg, command);
David Pursell71c83122015-09-14 15:33:50 -0700750}
751
Elliott Hughes6452a892015-04-29 12:28:13 -0700752static int adb_download_buffer(const char *service, const char *fn, const void* data, unsigned sz,
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700753 bool show_progress)
Doug Zongker447f0612012-01-09 14:54:53 -0800754{
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700755 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -0700756 int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error);
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700757 if (fd < 0) {
758 fprintf(stderr,"error: %s\n", error.c_str());
Doug Zongker447f0612012-01-09 14:54:53 -0800759 return -1;
760 }
761
762 int opt = CHUNK_SIZE;
Spencer Lowf055c192015-01-25 14:40:16 -0800763 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
Doug Zongker447f0612012-01-09 14:54:53 -0800764
Elliott Hughes6452a892015-04-29 12:28:13 -0700765 unsigned total = sz;
Dan Albertbac34742015-02-25 17:51:28 -0800766 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
Doug Zongker447f0612012-01-09 14:54:53 -0800767
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700768 if (show_progress) {
Elliott Hughes3e7048c2015-07-27 21:21:39 -0700769 const char* x = strrchr(service, ':');
770 if (x) service = x + 1;
Doug Zongker447f0612012-01-09 14:54:53 -0800771 }
772
Elliott Hughes6452a892015-04-29 12:28:13 -0700773 while (sz > 0) {
Doug Zongker447f0612012-01-09 14:54:53 -0800774 unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz;
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700775 if (!WriteFdExactly(fd, ptr, xfer)) {
776 std::string error;
777 adb_status(fd, &error);
778 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
Spencer Low351ecd12015-10-14 17:32:44 -0700779 adb_close(fd);
Doug Zongker447f0612012-01-09 14:54:53 -0800780 return -1;
781 }
782 sz -= xfer;
783 ptr += xfer;
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700784 if (show_progress) {
Magnus Eriksson86ae6d52013-03-05 07:37:32 +0100785 printf("sending: '%s' %4d%% \r", fn, (int)(100LL - ((100LL * sz) / (total))));
Doug Zongker447f0612012-01-09 14:54:53 -0800786 fflush(stdout);
787 }
788 }
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700789 if (show_progress) {
Doug Zongker447f0612012-01-09 14:54:53 -0800790 printf("\n");
791 }
792
Elliott Hughese67f1f82015-04-30 17:32:03 -0700793 if (!adb_status(fd, &error)) {
794 fprintf(stderr,"* error response '%s' *\n", error.c_str());
Spencer Low351ecd12015-10-14 17:32:44 -0700795 adb_close(fd);
Doug Zongker447f0612012-01-09 14:54:53 -0800796 return -1;
797 }
798
799 adb_close(fd);
800 return 0;
801}
802
Doug Zongker71fe5842014-06-26 15:35:36 -0700803#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE)
804
805/*
806 * The sideload-host protocol serves the data in a file (given on the
807 * command line) to the client, using a simple protocol:
808 *
809 * - The connect message includes the total number of bytes in the
810 * file and a block size chosen by us.
811 *
812 * - The other side sends the desired block number as eight decimal
813 * digits (eg "00000023" for block 23). Blocks are numbered from
814 * zero.
815 *
816 * - We send back the data of the requested block. The last block is
817 * likely to be partial; when the last block is requested we only
818 * send the part of the block that exists, it's not padded up to the
819 * block size.
820 *
821 * - When the other side sends "DONEDONE" instead of a block number,
822 * we hang up.
823 */
Elliott Hughes58305772015-04-17 13:57:15 -0700824static int adb_sideload_host(const char* fn) {
Doug Zongker71fe5842014-06-26 15:35:36 -0700825 unsigned sz;
826 size_t xfer = 0;
827 int status;
Dan Albertbac34742015-02-25 17:51:28 -0800828 int last_percent = -1;
829 int opt = SIDELOAD_HOST_BLOCK_SIZE;
Doug Zongker71fe5842014-06-26 15:35:36 -0700830
831 printf("loading: '%s'", fn);
832 fflush(stdout);
Dan Albertbac34742015-02-25 17:51:28 -0800833 uint8_t* data = reinterpret_cast<uint8_t*>(load_file(fn, &sz));
Doug Zongker71fe5842014-06-26 15:35:36 -0700834 if (data == 0) {
835 printf("\n");
836 fprintf(stderr, "* cannot read '%s' *\n", fn);
837 return -1;
838 }
839
Elliott Hughes6452a892015-04-29 12:28:13 -0700840 std::string service =
841 android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE);
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700842 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -0700843 int fd = adb_connect(service, &error);
Doug Zongker71fe5842014-06-26 15:35:36 -0700844 if (fd < 0) {
845 // Try falling back to the older sideload method. Maybe this
846 // is an older device that doesn't support sideload-host.
847 printf("\n");
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700848 status = adb_download_buffer("sideload", fn, data, sz, true);
Doug Zongker71fe5842014-06-26 15:35:36 -0700849 goto done;
850 }
851
Spencer Lowf055c192015-01-25 14:40:16 -0800852 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
Doug Zongker71fe5842014-06-26 15:35:36 -0700853
Elliott Hughesa7090b92015-04-17 17:03:59 -0700854 while (true) {
Elliott Hughes6452a892015-04-29 12:28:13 -0700855 char buf[9];
Dan Albertcc731cc2015-02-24 21:26:58 -0800856 if (!ReadFdExactly(fd, buf, 8)) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700857 fprintf(stderr, "* failed to read command: %s\n", strerror(errno));
Doug Zongker71fe5842014-06-26 15:35:36 -0700858 status = -1;
859 goto done;
860 }
Elliott Hughes6452a892015-04-29 12:28:13 -0700861 buf[8] = '\0';
Doug Zongker71fe5842014-06-26 15:35:36 -0700862
Elliott Hughes6452a892015-04-29 12:28:13 -0700863 if (strcmp("DONEDONE", buf) == 0) {
Doug Zongker71fe5842014-06-26 15:35:36 -0700864 status = 0;
865 break;
866 }
867
Doug Zongker71fe5842014-06-26 15:35:36 -0700868 int block = strtol(buf, NULL, 10);
869
870 size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
871 if (offset >= sz) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700872 fprintf(stderr, "* attempt to read block %d past end\n", block);
Doug Zongker71fe5842014-06-26 15:35:36 -0700873 status = -1;
874 goto done;
875 }
876 uint8_t* start = data + offset;
877 size_t offset_end = offset + SIDELOAD_HOST_BLOCK_SIZE;
878 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
879 if (offset_end > sz) {
880 to_write = sz - offset;
881 }
882
Dan Albertcc731cc2015-02-24 21:26:58 -0800883 if(!WriteFdExactly(fd, start, to_write)) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700884 adb_status(fd, &error);
885 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
Doug Zongker71fe5842014-06-26 15:35:36 -0700886 status = -1;
887 goto done;
888 }
889 xfer += to_write;
890
891 // For normal OTA packages, we expect to transfer every byte
892 // twice, plus a bit of overhead (one read during
893 // verification, one read of each byte for installation, plus
894 // extra access to things like the zip central directory).
895 // This estimate of the completion becomes 100% when we've
896 // transferred ~2.13 (=100/47) times the package size.
897 int percent = (int)(xfer * 47LL / (sz ? sz : 1));
898 if (percent != last_percent) {
899 printf("\rserving: '%s' (~%d%%) ", fn, percent);
900 fflush(stdout);
901 last_percent = percent;
902 }
903 }
904
Colin Cross6d6a8982014-07-07 14:12:41 -0700905 printf("\rTotal xfer: %.2fx%*s\n", (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, "");
Doug Zongker71fe5842014-06-26 15:35:36 -0700906
907 done:
908 if (fd >= 0) adb_close(fd);
909 free(data);
910 return status;
911}
912
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800913/**
914 * Run ppp in "notty" mode against a resource listed as the first parameter
915 * eg:
916 *
917 * ppp dev:/dev/omap_csmi_tty0 <ppp options>
918 *
919 */
Elliott Hughes58305772015-04-17 13:57:15 -0700920static int ppp(int argc, const char** argv) {
Yabin Cuie77b6a02014-11-11 09:24:11 -0800921#if defined(_WIN32)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800922 fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]);
923 return -1;
924#else
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800925 if (argc < 2) {
926 fprintf(stderr, "usage: adb %s <adb service name> [ppp opts]\n",
927 argv[0]);
928
929 return 1;
930 }
931
Dan Albertbac34742015-02-25 17:51:28 -0800932 const char* adb_service_name = argv[1];
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700933 std::string error;
934 int fd = adb_connect(adb_service_name, &error);
935 if (fd < 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800936 fprintf(stderr,"Error: Could not open adb service: %s. Error: %s\n",
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700937 adb_service_name, error.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800938 return 1;
939 }
940
Elliott Hughes078f0fc2015-04-29 08:35:59 -0700941 pid_t pid = fork();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800942
943 if (pid < 0) {
944 perror("from fork()");
945 return 1;
946 } else if (pid == 0) {
947 int err;
948 int i;
949 const char **ppp_args;
950
951 // copy args
952 ppp_args = (const char **) alloca(sizeof(char *) * argc + 1);
953 ppp_args[0] = "pppd";
954 for (i = 2 ; i < argc ; i++) {
955 //argv[2] and beyond become ppp_args[1] and beyond
956 ppp_args[i - 1] = argv[i];
957 }
958 ppp_args[i-1] = NULL;
959
960 // child side
961
962 dup2(fd, STDIN_FILENO);
963 dup2(fd, STDOUT_FILENO);
964 adb_close(STDERR_FILENO);
965 adb_close(fd);
966
967 err = execvp("pppd", (char * const *)ppp_args);
968
969 if (err < 0) {
970 perror("execing pppd");
971 }
972 exit(-1);
973 } else {
974 // parent side
975
976 adb_close(fd);
977 return 0;
978 }
Yabin Cuie77b6a02014-11-11 09:24:11 -0800979#endif /* !defined(_WIN32) */
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800980}
981
Elliott Hughes3bd73c12015-05-05 13:10:43 -0700982static bool wait_for_device(const char* service, TransportType t, const char* serial) {
Elliott Hughes2b101112015-05-04 19:29:32 -0700983 // Was the caller vague about what they'd like us to wait for?
984 // If so, check they weren't more specific in their choice of transport type.
985 if (strcmp(service, "wait-for-device") == 0) {
986 if (t == kTransportUsb) {
987 service = "wait-for-usb";
988 } else if (t == kTransportLocal) {
989 service = "wait-for-local";
990 } else {
991 service = "wait-for-any";
992 }
993 }
994
995 std::string cmd = format_host_command(service, t, serial);
Elliott Hughes424af022015-05-29 17:55:19 -0700996 return adb_command(cmd);
Elliott Hughes2b101112015-05-04 19:29:32 -0700997}
998
David Pursell70ef7b42015-09-30 13:35:42 -0700999// Connects to the device "shell" service with |command| and prints the
1000// resulting output.
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001001static int send_shell_command(TransportType transport_type, const char* serial,
David Pursell70ef7b42015-09-30 13:35:42 -07001002 const std::string& command,
1003 bool disable_shell_protocol) {
1004 // Only use shell protocol if it's supported and the caller doesn't want
1005 // to explicitly disable it.
1006 bool use_shell_protocol = false;
1007 if (!disable_shell_protocol) {
1008 FeatureSet features = GetFeatureSet(transport_type, serial);
1009 use_shell_protocol = CanUseFeature(features, kFeatureShell2);
1010 }
1011
1012 std::string service_string = ShellServiceString(use_shell_protocol, "",
1013 command);
1014
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001015 int fd;
1016 while (true) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001017 std::string error;
David Pursell70ef7b42015-09-30 13:35:42 -07001018 fd = adb_connect(service_string, &error);
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001019 if (fd >= 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001020 break;
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001021 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001022 fprintf(stderr,"- waiting for device -\n");
1023 adb_sleep_ms(1000);
Elliott Hughes2b101112015-05-04 19:29:32 -07001024 wait_for_device("wait-for-device", transport_type, serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001025 }
1026
David Pursell70ef7b42015-09-30 13:35:42 -07001027 int exit_code = read_and_dump(fd, use_shell_protocol);
David Pursell71c83122015-09-14 15:33:50 -07001028
1029 if (adb_close(fd) < 0) {
1030 PLOG(ERROR) << "failure closing FD " << fd;
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001031 }
David Pursell71c83122015-09-14 15:33:50 -07001032
1033 return exit_code;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001034}
1035
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001036static int logcat(TransportType transport, const char* serial, int argc, const char** argv) {
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001037 char* log_tags = getenv("ANDROID_LOG_TAGS");
1038 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001039
David Pursell70ef7b42015-09-30 13:35:42 -07001040 std::string cmd = "export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001041
Jeff Sharkeyfd546e82014-06-10 11:31:24 -07001042 if (!strcmp(argv[0], "longcat")) {
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001043 cmd += " -v long";
Christopher Tatedb0a8802011-11-30 13:00:33 -08001044 }
1045
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001046 --argc;
1047 ++argv;
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001048 while (argc-- > 0) {
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001049 cmd += " " + escape_arg(*argv++);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001050 }
1051
David Pursell70ef7b42015-09-30 13:35:42 -07001052 // No need for shell protocol with logcat, always disable for simplicity.
1053 return send_shell_command(transport, serial, cmd, true);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001054}
1055
Dan Albertbac34742015-02-25 17:51:28 -08001056static int backup(int argc, const char** argv) {
Elliott Hughes24f165f2015-08-21 20:31:31 -07001057 const char* filename = "backup.ab";
Christopher Tated2f54152011-04-21 12:53:28 -07001058
Christopher Tatec9cd3b92011-06-01 17:56:23 -07001059 /* find, extract, and use any -f argument */
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001060 for (int i = 1; i < argc; i++) {
Christopher Tatec9cd3b92011-06-01 17:56:23 -07001061 if (!strcmp("-f", argv[i])) {
1062 if (i == argc-1) {
1063 fprintf(stderr, "adb: -f passed with no filename\n");
1064 return usage();
1065 }
1066 filename = argv[i+1];
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001067 for (int j = i+2; j <= argc; ) {
Christopher Tatec9cd3b92011-06-01 17:56:23 -07001068 argv[i++] = argv[j++];
1069 }
1070 argc -= 2;
1071 argv[argc] = NULL;
1072 }
Christopher Tated2f54152011-04-21 12:53:28 -07001073 }
1074
Christopher Tatebb86bc52011-08-22 17:12:08 -07001075 /* bare "adb backup" or "adb backup -f filename" are not valid invocations */
1076 if (argc < 2) return usage();
1077
Christopher Tateb1dfffe2011-12-08 19:04:34 -08001078 adb_unlink(filename);
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001079 int outFd = adb_creat(filename, 0640);
Christopher Tated2f54152011-04-21 12:53:28 -07001080 if (outFd < 0) {
1081 fprintf(stderr, "adb: unable to open file %s\n", filename);
1082 return -1;
1083 }
1084
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001085 std::string cmd = "backup:";
1086 --argc;
1087 ++argv;
1088 while (argc-- > 0) {
1089 cmd += " " + escape_arg(*argv++);
Christopher Tated2f54152011-04-21 12:53:28 -07001090 }
1091
Yabin Cui7a3f8d62015-09-02 17:44:28 -07001092 D("backup. filename=%s cmd=%s", filename, cmd.c_str());
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001093 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07001094 int fd = adb_connect(cmd, &error);
Christopher Tated2f54152011-04-21 12:53:28 -07001095 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001096 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str());
Christopher Tated2f54152011-04-21 12:53:28 -07001097 adb_close(outFd);
1098 return -1;
1099 }
1100
Christopher Tatebffa4ca2012-01-06 15:43:03 -08001101 printf("Now unlock your device and confirm the backup operation.\n");
Christopher Tated2f54152011-04-21 12:53:28 -07001102 copy_to_file(fd, outFd);
1103
1104 adb_close(fd);
1105 adb_close(outFd);
1106 return 0;
1107}
1108
Dan Albertbac34742015-02-25 17:51:28 -08001109static int restore(int argc, const char** argv) {
Christopher Tate702967a2011-05-17 15:52:54 -07001110 if (argc != 2) return usage();
1111
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001112 const char* filename = argv[1];
1113 int tarFd = adb_open(filename, O_RDONLY);
Christopher Tate702967a2011-05-17 15:52:54 -07001114 if (tarFd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001115 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno));
Christopher Tate702967a2011-05-17 15:52:54 -07001116 return -1;
1117 }
1118
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001119 std::string error;
1120 int fd = adb_connect("restore:", &error);
Christopher Tate702967a2011-05-17 15:52:54 -07001121 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001122 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str());
Christopher Tate702967a2011-05-17 15:52:54 -07001123 adb_close(tarFd);
1124 return -1;
1125 }
1126
Christopher Tatebffa4ca2012-01-06 15:43:03 -08001127 printf("Now unlock your device and confirm the restore operation.\n");
Christopher Tate702967a2011-05-17 15:52:54 -07001128 copy_to_file(tarFd, fd);
1129
1130 adb_close(fd);
1131 adb_close(tarFd);
1132 return 0;
1133}
1134
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001135/* <hint> may be:
1136 * - A simple product name
1137 * e.g., "sooner"
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001138 * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir
1139 * e.g., "out/target/product/sooner"
1140 * - An absolute path to the PRODUCT_OUT dir
1141 * e.g., "/src/device/out/target/product/sooner"
1142 *
1143 * Given <hint>, try to construct an absolute path to the
1144 * ANDROID_PRODUCT_OUT dir.
1145 */
Elliott Hughes5c742702015-07-30 17:42:01 -07001146static std::string find_product_out_path(const std::string& hint) {
1147 if (hint.empty()) {
Elliott Hughes58305772015-04-17 13:57:15 -07001148 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001149 }
1150
Elliott Hughes58305772015-04-17 13:57:15 -07001151 // If it's already absolute, don't bother doing any work.
Elliott Hughes5c742702015-07-30 17:42:01 -07001152 if (adb_is_absolute_host_path(hint.c_str())) {
Elliott Hughes58305772015-04-17 13:57:15 -07001153 return hint;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001154 }
1155
Elliott Hughes58305772015-04-17 13:57:15 -07001156 // If there are any slashes in it, assume it's a relative path;
1157 // make it absolute.
Elliott Hughes5c742702015-07-30 17:42:01 -07001158 if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) {
Elliott Hughesa7090b92015-04-17 17:03:59 -07001159 std::string cwd;
1160 if (!getcwd(&cwd)) {
1161 fprintf(stderr, "adb: getcwd failed: %s\n", strerror(errno));
Elliott Hughes58305772015-04-17 13:57:15 -07001162 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001163 }
Elliott Hughes5c742702015-07-30 17:42:01 -07001164 return android::base::StringPrintf("%s%c%s", cwd.c_str(), OS_PATH_SEPARATOR, hint.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001165 }
1166
Elliott Hughes58305772015-04-17 13:57:15 -07001167 // It's a string without any slashes. Try to do something with it.
1168 //
1169 // Try to find the root of the build tree, and build a PRODUCT_OUT
1170 // path from there.
Elliott Hughesa7090b92015-04-17 17:03:59 -07001171 char* top = getenv("ANDROID_BUILD_TOP");
Elliott Hughes58305772015-04-17 13:57:15 -07001172 if (top == nullptr) {
Elliott Hughesa7090b92015-04-17 17:03:59 -07001173 fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n");
Elliott Hughes58305772015-04-17 13:57:15 -07001174 return "";
1175 }
Elliott Hughesa7090b92015-04-17 17:03:59 -07001176
1177 std::string path = top;
Elliott Hughes58305772015-04-17 13:57:15 -07001178 path += OS_PATH_SEPARATOR_STR;
1179 path += "out";
1180 path += OS_PATH_SEPARATOR_STR;
1181 path += "target";
1182 path += OS_PATH_SEPARATOR_STR;
1183 path += "product";
1184 path += OS_PATH_SEPARATOR_STR;
1185 path += hint;
1186 if (!directory_exists(path)) {
1187 fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; "
Elliott Hughes5c742702015-07-30 17:42:01 -07001188 "\"%s\" doesn't exist\n", hint.c_str(), path.c_str());
Elliott Hughesa7090b92015-04-17 17:03:59 -07001189 return "";
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001190 }
Elliott Hughes58305772015-04-17 13:57:15 -07001191 return path;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001192}
1193
Josh Gao05786772015-10-30 16:57:19 -07001194static void parse_push_pull_args(const char** arg, int narg,
1195 std::vector<const char*>* srcs,
1196 const char** dst, bool* copy_attrs) {
1197 *copy_attrs = false;
Mark Lindner76f2a932014-03-11 17:55:59 -07001198
Josh Gao05786772015-10-30 16:57:19 -07001199 srcs->clear();
1200 bool ignore_flags = false;
Lajos Molnarde8ff4a2013-04-19 12:41:09 -07001201 while (narg > 0) {
Josh Gao05786772015-10-30 16:57:19 -07001202 if (ignore_flags || *arg[0] != '-') {
1203 srcs->push_back(*arg);
Lajos Molnarde8ff4a2013-04-19 12:41:09 -07001204 } else {
Josh Gao05786772015-10-30 16:57:19 -07001205 if (!strcmp(*arg, "-p")) {
1206 // Silently ignore for backwards compatibility.
1207 } else if (!strcmp(*arg, "-a")) {
1208 *copy_attrs = true;
1209 } else if (!strcmp(*arg, "--")) {
1210 ignore_flags = true;
1211 } else {
1212 fprintf(stderr, "adb: unrecognized option '%s'\n", *arg);
1213 exit(1);
1214 }
Lajos Molnarde8ff4a2013-04-19 12:41:09 -07001215 }
Mark Lindner76f2a932014-03-11 17:55:59 -07001216 ++arg;
1217 --narg;
1218 }
1219
Josh Gao05786772015-10-30 16:57:19 -07001220 if (srcs->size() > 1) {
1221 *dst = srcs->back();
1222 srcs->pop_back();
Mark Lindner76f2a932014-03-11 17:55:59 -07001223 }
1224}
1225
Elliott Hughes6452a892015-04-29 12:28:13 -07001226static int adb_connect_command(const std::string& command) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001227 std::string error;
1228 int fd = adb_connect(command, &error);
Elliott Hughes5677c232015-05-07 23:37:40 -07001229 if (fd < 0) {
1230 fprintf(stderr, "error: %s\n", error.c_str());
1231 return 1;
Tao Bao175b7bb2015-03-29 11:22:34 -07001232 }
Elliott Hughes5677c232015-05-07 23:37:40 -07001233 read_and_dump(fd);
1234 adb_close(fd);
1235 return 0;
Tao Bao175b7bb2015-03-29 11:22:34 -07001236}
1237
Elliott Hughes6452a892015-04-29 12:28:13 -07001238static int adb_query_command(const std::string& command) {
1239 std::string result;
1240 std::string error;
1241 if (!adb_query(command, &result, &error)) {
1242 fprintf(stderr, "error: %s\n", error.c_str());
1243 return 1;
1244 }
1245 printf("%s\n", result.c_str());
1246 return 0;
1247}
1248
Spencer Lowa13df302015-09-07 16:20:13 -07001249// Disallow stdin, stdout, and stderr.
1250static bool _is_valid_ack_reply_fd(const int ack_reply_fd) {
1251#ifdef _WIN32
1252 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
1253 return (GetStdHandle(STD_INPUT_HANDLE) != ack_reply_handle) &&
1254 (GetStdHandle(STD_OUTPUT_HANDLE) != ack_reply_handle) &&
1255 (GetStdHandle(STD_ERROR_HANDLE) != ack_reply_handle);
1256#else
1257 return ack_reply_fd > 2;
1258#endif
1259}
1260
Elliott Hughesab52c182015-05-01 17:04:38 -07001261int adb_commandline(int argc, const char **argv) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001262 int no_daemon = 0;
1263 int is_daemon = 0;
David 'Digit' Turner305b4b02011-01-31 14:23:56 +01001264 int is_server = 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001265 int r;
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001266 TransportType transport_type = kTransportAny;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001267 int ack_reply_fd = -1;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001268
Elliott Hughes58305772015-04-17 13:57:15 -07001269 // If defined, this should be an absolute path to
1270 // the directory containing all of the various system images
1271 // for a particular product. If not defined, and the adb
1272 // command requires this information, then the user must
1273 // specify the path using "-p".
1274 char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT");
1275 if (ANDROID_PRODUCT_OUT != nullptr) {
1276 gProductOutPath = ANDROID_PRODUCT_OUT;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001277 }
1278 // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint
1279
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001280 /* Validate and assign the server port */
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001281 const char* server_port_str = getenv("ANDROID_ADB_SERVER_PORT");
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001282 int server_port = DEFAULT_ADB_PORT;
1283 if (server_port_str && strlen(server_port_str) > 0) {
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001284 server_port = strtol(server_port_str, nullptr, 0);
Matt Gumbeld7b33082012-11-14 10:16:17 -08001285 if (server_port <= 0 || server_port > 65535) {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001286 fprintf(stderr,
Spencer Lowf18fc082015-08-11 17:05:02 -07001287 "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive number less than 65536. Got \"%s\"\n",
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001288 server_port_str);
1289 return usage();
1290 }
1291 }
1292
Elliott Hughes8d28e192015-10-07 14:55:10 -07001293 // We need to check for -d and -e before we look at $ANDROID_SERIAL.
1294 const char* serial = nullptr;
1295
Riley Andrews98f58e82014-12-05 17:37:24 -08001296 while (argc > 0) {
1297 if (!strcmp(argv[0],"server")) {
David 'Digit' Turner305b4b02011-01-31 14:23:56 +01001298 is_server = 1;
Riley Andrews98f58e82014-12-05 17:37:24 -08001299 } else if (!strcmp(argv[0],"nodaemon")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001300 no_daemon = 1;
1301 } else if (!strcmp(argv[0], "fork-server")) {
1302 /* this is a special flag used only when the ADB client launches the ADB Server */
1303 is_daemon = 1;
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001304 } else if (!strcmp(argv[0], "--reply-fd")) {
1305 if (argc < 2) return usage();
1306 const char* reply_fd_str = argv[1];
1307 argc--;
1308 argv++;
1309 ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
Spencer Lowa13df302015-09-07 16:20:13 -07001310 if (!_is_valid_ack_reply_fd(ack_reply_fd)) {
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001311 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
1312 return usage();
1313 }
Riley Andrews98f58e82014-12-05 17:37:24 -08001314 } else if (!strncmp(argv[0], "-p", 2)) {
Elliott Hughes048b27c2015-07-31 13:18:22 -07001315 const char* product = nullptr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001316 if (argv[0][2] == '\0') {
1317 if (argc < 2) return usage();
1318 product = argv[1];
1319 argc--;
1320 argv++;
1321 } else {
Vairavan Srinivasan81273232012-08-04 16:40:50 -07001322 product = argv[0] + 2;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001323 }
Elliott Hughes048b27c2015-07-31 13:18:22 -07001324 gProductOutPath = find_product_out_path(product);
Elliott Hughes58305772015-04-17 13:57:15 -07001325 if (gProductOutPath.empty()) {
1326 fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001327 return usage();
1328 }
1329 } else if (argv[0][0]=='-' && argv[0][1]=='s') {
1330 if (isdigit(argv[0][2])) {
1331 serial = argv[0] + 2;
1332 } else {
Riley Andrews98f58e82014-12-05 17:37:24 -08001333 if (argc < 2 || argv[0][2] != '\0') return usage();
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001334 serial = argv[1];
1335 argc--;
1336 argv++;
1337 }
1338 } else if (!strcmp(argv[0],"-d")) {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001339 transport_type = kTransportUsb;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001340 } else if (!strcmp(argv[0],"-e")) {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001341 transport_type = kTransportLocal;
Matt Gumbeld7b33082012-11-14 10:16:17 -08001342 } else if (!strcmp(argv[0],"-a")) {
1343 gListenAll = 1;
Riley Andrews98f58e82014-12-05 17:37:24 -08001344 } else if (!strncmp(argv[0], "-H", 2)) {
Matt Gumbeld7b33082012-11-14 10:16:17 -08001345 const char *hostname = NULL;
1346 if (argv[0][2] == '\0') {
1347 if (argc < 2) return usage();
1348 hostname = argv[1];
1349 argc--;
1350 argv++;
1351 } else {
1352 hostname = argv[0] + 2;
1353 }
1354 adb_set_tcp_name(hostname);
1355
Riley Andrews98f58e82014-12-05 17:37:24 -08001356 } else if (!strncmp(argv[0], "-P", 2)) {
Matt Gumbeld7b33082012-11-14 10:16:17 -08001357 if (argv[0][2] == '\0') {
1358 if (argc < 2) return usage();
1359 server_port_str = argv[1];
1360 argc--;
1361 argv++;
1362 } else {
1363 server_port_str = argv[0] + 2;
1364 }
1365 if (strlen(server_port_str) > 0) {
1366 server_port = (int) strtol(server_port_str, NULL, 0);
1367 if (server_port <= 0 || server_port > 65535) {
1368 fprintf(stderr,
1369 "adb: port number must be a positive number less than 65536. Got \"%s\"\n",
1370 server_port_str);
1371 return usage();
1372 }
1373 } else {
1374 fprintf(stderr,
1375 "adb: port number must be a positive number less than 65536. Got empty string.\n");
1376 return usage();
1377 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001378 } else {
1379 /* out of recognized modifiers and flags */
1380 break;
1381 }
1382 argc--;
1383 argv++;
1384 }
1385
Elliott Hughes8d28e192015-10-07 14:55:10 -07001386 // If none of -d, -e, or -s were specified, try $ANDROID_SERIAL.
1387 if (transport_type == kTransportAny && serial == nullptr) {
1388 serial = getenv("ANDROID_SERIAL");
1389 }
1390
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001391 adb_set_transport(transport_type, serial);
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001392 adb_set_tcp_specifics(server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001393
David 'Digit' Turner305b4b02011-01-31 14:23:56 +01001394 if (is_server) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001395 if (no_daemon || is_daemon) {
Spencer Low5c398d22015-08-08 15:07:07 -07001396 if (is_daemon && (ack_reply_fd == -1)) {
Siva Velusamy9f2d1a92015-08-07 10:10:29 -07001397 fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
1398 return usage();
1399 }
1400 r = adb_main(is_daemon, server_port, ack_reply_fd);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001401 } else {
Stefan Hilzingera84a42e2010-04-19 12:21:12 +01001402 r = launch_server(server_port);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001403 }
Riley Andrews98f58e82014-12-05 17:37:24 -08001404 if (r) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001405 fprintf(stderr,"* could not start server *\n");
1406 }
1407 return r;
1408 }
1409
Riley Andrews98f58e82014-12-05 17:37:24 -08001410 if (argc == 0) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001411 return usage();
1412 }
1413
Riley Andrewsc8514c82014-12-05 17:32:46 -08001414 /* handle wait-for-* prefix */
1415 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) {
Dan Albertbac34742015-02-25 17:51:28 -08001416 const char* service = argv[0];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001417
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001418 if (!wait_for_device(service, transport_type, serial)) {
Riley Andrewsc8514c82014-12-05 17:32:46 -08001419 return 1;
1420 }
1421
Elliott Hughes2b101112015-05-04 19:29:32 -07001422 // Allow a command to be run after wait-for-device,
1423 // e.g. 'adb wait-for-device shell'.
Riley Andrewsc8514c82014-12-05 17:32:46 -08001424 if (argc == 1) {
1425 return 0;
1426 }
1427
1428 /* Fall through */
1429 argc--;
1430 argv++;
1431 }
1432
1433 /* adb_connect() commands */
Riley Andrews98f58e82014-12-05 17:37:24 -08001434 if (!strcmp(argv[0], "devices")) {
Dan Albertbac34742015-02-25 17:51:28 -08001435 const char *listopt;
Elliott Hughes6452a892015-04-29 12:28:13 -07001436 if (argc < 2) {
Scott Andersone109d262012-04-20 11:21:14 -07001437 listopt = "";
Elliott Hughes6452a892015-04-29 12:28:13 -07001438 } else if (argc == 2 && !strcmp(argv[1], "-l")) {
Scott Andersone109d262012-04-20 11:21:14 -07001439 listopt = argv[1];
Elliott Hughes6452a892015-04-29 12:28:13 -07001440 } else {
Scott Andersone109d262012-04-20 11:21:14 -07001441 fprintf(stderr, "Usage: adb devices [-l]\n");
1442 return 1;
1443 }
Elliott Hughes6452a892015-04-29 12:28:13 -07001444
1445 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt);
1446 printf("List of devices attached\n");
1447 return adb_query_command(query);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001448 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001449 else if (!strcmp(argv[0], "connect")) {
Mike Lockwoodff196702009-08-24 15:58:40 -07001450 if (argc != 2) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001451 fprintf(stderr, "Usage: adb connect <host>[:<port>]\n");
Mike Lockwoodff196702009-08-24 15:58:40 -07001452 return 1;
1453 }
Elliott Hughes6452a892015-04-29 12:28:13 -07001454
1455 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]);
1456 return adb_query_command(query);
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001457 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001458 else if (!strcmp(argv[0], "disconnect")) {
Mike Lockwoodcbbe79a2010-05-24 10:44:35 -04001459 if (argc > 2) {
1460 fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n");
1461 return 1;
1462 }
Elliott Hughes6452a892015-04-29 12:28:13 -07001463
1464 std::string query = android::base::StringPrintf("host:disconnect:%s",
1465 (argc == 2) ? argv[1] : "");
1466 return adb_query_command(query);
Mike Lockwoodff196702009-08-24 15:58:40 -07001467 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001468 else if (!strcmp(argv[0], "emu")) {
Spencer Low142ec752015-05-06 16:13:42 -07001469 return adb_send_emulator_command(argc, argv, serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001470 }
Elliott Hughesc15b17f2015-11-03 11:18:40 -08001471 else if (!strcmp(argv[0], "shell")) {
1472 return adb_shell(argc, argv, transport_type, serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001473 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001474 else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) {
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001475 int exec_in = !strcmp(argv[0], "exec-in");
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001476
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001477 std::string cmd = "exec:";
1478 cmd += argv[1];
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001479 argc -= 2;
1480 argv += 2;
1481 while (argc-- > 0) {
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001482 cmd += " " + escape_arg(*argv++);
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001483 }
1484
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001485 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07001486 int fd = adb_connect(cmd, &error);
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001487 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001488 fprintf(stderr, "error: %s\n", error.c_str());
Jeff Sharkey5d9d4342014-05-26 18:30:43 -07001489 return -1;
1490 }
1491
1492 if (exec_in) {
1493 copy_to_file(STDIN_FILENO, fd);
1494 } else {
1495 copy_to_file(fd, STDOUT_FILENO);
1496 }
1497
1498 adb_close(fd);
1499 return 0;
1500 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001501 else if (!strcmp(argv[0], "kill-server")) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001502 std::string error;
1503 int fd = _adb_connect("host:kill", &error);
Spencer Lowf18fc082015-08-11 17:05:02 -07001504 if (fd == -2) {
1505 // Failed to make network connection to server. Don't output the
1506 // network error since that is expected.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001507 fprintf(stderr,"* server not running *\n");
Spencer Lowf18fc082015-08-11 17:05:02 -07001508 // Successful exit code because the server is already "killed".
1509 return 0;
1510 } else if (fd == -1) {
1511 // Some other error.
1512 fprintf(stderr, "error: %s\n", error.c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001513 return 1;
Spencer Lowf18fc082015-08-11 17:05:02 -07001514 } else {
1515 // Successfully connected, kill command sent, okay status came back.
1516 // Server should exit() in a moment, if not already.
Spencer Low351ecd12015-10-14 17:32:44 -07001517 ReadOrderlyShutdown(fd);
Spencer Lowf18fc082015-08-11 17:05:02 -07001518 adb_close(fd);
1519 return 0;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001520 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001521 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001522 else if (!strcmp(argv[0], "sideload")) {
1523 if (argc != 2) return usage();
Doug Zongker71fe5842014-06-26 15:35:36 -07001524 if (adb_sideload_host(argv[1])) {
Doug Zongker447f0612012-01-09 14:54:53 -08001525 return 1;
1526 } else {
1527 return 0;
1528 }
1529 }
Elliott Hughes19d80b82015-07-21 16:13:40 -07001530 else if (!strcmp(argv[0], "tcpip") && argc > 1) {
1531 return adb_connect_command(android::base::StringPrintf("tcpip:%s", argv[1]));
1532 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001533 else if (!strcmp(argv[0], "remount") ||
1534 !strcmp(argv[0], "reboot") ||
1535 !strcmp(argv[0], "reboot-bootloader") ||
Riley Andrewsc8514c82014-12-05 17:32:46 -08001536 !strcmp(argv[0], "usb") ||
1537 !strcmp(argv[0], "root") ||
Dan Pasanen98858812014-10-06 12:57:20 -05001538 !strcmp(argv[0], "unroot") ||
Riley Andrewsc8514c82014-12-05 17:32:46 -08001539 !strcmp(argv[0], "disable-verity") ||
1540 !strcmp(argv[0], "enable-verity")) {
Elliott Hughes5677c232015-05-07 23:37:40 -07001541 std::string command;
Tao Bao175b7bb2015-03-29 11:22:34 -07001542 if (!strcmp(argv[0], "reboot-bootloader")) {
Elliott Hughes5677c232015-05-07 23:37:40 -07001543 command = "reboot:bootloader";
Tao Bao175b7bb2015-03-29 11:22:34 -07001544 } else if (argc > 1) {
Elliott Hughes5677c232015-05-07 23:37:40 -07001545 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]);
Tao Bao175b7bb2015-03-29 11:22:34 -07001546 } else {
Elliott Hughes5677c232015-05-07 23:37:40 -07001547 command = android::base::StringPrintf("%s:", argv[0]);
The Android Open Source Projecte037fd72009-03-13 13:04:37 -07001548 }
Tao Bao175b7bb2015-03-29 11:22:34 -07001549 return adb_connect_command(command);
The Android Open Source Projecte037fd72009-03-13 13:04:37 -07001550 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001551 else if (!strcmp(argv[0], "bugreport")) {
Dan Egnorc130ea72010-01-20 13:50:36 -08001552 if (argc != 1) return usage();
David Pursell70ef7b42015-09-30 13:35:42 -07001553 // No need for shell protocol with bugreport, always disable for
1554 // simplicity.
1555 return send_shell_command(transport_type, serial, "bugreport", true);
Mike Lockwoodf56d1b52009-09-03 14:54:58 -04001556 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001557 else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
Elliott Hughes424af022015-05-29 17:55:19 -07001558 bool reverse = !strcmp(argv[0], "reverse");
1559 ++argv;
1560 --argc;
1561 if (argc < 1) return usage();
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001562
1563 // Determine the <host-prefix> for this command.
Elliott Hughes424af022015-05-29 17:55:19 -07001564 std::string host_prefix;
David 'Digit' Turner25258692013-03-21 21:07:42 +01001565 if (reverse) {
Elliott Hughes424af022015-05-29 17:55:19 -07001566 host_prefix = "reverse";
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001567 } else {
David 'Digit' Turner25258692013-03-21 21:07:42 +01001568 if (serial) {
Elliott Hughes424af022015-05-29 17:55:19 -07001569 host_prefix = android::base::StringPrintf("host-serial:%s", serial);
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001570 } else if (transport_type == kTransportUsb) {
Elliott Hughes424af022015-05-29 17:55:19 -07001571 host_prefix = "host-usb";
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001572 } else if (transport_type == kTransportLocal) {
Elliott Hughes424af022015-05-29 17:55:19 -07001573 host_prefix = "host-local";
David 'Digit' Turner25258692013-03-21 21:07:42 +01001574 } else {
Elliott Hughes424af022015-05-29 17:55:19 -07001575 host_prefix = "host";
David 'Digit' Turner25258692013-03-21 21:07:42 +01001576 }
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001577 }
1578
Elliott Hughes424af022015-05-29 17:55:19 -07001579 std::string cmd;
1580 if (strcmp(argv[0], "--list") == 0) {
Elliott Hughesab52c182015-05-01 17:04:38 -07001581 if (argc != 1) return usage();
Elliott Hughes424af022015-05-29 17:55:19 -07001582 return adb_query_command(host_prefix + ":list-forward");
1583 } else if (strcmp(argv[0], "--remove-all") == 0) {
1584 if (argc != 1) return usage();
1585 cmd = host_prefix + ":killforward-all";
1586 } else if (strcmp(argv[0], "--remove") == 0) {
1587 // forward --remove <local>
Elliott Hughesab52c182015-05-01 17:04:38 -07001588 if (argc != 2) return usage();
Elliott Hughes424af022015-05-29 17:55:19 -07001589 cmd = host_prefix + ":killforward:" + argv[1];
1590 } else if (strcmp(argv[0], "--no-rebind") == 0) {
1591 // forward --no-rebind <local> <remote>
Elliott Hughesab52c182015-05-01 17:04:38 -07001592 if (argc != 3) return usage();
Elliott Hughes424af022015-05-29 17:55:19 -07001593 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2];
1594 } else {
1595 // forward <local> <remote>
1596 if (argc != 2) return usage();
1597 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
David 'Digit' Turner0d82fbf2012-11-14 15:01:55 +01001598 }
1599
Elliott Hughes424af022015-05-29 17:55:19 -07001600 return adb_command(cmd) ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001601 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001602 /* do_sync_*() commands */
Riley Andrewsc8514c82014-12-05 17:32:46 -08001603 else if (!strcmp(argv[0], "ls")) {
1604 if (argc != 2) return usage();
Elliott Hughesaa245492015-08-03 10:38:08 -07001605 return do_sync_ls(argv[1]) ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001606 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001607 else if (!strcmp(argv[0], "push")) {
Josh Gao05786772015-10-30 16:57:19 -07001608 bool copy_attrs = false;
1609 std::vector<const char*> srcs;
1610 const char* dst = nullptr;
Mark Lindner76f2a932014-03-11 17:55:59 -07001611
Josh Gao05786772015-10-30 16:57:19 -07001612 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
1613 if (srcs.empty() || !dst) return usage();
1614 return do_sync_push(srcs, dst) ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001615 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001616 else if (!strcmp(argv[0], "pull")) {
Josh Gao05786772015-10-30 16:57:19 -07001617 bool copy_attrs = false;
1618 std::vector<const char*> srcs;
1619 const char* dst = ".";
Mark Lindner76f2a932014-03-11 17:55:59 -07001620
Josh Gao05786772015-10-30 16:57:19 -07001621 parse_push_pull_args(&argv[1], argc - 1, &srcs, &dst, &copy_attrs);
1622 if (srcs.empty()) return usage();
1623 return do_sync_pull(srcs, dst, copy_attrs) ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001624 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001625 else if (!strcmp(argv[0], "install")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001626 if (argc < 2) return usage();
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001627 FeatureSet features = GetFeatureSet(transport_type, serial);
1628 if (CanUseFeature(features, kFeatureCmd)) {
1629 return install_app(transport_type, serial, argc, argv);
1630 }
1631 return install_app_legacy(transport_type, serial, argc, argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001632 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001633 else if (!strcmp(argv[0], "install-multiple")) {
Jeff Sharkey960df972014-06-09 17:30:57 -07001634 if (argc < 2) return usage();
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001635 return install_multiple_app(transport_type, serial, argc, argv);
Jeff Sharkey960df972014-06-09 17:30:57 -07001636 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001637 else if (!strcmp(argv[0], "uninstall")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001638 if (argc < 2) return usage();
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001639 FeatureSet features = GetFeatureSet(transport_type, serial);
1640 if (CanUseFeature(features, kFeatureCmd)) {
1641 return uninstall_app(transport_type, serial, argc, argv);
1642 }
1643 return uninstall_app_legacy(transport_type, serial, argc, argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001644 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001645 else if (!strcmp(argv[0], "sync")) {
Elliott Hughesd236d072015-04-21 10:17:07 -07001646 std::string src;
Elliott Hughes58305772015-04-17 13:57:15 -07001647 bool list_only = false;
Riley Andrews98f58e82014-12-05 17:37:24 -08001648 if (argc < 2) {
Elliott Hughes58305772015-04-17 13:57:15 -07001649 // No local path was specified.
Elliott Hughesd236d072015-04-21 10:17:07 -07001650 src = "";
Anthony Newnam705c9442010-02-22 08:36:49 -06001651 } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) {
Elliott Hughesd236d072015-04-21 10:17:07 -07001652 list_only = true;
Anthony Newnam705c9442010-02-22 08:36:49 -06001653 if (argc == 3) {
Elliott Hughesd236d072015-04-21 10:17:07 -07001654 src = argv[2];
Anthony Newnam705c9442010-02-22 08:36:49 -06001655 } else {
Elliott Hughesd236d072015-04-21 10:17:07 -07001656 src = "";
Anthony Newnam705c9442010-02-22 08:36:49 -06001657 }
Riley Andrews98f58e82014-12-05 17:37:24 -08001658 } else if (argc == 2) {
Elliott Hughes58305772015-04-17 13:57:15 -07001659 // A local path or "android"/"data" arg was specified.
Elliott Hughesd236d072015-04-21 10:17:07 -07001660 src = argv[1];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001661 } else {
1662 return usage();
1663 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001664
Elliott Hughesd236d072015-04-21 10:17:07 -07001665 if (src != "" &&
1666 src != "system" && src != "data" && src != "vendor" && src != "oem") {
Elliott Hughes58305772015-04-17 13:57:15 -07001667 return usage();
1668 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001669
Elliott Hughes58305772015-04-17 13:57:15 -07001670 std::string system_src_path = product_file("system");
1671 std::string data_src_path = product_file("data");
1672 std::string vendor_src_path = product_file("vendor");
1673 std::string oem_src_path = product_file("oem");
Elliott Hughes58305772015-04-17 13:57:15 -07001674
Elliott Hughesaa245492015-08-03 10:38:08 -07001675 bool okay = true;
1676 if (okay && (src.empty() || src == "system")) {
1677 okay = do_sync_sync(system_src_path, "/system", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001678 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001679 if (okay && (src.empty() || src == "vendor") && directory_exists(vendor_src_path)) {
1680 okay = do_sync_sync(vendor_src_path, "/vendor", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001681 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001682 if (okay && (src.empty() || src == "oem") && directory_exists(oem_src_path)) {
1683 okay = do_sync_sync(oem_src_path, "/oem", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001684 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001685 if (okay && (src.empty() || src == "data")) {
1686 okay = do_sync_sync(data_src_path, "/data", list_only);
Elliott Hughes58305772015-04-17 13:57:15 -07001687 }
Elliott Hughesaa245492015-08-03 10:38:08 -07001688 return okay ? 0 : 1;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001689 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001690 /* passthrough commands */
Riley Andrewsc8514c82014-12-05 17:32:46 -08001691 else if (!strcmp(argv[0],"get-state") ||
Scott Andersone109d262012-04-20 11:21:14 -07001692 !strcmp(argv[0],"get-serialno") ||
1693 !strcmp(argv[0],"get-devpath"))
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001694 {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001695 return adb_query_command(format_host_command(argv[0], transport_type, serial));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001696 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001697 /* other commands */
Riley Andrewsc8514c82014-12-05 17:32:46 -08001698 else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) {
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001699 return logcat(transport_type, serial, argc, argv);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001700 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001701 else if (!strcmp(argv[0],"ppp")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001702 return ppp(argc, argv);
1703 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001704 else if (!strcmp(argv[0], "start-server")) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001705 std::string error;
Spencer Lowf18fc082015-08-11 17:05:02 -07001706 const int result = adb_connect("host:start-server", &error);
1707 if (result < 0) {
1708 fprintf(stderr, "error: %s\n", error.c_str());
1709 }
1710 return result;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001711 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001712 else if (!strcmp(argv[0], "backup")) {
Christopher Tated2f54152011-04-21 12:53:28 -07001713 return backup(argc, argv);
1714 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001715 else if (!strcmp(argv[0], "restore")) {
Christopher Tate702967a2011-05-17 15:52:54 -07001716 return restore(argc, argv);
1717 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001718 else if (!strcmp(argv[0], "keygen")) {
Nick Kralevichbea3f9c2014-11-13 15:17:29 -08001719 if (argc < 2) return usage();
Yabin Cuiaed3c612015-09-22 15:52:57 -07001720 // Always print key generation information for keygen command.
1721 adb_trace_enable(AUTH);
Nick Kralevichbea3f9c2014-11-13 15:17:29 -08001722 return adb_auth_keygen(argv[1]);
1723 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001724 else if (!strcmp(argv[0], "jdwp")) {
Tao Bao175b7bb2015-03-29 11:22:34 -07001725 return adb_connect_command("jdwp");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001726 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001727 /* "adb /?" is a common idiom under Windows */
Riley Andrewsc8514c82014-12-05 17:32:46 -08001728 else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001729 help();
1730 return 0;
1731 }
Riley Andrewsc8514c82014-12-05 17:32:46 -08001732 else if (!strcmp(argv[0], "version")) {
Elliott Hughes42ae2602015-08-12 08:32:10 -07001733 fprintf(stdout, "%s", adb_version().c_str());
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001734 return 0;
1735 }
Dan Albert90d4b732015-05-20 18:58:41 -07001736 else if (!strcmp(argv[0], "features")) {
David Pursell4e2fd362015-09-22 10:43:08 -07001737 // Only list the features common to both the adb client and the device.
1738 FeatureSet features = GetFeatureSet(transport_type, serial);
1739 for (const std::string& name : features) {
David Pursell70ef7b42015-09-30 13:35:42 -07001740 if (CanUseFeature(features, name)) {
David Pursell4e2fd362015-09-22 10:43:08 -07001741 printf("%s\n", name.c_str());
1742 }
1743 }
1744 return 0;
Dan Albert90d4b732015-05-20 18:58:41 -07001745 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001746
1747 usage();
1748 return 1;
1749}
1750
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001751static int uninstall_app(TransportType transport, const char* serial, int argc, const char** argv) {
1752 // 'adb uninstall' takes the same arguments as 'cmd package uninstall' on device
1753 std::string cmd = "cmd package";
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001754 while (argc-- > 0) {
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001755 // deny the '-k' option until the remaining data/cache can be removed with adb/UI
1756 if (strcmp(*argv, "-k") == 0) {
1757 printf(
1758 "The -k option uninstalls the application while retaining the data/cache.\n"
1759 "At the moment, there is no way to remove the remaining data.\n"
1760 "You will have to reinstall the application with the same signature, and fully uninstall it.\n"
1761 "If you truly wish to continue, execute 'adb shell cmd package uninstall -k'.\n");
1762 return EXIT_FAILURE;
1763 }
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001764 cmd += " " + escape_arg(*argv++);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001765 }
1766
David Pursell70ef7b42015-09-30 13:35:42 -07001767 return send_shell_command(transport, serial, cmd, false);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001768}
1769
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001770static int install_app(TransportType transport, const char* serial, int argc, const char** argv) {
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001771 // The last argument must be the APK file
1772 const char* file = argv[argc - 1];
1773 const char* dot = strrchr(file, '.');
1774 bool found_apk = false;
Jeff Sharkey960df972014-06-09 17:30:57 -07001775 struct stat sb;
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001776 if (dot && !strcasecmp(dot, ".apk")) {
1777 if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
1778 fprintf(stderr, "Invalid APK file: %s\n", file);
1779 return EXIT_FAILURE;
Kenny Root597ea5b2011-08-05 11:19:45 -07001780 }
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001781 found_apk = true;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001782 }
1783
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001784 if (!found_apk) {
Jeff Sharkey960df972014-06-09 17:30:57 -07001785 fprintf(stderr, "Missing APK file\n");
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001786 return EXIT_FAILURE;
Kenny Root597ea5b2011-08-05 11:19:45 -07001787 }
1788
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001789 int localFd = adb_open(file, O_RDONLY);
1790 if (localFd < 0) {
1791 fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno));
1792 return 1;
1793 }
Kenny Root597ea5b2011-08-05 11:19:45 -07001794
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001795 std::string error;
1796 std::string cmd = "exec:cmd package";
1797
1798 // don't copy the APK name, but, copy the rest of the arguments as-is
1799 while (argc-- > 1) {
1800 cmd += " " + escape_arg(std::string(*argv++));
1801 }
1802
1803 // add size parameter [required for streaming installs]
1804 // do last to override any user specified value
1805 cmd += " " + android::base::StringPrintf("-S %" PRIu64, static_cast<uint64_t>(sb.st_size));
1806
1807 int remoteFd = adb_connect(cmd, &error);
1808 if (remoteFd < 0) {
1809 fprintf(stderr, "Connect error for write: %s\n", error.c_str());
1810 adb_close(localFd);
1811 return 1;
1812 }
1813
1814 char buf[BUFSIZ];
1815 copy_to_file(localFd, remoteFd);
1816 read_status_line(remoteFd, buf, sizeof(buf));
1817
1818 adb_close(localFd);
1819 adb_close(remoteFd);
1820
1821 if (strncmp("Success", buf, 7)) {
1822 fprintf(stderr, "Failed to write %s\n", file);
1823 fputs(buf, stderr);
1824 return 1;
1825 }
1826 fputs(buf, stderr);
1827 return 0;
Jeff Sharkey960df972014-06-09 17:30:57 -07001828}
1829
Elliott Hughes3bd73c12015-05-05 13:10:43 -07001830static int install_multiple_app(TransportType transport, const char* serial, int argc,
Elliott Hughes58305772015-04-17 13:57:15 -07001831 const char** argv)
Jeff Sharkey960df972014-06-09 17:30:57 -07001832{
Jeff Sharkey960df972014-06-09 17:30:57 -07001833 int i;
1834 struct stat sb;
Elliott Hughes2940ccf2015-04-17 14:07:52 -07001835 uint64_t total_size = 0;
Jeff Sharkey960df972014-06-09 17:30:57 -07001836
1837 // Find all APK arguments starting at end.
1838 // All other arguments passed through verbatim.
1839 int first_apk = -1;
1840 for (i = argc - 1; i >= 0; i--) {
Dan Albertbac34742015-02-25 17:51:28 -08001841 const char* file = argv[i];
Elliott Hughes3e7048c2015-07-27 21:21:39 -07001842 const char* dot = strrchr(file, '.');
Jeff Sharkey960df972014-06-09 17:30:57 -07001843 if (dot && !strcasecmp(dot, ".apk")) {
1844 if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
1845 fprintf(stderr, "Invalid APK file: %s\n", file);
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001846 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07001847 }
1848
1849 total_size += sb.st_size;
1850 first_apk = i;
1851 } else {
1852 break;
1853 }
Kenny Root597ea5b2011-08-05 11:19:45 -07001854 }
1855
Jeff Sharkey960df972014-06-09 17:30:57 -07001856 if (first_apk == -1) {
1857 fprintf(stderr, "Missing APK file\n");
1858 return 1;
1859 }
Kenny Root597ea5b2011-08-05 11:19:45 -07001860
Elliott Hughes2940ccf2015-04-17 14:07:52 -07001861 std::string cmd = android::base::StringPrintf("exec:pm install-create -S %" PRIu64, total_size);
Jeff Sharkey960df972014-06-09 17:30:57 -07001862 for (i = 1; i < first_apk; i++) {
Elliott Hughes6c34bba2015-04-17 20:11:08 -07001863 cmd += " " + escape_arg(argv[i]);
Jeff Sharkey960df972014-06-09 17:30:57 -07001864 }
1865
1866 // Create install session
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001867 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07001868 int fd = adb_connect(cmd, &error);
Jeff Sharkey960df972014-06-09 17:30:57 -07001869 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001870 fprintf(stderr, "Connect error for create: %s\n", error.c_str());
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001871 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07001872 }
Elliott Hughes2baae3a2015-04-17 10:59:34 -07001873 char buf[BUFSIZ];
Jeff Sharkey960df972014-06-09 17:30:57 -07001874 read_status_line(fd, buf, sizeof(buf));
1875 adb_close(fd);
1876
1877 int session_id = -1;
1878 if (!strncmp("Success", buf, 7)) {
1879 char* start = strrchr(buf, '[');
1880 char* end = strrchr(buf, ']');
1881 if (start && end) {
1882 *end = '\0';
1883 session_id = strtol(start + 1, NULL, 10);
1884 }
1885 }
1886 if (session_id < 0) {
1887 fprintf(stderr, "Failed to create session\n");
Christopher Tate71bbc672014-07-14 16:45:13 -07001888 fputs(buf, stderr);
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001889 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07001890 }
1891
1892 // Valid session, now stream the APKs
1893 int success = 1;
1894 for (i = first_apk; i < argc; i++) {
Dan Albertbac34742015-02-25 17:51:28 -08001895 const char* file = argv[i];
Jeff Sharkey960df972014-06-09 17:30:57 -07001896 if (stat(file, &sb) == -1) {
1897 fprintf(stderr, "Failed to stat %s\n", file);
1898 success = 0;
1899 goto finalize_session;
1900 }
1901
Elliott Hughes2940ccf2015-04-17 14:07:52 -07001902 std::string cmd = android::base::StringPrintf(
1903 "exec:pm install-write -S %" PRIu64 " %d %d_%s -",
Elliott Hughes5c742702015-07-30 17:42:01 -07001904 static_cast<uint64_t>(sb.st_size), session_id, i, adb_basename(file).c_str());
Jeff Sharkey960df972014-06-09 17:30:57 -07001905
1906 int localFd = adb_open(file, O_RDONLY);
1907 if (localFd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001908 fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno));
Jeff Sharkey960df972014-06-09 17:30:57 -07001909 success = 0;
1910 goto finalize_session;
1911 }
1912
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001913 std::string error;
Elliott Hughes6452a892015-04-29 12:28:13 -07001914 int remoteFd = adb_connect(cmd, &error);
Jeff Sharkey960df972014-06-09 17:30:57 -07001915 if (remoteFd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001916 fprintf(stderr, "Connect error for write: %s\n", error.c_str());
Jeff Sharkey960df972014-06-09 17:30:57 -07001917 adb_close(localFd);
1918 success = 0;
1919 goto finalize_session;
1920 }
1921
1922 copy_to_file(localFd, remoteFd);
1923 read_status_line(remoteFd, buf, sizeof(buf));
1924
1925 adb_close(localFd);
1926 adb_close(remoteFd);
1927
1928 if (strncmp("Success", buf, 7)) {
1929 fprintf(stderr, "Failed to write %s\n", file);
Christopher Tate71bbc672014-07-14 16:45:13 -07001930 fputs(buf, stderr);
Jeff Sharkey960df972014-06-09 17:30:57 -07001931 success = 0;
1932 goto finalize_session;
1933 }
1934 }
1935
1936finalize_session:
Jeff Sharkeyac77e1f2014-07-25 09:58:25 -07001937 // Commit session if we streamed everything okay; otherwise abandon
Elliott Hughes6452a892015-04-29 12:28:13 -07001938 std::string service =
1939 android::base::StringPrintf("exec:pm install-%s %d",
1940 success ? "commit" : "abandon", session_id);
1941 fd = adb_connect(service, &error);
Jeff Sharkey960df972014-06-09 17:30:57 -07001942 if (fd < 0) {
Elliott Hughes078f0fc2015-04-29 08:35:59 -07001943 fprintf(stderr, "Connect error for finalize: %s\n", error.c_str());
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001944 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07001945 }
1946 read_status_line(fd, buf, sizeof(buf));
1947 adb_close(fd);
1948
1949 if (!strncmp("Success", buf, 7)) {
Christopher Tate71bbc672014-07-14 16:45:13 -07001950 fputs(buf, stderr);
Jeff Sharkey960df972014-06-09 17:30:57 -07001951 return 0;
1952 } else {
1953 fprintf(stderr, "Failed to finalize session\n");
Christopher Tate71bbc672014-07-14 16:45:13 -07001954 fputs(buf, stderr);
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001955 return EXIT_FAILURE;
Jeff Sharkey960df972014-06-09 17:30:57 -07001956 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001957}
Todd Kennedy6fa848a2015-11-03 16:53:08 -08001958
1959static int pm_command(TransportType transport, const char* serial, int argc, const char** argv) {
1960 std::string cmd = "pm";
1961
1962 while (argc-- > 0) {
1963 cmd += " " + escape_arg(*argv++);
1964 }
1965
1966 return send_shell_command(transport, serial, cmd, false);
1967}
1968
1969static int uninstall_app_legacy(TransportType transport, const char* serial, int argc, const char** argv) {
1970 /* if the user choose the -k option, we refuse to do it until devices are
1971 out with the option to uninstall the remaining data somehow (adb/ui) */
1972 int i;
1973 for (i = 1; i < argc; i++) {
1974 if (!strcmp(argv[i], "-k")) {
1975 printf(
1976 "The -k option uninstalls the application while retaining the data/cache.\n"
1977 "At the moment, there is no way to remove the remaining data.\n"
1978 "You will have to reinstall the application with the same signature, and fully uninstall it.\n"
1979 "If you truly wish to continue, execute 'adb shell pm uninstall -k'\n.");
1980 return EXIT_FAILURE;
1981 }
1982 }
1983
1984 /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */
1985 return pm_command(transport, serial, argc, argv);
1986}
1987
1988static int delete_file(TransportType transport, const char* serial, const std::string& filename) {
1989 std::string cmd = "rm -f " + escape_arg(filename);
1990 return send_shell_command(transport, serial, cmd, false);
1991}
1992
1993static int install_app_legacy(TransportType transport, const char* serial, int argc, const char** argv) {
1994 static const char *const DATA_DEST = "/data/local/tmp/%s";
1995 static const char *const SD_DEST = "/sdcard/tmp/%s";
1996 const char* where = DATA_DEST;
1997 int i;
1998 struct stat sb;
1999
2000 for (i = 1; i < argc; i++) {
2001 if (!strcmp(argv[i], "-s")) {
2002 where = SD_DEST;
2003 }
2004 }
2005
2006 // Find last APK argument.
2007 // All other arguments passed through verbatim.
2008 int last_apk = -1;
2009 for (i = argc - 1; i >= 0; i--) {
2010 const char* file = argv[i];
2011 const char* dot = strrchr(file, '.');
2012 if (dot && !strcasecmp(dot, ".apk")) {
2013 if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) {
2014 fprintf(stderr, "Invalid APK file: %s\n", file);
2015 return EXIT_FAILURE;
2016 }
2017
2018 last_apk = i;
2019 break;
2020 }
2021 }
2022
2023 if (last_apk == -1) {
2024 fprintf(stderr, "Missing APK file\n");
2025 return EXIT_FAILURE;
2026 }
2027
2028 int result = -1;
2029 std::vector<const char*> apk_file = {argv[last_apk]};
2030 std::string apk_dest = android::base::StringPrintf(
2031 where, adb_basename(argv[last_apk]).c_str());
2032 if (!do_sync_push(apk_file, apk_dest.c_str())) goto cleanup_apk;
2033 argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */
2034 result = pm_command(transport, serial, argc, argv);
2035
2036cleanup_apk:
2037 delete_file(transport, serial, apk_dest);
2038 return result;
2039}