commandline.cpp revision 42ae2604f43ef88be748f125e8733f2c08b83fae
1/* 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 17#define TRACE_TAG TRACE_ADB 18 19#include "sysdeps.h" 20 21#include <assert.h> 22#include <ctype.h> 23#include <errno.h> 24#include <inttypes.h> 25#include <limits.h> 26#include <stdarg.h> 27#include <stdint.h> 28#include <stdio.h> 29#include <stdlib.h> 30#include <string.h> 31#include <sys/stat.h> 32#include <sys/types.h> 33 34#include <string> 35 36#include <base/stringprintf.h> 37 38#if !defined(_WIN32) 39#include <termios.h> 40#include <unistd.h> 41#endif 42 43#include "adb.h" 44#include "adb_auth.h" 45#include "adb_client.h" 46#include "adb_io.h" 47#include "adb_utils.h" 48#include "file_sync_service.h" 49 50static int install_app(TransportType t, const char* serial, int argc, const char** argv); 51static int install_multiple_app(TransportType t, const char* serial, int argc, const char** argv); 52static int uninstall_app(TransportType t, const char* serial, int argc, const char** argv); 53 54static std::string gProductOutPath; 55extern int gListenAll; 56 57static std::string product_file(const char *extra) { 58 if (gProductOutPath.empty()) { 59 fprintf(stderr, "adb: Product directory not specified; " 60 "use -p or define ANDROID_PRODUCT_OUT\n"); 61 exit(1); 62 } 63 64 return android::base::StringPrintf("%s%s%s", 65 gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra); 66} 67 68static void help() { 69 fprintf(stderr, "%s\n", adb_version().c_str()); 70 fprintf(stderr, 71 " -a - directs adb to listen on all interfaces for a connection\n" 72 " -d - directs command to the only connected USB device\n" 73 " returns an error if more than one USB device is present.\n" 74 " -e - directs command to the only running emulator.\n" 75 " returns an error if more than one emulator is running.\n" 76 " -s <specific device> - directs command to the device or emulator with the given\n" 77 " serial number or qualifier. Overrides ANDROID_SERIAL\n" 78 " environment variable.\n" 79 " -p <product name or path> - simple product name like 'sooner', or\n" 80 " a relative/absolute path to a product\n" 81 " out directory like 'out/target/product/sooner'.\n" 82 " If -p is not specified, the ANDROID_PRODUCT_OUT\n" 83 " environment variable is used, which must\n" 84 " be an absolute path.\n" 85 " -H - Name of adb server host (default: localhost)\n" 86 " -P - Port of adb server (default: 5037)\n" 87 " devices [-l] - list all connected devices\n" 88 " ('-l' will also list device qualifiers)\n" 89 " connect <host>[:<port>] - connect to a device via TCP/IP\n" 90 " Port 5555 is used by default if no port number is specified.\n" 91 " disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.\n" 92 " Port 5555 is used by default if no port number is specified.\n" 93 " Using this command with no additional arguments\n" 94 " will disconnect from all connected TCP/IP devices.\n" 95 "\n" 96 "device commands:\n" 97 " adb push [-p] <local> <remote>\n" 98 " - copy file/dir to device\n" 99 " ('-p' to display the transfer progress)\n" 100 " adb pull [-p] [-a] <remote> [<local>]\n" 101 " - copy file/dir from device\n" 102 " ('-p' to display the transfer progress)\n" 103 " ('-a' means copy timestamp and mode)\n" 104 " adb sync [ <directory> ] - copy host->device only if changed\n" 105 " (-l means list but don't copy)\n" 106 " adb shell - run remote shell interactively\n" 107 " adb shell <command> - run remote shell command\n" 108 " adb emu <command> - run emulator console command\n" 109 " adb logcat [ <filter-spec> ] - View device log\n" 110 " adb forward --list - list all forward socket connections.\n" 111 " the format is a list of lines with the following format:\n" 112 " <serial> \" \" <local> \" \" <remote> \"\\n\"\n" 113 " adb forward <local> <remote> - forward socket connections\n" 114 " forward specs are one of: \n" 115 " tcp:<port>\n" 116 " localabstract:<unix domain socket name>\n" 117 " localreserved:<unix domain socket name>\n" 118 " localfilesystem:<unix domain socket name>\n" 119 " dev:<character device name>\n" 120 " jdwp:<process pid> (remote only)\n" 121 " adb forward --no-rebind <local> <remote>\n" 122 " - same as 'adb forward <local> <remote>' but fails\n" 123 " if <local> is already forwarded\n" 124 " adb forward --remove <local> - remove a specific forward socket connection\n" 125 " adb forward --remove-all - remove all forward socket connections\n" 126 " adb reverse --list - list all reverse socket connections from device\n" 127 " adb reverse <remote> <local> - reverse socket connections\n" 128 " reverse specs are one of:\n" 129 " tcp:<port>\n" 130 " localabstract:<unix domain socket name>\n" 131 " localreserved:<unix domain socket name>\n" 132 " localfilesystem:<unix domain socket name>\n" 133 " adb reverse --norebind <remote> <local>\n" 134 " - same as 'adb reverse <remote> <local>' but fails\n" 135 " if <remote> is already reversed.\n" 136 " adb reverse --remove <remote>\n" 137 " - remove a specific reversed socket connection\n" 138 " adb reverse --remove-all - remove all reversed socket connections from device\n" 139 " adb jdwp - list PIDs of processes hosting a JDWP transport\n" 140 " adb install [-lrtsd] <file>\n" 141 " adb install-multiple [-lrtsdp] <file...>\n" 142 " - push this package file to the device and install it\n" 143 " (-l: forward lock application)\n" 144 " (-r: replace existing application)\n" 145 " (-t: allow test packages)\n" 146 " (-s: install application on sdcard)\n" 147 " (-d: allow version code downgrade)\n" 148 " (-p: partial application install)\n" 149 " adb uninstall [-k] <package> - remove this app package from the device\n" 150 " ('-k' means keep the data and cache directories)\n" 151 " adb bugreport - return all information from the device\n" 152 " that should be included in a bug report.\n" 153 "\n" 154 " adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]\n" 155 " - write an archive of the device's data to <file>.\n" 156 " If no -f option is supplied then the data is written\n" 157 " to \"backup.ab\" in the current directory.\n" 158 " (-apk|-noapk enable/disable backup of the .apks themselves\n" 159 " in the archive; the default is noapk.)\n" 160 " (-obb|-noobb enable/disable backup of any installed apk expansion\n" 161 " (aka .obb) files associated with each application; the default\n" 162 " is noobb.)\n" 163 " (-shared|-noshared enable/disable backup of the device's\n" 164 " shared storage / SD card contents; the default is noshared.)\n" 165 " (-all means to back up all installed applications)\n" 166 " (-system|-nosystem toggles whether -all automatically includes\n" 167 " system applications; the default is to include system apps)\n" 168 " (<packages...> is the list of applications to be backed up. If\n" 169 " the -all or -shared flags are passed, then the package\n" 170 " list is optional. Applications explicitly given on the\n" 171 " command line will be included even if -nosystem would\n" 172 " ordinarily cause them to be omitted.)\n" 173 "\n" 174 " adb restore <file> - restore device contents from the <file> backup archive\n" 175 "\n" 176 " adb disable-verity - disable dm-verity checking on USERDEBUG builds\n" 177 " adb enable-verity - re-enable dm-verity checking on USERDEBUG builds\n" 178 " adb keygen <file> - generate adb public/private key. The private key is stored in <file>,\n" 179 " and the public key is stored in <file>.pub. Any existing files\n" 180 " are overwritten.\n" 181 " adb help - show this help message\n" 182 " adb version - show version num\n" 183 "\n" 184 "scripting:\n" 185 " adb wait-for-device - block until device is online\n" 186 " adb start-server - ensure that there is a server running\n" 187 " adb kill-server - kill the server if it is running\n" 188 " adb get-state - prints: offline | bootloader | device\n" 189 " adb get-serialno - prints: <serial-number>\n" 190 " adb get-devpath - prints: <device-path>\n" 191 " adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write\n" 192 " adb reboot [bootloader|recovery]\n" 193 " - reboots the device, optionally into the bootloader or recovery program.\n" 194 " adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).\n" 195 " adb reboot sideload-auto-reboot\n" 196 " - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.\n" 197 " adb sideload <file> - sideloads the given package\n" 198 " adb root - restarts the adbd daemon with root permissions\n" 199 " adb unroot - restarts the adbd daemon without root permissions\n" 200 " adb usb - restarts the adbd daemon listening on USB\n" 201 " adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port\n" 202 "\n" 203 "networking:\n" 204 " adb ppp <tty> [parameters] - Run PPP over USB.\n" 205 " Note: you should not automatically start a PPP connection.\n" 206 " <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1\n" 207 " [parameters] - Eg. defaultroute debug dump local notty usepeerdns\n" 208 "\n" 209 "adb sync notes: adb sync [ <directory> ]\n" 210 " <localdir> can be interpreted in several ways:\n" 211 "\n" 212 " - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.\n" 213 "\n" 214 " - If it is \"system\", \"vendor\", \"oem\" or \"data\", only the corresponding partition\n" 215 " is updated.\n" 216 "\n" 217 "environment variables:\n" 218 " ADB_TRACE - Print debug information. A comma separated list of the following values\n" 219 " 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp\n" 220 " ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.\n" 221 " ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.\n" 222 ); 223} 224 225static int usage() { 226 help(); 227 return 1; 228} 229 230#if defined(_WIN32) 231 232// Implemented in sysdeps_win32.cpp. 233void stdin_raw_init(int fd); 234void stdin_raw_restore(int fd); 235 236#else 237static termios g_saved_terminal_state; 238 239static void stdin_raw_init(int fd) { 240 if (tcgetattr(fd, &g_saved_terminal_state)) return; 241 242 termios tio; 243 if (tcgetattr(fd, &tio)) return; 244 245 cfmakeraw(&tio); 246 247 // No timeout but request at least one character per read. 248 tio.c_cc[VTIME] = 0; 249 tio.c_cc[VMIN] = 1; 250 251 tcsetattr(fd, TCSAFLUSH, &tio); 252} 253 254static void stdin_raw_restore(int fd) { 255 tcsetattr(fd, TCSAFLUSH, &g_saved_terminal_state); 256} 257#endif 258 259static void read_and_dump(int fd) { 260 while (fd >= 0) { 261 D("read_and_dump(): pre adb_read(fd=%d)\n", fd); 262 char buf[BUFSIZ]; 263 int len = adb_read(fd, buf, sizeof(buf)); 264 D("read_and_dump(): post adb_read(fd=%d): len=%d\n", fd, len); 265 if (len <= 0) { 266 break; 267 } 268 269 fwrite(buf, 1, len, stdout); 270 fflush(stdout); 271 } 272} 273 274static void read_status_line(int fd, char* buf, size_t count) 275{ 276 count--; 277 while (count > 0) { 278 int len = adb_read(fd, buf, count); 279 if (len == 0) { 280 break; 281 } else if (len < 0) { 282 if (errno == EINTR) continue; 283 break; 284 } 285 286 buf += len; 287 count -= len; 288 } 289 *buf = '\0'; 290} 291 292static void copy_to_file(int inFd, int outFd) { 293 const size_t BUFSIZE = 32 * 1024; 294 char* buf = (char*) malloc(BUFSIZE); 295 if (buf == nullptr) fatal("couldn't allocate buffer for copy_to_file"); 296 int len; 297 long total = 0; 298#ifdef _WIN32 299 int old_stdin_mode = -1; 300 int old_stdout_mode = -1; 301#endif 302 303 D("copy_to_file(%d -> %d)\n", inFd, outFd); 304 305 if (inFd == STDIN_FILENO) { 306 stdin_raw_init(STDIN_FILENO); 307#ifdef _WIN32 308 old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY); 309 if (old_stdin_mode == -1) { 310 fatal_errno("could not set stdin to binary"); 311 } 312#endif 313 } 314 315#ifdef _WIN32 316 if (outFd == STDOUT_FILENO) { 317 old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY); 318 if (old_stdout_mode == -1) { 319 fatal_errno("could not set stdout to binary"); 320 } 321 } 322#endif 323 324 while (true) { 325 if (inFd == STDIN_FILENO) { 326 len = unix_read(inFd, buf, BUFSIZE); 327 } else { 328 len = adb_read(inFd, buf, BUFSIZE); 329 } 330 if (len == 0) { 331 D("copy_to_file() : read 0 bytes; exiting\n"); 332 break; 333 } 334 if (len < 0) { 335 if (errno == EINTR) { 336 D("copy_to_file() : EINTR, retrying\n"); 337 continue; 338 } 339 D("copy_to_file() : error %d\n", errno); 340 break; 341 } 342 if (outFd == STDOUT_FILENO) { 343 fwrite(buf, 1, len, stdout); 344 fflush(stdout); 345 } else { 346 adb_write(outFd, buf, len); 347 } 348 total += len; 349 } 350 351 if (inFd == STDIN_FILENO) { 352 stdin_raw_restore(STDIN_FILENO); 353#ifdef _WIN32 354 if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) { 355 fatal_errno("could not restore stdin mode"); 356 } 357#endif 358 } 359 360#ifdef _WIN32 361 if (outFd == STDOUT_FILENO) { 362 if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) { 363 fatal_errno("could not restore stdout mode"); 364 } 365 } 366#endif 367 368 D("copy_to_file() finished after %lu bytes\n", total); 369 free(buf); 370} 371 372static void *stdin_read_thread(void *x) 373{ 374 int fd, fdi; 375 unsigned char buf[1024]; 376 int r, n; 377 int state = 0; 378 379 int *fds = (int*) x; 380 fd = fds[0]; 381 fdi = fds[1]; 382 free(fds); 383 384 for(;;) { 385 /* fdi is really the client's stdin, so use read, not adb_read here */ 386 D("stdin_read_thread(): pre unix_read(fdi=%d,...)\n", fdi); 387 r = unix_read(fdi, buf, 1024); 388 D("stdin_read_thread(): post unix_read(fdi=%d,...)\n", fdi); 389 if(r == 0) break; 390 if(r < 0) { 391 if(errno == EINTR) continue; 392 break; 393 } 394 for(n = 0; n < r; n++){ 395 switch(buf[n]) { 396 case '\n': 397 state = 1; 398 break; 399 case '\r': 400 state = 1; 401 break; 402 case '~': 403 if(state == 1) state++; 404 break; 405 case '.': 406 if(state == 2) { 407 fprintf(stderr,"\n* disconnect *\n"); 408 stdin_raw_restore(fdi); 409 exit(0); 410 } 411 default: 412 state = 0; 413 } 414 } 415 r = adb_write(fd, buf, r); 416 if(r <= 0) { 417 break; 418 } 419 } 420 return 0; 421} 422 423static int interactive_shell() { 424 int fdi; 425 426 std::string error; 427 int fd = adb_connect("shell:", &error); 428 if (fd < 0) { 429 fprintf(stderr,"error: %s\n", error.c_str()); 430 return 1; 431 } 432 fdi = 0; //dup(0); 433 434 int* fds = reinterpret_cast<int*>(malloc(sizeof(int) * 2)); 435 if (fds == nullptr) { 436 fprintf(stderr, "couldn't allocate fds array: %s\n", strerror(errno)); 437 return 1; 438 } 439 440 fds[0] = fd; 441 fds[1] = fdi; 442 443 stdin_raw_init(fdi); 444 445 adb_thread_create(stdin_read_thread, fds); 446 read_and_dump(fd); 447 stdin_raw_restore(fdi); 448 return 0; 449} 450 451 452static std::string format_host_command(const char* command, TransportType type, const char* serial) { 453 if (serial) { 454 return android::base::StringPrintf("host-serial:%s:%s", serial, command); 455 } 456 457 const char* prefix = "host"; 458 if (type == kTransportUsb) { 459 prefix = "host-usb"; 460 } else if (type == kTransportLocal) { 461 prefix = "host-local"; 462 } 463 return android::base::StringPrintf("%s:%s", prefix, command); 464} 465 466static int adb_download_buffer(const char *service, const char *fn, const void* data, unsigned sz, 467 bool show_progress) 468{ 469 std::string error; 470 int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error); 471 if (fd < 0) { 472 fprintf(stderr,"error: %s\n", error.c_str()); 473 return -1; 474 } 475 476 int opt = CHUNK_SIZE; 477 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt)); 478 479 unsigned total = sz; 480 const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); 481 482 if (show_progress) { 483 const char* x = strrchr(service, ':'); 484 if (x) service = x + 1; 485 } 486 487 while (sz > 0) { 488 unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz; 489 if (!WriteFdExactly(fd, ptr, xfer)) { 490 std::string error; 491 adb_status(fd, &error); 492 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str()); 493 return -1; 494 } 495 sz -= xfer; 496 ptr += xfer; 497 if (show_progress) { 498 printf("sending: '%s' %4d%% \r", fn, (int)(100LL - ((100LL * sz) / (total)))); 499 fflush(stdout); 500 } 501 } 502 if (show_progress) { 503 printf("\n"); 504 } 505 506 if (!adb_status(fd, &error)) { 507 fprintf(stderr,"* error response '%s' *\n", error.c_str()); 508 return -1; 509 } 510 511 adb_close(fd); 512 return 0; 513} 514 515#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE) 516 517/* 518 * The sideload-host protocol serves the data in a file (given on the 519 * command line) to the client, using a simple protocol: 520 * 521 * - The connect message includes the total number of bytes in the 522 * file and a block size chosen by us. 523 * 524 * - The other side sends the desired block number as eight decimal 525 * digits (eg "00000023" for block 23). Blocks are numbered from 526 * zero. 527 * 528 * - We send back the data of the requested block. The last block is 529 * likely to be partial; when the last block is requested we only 530 * send the part of the block that exists, it's not padded up to the 531 * block size. 532 * 533 * - When the other side sends "DONEDONE" instead of a block number, 534 * we hang up. 535 */ 536static int adb_sideload_host(const char* fn) { 537 unsigned sz; 538 size_t xfer = 0; 539 int status; 540 int last_percent = -1; 541 int opt = SIDELOAD_HOST_BLOCK_SIZE; 542 543 printf("loading: '%s'", fn); 544 fflush(stdout); 545 uint8_t* data = reinterpret_cast<uint8_t*>(load_file(fn, &sz)); 546 if (data == 0) { 547 printf("\n"); 548 fprintf(stderr, "* cannot read '%s' *\n", fn); 549 return -1; 550 } 551 552 std::string service = 553 android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE); 554 std::string error; 555 int fd = adb_connect(service, &error); 556 if (fd < 0) { 557 // Try falling back to the older sideload method. Maybe this 558 // is an older device that doesn't support sideload-host. 559 printf("\n"); 560 status = adb_download_buffer("sideload", fn, data, sz, true); 561 goto done; 562 } 563 564 opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt)); 565 566 while (true) { 567 char buf[9]; 568 if (!ReadFdExactly(fd, buf, 8)) { 569 fprintf(stderr, "* failed to read command: %s\n", strerror(errno)); 570 status = -1; 571 goto done; 572 } 573 buf[8] = '\0'; 574 575 if (strcmp("DONEDONE", buf) == 0) { 576 status = 0; 577 break; 578 } 579 580 int block = strtol(buf, NULL, 10); 581 582 size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE; 583 if (offset >= sz) { 584 fprintf(stderr, "* attempt to read block %d past end\n", block); 585 status = -1; 586 goto done; 587 } 588 uint8_t* start = data + offset; 589 size_t offset_end = offset + SIDELOAD_HOST_BLOCK_SIZE; 590 size_t to_write = SIDELOAD_HOST_BLOCK_SIZE; 591 if (offset_end > sz) { 592 to_write = sz - offset; 593 } 594 595 if(!WriteFdExactly(fd, start, to_write)) { 596 adb_status(fd, &error); 597 fprintf(stderr,"* failed to write data '%s' *\n", error.c_str()); 598 status = -1; 599 goto done; 600 } 601 xfer += to_write; 602 603 // For normal OTA packages, we expect to transfer every byte 604 // twice, plus a bit of overhead (one read during 605 // verification, one read of each byte for installation, plus 606 // extra access to things like the zip central directory). 607 // This estimate of the completion becomes 100% when we've 608 // transferred ~2.13 (=100/47) times the package size. 609 int percent = (int)(xfer * 47LL / (sz ? sz : 1)); 610 if (percent != last_percent) { 611 printf("\rserving: '%s' (~%d%%) ", fn, percent); 612 fflush(stdout); 613 last_percent = percent; 614 } 615 } 616 617 printf("\rTotal xfer: %.2fx%*s\n", (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, ""); 618 619 done: 620 if (fd >= 0) adb_close(fd); 621 free(data); 622 return status; 623} 624 625/** 626 * Run ppp in "notty" mode against a resource listed as the first parameter 627 * eg: 628 * 629 * ppp dev:/dev/omap_csmi_tty0 <ppp options> 630 * 631 */ 632static int ppp(int argc, const char** argv) { 633#if defined(_WIN32) 634 fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]); 635 return -1; 636#else 637 if (argc < 2) { 638 fprintf(stderr, "usage: adb %s <adb service name> [ppp opts]\n", 639 argv[0]); 640 641 return 1; 642 } 643 644 const char* adb_service_name = argv[1]; 645 std::string error; 646 int fd = adb_connect(adb_service_name, &error); 647 if (fd < 0) { 648 fprintf(stderr,"Error: Could not open adb service: %s. Error: %s\n", 649 adb_service_name, error.c_str()); 650 return 1; 651 } 652 653 pid_t pid = fork(); 654 655 if (pid < 0) { 656 perror("from fork()"); 657 return 1; 658 } else if (pid == 0) { 659 int err; 660 int i; 661 const char **ppp_args; 662 663 // copy args 664 ppp_args = (const char **) alloca(sizeof(char *) * argc + 1); 665 ppp_args[0] = "pppd"; 666 for (i = 2 ; i < argc ; i++) { 667 //argv[2] and beyond become ppp_args[1] and beyond 668 ppp_args[i - 1] = argv[i]; 669 } 670 ppp_args[i-1] = NULL; 671 672 // child side 673 674 dup2(fd, STDIN_FILENO); 675 dup2(fd, STDOUT_FILENO); 676 adb_close(STDERR_FILENO); 677 adb_close(fd); 678 679 err = execvp("pppd", (char * const *)ppp_args); 680 681 if (err < 0) { 682 perror("execing pppd"); 683 } 684 exit(-1); 685 } else { 686 // parent side 687 688 adb_close(fd); 689 return 0; 690 } 691#endif /* !defined(_WIN32) */ 692} 693 694static bool wait_for_device(const char* service, TransportType t, const char* serial) { 695 // Was the caller vague about what they'd like us to wait for? 696 // If so, check they weren't more specific in their choice of transport type. 697 if (strcmp(service, "wait-for-device") == 0) { 698 if (t == kTransportUsb) { 699 service = "wait-for-usb"; 700 } else if (t == kTransportLocal) { 701 service = "wait-for-local"; 702 } else { 703 service = "wait-for-any"; 704 } 705 } 706 707 std::string cmd = format_host_command(service, t, serial); 708 return adb_command(cmd); 709} 710 711static int send_shell_command(TransportType transport_type, const char* serial, 712 const std::string& command) { 713 int fd; 714 while (true) { 715 std::string error; 716 fd = adb_connect(command, &error); 717 if (fd >= 0) { 718 break; 719 } 720 fprintf(stderr,"- waiting for device -\n"); 721 adb_sleep_ms(1000); 722 wait_for_device("wait-for-device", transport_type, serial); 723 } 724 725 read_and_dump(fd); 726 int rc = adb_close(fd); 727 if (rc) { 728 perror("close"); 729 } 730 return rc; 731} 732 733static int logcat(TransportType transport, const char* serial, int argc, const char** argv) { 734 char* log_tags = getenv("ANDROID_LOG_TAGS"); 735 std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags); 736 737 std::string cmd = "shell:export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat"; 738 739 if (!strcmp(argv[0], "longcat")) { 740 cmd += " -v long"; 741 } 742 743 --argc; 744 ++argv; 745 while (argc-- > 0) { 746 cmd += " " + escape_arg(*argv++); 747 } 748 749 return send_shell_command(transport, serial, cmd); 750} 751 752static int backup(int argc, const char** argv) { 753 const char* filename = "./backup.ab"; 754 755 /* find, extract, and use any -f argument */ 756 for (int i = 1; i < argc; i++) { 757 if (!strcmp("-f", argv[i])) { 758 if (i == argc-1) { 759 fprintf(stderr, "adb: -f passed with no filename\n"); 760 return usage(); 761 } 762 filename = argv[i+1]; 763 for (int j = i+2; j <= argc; ) { 764 argv[i++] = argv[j++]; 765 } 766 argc -= 2; 767 argv[argc] = NULL; 768 } 769 } 770 771 /* bare "adb backup" or "adb backup -f filename" are not valid invocations */ 772 if (argc < 2) return usage(); 773 774 adb_unlink(filename); 775 mkdirs(filename); 776 int outFd = adb_creat(filename, 0640); 777 if (outFd < 0) { 778 fprintf(stderr, "adb: unable to open file %s\n", filename); 779 return -1; 780 } 781 782 std::string cmd = "backup:"; 783 --argc; 784 ++argv; 785 while (argc-- > 0) { 786 cmd += " " + escape_arg(*argv++); 787 } 788 789 D("backup. filename=%s cmd=%s\n", filename, cmd.c_str()); 790 std::string error; 791 int fd = adb_connect(cmd, &error); 792 if (fd < 0) { 793 fprintf(stderr, "adb: unable to connect for backup: %s\n", error.c_str()); 794 adb_close(outFd); 795 return -1; 796 } 797 798 printf("Now unlock your device and confirm the backup operation.\n"); 799 copy_to_file(fd, outFd); 800 801 adb_close(fd); 802 adb_close(outFd); 803 return 0; 804} 805 806static int restore(int argc, const char** argv) { 807 if (argc != 2) return usage(); 808 809 const char* filename = argv[1]; 810 int tarFd = adb_open(filename, O_RDONLY); 811 if (tarFd < 0) { 812 fprintf(stderr, "adb: unable to open file %s: %s\n", filename, strerror(errno)); 813 return -1; 814 } 815 816 std::string error; 817 int fd = adb_connect("restore:", &error); 818 if (fd < 0) { 819 fprintf(stderr, "adb: unable to connect for restore: %s\n", error.c_str()); 820 adb_close(tarFd); 821 return -1; 822 } 823 824 printf("Now unlock your device and confirm the restore operation.\n"); 825 copy_to_file(tarFd, fd); 826 827 adb_close(fd); 828 adb_close(tarFd); 829 return 0; 830} 831 832/* <hint> may be: 833 * - A simple product name 834 * e.g., "sooner" 835 * - A relative path from the CWD to the ANDROID_PRODUCT_OUT dir 836 * e.g., "out/target/product/sooner" 837 * - An absolute path to the PRODUCT_OUT dir 838 * e.g., "/src/device/out/target/product/sooner" 839 * 840 * Given <hint>, try to construct an absolute path to the 841 * ANDROID_PRODUCT_OUT dir. 842 */ 843static std::string find_product_out_path(const std::string& hint) { 844 if (hint.empty()) { 845 return ""; 846 } 847 848 // If it's already absolute, don't bother doing any work. 849 if (adb_is_absolute_host_path(hint.c_str())) { 850 return hint; 851 } 852 853 // If there are any slashes in it, assume it's a relative path; 854 // make it absolute. 855 if (hint.find_first_of(OS_PATH_SEPARATORS) != std::string::npos) { 856 std::string cwd; 857 if (!getcwd(&cwd)) { 858 fprintf(stderr, "adb: getcwd failed: %s\n", strerror(errno)); 859 return ""; 860 } 861 return android::base::StringPrintf("%s%c%s", cwd.c_str(), OS_PATH_SEPARATOR, hint.c_str()); 862 } 863 864 // It's a string without any slashes. Try to do something with it. 865 // 866 // Try to find the root of the build tree, and build a PRODUCT_OUT 867 // path from there. 868 char* top = getenv("ANDROID_BUILD_TOP"); 869 if (top == nullptr) { 870 fprintf(stderr, "adb: ANDROID_BUILD_TOP not set!\n"); 871 return ""; 872 } 873 874 std::string path = top; 875 path += OS_PATH_SEPARATOR_STR; 876 path += "out"; 877 path += OS_PATH_SEPARATOR_STR; 878 path += "target"; 879 path += OS_PATH_SEPARATOR_STR; 880 path += "product"; 881 path += OS_PATH_SEPARATOR_STR; 882 path += hint; 883 if (!directory_exists(path)) { 884 fprintf(stderr, "adb: Couldn't find a product dir based on -p %s; " 885 "\"%s\" doesn't exist\n", hint.c_str(), path.c_str()); 886 return ""; 887 } 888 return path; 889} 890 891static void parse_push_pull_args(const char **arg, int narg, char const **path1, 892 char const **path2, int *show_progress, 893 int *copy_attrs) { 894 *show_progress = 0; 895 *copy_attrs = 0; 896 897 while (narg > 0) { 898 if (!strcmp(*arg, "-p")) { 899 *show_progress = 1; 900 } else if (!strcmp(*arg, "-a")) { 901 *copy_attrs = 1; 902 } else { 903 break; 904 } 905 ++arg; 906 --narg; 907 } 908 909 if (narg > 0) { 910 *path1 = *arg; 911 ++arg; 912 --narg; 913 } 914 915 if (narg > 0) { 916 *path2 = *arg; 917 } 918} 919 920static int adb_connect_command(const std::string& command) { 921 std::string error; 922 int fd = adb_connect(command, &error); 923 if (fd < 0) { 924 fprintf(stderr, "error: %s\n", error.c_str()); 925 return 1; 926 } 927 read_and_dump(fd); 928 adb_close(fd); 929 return 0; 930} 931 932static int adb_query_command(const std::string& command) { 933 std::string result; 934 std::string error; 935 if (!adb_query(command, &result, &error)) { 936 fprintf(stderr, "error: %s\n", error.c_str()); 937 return 1; 938 } 939 printf("%s\n", result.c_str()); 940 return 0; 941} 942 943int adb_commandline(int argc, const char **argv) { 944 int no_daemon = 0; 945 int is_daemon = 0; 946 int is_server = 0; 947 int r; 948 TransportType transport_type = kTransportAny; 949 int ack_reply_fd = -1; 950 951 // If defined, this should be an absolute path to 952 // the directory containing all of the various system images 953 // for a particular product. If not defined, and the adb 954 // command requires this information, then the user must 955 // specify the path using "-p". 956 char* ANDROID_PRODUCT_OUT = getenv("ANDROID_PRODUCT_OUT"); 957 if (ANDROID_PRODUCT_OUT != nullptr) { 958 gProductOutPath = ANDROID_PRODUCT_OUT; 959 } 960 // TODO: also try TARGET_PRODUCT/TARGET_DEVICE as a hint 961 962 const char* serial = getenv("ANDROID_SERIAL"); 963 964 /* Validate and assign the server port */ 965 const char* server_port_str = getenv("ANDROID_ADB_SERVER_PORT"); 966 int server_port = DEFAULT_ADB_PORT; 967 if (server_port_str && strlen(server_port_str) > 0) { 968 server_port = strtol(server_port_str, nullptr, 0); 969 if (server_port <= 0 || server_port > 65535) { 970 fprintf(stderr, 971 "adb: Env var ANDROID_ADB_SERVER_PORT must be a positive number less than 65535. Got \"%s\"\n", 972 server_port_str); 973 return usage(); 974 } 975 } 976 977 /* modifiers and flags */ 978 while (argc > 0) { 979 if (!strcmp(argv[0],"server")) { 980 is_server = 1; 981 } else if (!strcmp(argv[0],"nodaemon")) { 982 no_daemon = 1; 983 } else if (!strcmp(argv[0], "fork-server")) { 984 /* this is a special flag used only when the ADB client launches the ADB Server */ 985 is_daemon = 1; 986 } else if (!strcmp(argv[0], "--reply-fd")) { 987 if (argc < 2) return usage(); 988 const char* reply_fd_str = argv[1]; 989 argc--; 990 argv++; 991 ack_reply_fd = strtol(reply_fd_str, nullptr, 10); 992#ifdef _WIN32 993 const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd); 994 if ((GetStdHandle(STD_INPUT_HANDLE) == ack_reply_handle) || 995 (GetStdHandle(STD_OUTPUT_HANDLE) == ack_reply_handle) || 996 (GetStdHandle(STD_ERROR_HANDLE) == ack_reply_handle)) { 997#else 998 if (ack_reply_fd <= 2) { // Disallow stdin, stdout, and stderr. 999#endif 1000 fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str); 1001 return usage(); 1002 } 1003 } else if (!strncmp(argv[0], "-p", 2)) { 1004 const char* product = nullptr; 1005 if (argv[0][2] == '\0') { 1006 if (argc < 2) return usage(); 1007 product = argv[1]; 1008 argc--; 1009 argv++; 1010 } else { 1011 product = argv[0] + 2; 1012 } 1013 gProductOutPath = find_product_out_path(product); 1014 if (gProductOutPath.empty()) { 1015 fprintf(stderr, "adb: could not resolve \"-p %s\"\n", product); 1016 return usage(); 1017 } 1018 } else if (argv[0][0]=='-' && argv[0][1]=='s') { 1019 if (isdigit(argv[0][2])) { 1020 serial = argv[0] + 2; 1021 } else { 1022 if (argc < 2 || argv[0][2] != '\0') return usage(); 1023 serial = argv[1]; 1024 argc--; 1025 argv++; 1026 } 1027 } else if (!strcmp(argv[0],"-d")) { 1028 transport_type = kTransportUsb; 1029 } else if (!strcmp(argv[0],"-e")) { 1030 transport_type = kTransportLocal; 1031 } else if (!strcmp(argv[0],"-a")) { 1032 gListenAll = 1; 1033 } else if (!strncmp(argv[0], "-H", 2)) { 1034 const char *hostname = NULL; 1035 if (argv[0][2] == '\0') { 1036 if (argc < 2) return usage(); 1037 hostname = argv[1]; 1038 argc--; 1039 argv++; 1040 } else { 1041 hostname = argv[0] + 2; 1042 } 1043 adb_set_tcp_name(hostname); 1044 1045 } else if (!strncmp(argv[0], "-P", 2)) { 1046 if (argv[0][2] == '\0') { 1047 if (argc < 2) return usage(); 1048 server_port_str = argv[1]; 1049 argc--; 1050 argv++; 1051 } else { 1052 server_port_str = argv[0] + 2; 1053 } 1054 if (strlen(server_port_str) > 0) { 1055 server_port = (int) strtol(server_port_str, NULL, 0); 1056 if (server_port <= 0 || server_port > 65535) { 1057 fprintf(stderr, 1058 "adb: port number must be a positive number less than 65536. Got \"%s\"\n", 1059 server_port_str); 1060 return usage(); 1061 } 1062 } else { 1063 fprintf(stderr, 1064 "adb: port number must be a positive number less than 65536. Got empty string.\n"); 1065 return usage(); 1066 } 1067 } else { 1068 /* out of recognized modifiers and flags */ 1069 break; 1070 } 1071 argc--; 1072 argv++; 1073 } 1074 1075 adb_set_transport(transport_type, serial); 1076 adb_set_tcp_specifics(server_port); 1077 1078 if (is_server) { 1079 if (no_daemon || is_daemon) { 1080 if (is_daemon && (ack_reply_fd == -1)) { 1081 fprintf(stderr, "reply fd for adb server to client communication not specified.\n"); 1082 return usage(); 1083 } 1084 r = adb_main(is_daemon, server_port, ack_reply_fd); 1085 } else { 1086 r = launch_server(server_port); 1087 } 1088 if (r) { 1089 fprintf(stderr,"* could not start server *\n"); 1090 } 1091 return r; 1092 } 1093 1094 if (argc == 0) { 1095 return usage(); 1096 } 1097 1098 /* handle wait-for-* prefix */ 1099 if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) { 1100 const char* service = argv[0]; 1101 1102 if (!wait_for_device(service, transport_type, serial)) { 1103 return 1; 1104 } 1105 1106 // Allow a command to be run after wait-for-device, 1107 // e.g. 'adb wait-for-device shell'. 1108 if (argc == 1) { 1109 return 0; 1110 } 1111 1112 /* Fall through */ 1113 argc--; 1114 argv++; 1115 } 1116 1117 /* adb_connect() commands */ 1118 if (!strcmp(argv[0], "devices")) { 1119 const char *listopt; 1120 if (argc < 2) { 1121 listopt = ""; 1122 } else if (argc == 2 && !strcmp(argv[1], "-l")) { 1123 listopt = argv[1]; 1124 } else { 1125 fprintf(stderr, "Usage: adb devices [-l]\n"); 1126 return 1; 1127 } 1128 1129 std::string query = android::base::StringPrintf("host:%s%s", argv[0], listopt); 1130 printf("List of devices attached\n"); 1131 return adb_query_command(query); 1132 } 1133 else if (!strcmp(argv[0], "connect")) { 1134 if (argc != 2) { 1135 fprintf(stderr, "Usage: adb connect <host>[:<port>]\n"); 1136 return 1; 1137 } 1138 1139 std::string query = android::base::StringPrintf("host:connect:%s", argv[1]); 1140 return adb_query_command(query); 1141 } 1142 else if (!strcmp(argv[0], "disconnect")) { 1143 if (argc > 2) { 1144 fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n"); 1145 return 1; 1146 } 1147 1148 std::string query = android::base::StringPrintf("host:disconnect:%s", 1149 (argc == 2) ? argv[1] : ""); 1150 return adb_query_command(query); 1151 } 1152 else if (!strcmp(argv[0], "emu")) { 1153 return adb_send_emulator_command(argc, argv, serial); 1154 } 1155 else if (!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) { 1156 char h = (argv[0][0] == 'h'); 1157 1158 if (h) { 1159 printf("\x1b[41;33m"); 1160 fflush(stdout); 1161 } 1162 1163 if (argc < 2) { 1164 D("starting interactive shell\n"); 1165 r = interactive_shell(); 1166 if (h) { 1167 printf("\x1b[0m"); 1168 fflush(stdout); 1169 } 1170 return r; 1171 } 1172 1173 std::string cmd = "shell:"; 1174 --argc; 1175 ++argv; 1176 while (argc-- > 0) { 1177 // We don't escape here, just like ssh(1). http://b/20564385. 1178 cmd += *argv++; 1179 if (*argv) cmd += " "; 1180 } 1181 1182 while (true) { 1183 D("interactive shell loop. cmd=%s\n", cmd.c_str()); 1184 std::string error; 1185 int fd = adb_connect(cmd, &error); 1186 int r; 1187 if (fd >= 0) { 1188 D("about to read_and_dump(fd=%d)\n", fd); 1189 read_and_dump(fd); 1190 D("read_and_dump() done.\n"); 1191 adb_close(fd); 1192 r = 0; 1193 } else { 1194 fprintf(stderr,"error: %s\n", error.c_str()); 1195 r = -1; 1196 } 1197 1198 if (h) { 1199 printf("\x1b[0m"); 1200 fflush(stdout); 1201 } 1202 D("interactive shell loop. return r=%d\n", r); 1203 return r; 1204 } 1205 } 1206 else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) { 1207 int exec_in = !strcmp(argv[0], "exec-in"); 1208 1209 std::string cmd = "exec:"; 1210 cmd += argv[1]; 1211 argc -= 2; 1212 argv += 2; 1213 while (argc-- > 0) { 1214 cmd += " " + escape_arg(*argv++); 1215 } 1216 1217 std::string error; 1218 int fd = adb_connect(cmd, &error); 1219 if (fd < 0) { 1220 fprintf(stderr, "error: %s\n", error.c_str()); 1221 return -1; 1222 } 1223 1224 if (exec_in) { 1225 copy_to_file(STDIN_FILENO, fd); 1226 } else { 1227 copy_to_file(fd, STDOUT_FILENO); 1228 } 1229 1230 adb_close(fd); 1231 return 0; 1232 } 1233 else if (!strcmp(argv[0], "kill-server")) { 1234 std::string error; 1235 int fd = _adb_connect("host:kill", &error); 1236 if (fd == -1) { 1237 fprintf(stderr,"* server not running *\n"); 1238 return 1; 1239 } 1240 return 0; 1241 } 1242 else if (!strcmp(argv[0], "sideload")) { 1243 if (argc != 2) return usage(); 1244 if (adb_sideload_host(argv[1])) { 1245 return 1; 1246 } else { 1247 return 0; 1248 } 1249 } 1250 else if (!strcmp(argv[0], "tcpip") && argc > 1) { 1251 return adb_connect_command(android::base::StringPrintf("tcpip:%s", argv[1])); 1252 } 1253 else if (!strcmp(argv[0], "remount") || 1254 !strcmp(argv[0], "reboot") || 1255 !strcmp(argv[0], "reboot-bootloader") || 1256 !strcmp(argv[0], "usb") || 1257 !strcmp(argv[0], "root") || 1258 !strcmp(argv[0], "unroot") || 1259 !strcmp(argv[0], "disable-verity") || 1260 !strcmp(argv[0], "enable-verity")) { 1261 std::string command; 1262 if (!strcmp(argv[0], "reboot-bootloader")) { 1263 command = "reboot:bootloader"; 1264 } else if (argc > 1) { 1265 command = android::base::StringPrintf("%s:%s", argv[0], argv[1]); 1266 } else { 1267 command = android::base::StringPrintf("%s:", argv[0]); 1268 } 1269 return adb_connect_command(command); 1270 } 1271 else if (!strcmp(argv[0], "bugreport")) { 1272 if (argc != 1) return usage(); 1273 return send_shell_command(transport_type, serial, "shell:bugreport"); 1274 } 1275 else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) { 1276 bool reverse = !strcmp(argv[0], "reverse"); 1277 ++argv; 1278 --argc; 1279 if (argc < 1) return usage(); 1280 1281 // Determine the <host-prefix> for this command. 1282 std::string host_prefix; 1283 if (reverse) { 1284 host_prefix = "reverse"; 1285 } else { 1286 if (serial) { 1287 host_prefix = android::base::StringPrintf("host-serial:%s", serial); 1288 } else if (transport_type == kTransportUsb) { 1289 host_prefix = "host-usb"; 1290 } else if (transport_type == kTransportLocal) { 1291 host_prefix = "host-local"; 1292 } else { 1293 host_prefix = "host"; 1294 } 1295 } 1296 1297 std::string cmd; 1298 if (strcmp(argv[0], "--list") == 0) { 1299 if (argc != 1) return usage(); 1300 return adb_query_command(host_prefix + ":list-forward"); 1301 } else if (strcmp(argv[0], "--remove-all") == 0) { 1302 if (argc != 1) return usage(); 1303 cmd = host_prefix + ":killforward-all"; 1304 } else if (strcmp(argv[0], "--remove") == 0) { 1305 // forward --remove <local> 1306 if (argc != 2) return usage(); 1307 cmd = host_prefix + ":killforward:" + argv[1]; 1308 } else if (strcmp(argv[0], "--no-rebind") == 0) { 1309 // forward --no-rebind <local> <remote> 1310 if (argc != 3) return usage(); 1311 cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2]; 1312 } else { 1313 // forward <local> <remote> 1314 if (argc != 2) return usage(); 1315 cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1]; 1316 } 1317 1318 return adb_command(cmd) ? 0 : 1; 1319 } 1320 /* do_sync_*() commands */ 1321 else if (!strcmp(argv[0], "ls")) { 1322 if (argc != 2) return usage(); 1323 return do_sync_ls(argv[1]); 1324 } 1325 else if (!strcmp(argv[0], "push")) { 1326 int show_progress = 0; 1327 int copy_attrs = 0; // unused 1328 const char* lpath = NULL, *rpath = NULL; 1329 1330 parse_push_pull_args(&argv[1], argc - 1, &lpath, &rpath, &show_progress, ©_attrs); 1331 1332 if ((lpath != NULL) && (rpath != NULL)) { 1333 return do_sync_push(lpath, rpath, show_progress); 1334 } 1335 1336 return usage(); 1337 } 1338 else if (!strcmp(argv[0], "pull")) { 1339 int show_progress = 0; 1340 int copy_attrs = 0; 1341 const char* rpath = NULL, *lpath = "."; 1342 1343 parse_push_pull_args(&argv[1], argc - 1, &rpath, &lpath, &show_progress, ©_attrs); 1344 1345 if (rpath != NULL) { 1346 return do_sync_pull(rpath, lpath, show_progress, copy_attrs); 1347 } 1348 1349 return usage(); 1350 } 1351 else if (!strcmp(argv[0], "install")) { 1352 if (argc < 2) return usage(); 1353 return install_app(transport_type, serial, argc, argv); 1354 } 1355 else if (!strcmp(argv[0], "install-multiple")) { 1356 if (argc < 2) return usage(); 1357 return install_multiple_app(transport_type, serial, argc, argv); 1358 } 1359 else if (!strcmp(argv[0], "uninstall")) { 1360 if (argc < 2) return usage(); 1361 return uninstall_app(transport_type, serial, argc, argv); 1362 } 1363 else if (!strcmp(argv[0], "sync")) { 1364 std::string src; 1365 bool list_only = false; 1366 if (argc < 2) { 1367 // No local path was specified. 1368 src = ""; 1369 } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) { 1370 list_only = true; 1371 if (argc == 3) { 1372 src = argv[2]; 1373 } else { 1374 src = ""; 1375 } 1376 } else if (argc == 2) { 1377 // A local path or "android"/"data" arg was specified. 1378 src = argv[1]; 1379 } else { 1380 return usage(); 1381 } 1382 1383 if (src != "" && 1384 src != "system" && src != "data" && src != "vendor" && src != "oem") { 1385 return usage(); 1386 } 1387 1388 std::string system_src_path = product_file("system"); 1389 std::string data_src_path = product_file("data"); 1390 std::string vendor_src_path = product_file("vendor"); 1391 std::string oem_src_path = product_file("oem"); 1392 1393 int rc = 0; 1394 if (rc == 0 && (src.empty() || src == "system")) { 1395 rc = do_sync_sync(system_src_path, "/system", list_only); 1396 } 1397 if (rc == 0 && (src.empty() || src == "vendor") && directory_exists(vendor_src_path)) { 1398 rc = do_sync_sync(vendor_src_path, "/vendor", list_only); 1399 } 1400 if (rc == 0 && (src.empty() || src == "oem") && directory_exists(oem_src_path)) { 1401 rc = do_sync_sync(oem_src_path, "/oem", list_only); 1402 } 1403 if (rc == 0 && (src.empty() || src == "data")) { 1404 rc = do_sync_sync(data_src_path, "/data", list_only); 1405 } 1406 return rc; 1407 } 1408 /* passthrough commands */ 1409 else if (!strcmp(argv[0],"get-state") || 1410 !strcmp(argv[0],"get-serialno") || 1411 !strcmp(argv[0],"get-devpath")) 1412 { 1413 return adb_query_command(format_host_command(argv[0], transport_type, serial)); 1414 } 1415 /* other commands */ 1416 else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) { 1417 return logcat(transport_type, serial, argc, argv); 1418 } 1419 else if (!strcmp(argv[0],"ppp")) { 1420 return ppp(argc, argv); 1421 } 1422 else if (!strcmp(argv[0], "start-server")) { 1423 std::string error; 1424 return adb_connect("host:start-server", &error); 1425 } 1426 else if (!strcmp(argv[0], "backup")) { 1427 return backup(argc, argv); 1428 } 1429 else if (!strcmp(argv[0], "restore")) { 1430 return restore(argc, argv); 1431 } 1432 else if (!strcmp(argv[0], "keygen")) { 1433 if (argc < 2) return usage(); 1434 return adb_auth_keygen(argv[1]); 1435 } 1436 else if (!strcmp(argv[0], "jdwp")) { 1437 return adb_connect_command("jdwp"); 1438 } 1439 /* "adb /?" is a common idiom under Windows */ 1440 else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) { 1441 help(); 1442 return 0; 1443 } 1444 else if (!strcmp(argv[0], "version")) { 1445 fprintf(stdout, "%s", adb_version().c_str()); 1446 return 0; 1447 } 1448 1449 usage(); 1450 return 1; 1451} 1452 1453static int pm_command(TransportType transport, const char* serial, int argc, const char** argv) { 1454 std::string cmd = "shell:pm"; 1455 1456 while (argc-- > 0) { 1457 cmd += " " + escape_arg(*argv++); 1458 } 1459 1460 return send_shell_command(transport, serial, cmd); 1461} 1462 1463static int uninstall_app(TransportType transport, const char* serial, int argc, const char** argv) { 1464 /* if the user choose the -k option, we refuse to do it until devices are 1465 out with the option to uninstall the remaining data somehow (adb/ui) */ 1466 if (argc == 3 && strcmp(argv[1], "-k") == 0) 1467 { 1468 printf( 1469 "The -k option uninstalls the application while retaining the data/cache.\n" 1470 "At the moment, there is no way to remove the remaining data.\n" 1471 "You will have to reinstall the application with the same signature, and fully uninstall it.\n" 1472 "If you truly wish to continue, execute 'adb shell pm uninstall -k %s'\n", argv[2]); 1473 return -1; 1474 } 1475 1476 /* 'adb uninstall' takes the same arguments as 'pm uninstall' on device */ 1477 return pm_command(transport, serial, argc, argv); 1478} 1479 1480static int delete_file(TransportType transport, const char* serial, const std::string& filename) { 1481 std::string cmd = "shell:rm -f " + escape_arg(filename); 1482 return send_shell_command(transport, serial, cmd); 1483} 1484 1485static int install_app(TransportType transport, const char* serial, int argc, const char** argv) { 1486 static const char *const DATA_DEST = "/data/local/tmp/%s"; 1487 static const char *const SD_DEST = "/sdcard/tmp/%s"; 1488 const char* where = DATA_DEST; 1489 int i; 1490 struct stat sb; 1491 1492 for (i = 1; i < argc; i++) { 1493 if (!strcmp(argv[i], "-s")) { 1494 where = SD_DEST; 1495 } 1496 } 1497 1498 // Find last APK argument. 1499 // All other arguments passed through verbatim. 1500 int last_apk = -1; 1501 for (i = argc - 1; i >= 0; i--) { 1502 const char* file = argv[i]; 1503 const char* dot = strrchr(file, '.'); 1504 if (dot && !strcasecmp(dot, ".apk")) { 1505 if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) { 1506 fprintf(stderr, "Invalid APK file: %s\n", file); 1507 return -1; 1508 } 1509 1510 last_apk = i; 1511 break; 1512 } 1513 } 1514 1515 if (last_apk == -1) { 1516 fprintf(stderr, "Missing APK file\n"); 1517 return -1; 1518 } 1519 1520 const char* apk_file = argv[last_apk]; 1521 std::string apk_dest = android::base::StringPrintf(where, adb_basename(apk_file).c_str()); 1522 int err = do_sync_push(apk_file, apk_dest.c_str(), 0 /* no show progress */); 1523 if (err) { 1524 goto cleanup_apk; 1525 } else { 1526 argv[last_apk] = apk_dest.c_str(); /* destination name, not source location */ 1527 } 1528 1529 err = pm_command(transport, serial, argc, argv); 1530 1531cleanup_apk: 1532 delete_file(transport, serial, apk_dest); 1533 return err; 1534} 1535 1536static int install_multiple_app(TransportType transport, const char* serial, int argc, 1537 const char** argv) 1538{ 1539 int i; 1540 struct stat sb; 1541 uint64_t total_size = 0; 1542 1543 // Find all APK arguments starting at end. 1544 // All other arguments passed through verbatim. 1545 int first_apk = -1; 1546 for (i = argc - 1; i >= 0; i--) { 1547 const char* file = argv[i]; 1548 const char* dot = strrchr(file, '.'); 1549 if (dot && !strcasecmp(dot, ".apk")) { 1550 if (stat(file, &sb) == -1 || !S_ISREG(sb.st_mode)) { 1551 fprintf(stderr, "Invalid APK file: %s\n", file); 1552 return -1; 1553 } 1554 1555 total_size += sb.st_size; 1556 first_apk = i; 1557 } else { 1558 break; 1559 } 1560 } 1561 1562 if (first_apk == -1) { 1563 fprintf(stderr, "Missing APK file\n"); 1564 return 1; 1565 } 1566 1567 std::string cmd = android::base::StringPrintf("exec:pm install-create -S %" PRIu64, total_size); 1568 for (i = 1; i < first_apk; i++) { 1569 cmd += " " + escape_arg(argv[i]); 1570 } 1571 1572 // Create install session 1573 std::string error; 1574 int fd = adb_connect(cmd, &error); 1575 if (fd < 0) { 1576 fprintf(stderr, "Connect error for create: %s\n", error.c_str()); 1577 return -1; 1578 } 1579 char buf[BUFSIZ]; 1580 read_status_line(fd, buf, sizeof(buf)); 1581 adb_close(fd); 1582 1583 int session_id = -1; 1584 if (!strncmp("Success", buf, 7)) { 1585 char* start = strrchr(buf, '['); 1586 char* end = strrchr(buf, ']'); 1587 if (start && end) { 1588 *end = '\0'; 1589 session_id = strtol(start + 1, NULL, 10); 1590 } 1591 } 1592 if (session_id < 0) { 1593 fprintf(stderr, "Failed to create session\n"); 1594 fputs(buf, stderr); 1595 return -1; 1596 } 1597 1598 // Valid session, now stream the APKs 1599 int success = 1; 1600 for (i = first_apk; i < argc; i++) { 1601 const char* file = argv[i]; 1602 if (stat(file, &sb) == -1) { 1603 fprintf(stderr, "Failed to stat %s\n", file); 1604 success = 0; 1605 goto finalize_session; 1606 } 1607 1608 std::string cmd = android::base::StringPrintf( 1609 "exec:pm install-write -S %" PRIu64 " %d %d_%s -", 1610 static_cast<uint64_t>(sb.st_size), session_id, i, adb_basename(file).c_str()); 1611 1612 int localFd = adb_open(file, O_RDONLY); 1613 if (localFd < 0) { 1614 fprintf(stderr, "Failed to open %s: %s\n", file, strerror(errno)); 1615 success = 0; 1616 goto finalize_session; 1617 } 1618 1619 std::string error; 1620 int remoteFd = adb_connect(cmd, &error); 1621 if (remoteFd < 0) { 1622 fprintf(stderr, "Connect error for write: %s\n", error.c_str()); 1623 adb_close(localFd); 1624 success = 0; 1625 goto finalize_session; 1626 } 1627 1628 copy_to_file(localFd, remoteFd); 1629 read_status_line(remoteFd, buf, sizeof(buf)); 1630 1631 adb_close(localFd); 1632 adb_close(remoteFd); 1633 1634 if (strncmp("Success", buf, 7)) { 1635 fprintf(stderr, "Failed to write %s\n", file); 1636 fputs(buf, stderr); 1637 success = 0; 1638 goto finalize_session; 1639 } 1640 } 1641 1642finalize_session: 1643 // Commit session if we streamed everything okay; otherwise abandon 1644 std::string service = 1645 android::base::StringPrintf("exec:pm install-%s %d", 1646 success ? "commit" : "abandon", session_id); 1647 fd = adb_connect(service, &error); 1648 if (fd < 0) { 1649 fprintf(stderr, "Connect error for finalize: %s\n", error.c_str()); 1650 return -1; 1651 } 1652 read_status_line(fd, buf, sizeof(buf)); 1653 adb_close(fd); 1654 1655 if (!strncmp("Success", buf, 7)) { 1656 fputs(buf, stderr); 1657 return 0; 1658 } else { 1659 fprintf(stderr, "Failed to finalize session\n"); 1660 fputs(buf, stderr); 1661 return -1; 1662 } 1663} 1664