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