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