forked from weiqifa0/android-adb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommandline.cpp
More file actions
2246 lines (2003 loc) · 80.2 KB
/
commandline.cpp
File metadata and controls
2246 lines (2003 loc) · 80.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define TRACE_TAG ADB
#include "sysdeps.h"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <memory>
#include <string>
#include <vector>
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#if !defined(_WIN32)
#include <signal.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#endif
#include "adb.h"
#include "adb_auth.h"
#include "adb_client.h"
#include "adb_io.h"
#include "adb_utils.h"
#include "bugreport.h"
#include "commandline.h"
#include "file_sync_service.h"
#include "services.h"
#include "shell_service.h"
static int install_app(TransportType t, const char* serial, int argc, const char** argv);
static int install_multiple_app(TransportType t, const char* serial, int argc, const char** argv);
static int uninstall_app(TransportType t, const char* serial, int argc, const char** argv);
static int install_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
static int uninstall_app_legacy(TransportType t, const char* serial, int argc, const char** argv);
static auto& gProductOutPath = *new std::string();
extern int gListenAll;
DefaultStandardStreamsCallback DEFAULT_STANDARD_STREAMS_CALLBACK(nullptr, nullptr);
static std::string product_file(const char *extra) {
if (gProductOutPath.empty()) {
fprintf(stderr, "adb: Product directory not specified; "
"use -p or define ANDROID_PRODUCT_OUT\n");
exit(1);
}
return android::base::StringPrintf("%s%s%s",
gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra);
}
static void help() {
fprintf(stderr, "%s\n", adb_version().c_str());
// clang-format off
fprintf(stderr,
"root for hd\n"
" -a - directs adb to listen on all interfaces for a connection\n"
" -d - directs command to the only connected USB device\n"
" returns an error if more than one USB device is present.\n"
" -e - directs command to the only running emulator.\n"
" returns an error if more than one emulator is running.\n"
" -s <specific device> - directs command to the device or emulator with the given\n"
" serial number or qualifier. Overrides ANDROID_SERIAL\n"
" environment variable.\n"
" -p <product name or path> - simple product name like 'sooner', or\n"
" a relative/absolute path to a product\n"
" out directory like 'out/target/product/sooner'.\n"
" If -p is not specified, the ANDROID_PRODUCT_OUT\n"
" environment variable is used, which must\n"
" be an absolute path.\n"
" -H - Name of adb server host (default: localhost)\n"
" -P - Port of adb server (default: 5037)\n"
" devices [-l] - list all connected devices\n"
" ('-l' will also list device qualifiers)\n"
" connect <host>[:<port>] - connect to a device via TCP/IP\n"
" Port 5555 is used by default if no port number is specified.\n"
" disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.\n"
" Port 5555 is used by default if no port number is specified.\n"
" Using this command with no additional arguments\n"
" will disconnect from all connected TCP/IP devices.\n"
"\n"
"device commands:\n"
" adb push <local>... <remote>\n"
" - copy files/dirs to device\n"
" adb pull [-a] <remote>... <local>\n"
" - copy files/dirs from device\n"
" (-a preserves file timestamp and mode)\n"
" adb sync [ <directory> ] - copy host->device only if changed\n"
" (-l means list but don't copy)\n"
" adb shell [-e escape] [-n] [-Tt] [-x] [command]\n"
" - run remote shell command (interactive shell if no command given)\n"
" (-e: choose escape character, or \"none\"; default '~')\n"
" (-n: don't read from stdin)\n"
" (-T: disable PTY allocation)\n"
" (-t: force PTY allocation)\n"
" (-x: disable remote exit codes and stdout/stderr separation)\n"
" adb emu <command> - run emulator console command\n"
" adb logcat [ <filter-spec> ] - View device log\n"
" adb forward --list - list all forward socket connections.\n"
" the format is a list of lines with the following format:\n"
" <serial> \" \" <local> \" \" <remote> \"\\n\"\n"
" adb forward <local> <remote> - forward socket connections\n"
" forward specs are one of: \n"
" tcp:<port>\n"
" localabstract:<unix domain socket name>\n"
" localreserved:<unix domain socket name>\n"
" localfilesystem:<unix domain socket name>\n"
" dev:<character device name>\n"
" jdwp:<process pid> (remote only)\n"
" adb forward --no-rebind <local> <remote>\n"
" - same as 'adb forward <local> <remote>' but fails\n"
" if <local> is already forwarded\n"
" adb forward --remove <local> - remove a specific forward socket connection\n"
" adb forward --remove-all - remove all forward socket connections\n"
" adb reverse --list - list all reverse socket connections from device\n"
" adb reverse <remote> <local> - reverse socket connections\n"
" reverse specs are one of:\n"
" tcp:<port>\n"
" localabstract:<unix domain socket name>\n"
" localreserved:<unix domain socket name>\n"
" localfilesystem:<unix domain socket name>\n"
" adb reverse --no-rebind <remote> <local>\n"
" - same as 'adb reverse <remote> <local>' but fails\n"
" if <remote> is already reversed.\n"
" adb reverse --remove <remote>\n"
" - remove a specific reversed socket connection\n"
" adb reverse --remove-all - remove all reversed socket connections from device\n"
" adb jdwp - list PIDs of processes hosting a JDWP transport\n"
" adb install [-lrtsdg] <file>\n"
" - push this package file to the device and install it\n"
" (-l: forward lock application)\n"
" (-r: replace existing application)\n"
" (-t: allow test packages)\n"
" (-s: install application on sdcard)\n"
" (-d: allow version code downgrade (debuggable packages only))\n"
" (-g: grant all runtime permissions)\n"
" adb install-multiple [-lrtsdpg] <file...>\n"
" - push this package file to the device and install it\n"
" (-l: forward lock application)\n"
" (-r: replace existing application)\n"
" (-t: allow test packages)\n"
" (-s: install application on sdcard)\n"
" (-d: allow version code downgrade (debuggable packages only))\n"
" (-p: partial application install)\n"
" (-g: grant all runtime permissions)\n"
" adb uninstall [-k] <package> - remove this app package from the device\n"
" ('-k' means keep the data and cache directories)\n"
" adb bugreport [<path>] - return all information from the device that should be included in a zipped bug report.\n"
" If <path> is a file, the bug report will be saved as that file.\n"
" If <path> is a directory, the bug report will be saved in that directory with the name provided by the device.\n"
" If <path> is omitted, the bug report will be saved in the current directory with the name provided by the device.\n"
" NOTE: if the device does not support zipped bug reports, the bug report will be output on stdout.\n"
" adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]\n"
" - write an archive of the device's data to <file>.\n"
" If no -f option is supplied then the data is written\n"
" to \"backup.ab\" in the current directory.\n"
" (-apk|-noapk enable/disable backup of the .apks themselves\n"
" in the archive; the default is noapk.)\n"
" (-obb|-noobb enable/disable backup of any installed apk expansion\n"
" (aka .obb) files associated with each application; the default\n"
" is noobb.)\n"
" (-shared|-noshared enable/disable backup of the device's\n"
" shared storage / SD card contents; the default is noshared.)\n"
" (-all means to back up all installed applications)\n"
" (-system|-nosystem toggles whether -all automatically includes\n"
" system applications; the default is to include system apps)\n"
" (<packages...> is the list of applications to be backed up. If\n"
" the -all or -shared flags are passed, then the package\n"
" list is optional. Applications explicitly given on the\n"
" command line will be included even if -nosystem would\n"
" ordinarily cause them to be omitted.)\n"
"\n"
" adb restore <file> - restore device contents from the <file> backup archive\n"
"\n"
" adb disable-verity - disable dm-verity checking on USERDEBUG builds\n"
" adb enable-verity - re-enable dm-verity checking on USERDEBUG builds\n"
" adb keygen <file> - generate adb public/private key. The private key is stored in <file>,\n"
" and the public key is stored in <file>.pub. Any existing files\n"
" are overwritten.\n"
" adb help - show this help message\n"
" adb version - show version num\n"
"\n"
"scripting:\n"
" adb wait-for[-<transport>]-<state>\n"
" - wait for device to be in the given state:\n"
" device, recovery, sideload, or bootloader\n"
" Transport is: usb, local or any [default=any]\n"
" adb start-server - ensure that there is a server running\n"
" adb kill-server - kill the server if it is running\n"
" adb get-state - prints: offline | bootloader | device\n"
" adb get-serialno - prints: <serial-number>\n"
" adb get-devpath - prints: <device-path>\n"
" adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write\n"
" adb reboot [bootloader|recovery]\n"
" - reboots the device, optionally into the bootloader or recovery program.\n"
" adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).\n"
" adb reboot sideload-auto-reboot\n"
" - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.\n"
" adb sideload <file> - sideloads the given package\n"
" adb root - restarts the adbd daemon with root permissions\n"
" adb unroot - restarts the adbd daemon without root permissions\n"
" adb usb - restarts the adbd daemon listening on USB\n"
" adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port\n"
"\n"
"networking:\n"
" adb ppp <tty> [parameters] - Run PPP over USB.\n"
" Note: you should not automatically start a PPP connection.\n"
" <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1\n"
" [parameters] - Eg. defaultroute debug dump local notty usepeerdns\n"
"\n"
"adb sync notes: adb sync [ <directory> ]\n"
" <localdir> can be interpreted in several ways:\n"
"\n"
" - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.\n"
"\n"
" - If it is \"system\", \"vendor\", \"oem\" or \"data\", only the corresponding partition\n"
" is updated.\n"
"\n"
"internal debugging:\n"
" adb reconnect Kick current connection from host side and make it reconnect.\n"
" adb reconnect device Kick current connection from device side and make it reconnect.\n"
"environment variables:\n"
" ADB_TRACE - Print debug information. A comma separated list of the following values\n"
" 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp\n"
" ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.\n"
" ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.\n");
// clang-format on
}
int usage() {
help();
return 1;
}
#if defined(_WIN32)
// Implemented in sysdeps_win32.cpp.
void stdin_raw_init();
void stdin_raw_restore();
#else
static termios g_saved_terminal_state;
static void stdin_raw_init() {
if (tcgetattr(STDIN_FILENO, &g_saved_terminal_state)) return;
termios tio;
if (tcgetattr(STDIN_FILENO, &tio)) return;
cfmakeraw(&tio);
// No timeout but request at least one character per read.
tio.c_cc[VTIME] = 0;
tio.c_cc[VMIN] = 1;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &tio);
}
static void stdin_raw_restore() {
tcsetattr(STDIN_FILENO, TCSAFLUSH, &g_saved_terminal_state);
}
#endif
// Reads from |fd| and prints received data. If |use_shell_protocol| is true
// this expects that incoming data will use the shell protocol, in which case
// stdout/stderr are routed independently and the remote exit code will be
// returned.
// if |callback| is non-null, stdout/stderr output will be handled by it.
int read_and_dump(int fd, bool use_shell_protocol = false,
StandardStreamsCallbackInterface* callback = &DEFAULT_STANDARD_STREAMS_CALLBACK) {
int exit_code = 0;
if (fd < 0) return exit_code;
std::unique_ptr<ShellProtocol> protocol;
int length = 0;
char raw_buffer[BUFSIZ];
char* buffer_ptr = raw_buffer;
if (use_shell_protocol) {
protocol.reset(new ShellProtocol(fd));
if (!protocol) {
LOG(ERROR) << "failed to allocate memory for ShellProtocol object";
return 1;
}
buffer_ptr = protocol->data();
}
while (true) {
if (use_shell_protocol) {
if (!protocol->Read()) {
break;
}
length = protocol->data_length();
switch (protocol->id()) {
case ShellProtocol::kIdStdout:
callback->OnStdout(buffer_ptr, length);
break;
case ShellProtocol::kIdStderr:
callback->OnStderr(buffer_ptr, length);
break;
case ShellProtocol::kIdExit:
exit_code = protocol->data()[0];
continue;
default:
continue;
}
length = protocol->data_length();
} else {
D("read_and_dump(): pre adb_read(fd=%d)", fd);
length = adb_read(fd, raw_buffer, sizeof(raw_buffer));
D("read_and_dump(): post adb_read(fd=%d): length=%d", fd, length);
if (length <= 0) {
break;
}
callback->OnStdout(buffer_ptr, length);
}
}
return callback->Done(exit_code);
}
static void read_status_line(int fd, char* buf, size_t count)
{
count--;
while (count > 0) {
int len = adb_read(fd, buf, count);
if (len <= 0) {
break;
}
buf += len;
count -= len;
}
*buf = '\0';
}
static void stdinout_raw_prologue(int inFd, int outFd, int& old_stdin_mode, int& old_stdout_mode) {
if (inFd == STDIN_FILENO) {
stdin_raw_init();
#ifdef _WIN32
old_stdin_mode = _setmode(STDIN_FILENO, _O_BINARY);
if (old_stdin_mode == -1) {
fatal_errno("could not set stdin to binary");
}
#endif
}
#ifdef _WIN32
if (outFd == STDOUT_FILENO) {
old_stdout_mode = _setmode(STDOUT_FILENO, _O_BINARY);
if (old_stdout_mode == -1) {
fatal_errno("could not set stdout to binary");
}
}
#endif
}
static void stdinout_raw_epilogue(int inFd, int outFd, int old_stdin_mode, int old_stdout_mode) {
if (inFd == STDIN_FILENO) {
stdin_raw_restore();
#ifdef _WIN32
if (_setmode(STDIN_FILENO, old_stdin_mode) == -1) {
fatal_errno("could not restore stdin mode");
}
#endif
}
#ifdef _WIN32
if (outFd == STDOUT_FILENO) {
if (_setmode(STDOUT_FILENO, old_stdout_mode) == -1) {
fatal_errno("could not restore stdout mode");
}
}
#endif
}
static void copy_to_file(int inFd, int outFd) {
const size_t BUFSIZE = 32 * 1024;
char* buf = (char*) malloc(BUFSIZE);
if (buf == nullptr) fatal("couldn't allocate buffer for copy_to_file");
int len;
long total = 0;
int old_stdin_mode = -1;
int old_stdout_mode = -1;
D("copy_to_file(%d -> %d)", inFd, outFd);
stdinout_raw_prologue(inFd, outFd, old_stdin_mode, old_stdout_mode);
while (true) {
if (inFd == STDIN_FILENO) {
len = unix_read(inFd, buf, BUFSIZE);
} else {
len = adb_read(inFd, buf, BUFSIZE);
}
if (len == 0) {
D("copy_to_file() : read 0 bytes; exiting");
break;
}
if (len < 0) {
D("copy_to_file(): read failed: %s", strerror(errno));
break;
}
if (outFd == STDOUT_FILENO) {
fwrite(buf, 1, len, stdout);
fflush(stdout);
} else {
adb_write(outFd, buf, len);
}
total += len;
}
stdinout_raw_epilogue(inFd, outFd, old_stdin_mode, old_stdout_mode);
D("copy_to_file() finished after %lu bytes", total);
free(buf);
}
static void send_window_size_change(int fd, std::unique_ptr<ShellProtocol>& shell) {
// Old devices can't handle window size changes.
if (shell == nullptr) return;
#if defined(_WIN32)
struct winsize {
unsigned short ws_row;
unsigned short ws_col;
unsigned short ws_xpixel;
unsigned short ws_ypixel;
};
#endif
winsize ws;
#if defined(_WIN32)
// If stdout is redirected to a non-console, we won't be able to get the
// console size, but that makes sense.
const intptr_t intptr_handle = _get_osfhandle(STDOUT_FILENO);
if (intptr_handle == -1) return;
const HANDLE handle = reinterpret_cast<const HANDLE>(intptr_handle);
CONSOLE_SCREEN_BUFFER_INFO info;
memset(&info, 0, sizeof(info));
if (!GetConsoleScreenBufferInfo(handle, &info)) return;
memset(&ws, 0, sizeof(ws));
// The number of visible rows, excluding offscreen scroll-back rows which are in info.dwSize.Y.
ws.ws_row = info.srWindow.Bottom - info.srWindow.Top + 1;
// If the user has disabled "Wrap text output on resize", they can make the screen buffer wider
// than the window, in which case we should use the width of the buffer.
ws.ws_col = info.dwSize.X;
#else
if (ioctl(fd, TIOCGWINSZ, &ws) == -1) return;
#endif
// Send the new window size as human-readable ASCII for debugging convenience.
size_t l = snprintf(shell->data(), shell->data_capacity(), "%dx%d,%dx%d",
ws.ws_row, ws.ws_col, ws.ws_xpixel, ws.ws_ypixel);
shell->Write(ShellProtocol::kIdWindowSizeChange, l + 1);
}
// Used to pass multiple values to the stdin read thread.
struct StdinReadArgs {
int stdin_fd, write_fd;
bool raw_stdin;
std::unique_ptr<ShellProtocol> protocol;
char escape_char;
};
// Loops to read from stdin and push the data to the given FD.
// The argument should be a pointer to a StdinReadArgs object. This function
// will take ownership of the object and delete it when finished.
static void stdin_read_thread_loop(void* x) {
std::unique_ptr<StdinReadArgs> args(reinterpret_cast<StdinReadArgs*>(x));
#if !defined(_WIN32)
// Mask SIGTTIN in case we're in a backgrounded process.
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGTTIN);
pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
#endif
#if defined(_WIN32)
// _get_interesting_input_record_uncached() causes unix_read_interruptible()
// to return -1 with errno == EINTR if the window size changes.
#else
// Unblock SIGWINCH for this thread, so our read(2) below will be
// interrupted if the window size changes.
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGWINCH);
pthread_sigmask(SIG_UNBLOCK, &mask, nullptr);
#endif
// Set up the initial window size.
send_window_size_change(args->stdin_fd, args->protocol);
char raw_buffer[BUFSIZ];
char* buffer_ptr = raw_buffer;
size_t buffer_size = sizeof(raw_buffer);
if (args->protocol != nullptr) {
buffer_ptr = args->protocol->data();
buffer_size = args->protocol->data_capacity();
}
// If we need to parse escape sequences, make life easy.
if (args->raw_stdin && args->escape_char != '\0') {
buffer_size = 1;
}
enum EscapeState { kMidFlow, kStartOfLine, kInEscape };
EscapeState state = kStartOfLine;
while (true) {
// Use unix_read_interruptible() rather than adb_read() for stdin.
D("stdin_read_thread_loop(): pre unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
int r = unix_read_interruptible(args->stdin_fd, buffer_ptr,
buffer_size);
if (r == -1 && errno == EINTR) {
send_window_size_change(args->stdin_fd, args->protocol);
continue;
}
D("stdin_read_thread_loop(): post unix_read_interruptible(fdi=%d,...)", args->stdin_fd);
if (r <= 0) {
// Only devices using the shell protocol know to close subprocess
// stdin. For older devices we want to just leave the connection
// open, otherwise an unpredictable amount of return data could
// be lost due to the FD closing before all data has been received.
if (args->protocol) {
args->protocol->Write(ShellProtocol::kIdCloseStdin, 0);
}
break;
}
// If we made stdin raw, check input for escape sequences. In
// this situation signals like Ctrl+C are sent remotely rather than
// interpreted locally so this provides an emergency out if the remote
// process starts ignoring the signal. SSH also does this, see the
// "escape characters" section on the ssh man page for more info.
if (args->raw_stdin && args->escape_char != '\0') {
char ch = buffer_ptr[0];
if (ch == args->escape_char) {
if (state == kStartOfLine) {
state = kInEscape;
// Swallow the escape character.
continue;
} else {
state = kMidFlow;
}
} else {
if (state == kInEscape) {
if (ch == '.') {
fprintf(stderr,"\r\n[ disconnected ]\r\n");
stdin_raw_restore();
exit(0);
} else {
// We swallowed an escape character that wasn't part of
// a valid escape sequence; time to cough it up.
buffer_ptr[0] = args->escape_char;
buffer_ptr[1] = ch;
++r;
}
}
state = (ch == '\n' || ch == '\r') ? kStartOfLine : kMidFlow;
}
}
if (args->protocol) {
if (!args->protocol->Write(ShellProtocol::kIdStdin, r)) {
break;
}
} else {
if (!WriteFdExactly(args->write_fd, buffer_ptr, r)) {
break;
}
}
}
}
// Returns a shell service string with the indicated arguments and command.
static std::string ShellServiceString(bool use_shell_protocol,
const std::string& type_arg,
const std::string& command) {
std::vector<std::string> args;
if (use_shell_protocol) {
args.push_back(kShellServiceArgShellProtocol);
const char* terminal_type = getenv("TERM");
if (terminal_type != nullptr) {
args.push_back(std::string("TERM=") + terminal_type);
}
}
if (!type_arg.empty()) {
args.push_back(type_arg);
}
// Shell service string can look like: shell[,arg1,arg2,...]:[command].
return android::base::StringPrintf("shell%s%s:%s",
args.empty() ? "" : ",",
android::base::Join(args, ',').c_str(),
command.c_str());
}
// Connects to a shell on the device and read/writes data.
//
// Note: currently this function doesn't properly clean up resources; the
// FD connected to the adb server is never closed and the stdin read thread
// may never exit.
//
// On success returns the remote exit code if |use_shell_protocol| is true,
// 0 otherwise. On failure returns 1.
static int RemoteShell(bool use_shell_protocol, const std::string& type_arg,
char escape_char,
const std::string& command) {
std::string service_string = ShellServiceString(use_shell_protocol,
type_arg, command);
// Make local stdin raw if the device allocates a PTY, which happens if:
// 1. We are explicitly asking for a PTY shell, or
// 2. We don't specify shell type and are starting an interactive session.
bool raw_stdin = (type_arg == kShellServiceArgPty ||
(type_arg.empty() && command.empty()));
std::string error;
int fd = adb_connect(service_string, &error);
if (fd < 0) {
fprintf(stderr,"error: %s\n", error.c_str());
return 1;
}
StdinReadArgs* args = new StdinReadArgs;
if (!args) {
LOG(ERROR) << "couldn't allocate StdinReadArgs object";
return 1;
}
args->stdin_fd = STDIN_FILENO;
args->write_fd = fd;
args->raw_stdin = raw_stdin;
args->escape_char = escape_char;
if (use_shell_protocol) {
args->protocol.reset(new ShellProtocol(args->write_fd));
}
if (raw_stdin) stdin_raw_init();
#if !defined(_WIN32)
// Ensure our process is notified if the local window size changes.
// We use sigaction(2) to ensure that the SA_RESTART flag is not set,
// because the whole reason we're sending signals is to unblock the read(2)!
// That also means we don't need to do anything in the signal handler:
// the side effect of delivering the signal is all we need.
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = [](int) {};
sa.sa_flags = 0;
sigaction(SIGWINCH, &sa, nullptr);
// Now block SIGWINCH in this thread (the main thread) and all threads spawned
// from it. The stdin read thread will unblock this signal to ensure that it's
// the thread that receives the signal.
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGWINCH);
pthread_sigmask(SIG_BLOCK, &mask, nullptr);
#endif
// TODO: combine read_and_dump with stdin_read_thread to make life simpler?
int exit_code = 1;
if (!adb_thread_create(stdin_read_thread_loop, args)) {
PLOG(ERROR) << "error starting stdin read thread";
delete args;
} else {
exit_code = read_and_dump(fd, use_shell_protocol);
}
// TODO: properly exit stdin_read_thread_loop and close |fd|.
// TODO: we should probably install signal handlers for this.
// TODO: can we use atexit? even on Windows?
if (raw_stdin) stdin_raw_restore();
return exit_code;
}
static int adb_shell(int argc, const char** argv) {
FeatureSet features;
std::string error;
if (!adb_get_feature_set(&features, &error)) {
fprintf(stderr, "error: %s\n", error.c_str());
return 1;
}
bool use_shell_protocol = CanUseFeature(features, kFeatureShell2);
if (!use_shell_protocol) {
D("shell protocol not supported, using raw data transfer");
} else {
D("using shell protocol");
}
// Parse shell-specific command-line options.
// argv[0] is always "shell".
--argc;
++argv;
int t_arg_count = 0;
char escape_char = '~';
while (argc) {
if (!strcmp(argv[0], "-e")) {
if (argc < 2 || !(strlen(argv[1]) == 1 || strcmp(argv[1], "none") == 0)) {
fprintf(stderr, "error: -e requires a single-character argument or 'none'\n");
return 1;
}
escape_char = (strcmp(argv[1], "none") == 0) ? 0 : argv[1][0];
argc -= 2;
argv += 2;
} else if (!strcmp(argv[0], "-T") || !strcmp(argv[0], "-t")) {
// Like ssh, -t arguments are cumulative so that multiple -t's
// are needed to force a PTY.
if (argv[0][1] == 't') {
++t_arg_count;
} else {
t_arg_count = -1;
}
--argc;
++argv;
} else if (!strcmp(argv[0], "-x")) {
use_shell_protocol = false;
--argc;
++argv;
} else if (!strcmp(argv[0], "-n")) {
close_stdin();
--argc;
++argv;
} else {
break;
}
}
// Legacy shell protocol requires a remote PTY to close the subprocess properly which creates
// some weird interactions with -tT.
if (!use_shell_protocol && t_arg_count != 0) {
if (!CanUseFeature(features, kFeatureShell2)) {
fprintf(stderr, "error: target doesn't support PTY args -Tt\n");
} else {
fprintf(stderr, "error: PTY args -Tt cannot be used with -x\n");
}
return 1;
}
std::string shell_type_arg;
if (CanUseFeature(features, kFeatureShell2)) {
if (t_arg_count < 0) {
shell_type_arg = kShellServiceArgRaw;
} else if (t_arg_count == 0) {
// If stdin isn't a TTY, default to a raw shell; this lets
// things like `adb shell < my_script.sh` work as expected.
// Otherwise leave |shell_type_arg| blank which uses PTY for
// interactive shells and raw for non-interactive.
if (!unix_isatty(STDIN_FILENO)) {
shell_type_arg = kShellServiceArgRaw;
}
} else if (t_arg_count == 1) {
// A single -t arg isn't enough to override implicit -T.
if (!unix_isatty(STDIN_FILENO)) {
fprintf(stderr,
"Remote PTY will not be allocated because stdin is not a terminal.\n"
"Use multiple -t options to force remote PTY allocation.\n");
shell_type_arg = kShellServiceArgRaw;
} else {
shell_type_arg = kShellServiceArgPty;
}
} else {
shell_type_arg = kShellServiceArgPty;
}
}
std::string command;
if (argc) {
// We don't escape here, just like ssh(1). http://b/20564385.
command = android::base::Join(std::vector<const char*>(argv, argv + argc), ' ');
}
return RemoteShell(use_shell_protocol, shell_type_arg, escape_char, command);
}
static int adb_download_buffer(const char *service, const char *fn, const void* data, unsigned sz,
bool show_progress)
{
std::string error;
int fd = adb_connect(android::base::StringPrintf("%s:%d", service, sz), &error);
if (fd < 0) {
fprintf(stderr,"error: %s\n", error.c_str());
return -1;
}
int opt = CHUNK_SIZE;
opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
unsigned total = sz;
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data);
if (show_progress) {
const char* x = strrchr(service, ':');
if (x) service = x + 1;
}
while (sz > 0) {
unsigned xfer = (sz > CHUNK_SIZE) ? CHUNK_SIZE : sz;
if (!WriteFdExactly(fd, ptr, xfer)) {
std::string error;
adb_status(fd, &error);
fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
adb_close(fd);
return -1;
}
sz -= xfer;
ptr += xfer;
if (show_progress) {
printf("sending: '%s' %4d%% \r", fn, (int)(100LL - ((100LL * sz) / (total))));
fflush(stdout);
}
}
if (show_progress) {
printf("\n");
}
if (!adb_status(fd, &error)) {
fprintf(stderr,"* error response '%s' *\n", error.c_str());
adb_close(fd);
return -1;
}
adb_close(fd);
return 0;
}
#define SIDELOAD_HOST_BLOCK_SIZE (CHUNK_SIZE)
/*
* The sideload-host protocol serves the data in a file (given on the
* command line) to the client, using a simple protocol:
*
* - The connect message includes the total number of bytes in the
* file and a block size chosen by us.
*
* - The other side sends the desired block number as eight decimal
* digits (eg "00000023" for block 23). Blocks are numbered from
* zero.
*
* - We send back the data of the requested block. The last block is
* likely to be partial; when the last block is requested we only
* send the part of the block that exists, it's not padded up to the
* block size.
*
* - When the other side sends "DONEDONE" instead of a block number,
* we hang up.
*/
static int adb_sideload_host(const char* fn) {
unsigned sz;
size_t xfer = 0;
int status;
int last_percent = -1;
int opt = SIDELOAD_HOST_BLOCK_SIZE;
printf("loading: '%s'", fn);
fflush(stdout);
uint8_t* data = reinterpret_cast<uint8_t*>(load_file(fn, &sz));
if (data == 0) {
printf("\n");
fprintf(stderr, "* cannot read '%s' *\n", fn);
return -1;
}
std::string service =
android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE);
std::string error;
int fd = adb_connect(service, &error);
if (fd < 0) {
// Try falling back to the older sideload method. Maybe this
// is an older device that doesn't support sideload-host.
printf("\n");
status = adb_download_buffer("sideload", fn, data, sz, true);
goto done;
}
opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
while (true) {
char buf[9];
if (!ReadFdExactly(fd, buf, 8)) {
fprintf(stderr, "* failed to read command: %s\n", strerror(errno));
status = -1;
goto done;
}
buf[8] = '\0';
if (strcmp("DONEDONE", buf) == 0) {
status = 0;
break;
}
int block = strtol(buf, NULL, 10);
size_t offset = block * SIDELOAD_HOST_BLOCK_SIZE;
if (offset >= sz) {
fprintf(stderr, "* attempt to read block %d past end\n", block);
status = -1;
goto done;
}
uint8_t* start = data + offset;
size_t offset_end = offset + SIDELOAD_HOST_BLOCK_SIZE;
size_t to_write = SIDELOAD_HOST_BLOCK_SIZE;
if (offset_end > sz) {
to_write = sz - offset;
}
if(!WriteFdExactly(fd, start, to_write)) {
adb_status(fd, &error);
fprintf(stderr,"* failed to write data '%s' *\n", error.c_str());
status = -1;
goto done;
}
xfer += to_write;
// For normal OTA packages, we expect to transfer every byte
// twice, plus a bit of overhead (one read during
// verification, one read of each byte for installation, plus
// extra access to things like the zip central directory).
// This estimate of the completion becomes 100% when we've
// transferred ~2.13 (=100/47) times the package size.
int percent = (int)(xfer * 47LL / (sz ? sz : 1));
if (percent != last_percent) {
printf("\rserving: '%s' (~%d%%) ", fn, percent);
fflush(stdout);
last_percent = percent;
}
}
printf("\rTotal xfer: %.2fx%*s\n", (double)xfer / (sz ? sz : 1), (int)strlen(fn)+10, "");
done:
if (fd >= 0) adb_close(fd);
free(data);
return status;
}
/**
* Run ppp in "notty" mode against a resource listed as the first parameter
* eg:
*
* ppp dev:/dev/omap_csmi_tty0 <ppp options>
*
*/
static int ppp(int argc, const char** argv) {
#if defined(_WIN32)
fprintf(stderr, "error: adb %s not implemented on Win32\n", argv[0]);
return -1;
#else
if (argc < 2) {
fprintf(stderr, "usage: adb %s <adb service name> [ppp opts]\n",
argv[0]);
return 1;
}
const char* adb_service_name = argv[1];
std::string error;
int fd = adb_connect(adb_service_name, &error);
if (fd < 0) {
fprintf(stderr,"Error: Could not open adb service: %s. Error: %s\n",