This repository has been archived by the owner on Dec 3, 2019. It is now read-only.
mirrored from https://chromium.googlesource.com/catapult
-
Notifications
You must be signed in to change notification settings - Fork 564
/
device_utils.py
4019 lines (3495 loc) · 148 KB
/
device_utils.py
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 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides a variety of device interactions based on adb."""
# pylint: disable=unused-argument
import calendar
import collections
import contextlib
import fnmatch
import json
import logging
import math
import os
import posixpath
import pprint
import random
import re
import shutil
import stat
import sys
import tempfile
import time
import threading
import uuid
import six
from devil import base_error
from devil import devil_env
from devil.utils import cmd_helper
from devil.android import apk_helper
from devil.android import device_signal
from devil.android import decorators
from devil.android import device_errors
from devil.android import device_temp_file
from devil.android import install_commands
from devil.android import logcat_monitor
from devil.android import md5sum
from devil.android.sdk import adb_wrapper
from devil.android.sdk import intent
from devil.android.sdk import keyevent
from devil.android.sdk import version_codes
from devil.utils import host_utils
from devil.utils import parallelizer
from devil.utils import reraiser_thread
from devil.utils import timeout_retry
from devil.utils import zip_utils
with devil_env.SysPath(devil_env.PY_UTILS_PATH):
from py_utils import tempfile_ext
try:
from devil.utils import reset_usb
except ImportError:
# Fail silently if we can't import reset_usb. We're likely on windows.
reset_usb = None
logger = logging.getLogger(__name__)
_DEFAULT_TIMEOUT = 30
_DEFAULT_RETRIES = 3
# TODO(agrieve): Would be better to make this timeout based off of data size.
# Needs to be large for remote devices & speed depends on internet connection.
# Debug Chrome builds can be 200mb+.
_FILE_TRANSFER_TIMEOUT = 7 * 60
# A sentinel object for default values
# TODO(jbudorick): revisit how default values are handled by
# the timeout_retry decorators.
DEFAULT = object()
# A sentinel object to require that calls to RunShellCommand force running the
# command with su even if the device has been rooted. To use, pass into the
# as_root param.
_FORCE_SU = object()
# Lists all files for the specified directories.
# In order to minimize data transfer, prints directories as absolute paths
# followed by files within that directory without their path.
_FILE_LIST_SCRIPT = """
function list_files() {
for f in "$1"/{.,}*
do
if [ "$f" == "." ] || [ "$f" == ".." ] || [ "$f" == "${1}/.*" ] \
|| [ "$f" == "${1}/*" ]
then
continue
fi
base=${f##*/} # Get the basename for the file, dropping the path.
echo "$base"
done
}
for dir in %s
do
if [ -d "$dir" ]; then
echo "$dir"
list_files "$dir"
fi
done
"""
_RESTART_ADBD_SCRIPT = """
trap '' HUP
trap '' TERM
trap '' PIPE
function restart() {
stop adbd
start adbd
}
restart &
"""
_UNZIP_AND_CHMOD_SCRIPT = """
{bin_dir}/unzip {zip_file} && (for dir in {dirs}
do
chmod -R 777 "$dir" || exit 1
done)
"""
# Not all permissions can be set.
_PERMISSIONS_DENYLIST_RE = re.compile('|'.join(
fnmatch.translate(p) for p in [
'android.permission.ACCESS_LOCATION_EXTRA_COMMANDS',
'android.permission.ACCESS_MOCK_LOCATION',
'android.permission.ACCESS_NETWORK_STATE',
'android.permission.ACCESS_NOTIFICATION_POLICY',
'android.permission.ACCESS_VR_STATE',
'android.permission.ACCESS_WIFI_STATE',
'android.permission.AUTHENTICATE_ACCOUNTS',
'android.permission.BLUETOOTH',
'android.permission.BLUETOOTH_ADMIN',
'android.permission.BROADCAST_STICKY',
'android.permission.CHANGE_NETWORK_STATE',
'android.permission.CHANGE_WIFI_MULTICAST_STATE',
'android.permission.CHANGE_WIFI_STATE',
'android.permission.DISABLE_KEYGUARD',
'android.permission.DOWNLOAD_WITHOUT_NOTIFICATION',
'android.permission.EXPAND_STATUS_BAR',
'android.permission.FOREGROUND_SERVICE',
'android.permission.GET_PACKAGE_SIZE',
'android.permission.INSTALL_SHORTCUT',
'android.permission.INJECT_EVENTS',
'android.permission.INTERNET',
'android.permission.KILL_BACKGROUND_PROCESSES',
'android.permission.MANAGE_ACCOUNTS',
'android.permission.MANAGE_EXTERNAL_STORAGE',
'android.permission.MODIFY_AUDIO_SETTINGS',
'android.permission.NFC',
'android.permission.QUERY_ALL_PACKAGES',
'android.permission.READ_SYNC_SETTINGS',
'android.permission.READ_SYNC_STATS',
'android.permission.RECEIVE_BOOT_COMPLETED',
'android.permission.RECORD_VIDEO',
'android.permission.REORDER_TASKS',
'android.permission.REQUEST_INSTALL_PACKAGES',
'android.permission.RESTRICTED_VR_ACCESS',
'android.permission.RUN_INSTRUMENTATION',
'android.permission.SET_ALARM',
'android.permission.SET_TIME_ZONE',
'android.permission.SET_WALLPAPER',
'android.permission.SET_WALLPAPER_HINTS',
'android.permission.TRANSMIT_IR',
'android.permission.USE_CREDENTIALS',
'android.permission.USE_FINGERPRINT',
'android.permission.VIBRATE',
'android.permission.WAKE_LOCK',
'android.permission.WRITE_SYNC_SETTINGS',
'com.android.browser.permission.READ_HISTORY_BOOKMARKS',
'com.android.browser.permission.WRITE_HISTORY_BOOKMARKS',
'com.android.launcher.permission.INSTALL_SHORTCUT',
'com.chrome.permission.DEVICE_EXTRAS',
'com.google.android.apps.now.CURRENT_ACCOUNT_ACCESS',
'com.google.android.c2dm.permission.RECEIVE',
'com.google.android.providers.gsf.permission.READ_GSERVICES',
'com.google.vr.vrcore.permission.VRCORE_INTERNAL',
'com.sec.enterprise.knox.MDM_CONTENT_PROVIDER',
'*.permission.C2D_MESSAGE',
'*.permission.READ_WRITE_BOOKMARK_FOLDERS',
'*.TOS_ACKED',
]))
_SHELL_OUTPUT_SEPARATOR = '~X~'
_PERMISSIONS_EXCEPTION_RE = re.compile(r'java\.lang\.\w+Exception: .*$',
re.MULTILINE)
_CURRENT_FOCUS_CRASH_RE = re.compile(
r'\s*mCurrentFocus.*Application (Error|Not Responding): (\S+)}')
_GETPROP_RE = re.compile(r'\[(.*?)\]: \[(.*?)\]')
_VERSION_CODE_SDK_RE = re.compile(
r'\s*versionCode=(\d+).*minSdk=(\d+).*targetSdk=(.*)\s*')
_USER_ID_RE = re.compile(r'.*userId=')
# Regex to parse the long (-l) output of 'ls' command, c.f.
# https://github.com/landley/toybox/blob/master/toys/posix/ls.c#L446
# yapf: disable
_LONG_LS_OUTPUT_RE = re.compile(
r'(?P<st_mode>[\w-]{10})\s+' # File permissions
r'(?:(?P<st_nlink>\d+)\s+)?' # Number of links (optional)
r'(?P<st_owner>\w+)\s+' # Name of owner
r'(?P<st_group>\w+)\s+' # Group of owner
r'(?:' # Either ...
r'(?P<st_rdev_major>\d+),\s+' # Device major, and
r'(?P<st_rdev_minor>\d+)\s+' # Device minor
r'|' # .. or
r'(?P<st_size>\d+)\s+' # Size in bytes
r')?' # .. or nothing
r'(?P<st_mtime>\d{4}-\d\d-\d\d \d\d:\d\d)\s+' # Modification date/time
r'(?P<filename>.+?)' # File name
r'(?: -> (?P<symbolic_link_to>.+))?' # Symbolic link (optional)
r'$' # End of string
)
# yapf: enable
_LS_DATE_FORMAT = '%Y-%m-%d %H:%M'
_FILE_MODE_RE = re.compile(r'[dbclps-](?:[r-][w-][xSs-]){2}[r-][w-][xTt-]$')
_FILE_MODE_KIND = {
'd': stat.S_IFDIR,
'b': stat.S_IFBLK,
'c': stat.S_IFCHR,
'l': stat.S_IFLNK,
'p': stat.S_IFIFO,
's': stat.S_IFSOCK,
'-': stat.S_IFREG
}
_FILE_MODE_PERMS = [
stat.S_IRUSR,
stat.S_IWUSR,
stat.S_IXUSR,
stat.S_IRGRP,
stat.S_IWGRP,
stat.S_IXGRP,
stat.S_IROTH,
stat.S_IWOTH,
stat.S_IXOTH,
]
_FILE_MODE_SPECIAL = [
('s', stat.S_ISUID),
('s', stat.S_ISGID),
('t', stat.S_ISVTX),
]
_PS_COLUMNS = {'pid': 1, 'ppid': 2, 'name': -1}
_SELINUX_MODE = {'enforcing': True, 'permissive': False, 'disabled': None}
# Some devices require different logic for checking if root is necessary
_SPECIAL_ROOT_DEVICE_LIST = [
'marlin', # Pixel XL
'sailfish', # Pixel
'taimen', # Pixel 2 XL
'vega', # Lenovo Mirage Solo
'walleye', # Pixel 2
'crosshatch', # Pixel 3 XL
'blueline', # Pixel 3
'sargo', # Pixel 3a
'bonito', # Pixel 3a XL
'sdk_goog3_x86', # Crow emulator
]
_SPECIAL_ROOT_DEVICE_LIST += [
'aosp_%s' % _d for _d in _SPECIAL_ROOT_DEVICE_LIST
]
# Somce devices are slow/timeout when using default install.
# Devices listed here will perform no_streaming app installation.
_NO_STREAMING_DEVICE_LIST = [
'flounder', # Nexus 9
'volantis', # Another product name for Nexus 9
]
_IMEI_RE = re.compile(r' Device ID = (.+)$')
# The following regex is used to match result parcels like:
"""
Result: Parcel(
0x00000000: 00000000 0000000f 00350033 00360033 '........3.5.3.6.'
0x00000010: 00360032 00370030 00300032 00300039 '2.6.0.7.2.0.9.0.'
0x00000020: 00380033 00000039 '3.8.9... ')
"""
_PARCEL_RESULT_RE = re.compile(
r'0x[0-9a-f]{8}\: (?:[0-9a-f]{8}\s+){1,4}\'(.{16})\'')
# http://bit.ly/2WLZhUF added a timeout to adb wait-for-device. We sometimes
# want to wait longer than the implicit call within adb root allows.
_WAIT_FOR_DEVICE_TIMEOUT_STR = 'timeout expired while waiting for device'
_WEBVIEW_SYSUPDATE_CURRENT_PKG_RE = re.compile(
r'Current WebView package.*:.*\(([a-z.]*),')
_WEBVIEW_SYSUPDATE_NULL_PKG_RE = re.compile(r'Current WebView package is null')
_WEBVIEW_SYSUPDATE_FALLBACK_LOGIC_RE = re.compile(
r'Fallback logic enabled: (true|false)')
_WEBVIEW_SYSUPDATE_PACKAGE_INSTALLED_RE = re.compile(
r'(?:Valid|Invalid) package\s+(\S+)\s+\(.*\),?\s+(.*)$')
_WEBVIEW_SYSUPDATE_PACKAGE_NOT_INSTALLED_RE = re.compile(
r'(\S+)\s+(is NOT installed\.)')
_WEBVIEW_SYSUPDATE_MIN_VERSION_CODE = re.compile(
r'Minimum WebView version code: (\d+)')
_GOOGLE_FEATURES_RE = re.compile(r'^\s*com\.google\.')
_EMULATOR_RE = re.compile(r'^generic_.*$')
# Regular expressions for determining if a package is installed using the
# output of `dumpsys package`.
# Matches lines like "Package [com.google.android.youtube] (c491050):".
# or "Package [org.chromium.trichromelibrary_425300033] (e476383):"
_DUMPSYS_PACKAGE_RE_STR =\
r'^\s*Package\s*\[%s(_(?P<version_code>\d*))?\]\s*\(\w*\):$'
PS_COLUMNS = ('name', 'pid', 'ppid')
ProcessInfo = collections.namedtuple('ProcessInfo', PS_COLUMNS)
# The list of Rock960 device family.
ROCK960_DEVICE_LIST = [
'rk3399', 'rk3399-all', 'rk3399-box'
]
@decorators.WithExplicitTimeoutAndRetries(_DEFAULT_TIMEOUT, _DEFAULT_RETRIES)
def GetAVDs():
"""Returns a list of Android Virtual Devices.
Returns:
A list containing the configured AVDs.
"""
lines = cmd_helper.GetCmdOutput([
os.path.join(
devil_env.config.LocalPath('android_sdk'), 'tools', 'android'),
'list', 'avd'
]).splitlines()
avds = []
for line in lines:
if 'Name:' not in line:
continue
key, value = (s.strip() for s in line.split(':', 1))
if key == 'Name':
avds.append(value)
return avds
def _ParseModeString(mode_str):
"""Parse a mode string, e.g. 'drwxrwxrwx', into a st_mode value.
Effectively the reverse of |mode_to_string| in, e.g.:
https://github.com/landley/toybox/blob/master/lib/lib.c#L896
"""
if not _FILE_MODE_RE.match(mode_str):
raise ValueError('Unexpected file mode %r', mode_str)
mode = _FILE_MODE_KIND[mode_str[0]]
for c, flag in zip(mode_str[1:], _FILE_MODE_PERMS):
if c != '-' and c.islower():
mode |= flag
for c, (t, flag) in zip(mode_str[3::3], _FILE_MODE_SPECIAL):
if c.lower() == t:
mode |= flag
return mode
def _GetTimeStamp():
"""Return a basic ISO 8601 time stamp with the current local time."""
return time.strftime('%Y%m%dT%H%M%S', time.localtime())
def _JoinLines(lines):
# makes sure that the last line is also terminated, and is more memory
# efficient than first appending an end-line to each line and then joining
# all of them together.
return ''.join(s for line in lines for s in (line, '\n'))
def _CreateAdbWrapper(device):
if isinstance(device, adb_wrapper.AdbWrapper):
return device
else:
return adb_wrapper.AdbWrapper(device)
def _FormatPartialOutputError(output):
lines = output.splitlines() \
if isinstance(output, six.string_types) else output
message = ['Partial output found:']
if len(lines) > 11:
message.extend('- %s' % line for line in lines[:5])
message.extend('<snip>')
message.extend('- %s' % line for line in lines[-5:])
else:
message.extend('- %s' % line for line in lines)
return '\n'.join(message)
_PushableComponents = collections.namedtuple('_PushableComponents',
('host', 'device', 'collapse'))
def _IterPushableComponents(host_path, device_path):
"""Yields a sequence of paths that can be pushed directly via adb push.
`adb push` doesn't currently handle pushing directories that contain
symlinks: https://bit.ly/2pMBlW5
To circumvent this issue, we get the smallest set of files and/or
directories that can be pushed without attempting to push a directory
that contains a symlink.
This function does so by recursing through |host_path|. Each call
yields 3-tuples that include the smallest set of (host, device) path pairs
that can be passed to adb push and a bool indicating whether the parent
directory can be pushed -- i.e., if True, the host path is neither a
symlink nor a directory that contains a symlink.
Args:
host_path: an absolute path of a file or directory on the host
device_path: an absolute path of a file or directory on the device
Yields:
3-tuples containing
host (str): the host path, with symlinks dereferenced
device (str): the device path
collapse (bool): whether this entity permits its parent to be pushed
in its entirety. (Parents need permission from all child entities
in order to be pushed in their entirety.)
"""
if os.path.isfile(host_path):
yield _PushableComponents(
os.path.realpath(host_path), device_path, not os.path.islink(host_path))
else:
components = []
for child in os.listdir(host_path):
components.extend(
_IterPushableComponents(
os.path.join(host_path, child), posixpath.join(
device_path, child)))
if all(c.collapse for c in components):
yield _PushableComponents(
os.path.realpath(host_path), device_path,
not os.path.islink(host_path))
else:
for c in components:
yield c
class DeviceUtils(object):
_MAX_ADB_COMMAND_LENGTH = 512
_MAX_ADB_OUTPUT_LENGTH = 32768
_RESUMED_LAUNCHER_ACTIVITY_RE = re.compile(
r'\s*mResumedActivity.*(Launcher|launcher).*')
_VALID_SHELL_VARIABLE = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$')
LOCAL_PROPERTIES_PATH = posixpath.join('/', 'data', 'local.prop')
# Property in /data/local.prop that controls Java assertions.
JAVA_ASSERT_PROPERTY = 'dalvik.vm.enableassertions'
def __init__(self,
device,
enable_device_files_cache=False,
default_timeout=_DEFAULT_TIMEOUT,
default_retries=_DEFAULT_RETRIES):
"""DeviceUtils constructor.
Args:
device: Either a device serial, an existing AdbWrapper instance, or an
an existing AndroidCommands instance.
enable_device_files_cache: For PushChangedFiles(), cache checksums of
pushed files rather than recomputing them on a subsequent call.
default_timeout: An integer containing the default number of seconds to
wait for an operation to complete if no explicit value is provided.
default_retries: An integer containing the default number or times an
operation should be retried on failure if no explicit value is provided.
"""
self.adb = None
if isinstance(device, six.string_types):
self.adb = _CreateAdbWrapper(device)
elif isinstance(device, adb_wrapper.AdbWrapper):
self.adb = device
else:
raise ValueError('Unsupported device value: %r' % device)
self._commands_installed = None
self._default_timeout = default_timeout
self._default_retries = default_retries
self._enable_device_files_cache = enable_device_files_cache
self._cache = {}
self._client_caches = {}
self._cache_lock = threading.RLock()
assert hasattr(self, decorators.DEFAULT_TIMEOUT_ATTR)
assert hasattr(self, decorators.DEFAULT_RETRIES_ATTR)
self.ClearCache()
@property
def serial(self):
"""Returns the device serial."""
return self.adb.GetDeviceSerial()
def __eq__(self, other):
"""Checks whether |other| refers to the same device as |self|.
Args:
other: The object to compare to. This can be a basestring, an instance
of adb_wrapper.AdbWrapper, or an instance of DeviceUtils.
Returns:
Whether |other| refers to the same device as |self|.
"""
return self.serial == str(other)
def __lt__(self, other):
"""Compares two instances of DeviceUtils.
This merely compares their serial numbers.
Args:
other: The instance of DeviceUtils to compare to.
Returns:
Whether |self| is less than |other|.
"""
return self.serial < other.serial
def __str__(self):
"""Returns the device serial."""
return self.serial
@decorators.WithTimeoutAndRetriesFromInstance()
def IsOnline(self, timeout=None, retries=None):
"""Checks whether the device is online.
Args:
timeout: timeout in seconds
retries: number of retries
Returns:
True if the device is online, False otherwise.
Raises:
CommandTimeoutError on timeout.
"""
try:
return self.adb.GetState() == 'device'
except base_error.BaseError as exc:
logger.info('Failed to get state: %s', exc, exc_info=True)
return False
@decorators.WithTimeoutAndRetriesFromInstance()
def HasRoot(self, timeout=None, retries=None):
"""Checks whether or not adbd has root privileges.
A device is considered to have root if all commands are implicitly run
with elevated privileges, i.e. without having to use "su" to run them.
Note that some devices do not allow this implicit privilige elevation,
but _can_ run commands as root just fine when done explicitly with "su".
To check if your device can run commands with elevated privileges at all
use:
device.HasRoot() or device.NeedsSU()
Luckily, for the most part you don't need to worry about this and using
RunShellCommand(cmd, as_root=True) will figure out for you the right
command incantation to run with elevated privileges.
Args:
timeout: timeout in seconds
retries: number of retries
Returns:
True if adbd has root privileges, False otherwise.
Raises:
CommandTimeoutError on timeout.
DeviceUnreachableError on missing device.
"""
if self.build_type == 'eng':
# 'eng' builds have root enabled by default and the adb session cannot
# be unrooted.
return True
# Check if uid is 0. Such behavior has remained unchanged since
# android 2.2.3 (https://bit.ly/2QQzg67)
output = self.RunShellCommand(['id'], single_line=True)
return output.startswith('uid=0(root)')
def NeedsSU(self, timeout=DEFAULT, retries=DEFAULT):
"""Checks whether 'su' is needed to access protected resources.
Args:
timeout: timeout in seconds
retries: number of retries
Returns:
True if 'su' is available on the device and is needed to to access
protected resources; False otherwise if either 'su' is not available
(e.g. because the device has a user build), or not needed (because adbd
already has root privileges).
Raises:
CommandTimeoutError on timeout.
DeviceUnreachableError on missing device.
"""
if 'needs_su' not in self._cache:
cmd = '%s && ! ls /root' % self._Su('ls /root')
# Devices using the system-as-root partition layout appear to not have
# a /root directory. See http://bit.ly/37F34sx for more context.
if (self.build_system_root_image == 'true'
or self.build_version_sdk >= version_codes.Q
# This may be redundant with the checks above.
or self.product_name in _SPECIAL_ROOT_DEVICE_LIST):
if self.HasRoot():
self._cache['needs_su'] = False
return False
cmd = 'which which && which su'
try:
self.RunShellCommand(
cmd,
shell=True,
check_return=True,
timeout=self._default_timeout if timeout is DEFAULT else timeout,
retries=self._default_retries if retries is DEFAULT else retries)
self._cache['needs_su'] = True
except device_errors.AdbCommandFailedError:
self._cache['needs_su'] = False
return self._cache['needs_su']
def _Su(self, command):
if self.build_version_sdk >= version_codes.MARSHMALLOW:
return 'su 0 %s' % command
return 'su -c %s' % command
@decorators.WithTimeoutAndRetriesFromInstance()
def EnableRoot(self, timeout=None, retries=None):
"""Restarts adbd with root privileges.
Args:
timeout: timeout in seconds
retries: number of retries
Raises:
CommandFailedError if root could not be enabled.
CommandTimeoutError on timeout.
"""
if 'needs_su' in self._cache:
del self._cache['needs_su']
try:
self.adb.Root()
except device_errors.AdbCommandFailedError as e:
if self.IsUserBuild():
raise device_errors.RootUserBuildError(device_serial=str(self))
elif e.output and _WAIT_FOR_DEVICE_TIMEOUT_STR in e.output:
# adb 1.0.41 added a call to wait-for-device *inside* root
# with a timeout that can be too short in some cases.
# If we hit that timeout, ignore it & do our own wait below.
pass
else:
raise # Failed probably due to some other reason.
def device_online_with_root():
try:
self.adb.WaitForDevice()
return self.HasRoot()
except (device_errors.AdbCommandFailedError,
device_errors.DeviceUnreachableError):
return False
timeout_retry.WaitFor(device_online_with_root, wait_period=1)
@decorators.WithTimeoutAndRetriesFromInstance()
def IsUserBuild(self, timeout=None, retries=None):
"""Checks whether or not the device is running a user build.
Args:
timeout: timeout in seconds
retries: number of retries
Returns:
True if the device is running a user build, False otherwise (i.e. if
it's running a userdebug build).
Raises:
CommandTimeoutError on timeout.
DeviceUnreachableError on missing device.
"""
return self.build_type == 'user'
@decorators.WithTimeoutAndRetriesFromInstance()
def GetExternalStoragePath(self, timeout=None, retries=None):
"""Get the device's path to its SD card.
Note: this path is read-only by apps in R+. Use GetAppWritablePath() to
obtain a path writable by apps.
Args:
timeout: timeout in seconds
retries: number of retries
Returns:
The device's path to its SD card.
Raises:
CommandFailedError if the external storage path could not be determined.
CommandTimeoutError on timeout.
DeviceUnreachableError on missing device.
"""
self._EnsureCacheInitialized()
if not self._cache['external_storage']:
raise device_errors.CommandFailedError('$EXTERNAL_STORAGE is not set',
str(self))
return self._cache['external_storage']
def GetAppWritablePath(self, timeout=None, retries=None):
"""Get a path that on the device's SD card that apps can write.
Args:
timeout: timeout in seconds
retries: number of retries
Returns:
A app-writeable path on the device's SD card.
Raises:
CommandFailedError if the external storage path could not be determined.
CommandTimeoutError on timeout.
DeviceUnreachableError on missing device.
"""
if self.build_version_sdk >= version_codes.Q:
# On Q+ apps don't require permissions to access well-defined media
# locations like /sdcard/Download. On R+ the WRITE_EXTERNAL_STORAGE
# permission no longer provides access to the external storage root. See
# https://developer.android.com/preview/privacy/storage#permissions-target-11
# So use /sdcard/Download for the app-writable path on those versions.
return posixpath.join(self.GetExternalStoragePath(), 'Download')
return self.GetExternalStoragePath()
@decorators.WithTimeoutAndRetriesFromInstance()
def GetIMEI(self, timeout=None, retries=None):
"""Get the device's IMEI.
Args:
timeout: timeout in seconds
retries: number of retries
Returns:
The device's IMEI.
Raises:
AdbCommandFailedError on error
"""
if self._cache.get('imei') is not None:
return self._cache.get('imei')
if self.build_version_sdk < 21:
out = self.RunShellCommand(['dumpsys', 'iphonesubinfo'],
raw_output=True,
check_return=True)
if out:
match = re.search(_IMEI_RE, out)
if match:
self._cache['imei'] = match.group(1)
return self._cache['imei']
else:
out = self.RunShellCommand(['service', 'call', 'iphonesubinfo', '1'],
check_return=True)
if out:
imei = ''
for line in out:
match = re.search(_PARCEL_RESULT_RE, line)
if match:
imei = imei + match.group(1)
imei = imei.replace('.', '').strip()
if imei:
self._cache['imei'] = imei
return self._cache['imei']
raise device_errors.CommandFailedError('Unable to fetch IMEI.')
@decorators.WithTimeoutAndRetriesFromInstance()
def IsApplicationInstalled(
self, package, version_code=None, timeout=None, retries=None):
"""Determines whether a particular package is installed on the device.
Args:
package: Name of the package.
version_code: The version of the package to check for as an int, if
applicable. Only used for static shared libraries, otherwise ignored.
Returns:
True if the application is installed, False otherwise.
"""
# `pm list packages` doesn't include the version code, so if it was
# provided, skip this since we can't guarantee that the installed
# version is the requested version.
if version_code is None:
# `pm list packages` allows matching substrings, but we want exact matches
# only.
matching_packages = self.RunShellCommand(
['pm', 'list', 'packages', package], check_return=True)
desired_line = 'package:' + package
found_package = desired_line in matching_packages
if found_package:
return True
# Some packages do not properly show up via `pm list packages`, so fall back
# to checking via `dumpsys package`.
matcher = re.compile(_DUMPSYS_PACKAGE_RE_STR % package)
dumpsys_output = self.RunShellCommand(
['dumpsys', 'package'], check_return=True, large_output=True)
for line in dumpsys_output:
match = matcher.match(line)
# We should have one of these cases:
# 1. The package is a regular app, in which case it will show up without
# its version code in the line we're filtering for.
# 2. The package is a static shared library, in which case one or more
# entries with the version code can show up, but not one without the
# version code.
if match:
installed_version_code = match.groupdict().get('version_code')
if (installed_version_code is None
or installed_version_code == str(version_code)):
return True
return False
@decorators.WithTimeoutAndRetriesFromInstance()
def GetApplicationPaths(self, package, timeout=None, retries=None):
"""Get the paths of the installed apks on the device for the given package.
Args:
package: Name of the package.
Returns:
List of paths to the apks on the device for the given package.
"""
return self._GetApplicationPathsInternal(package)
def _GetApplicationPathsInternal(self, package, skip_cache=False):
cached_result = self._cache['package_apk_paths'].get(package)
if cached_result is not None and not skip_cache:
if package in self._cache['package_apk_paths_to_verify']:
self._cache['package_apk_paths_to_verify'].remove(package)
# Don't verify an app that is not thought to be installed. We are
# concerned only with apps we think are installed having been
# uninstalled manually.
if cached_result and not self.PathExists(cached_result):
cached_result = None
self._cache['package_apk_checksums'].pop(package, 0)
if cached_result is not None:
return list(cached_result)
# 'pm path' is liable to incorrectly exit with a nonzero number starting
# in Lollipop.
# TODO(jbudorick): Check if this is fixed as new Android versions are
# released to put an upper bound on this.
should_check_return = (self.build_version_sdk < version_codes.LOLLIPOP)
output = self.RunShellCommand(['pm', 'path', package],
check_return=should_check_return)
apks = []
bad_output = False
for line in output:
if line.startswith('package:'):
apks.append(line[len('package:'):])
elif line.startswith('WARNING:'):
continue
else:
bad_output = True # Unexpected line in output.
if not apks and output:
if bad_output:
raise device_errors.CommandFailedError(
'Unexpected pm path output: %r' % '\n'.join(output), str(self))
else:
logger.warning('pm returned no paths but the following warnings:')
for line in output:
logger.warning('- %s', line)
self._cache['package_apk_paths'][package] = list(apks)
return apks
@decorators.WithTimeoutAndRetriesFromInstance()
def GetApplicationVersion(self, package, timeout=None, retries=None):
"""Get the version name of a package installed on the device.
Args:
package: Name of the package.
Returns:
A string with the version name or None if the package is not found
on the device.
"""
output = self.RunShellCommand(['dumpsys', 'package', package],
check_return=True)
if not output:
return None
for line in output:
line = line.strip()
if line.startswith('versionName='):
return line[len('versionName='):]
raise device_errors.CommandFailedError(
'Version name for %s not found on dumpsys output' % package, str(self))
@decorators.WithTimeoutAndRetriesFromInstance()
def GetApplicationTargetSdk(self, package, timeout=None, retries=None):
"""Get the targetSdkVersion of a package installed on the device.
Args:
package: Name of the package.
Returns:
A string with the targetSdkVersion or None if the package is not found on
the device. Note: this cannot always be cast to an integer. If this
application targets a pre-release SDK, this returns the version codename
instead (ex. "R").
"""
if not self.IsApplicationInstalled(package):
return None
lines = self._GetDumpsysOutput(['package', package], 'targetSdk=')
for line in lines:
m = _VERSION_CODE_SDK_RE.match(line)
if m:
value = m.group(3)
# 10000 is the code used by Android for a pre-finalized SDK.
if value == '10000':
return self.GetProp('ro.build.version.codename', cache=True)
else:
return value
raise device_errors.CommandFailedError(
'targetSdkVersion for %s not found on dumpsys output' % package,
str(self))
@decorators.WithTimeoutAndRetriesFromInstance()
def GetPackageArchitecture(self, package, timeout=None, retries=None):
"""Get the architecture of a package installed on the device.
Args:
package: Name of the package.
Returns:
A string with the architecture, or None if the package is missing.
"""
lines = self._GetDumpsysOutput(['package', package], 'primaryCpuAbi')
if lines:
_, _, package_arch = lines[-1].partition('=')
return package_arch.strip()
return None
@decorators.WithTimeoutAndRetriesFromInstance()
def GetApplicationDataDirectory(self, package, timeout=None, retries=None):
"""Get the data directory on the device for the given package.
Args:
package: Name of the package.
Returns:
The package's data directory.
Raises:
CommandFailedError if the package's data directory can't be found,
whether because it's not installed or otherwise.
"""
if not self.IsApplicationInstalled(package):
raise device_errors.CommandFailedError('%s is not installed' % package,
str(self))
output = self._RunPipedShellCommand(
'pm dump %s | grep dataDir=' % cmd_helper.SingleQuote(package))
for line in output:
_, _, dataDir = line.partition('dataDir=')
if dataDir:
return dataDir
raise device_errors.CommandFailedError(
'Could not find data directory for %s' % package, str(self))
@decorators.WithTimeoutAndRetriesFromInstance()
def GetSecurityContextForPackage(self,
package,
encrypted=False,
timeout=None,
retries=None):
"""Gets the SELinux security context for the given package.
Args:
package: Name of the package.
encrypted: Whether to check in the encrypted data directory
(/data/user_de/0/) or the unencrypted data directory (/data/data/).
Returns:
The package's security context as a string, or None if not found.
"""
directory = '/data/user_de/0/' if encrypted else '/data/data/'
for line in self.RunShellCommand(['ls', '-Z', directory],
as_root=True,
check_return=True):
split_line = line.split()
# ls -Z output differs between Android versions, but the package is
# always last and the context always starts with "u:object"
if split_line[-1] == package:
for column in split_line:
if column.startswith('u:object'):
return column
return None
def TakeBugReport(self, path, timeout=60 * 5, retries=None):
"""Takes a bug report and dumps it to the specified path.
This doesn't use adb's bugreport option since its behavior is dependent on
both adb version and device OS version. To make it simpler, this directly
runs the bugreport command on the device itself and dumps the stdout to a
file.
Args:
path: Path on the host to drop the bug report.
timeout: (optional) Timeout per try in seconds.