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