-
Notifications
You must be signed in to change notification settings - Fork 67
/
streamline_me.py
executable file
·1856 lines (1463 loc) · 63.9 KB
/
streamline_me.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
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (C) 2019-2024 by Arm Limited.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
The `streamline_me.py` script helps set up either an interactive Streamline
capture, or a headless gatord capture, for a single debuggable package running
on a non-rooted Android device or both debuggable and non-debuggable packages
on rooted Android device. This script requires Python 3.5 or higher.
Prerequisites
=============
The test application APK pre-installed on to the target device prior to
starting this script. If the device is not rooted, the APK must be debuggable.
By default the script will look for the `gatord` binary to use in the current
working directory on the host. The following instructions will assume that
this is the case, but a user can specify a different path using the `--daemon`
command line option.
Headless captures need a capture configuration; by default the script will look
for a `configuration.xml` configuration file in the current working directory
on the host. The following instructions will assume that this is the case, but
a user can specify a different path using the `--config` command line option.
Note that interactive captures can optionally also specify the `--config`
option to use a pre-determined set of counters, but this is optional as
interactive use will prompt for a configuration via the Streamline GUI.
Interactive capture
===================
Interactive captures set up gatord on the device, but use the Streamline GUI
for configuring and capturing data. For a simple interactive captures run the
following command line:
python streamline_me.py --package <name>
The on-screen prompts will inform you when it is safe to switch to the
Streamline GUI and capture your test data.
Once you have finished the data capture in Streamline return to the console
running the script and press the <Enter> key to clean up the device and
complete the test run.
If you do not know your package name you can run without the `--package`
option. In this case the script will search your device for debuggable packages
and prompt you to select one. The search can be quite slow, so it is
recommended to use the `--package` option once you know the package name.
Headless capture
================
Headless captures setup gatord on the device, and use gatord standalone to
capture data without the Streamline GUI connected. For a simple headless
capture run the following command line:
python streamline_me.py --package <name> --headless <output>
This will use the `configuration.xml` in the current working directory to
perform a headless capture and store the results back to the output location on
the host. Outputs may be either a directory of the format <name.apc> or a file
of the format <name.apc.zip>. The path leading up to the output location must
exist already; the script will exit with an error if it doesn't.
By default headless captures stop when the test application exits on the
target. Note that the application must exit, not suspend. Alternatively
a fixed timeout can be specified using the `--headless-timeout` option,
which will capture that many seconds of data before exiting.
Headless captures will throw an error if the output location already exists.
To avoid this you can run with the `--overwrite` option, which will forcefully
delete the existing location and replace it with new data.
The output file can be imported into the Streamline GUI via two methods:
* If you wrote an ".apc" directory you can drag the directory from the host
OS file explorer into the Streamline Data View capture list.
* If you wrote an ".apc.zip" file you can either drag the file from the host
OS file explorer into the Streamline Data View capture list, or you can
import the file using the import button in the Data View.
Hosts with multiple devices connected
=====================================
For host machines with a single debuggable device connected, this script will
auto-detect and use that device. If you have a machine with multiple devices
connected, for example a continuous integration server, you must either select
the device interactively from the menu or specify the device name on the
command line. For convenience, the command line may be a partial prefix of the
full name, provided that the prefix uniquely identifies a single device.
"""
# Early imports for a basic Python 2.7 compat check
from __future__ import print_function
import sys
try:
import argparse as ap
import atexit
import datetime
import math
import os
import re
import shlex
import shutil
import subprocess as sp
import tarfile
import tempfile
import textwrap
import time
# Standard library import failure implies old Python
except ImportError:
print("ERROR: Script requires Python 3.8 or newer")
sys.exit(1)
# We know we have an API break with Python 3.4 or older
if (sys.version_info[0] < 3) or \
(sys.version_info[0] == 3 and sys.version_info[1] < 8):
print("ERROR: Script requires Python 3.8 or newer")
sys.exit(1)
DEBUG_GATORD = False
PKG_DATA_DIR = None
# Android temp directory
ANDROID_TMP_DIR = "/data/local/tmp/"
# The minimum version Arm officially supports for this script
ANDROID_MIN_SUPPORTED_VERSION = 29
# OpenGL ES needs SDK version 29 (Android 10) for layers
ANDROID_MIN_OPENGLES_SDK = 29
# Vulkan needs SDK version 28 (Android 9) for layers
ANDROID_MIN_VULKAN_SDK = 28
# Performance Advisor configuration file name
CONFIG_FILE = "pa_lwi.conf"
# Maximum log line length
LINE_LENGTH = 80
# Expected layer names
EXPECTED_VULKAN_LAYER_NAME = "VK_LAYER_ARM_LWI"
EXPECTED_VULKAN_LAYER_FILE = "libVkLayerLWI.so"
EXPECTED_GLES_LAYER_FILE_NAME = "libGLESLayerLWI.so"
EXPECTED_VALIDATION_LAYER_NAME = "VK_LAYER_KHRONOS_validation"
class ArgFormatter(ap.HelpFormatter):
"""
Custom argparse formatter to allow newlines in option text.
"""
PREFIX = 'AF@'
def _split_lines(self, text, width):
# Use our custom formatter if enabled
if text.startswith(self.PREFIX):
return text[len(self.PREFIX):].splitlines()
# Fall back to the default argparse formatter otherwise
return ap.HelpFormatter._split_lines(self, text, width) # pylint: disable=protected-access
class Device:
"""
A basic wrapper around adb, allowing a specific device to be registered.
Attributes:
device: The name of the device to call, or None for non-specific use.
"""
def __init__(self, deviceName=None):
"""
Create a new device, defaulting to non-specific use.
Args:
deviceName: The device identifier, as returned by "adb devices",
or None for non-specific use.
"""
self.device = deviceName
self.is_root = None
def adb_async(self, *args):
"""
Call `adb` to start a command, but do not wait for it to complete.
Args:
*args: List of command line parameters.
Returns:
The process instance.
"""
# Run gatord
commands = ["adb"]
if self.device:
commands.extend(["-s", self.device])
commands.extend(args)
# Note do not use shell=True; arguments are not safely escaped
# Sink inputs to DEVNULL to stop the child process stealing keyboard
# Sink outputs to DEVNULL to stop full output buffers blocking child
if DEBUG_GATORD:
stde = sys.stderr
process = sp.Popen(commands, universal_newlines=True,
stdin=stde, stdout=stde)
else:
devn = sp.DEVNULL
process = sp.Popen(commands, stdin=devn, stdout=devn, # pylint: disable=consider-using-with
stderr=devn)
return process
def adb_quiet(self, *args):
"""
Call `adb` to run a command, but ignore output and errors.
Args:
*args : List of command line parameters.
"""
commands = ["adb"]
if self.device:
commands.extend(["-s", self.device])
commands.extend(args)
# Note do not use shell=True; arguments are not safely escaped
sp.run(commands, stdout=sp.DEVNULL,
stderr=sp.DEVNULL, check=False)
def adb(self, *args, **kwargs):
"""
Call `adb` to run command, and capture output and results.
Args:
*args: List of command line parameters.
**kwargs: text: Is output is text, or binary?
shell: Use the host shell?
quote: Quote arguments before forwarding
Returns:
The contents of stdout.
Raises:
CalledProcessError: The subprocess was not successfully executed.
"""
commands = ["adb"]
if self.device:
commands.extend(["-s", self.device])
commands.extend(args)
text = kwargs.get("text", True)
shell = kwargs.get("shell", False)
quote = kwargs.get("quote", False)
# Run on the host shell
if shell:
# Unix shells need a flattened command for shell commands
if os.name != 'nt':
quotedCommands = []
for command in commands:
if command != ">":
command = shlex.quote(command)
quotedCommands.append(command)
commands = " ".join(quotedCommands)
# Run on the device but with shell argument quoting
if quote:
for i, command in enumerate(commands):
commands[i] = shlex.quote(command)
rep = sp.run(commands, check=True, shell=shell, stdout=sp.PIPE,
stderr=sp.PIPE, universal_newlines=text)
return rep.stdout
def adb_run_as(self, package, *args, quiet=False):
"""
Call `adb` to run command as a package using `run-as` or as root,
if root is accessible. If command will be run as root, this function
will change CWD to the package data directory before executing the command.
Args:
package: Package name to run-as or chage CWD to.
*args: List of command line parameters.
quiet: If True, ignors output from adb.
Returns:
The contents of stdout or Nothing, if quiet=True.
Raises:
CalledProcessError: The subprocess was not successfully executed.
"""
global PKG_DATA_DIR # pylint: disable=global-statement
if package is None or PKG_DATA_DIR is None:
PKG_DATA_DIR = ""
return self.adb("shell", args)
command = []
if self.has_root_access():
args_string = " ".join(args)
command = ["shell", "su", "0", "sh", "-c"]
command.append(f"'cd {PKG_DATA_DIR} && {args_string}'")
else:
command = ["shell", "run-as", package]
command.extend(args)
if quiet:
return self.adb_quiet(*command)
return self.adb(*command)
def has_root_access(self):
"""
Checks if user can get root access on this device
Returns:
True if root access can be gained, False otherwise.
"""
if self.is_root is None:
subCmd = "su 0 echo true || exit 0"
cmdOutput = self.adb("shell", subCmd)
self.is_root = "true" in cmdOutput
return self.is_root
def select_from_menu(title, menuEntries):
"""
Prompt user to select from an on-screen menu.
If the option list contains only a single option it will be auto-selected.
Args:
title: The title string.
menuEntries: The list of options.
Returns:
The selected list index, or None if no selection made.
"""
assert len(menuEntries) > 0 # The caller is responsible for handling this case
if len(menuEntries) == 1:
print("\nSelect a %s:" % title)
print(" Auto-selected %s" % menuEntries[0])
return 0
selection = None
while True:
try:
# Print the menu
print("\nSelect a %s:" % title)
countW = int(math.log10(len(menuEntries))) + 1
message = " %%%uu) %%s" % countW
for i, entry in enumerate(menuEntries):
print(message % (i + 1, entry))
print(message % (0, "Exit script"))
# Process the response
response = int(input("\n Select entry: "))
if response == 0:
return None
if 0 < response <= len(menuEntries):
selection = response - 1
break
raise ValueError()
except ValueError:
print(" Please enter an int in range 0-%u" % len(menuEntries))
print("\n Selected %s" % menuEntries[selection])
return selection
def get_android_version(device):
"""
Get the Android version of a given device.
Args:
device: The device instance.
Returns:
The Android version.
"""
ver = device.adb("shell", "getprop", "ro.build.version.sdk")
return float(ver)
def get_device_model(device):
"""
Get the model of a given device
Args:
device: The device instance.
Returns:
The device model or None if the call failed.
"""
try:
logFile = device.adb("shell", "getprop", "ro.product.model")
return logFile.strip()
except sp.CalledProcessError:
return None
def is_package_32bit_abi(device, package):
"""
Get the target ABI of a given package.
Args:
device: The device instance.
package: The package name.
Returns:
True if application needs 32-bit, else 64-bit
"""
preferredABI = None
# Match against the primary ABI loaded by the application
output = device.adb("shell", "pm", "dump", package,
"|", "grep", "primaryCpuAbi")
pattern = re.compile("primaryCpuAbi=(\\S+)")
match = pattern.search(output)
if match:
matchABI = match.group(1)
if matchABI != "null":
preferredABI = matchABI
# If that fails match against the default device ABI
if preferredABI is None:
preferredABI = device.adb("shell", "getprop", "ro.product.cpu.abi")
return preferredABI in ["armeabi-v7a", "armeabi"]
def is_gatord_running(device):
"""
Returns true if an instance of gatord is running on the remote device.
Args:
device: The device instance.
Returns:
True if running
"""
# We grep for gatord, but have to filter out the sh and grep commands that
# also contain the word 'gatord'.
# In case a capture is running on a renamed gatord, we try to find the
# external agent forked arg, if the first search fails
for name in ["gatord", "agent-external"]:
output = device.adb("shell", "ps", "-ef", "|",
"grep", name, "|", "grep", "-v", "grep")
if len(output.strip()) > 0:
return True
return False
def get_connected_devices():
"""
Get the list of devices that are connected to this host.
Returns:
tuple ([(name, model)], [name])
First tuple element is a list of available device, the second is a list
of devices that are seen but not accessible (typically because adb has
not been authorized on the device).
"""
devices = []
try:
adb = Device()
logFile = adb.adb("devices")
for line in logFile.splitlines():
line = line.rstrip()
# Match devices that are available for adb. Note devices may be
# flagged as not available if get_device_model() fails, which can
# happen with dev boards accessed over wired Ethernet.
if line.endswith("device"):
deviceName = line.split()[0]
model = get_device_model(Device(deviceName))
devices.append((deviceName, model))
# Match devices that are detectable, but not usable
elif line.endswith(('offline', 'unauthorized')):
deviceName = line.split()[0]
devices.append((deviceName, None))
except sp.CalledProcessError:
return (None, None)
badDevices = sorted([x[0] for x in devices if x[1] is None])
goodDevices = sorted([x for x in devices if x[1] is not None])
return (goodDevices, badDevices)
def get_device_name(devName, interactive):
"""
Helper function to determine which device name to use.
Args:
devName: The user-specified device name on the command line. This may
be a prefix of the full name (not case sensitive), or None
(auto-select).
interactive: Is this an interactive session which can use menu prompts?
"""
goodDvs, badDvs = get_connected_devices()
# Always log devices that are available
if badDvs:
print("\nSearching for devices:")
for device in badDvs:
print(" %s found, but not debuggable" % device)
# No devices found
if not goodDvs:
print("ERROR: Device must be connected; none available")
return None
# In non-interactive mode or user device check we have unambiguous device
if not interactive or devName:
if devName:
search = devName.lower()
userDvs = [x for x in goodDvs if x[0].lower().startswith(search)]
# User device not found ...
if not userDvs:
print("ERROR: Device '%s' not found or not usable" % devName)
return None
# User device found too many times ...
if len(userDvs) > 1:
print("ERROR: Device '%s' is ambiguous" % devName)
return None
return userDvs[0][0]
# Non-specific devices found too many times
if len(goodDvs) > 1:
print("ERROR: Device must be specified; multiple available")
return None
return goodDvs[0][0]
# In interactive mode use the menu selector; print header if not already
if not badDvs:
print("\nSearching for devices:")
for device, model in goodDvs:
print(" %s / %s found" % (device, model))
menuEntries = ["%s / %s" % x for x in goodDvs]
if len(menuEntries) < 1:
print("\nERROR: Device not selected; none available")
return None
deviceIndex = select_from_menu("device", menuEntries)
if deviceIndex is None:
print("\nERROR: Device not selected; multiple available")
return None
return goodDvs[deviceIndex][0]
def get_gpu_name(device):
"""
Determine the GPU name from dumpsys queries.
Immortalis GPUs report in dumpsys as e.g., Mali-G715-Immortalis.
Args:
device: The device instance.
"""
print("\nSearching for an Arm GPU:")
try:
logFile = device.adb("shell", "dumpsys", "SurfaceFlinger")
pattern = re.compile("Mali-([TG][0-9]+)(-Immortalis)?")
match = pattern.search(logFile)
if match:
gpu = match.group(1)
brand = "Mali" if not match.group(2) else "Immortalis"
print(" %s-%s GPU found" % (brand, gpu))
else:
print(" No Arm GPU found")
except sp.CalledProcessError:
print(" Failed to query device")
def get_package_name(device, pkgName, showAllPackages, interactive):
"""
Helper function to determine which package to use.
Args:
device: The device instance.
pkgName: The user-specified package name or glob selector (regex) on the command line.
This may be the full name (case-sensitive), or None (auto-select).
showDebuggableOnly: Determines if non-debuggable packages are displayed
default is True
interactive: Is this an interactive session which can use menu prompts?
Returns:
Package name and package debuggability if a single matching package was found.
None, otherwise.
"""
# pylint: disable-msg=too-many-locals
goodPkg = []
is_debuggable = False
# In non-interactive mode or with a user-specified package, then check it
if not interactive or pkgName:
if not pkgName:
print("ERROR: Package must be specified")
return None, None
allPkg = get_package_list(
device, not showAllPackages, showMainIntentOnly=False)
matchesSinglePackage = True
# Accept a regex (*) for the package name
if pkgName not in allPkg:
try:
r = "%s$" % re.escape(pkgName).replace(r"\*", ".*")
regex = re.compile(r)
goodPkg = list(filter(regex.match, allPkg))
if len(goodPkg) == 1:
pkgName = goodPkg[0]
elif len(goodPkg) > 1:
matchesSinglePackage = False
elif not goodPkg:
raise ValueError()
except (ValueError, re.error):
print("ERROR: Package '%s' not found." % pkgName)
return None, None
if not matchesSinglePackage and not interactive:
print("ERROR: Multiple packages found when --package used. Listed packages:")
print("\n".join(goodPkg))
return None, None
is_debuggable = is_package_debuggable(device, pkgName)
if not is_debuggable and matchesSinglePackage and not showAllPackages:
print("ERROR: Package '%s' not debuggable" % pkgName)
return None, None
if matchesSinglePackage:
# Match the output format of the menu when a single package listed
print("\nSelect a package:")
print(" Auto-selected %s" % pkgName)
return pkgName, is_debuggable
# In interactive mode without named package then find one, with prompt ...
debuggableMessage = 'debuggable' if not showAllPackages else 'all'
print("\nSearching for %s packages:" % debuggableMessage)
pleaseWait = " Please wait for search to complete..."
print(pleaseWait, end="\r")
# If this wasn't populated before, we can use the packaged filtered by package name
if not goodPkg:
goodPkg = get_package_list(
device, not showAllPackages, showMainIntentOnly=True)
plural = "s" if len(goodPkg) != 1 else ""
message = " %u package%s found" % (len(goodPkg), plural)
template = "\r%%-%us" % len(pleaseWait)
print(template % message)
if len(goodPkg) < 1:
print("\nERROR: No packages with MAIN activities found")
return None, None
pkgIndex = select_from_menu(
"%s packages" % debuggableMessage, goodPkg)
if pkgIndex is None:
print("\nNo package selected, exiting ...")
return "", None
is_debuggable = is_package_debuggable(device, goodPkg[pkgIndex])
if not is_debuggable and not showAllPackages:
print("ERROR: Package '%s' is not debuggable" %
goodPkg[pkgIndex])
return None, None
return goodPkg[pkgIndex], is_debuggable
def get_main_activity(device, package):
cmd = (f"dumpsys package {package} " +
r"| grep -A1 'android.intent.action.MAIN:' " +
r'| tr " " "\n" ' +
f"| grep {package}/ " +
r"|| exit 0")
output = device.adb("shell", "sh", "-c", f"'{cmd}'")
if not output:
return None
return str(output).replace(f"{package}/", "").strip()
def is_package_debuggable(device, package):
"""
Test if a package is debuggable.
Args:
device: The device instance.
package: The package name.
Returns:
`True` if the package is debuggable, else `False`.
"""
try:
subCmd = "if run-as %s true ; then echo %s ; fi" % (package, package)
logFile = device.adb("shell", subCmd)
return logFile.strip() == package
except sp.CalledProcessError:
return False
def get_package_data_dir(device, package):
"""
Gets the package data directory in Android system
Args:
device: The device instance.
package: The package name.
Returns:
package data directory or None on error.
"""
try:
subCmd = "dumpsys package %s | grep dataDir" % package
dumpsysOutput = device.adb("shell", subCmd)
return dumpsysOutput.replace("dataDir=", "").strip()
except sp.CalledProcessError:
return None
def get_package_list(device, showDebuggableOnly, showMainIntentOnly=True):
"""
Fetch the list of packages on the target device.
Args:
device: The device instance.
showDebuggableOnly: whether the list should show only
debuggable packages.
showMainIntentOnly: whether the list should show only
packages with a MAIN activity.
Returns:
The list of packages, or an empty list on error.
"""
opt = "-3" if showDebuggableOnly else ""
command = "pm list packages -e %s | sed 's/^package://' | sort" % opt
if showDebuggableOnly:
# Test if the package is debuggable on the device
subCmd0 = "if run-as $0 true ; then echo $0 ; fi"
command += " | xargs -n1 sh -c '%s' 2> /dev/null" % subCmd0
if showMainIntentOnly:
# Test if the package has a MAIN activity
subCmd1 = ("dumpsys package $0 | if grep "
"-q \"android.intent.action.MAIN\" ; then echo $0 ; fi")
command += " | xargs -n1 sh -c '%s' 2> /dev/null" % subCmd1
try:
package_list = device.adb("shell", command).splitlines()
# some shells (seen on android 10 and 9) report "sh" as a valid package
if "sh" in package_list:
package_list.remove("sh")
return package_list
except sp.CalledProcessError:
return []
def push_lwi_config(device, args, _package):
"""
Create a configuration file for LWI and push it onto the device.
Args:
args: struct of parameters
"""
# Semantics are different in the LWI
tempFileDescriptor, tempPath = tempfile.mkstemp()
try:
with os.fdopen(tempFileDescriptor, 'w') as paramFile:
paramFile.write("ANDROID_USER=0\n")
paramFile.write("MODE=%s\n" % str(args.lwiMode))
paramFile.write("FPS_WINDOW=%d\n" % int(args.fpsWindow))
paramFile.write("FPS_THRESHOLD=%d\n" % int(args.fpsThreshold))
paramFile.write("FRAME_START=%d\n" % int(args.frameStart))
paramFile.write("FRAME_END=%d\n" % int(args.frameEnd))
paramFile.write("MIN_FRAME_GAP=%d\n" % int(args.frameGap))
paramFile.write("COMPRESS_IMG=%s\n" % int(args.compress))
paramFile.write("CAPTURE_TIMEOUT=%s\n" % int(args.timeout))
except IOError:
infoStr = ("\nERROR: an error occurred when creating a local"
" temporary config file: {}\n".format(tempPath))
print(textwrap.fill(infoStr, LINE_LENGTH))
return False
# Push the file onto target
device_config_file = ANDROID_TMP_DIR + CONFIG_FILE
device.adb("shell", "rm", "-f", device_config_file)
device.adb("push", tempPath, device_config_file)
os.remove(tempPath)
# Check if file's been actually pushed
try:
device.adb("shell", "ls", device_config_file)
except sp.CalledProcessError:
return False
# Set permission
device.adb("shell", "chmod", "666", device_config_file)
return True
# Write the screenshots into output directory
# TODO: Move this into docstring.
def write_capture(device, outDir, package):
captureName = "pa_lwi"
with tempfile.NamedTemporaryFile() as fileHandle:
# Fetch the results by streaming a tar file; we can't "adb pull"
# directly for new Android applications due to SELinux policy
tempName = fileHandle.name
fileHandle.close()
pkg_data_dir = get_package_data_dir(device, package)
is_root = device.has_root_access()
if is_root:
device.adb("exec-out", "su", "0", "sh", "-c",
f"cd {pkg_data_dir} && tar -c ./{captureName}", ">", tempName,
text=False, shell=True)
else:
device.adb("exec-out", "run-as", package, "tar", "-c",
captureName, ">", tempName, text=False, shell=True)
# Repack the tar file into the required output format
with tempfile.TemporaryDirectory() as tempDir:
with tarfile.TarFile(tempName) as tarHandle:
# Extract the tar file
tarHandle.extractall(tempDir)
# Rename to the required name
oldName = os.path.join(tempDir, captureName)
for file_name in os.listdir(oldName):
shutil.move(os.path.join(oldName, file_name), outDir)
return True
def pull_screenshots(device, lwiOutDir, package, cleanUp=True):
"""
Download slow frame screenshots from the target to the host.
Args:
device: The device to connect to.
lwiOutDir: The destination directory.
package: The package on the device.
cleanUp: Should we clean up the device after downloading?
"""
# Check if capture exists
adb_stdout = ""
try:
adb_stdout = device.adb_run_as(package, "ls", "pa_lwi")
except sp.CalledProcessError:
# Command failed, there is no capture, nothing to do
pass
if "No such file" in adb_stdout or adb_stdout == "":
print(" INFO: No screen captures found")
return True
# Also copy config into pa_lwi dir
try:
device_config_file = ANDROID_TMP_DIR + CONFIG_FILE
device.adb_run_as(package, "ls", device_config_file)
device.adb_run_as(package, "cp", device_config_file, "pa_lwi")
except sp.CalledProcessError:
print(" WARNING: No configuration file found")
# Download from the device
if not write_capture(device, lwiOutDir, package):
return False
# Clean up
if cleanUp:
device.adb_run_as(package, "rm", "-rf", "pa_lwi")
device.adb_run_as(package, "rm", "-rf", "pa_lwi.tar")
return True
def enable_vulkan_debug_layer(device, args):
"""
How to load/enable vulkan here will be determined by two things:
1) What API version the target is running:
Devices running Android 9 (sdk 28) or above will use sandboxed
library within app local storage.
Devices running lower version of Android will
use global layer activation
2) What version of ndk we built with:
With NDK r21+ per app layer activation will be possible without
access to app's sources.
Args:
device: The device instance.
args: The command arguments.
"""
print("\nInstalling Vulkan debug layer")
vkLayerBaseName = os.path.basename(os.path.normpath(args.vkLayerLibPath))
if vkLayerBaseName != EXPECTED_VULKAN_LAYER_FILE:
print("\nWARNING: The Vulkan layer is not the default layer")
if args.androidVersion < ANDROID_MIN_VULKAN_SDK:
device.adb("shell", "setprop", "debug.vulkan.layers",
EXPECTED_VULKAN_LAYER_NAME)
else:
device.adb("push", args.vkLayerLibPath, ANDROID_TMP_DIR)
device.adb_run_as(args.package, "cp",
ANDROID_TMP_DIR + vkLayerBaseName, ".")
device.adb("shell", "settings", "put", "global",
"enable_gpu_debug_layers", "1")
device.adb("shell", "settings", "put", "global",
"gpu_debug_app", args.package)
if args.lwiVal:
device.adb("shell", "settings", "put", "global", "gpu_debug_layers",
EXPECTED_VULKAN_LAYER_NAME + ":" + EXPECTED_VALIDATION_LAYER_NAME)
else:
device.adb("shell", "settings", "put", "global",
"gpu_debug_layers", EXPECTED_VULKAN_LAYER_NAME)
def enable_gles_debug_layer(device, args):
"""
Args:
device: The device instance.
args: The command arguments.
"""
print("\nInstalling OpenGL ES debug layer")
glesLayerBaseName = os.path.basename(
os.path.normpath(args.glesLayerLibPath))
if glesLayerBaseName != EXPECTED_GLES_LAYER_FILE_NAME:
print("\nWARNING: The OpenGL ES layer is not the default layer")