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