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