PageRenderTime 62ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/bin/android_ndk_perf.py

https://gitlab.com/adam.lukaitis/fplutil
Python | 1467 lines | 1447 code | 1 blank | 19 comment | 0 complexity | 3817365ceb76a941b3179c3efcee0870 MD5 | raw file
  1. #!/usr/bin/python
  2. # Copyright 2014 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """@file bin/android_ndk_perf.py Linux perf automation for Android.
  16. Detailed usage: android_ndk_perf.py [options] perf_command [perf_arguments]
  17. perf_command can be any valid command for the Linux perf tool or
  18. "visualize" to display a visualization of the performance report.
  19. Caveats:
  20. * "stat" and "top" require root access to the target device.
  21. * "record" is *not* able to annotate traces with symbols from samples taken
  22. in the kernel without root access to the target device.
  23. """
  24. import argparse
  25. import distutils.spawn
  26. import json
  27. import os
  28. import platform
  29. import re
  30. import signal
  31. import subprocess
  32. import sys
  33. import tempfile
  34. import threading
  35. import time
  36. import xml.dom.minidom as minidom
  37. ## Directory containing this script.
  38. SCRIPT_DIRECTORY = os.path.abspath(os.path.dirname(__file__))
  39. ## Directory containing perf binaries and other tools used by this script.
  40. PERF_TOOLS_DIRECTORY = os.path.abspath(os.path.join(SCRIPT_DIRECTORY,
  41. os.path.pardir, 'perf'))
  42. ## Target directory on the Android device used to push the perf executable and
  43. ## associated tools.
  44. REMOTE_TEMP_DIRECTORY = '/data/local/tmp'
  45. ## Android manifest filename.
  46. MANIFEST_NAME = 'AndroidManifest.xml'
  47. ## Set of tested devices that are known to support perf.
  48. SUPPORTED_DEVICES = set([
  49. 'mantaray', # Nexus 10
  50. 'nakasi', # Nexus 7 (2012)
  51. ])
  52. ## Set of tested devices that are known to have broken support for perf.
  53. BROKEN_DEVICES = set([
  54. 'razor', # Nexus 7 (2013)
  55. 'hammerhead', # Nexus 5
  56. ])
  57. ## Maps a python platform.machine() string to a list of compatible Android
  58. ## (AOSP) build system architecture.
  59. HOST_MACHINE_TYPE_TO_ARCHITECTURE = {
  60. 'x86_64': ['x86_64', 'x86'], # Linux / OSX.
  61. 'AMD64': ['x86_64', 'x86'], # Windows.
  62. }
  63. ## Set of regular expressions that map a platform.system() to an Android
  64. ## (AOSP) build system OS name.
  65. HOST_SYSTEM_TO_OS_NAME = (
  66. (re.compile(r'Darwin'), 'darwin'),
  67. (re.compile(r'Linux'), 'linux'),
  68. (re.compile(r'Windows'), 'windows'),
  69. (re.compile(r'CYGWIN.*'), 'windows')
  70. )
  71. ## Maps an ABI to a set of compatible Android (AOSP) architectures.
  72. ANDROID_ABI_TO_ARCHITECTURE = {
  73. 'armeabi': ['arm'],
  74. 'armeabi-v7a': ['arm'],
  75. 'arm64-v8a': ['arm64', 'arm'],
  76. 'x86': ['x86'],
  77. 'x86-64': ['x86-64', 'x86'],
  78. 'mips': ['mips'],
  79. }
  80. ## Directory containing perf and perfhost binaries.
  81. PERF_TOOLS_BIN_DIRECTORY = os.path.join(PERF_TOOLS_DIRECTORY, 'bin')
  82. ## List of paths to search for a host binary.
  83. HOST_BINARY_SEARCH_PATHS = [
  84. PERF_TOOLS_BIN_DIRECTORY,
  85. os.path.join(PERF_TOOLS_DIRECTORY, 'tools', 'telemetry', 'telemetry',
  86. 'core', 'platform', 'profiler', 'perf_vis'),
  87. ]
  88. ## List of paths to search for a target (Android) binary.
  89. TARGET_BINARY_SEARCH_PATHS = [
  90. PERF_TOOLS_BIN_DIRECTORY,
  91. PERF_TOOLS_DIRECTORY,
  92. ]
  93. ## API level perf was introduced into AOSP.
  94. PERF_MIN_API_LEVEL = 16
  95. ## Name of the perf binary that runs on the host machine.
  96. PERFHOST_BINARY = 'perfhost'
  97. ## Binary which converts from a perf trace to JSON.
  98. PERF_TO_TRACING = 'perf_to_tracing_json'
  99. ## Binary visualizes JSON output of PERF_TO_TRACING using HTML.
  100. PERF_VIS = 'perf-vis'
  101. ## Perf binaries not supported warning message.
  102. PERF_BINARIES_NOT_SUPPORTED = """
  103. WARNING: The precompiled perf binaries may not be compatable with android
  104. version %(ver)s. If you enounter issues please try version %(ver)s or higher.
  105. """
  106. ## Performance counters broken warning message.
  107. PERFORMANCE_COUNTERS_BROKEN = """
  108. WARNING: %s is known to have broken performance counters. It is recommended
  109. that you use a different device to record perf data.
  110. """
  111. ## Device not supported warning message.
  112. NOT_SUPPORTED_DEVICE = """
  113. WARNING: %s is not in the list of supported devices. It is likely that the
  114. performance counters don't work so you may need to try a different device.
  115. """
  116. ## Device not rooted error message.
  117. DEVICE_NOT_ROOTED = """
  118. WARNING: perf command "%s" requires a rooted device. Try running "adb root"
  119. before attempting to use this command.
  120. """
  121. ## Chrome web browser isn't found.
  122. CHROME_NOT_FOUND = """
  123. WARNING: %s is not Google Chrome and therefore may not be able
  124. to display the performance data.
  125. """
  126. ## Unable to collect CPU frequency data.
  127. CPU_FREQ_NOT_AVAILABLE = """
  128. WARNING: Unable to collect CPU frequency data.
  129. %s
  130. """
  131. ## Unable to get process ID message.
  132. UNABLE_TO_GET_PROCESS_ID = 'Unable to get process ID of package %s'
  133. ## Regular expression which matches the libraries referenced by
  134. ## "perf buildid-list --with-hits -i ${input_file}".
  135. PERF_BUILDID_LIST_MATCH_OBJ_RE = re.compile(r'^[^ ]* ([^\[][^ ]*[^\]])')
  136. ## Regular expression which extracts the CPU number from a path in
  137. ## /sys/devices/system/cpu.
  138. SYS_DEVICES_CPU_NUMBER_RE = re.compile(
  139. r'/sys/devices/system/cpu/cpu([0-9]+)/.*')
  140. ## Regular expression which parses a sample even header from a perf trace dump
  141. ## e.g the output of "perf script -D".
  142. PERF_DUMP_EVENT_SAMPLE_RE = re.compile(
  143. r'^(?P<unknown>\d+)\s+'
  144. r'(?P<file_offset>0x[0-9a-fA-F]+)\s+'
  145. r'\[(?P<event_header_size>[^\]]+)\]:\s+'
  146. r'(?P<perf_event_type>PERF_RECORD_[^(]+)'
  147. r'(?P<perf_event_misc>\([^\)]+\)):\s+'
  148. r'(?P<pid>\d+)/'
  149. r'(?P<tid>\d+):\s+'
  150. r'(?P<ip>0x[0-9a-fA-F]+)\s+'
  151. r'period:\s+(?P<period>\d+)')
  152. ## Regular expression which parses the perf report output from a trace dump.
  153. PERF_DUMP_EVENT_SAMPLE_REPORT_RE = re.compile(
  154. r'(?P<comm>.*)\s+'
  155. r'(?P<tid>[0-9]+)\s+'
  156. r'(?P<time>[0-9]+\.[0-9]+):\s+'
  157. r'(?P<event>.*):\s*$')
  158. ## Regular expression which extracts fields from a stack track in
  159. ## run_perf_visualizer().
  160. PERF_REPORT_STACK_RE = re.compile(
  161. r'^\t\s+(?P<ip>[0-9a-zA-Z]+)\s+(?P<symbol>.*)\s+(?P<dso>\(.*\))$')
  162. ## Prefix of each stack line in a perf report or dump.
  163. PERF_REPORT_STACK_PREFIX = '\t '
  164. ## Regular expression which extracts the output html filename from PERF_VIS.
  165. PERF_VIS_OUTPUT_FILE_RE = re.compile(r'.*output:\s+(.*\.html).*')
  166. ## Name of the file used to hold CPU frequency data.
  167. CPUFREQ_JSON = 'cpufreq.json'
  168. ## Parses a string attribute from the manifest output of aapt list.
  169. AAPT_MANIFEST_ATTRIBUTE_RE = re.compile(
  170. r'\s*A:\s+(?P<attribute>[^(=]*)[^=]*=[^"(]*[^")]*[")@](?P<value>[^"]*)')
  171. class Error(Exception):
  172. """General error thrown by this module."""
  173. pass
  174. class CommandFailedError(Error):
  175. """Thrown when a shell command fails.
  176. Attributes:
  177. returncode: Status of the failed command.
  178. """
  179. def __init__(self, error_string, returncode):
  180. """Initialize this instance.
  181. Args:
  182. error_string: String associated with the exception.
  183. returncode: Assigned to return_status of this instance.
  184. """
  185. super(CommandFailedError, self).__init__(error_string)
  186. self.returncode = returncode
  187. class BinaryNotFoundError(Error):
  188. """Thrown when a binary isn't found."""
  189. pass
  190. class Adb(object):
  191. """Executes ADB commands on a device.
  192. Attributes:
  193. _serial: Device serial number to connect to. If this is an empty string
  194. this class will use the first device connected if only one device is
  195. connected.
  196. cached_properties: Dictionary of cached properties of the device.
  197. verbose: Whether to display all shell commands run by this class.
  198. adb_path: Path to the ADB executable.
  199. command_handler: Callable which executes subprocesses. See
  200. execute_command().
  201. Class Attributes:
  202. _MATCH_DEVICES: Regular expression which matches connected devices.
  203. _MATCH_PROPERTY: Regular expression which matches properties returned by
  204. the getprop shell command.
  205. _GET_PID: Shell script fragment which retrieves the PID of a package.
  206. """
  207. class Error(Exception):
  208. """Thrown when the Adb object detects an error."""
  209. pass
  210. class ShellCommand(object):
  211. """Callable object which can be used to run shell commands.
  212. Attributes:
  213. adb: Adb instance to relay shell commands to.
  214. """
  215. def __init__(self, adb):
  216. """Initialize this instance.
  217. Args:
  218. adb: Adb instance to relay shell commands to.
  219. """
  220. self.adb = adb
  221. def __call__(self, executable, executable_args, error, **kwargs):
  222. """Run a shell command on the device associated with this instance.
  223. Args:
  224. executable: String added to the start of the command line.
  225. executable_args: List of strings that are joined with whitespace to
  226. form the shell command.
  227. error: The message to print if the command fails.
  228. **kwargs: Keyword arguments passed to the command_handler attribute.
  229. Returns:
  230. (stdout, stderr, kbdint) where stdout is a string containing the
  231. standard output stream and stderr is a string containing the
  232. standard error stream and kbdint is whether a keyboard interrupt
  233. occurred.
  234. """
  235. args = [executable]
  236. args.extend(executable_args)
  237. return self.adb.shell_command(' '.join(args), error, **kwargs)
  238. _MATCH_DEVICES = re.compile(r'^(List of devices attached\s*\n)|(\n)$')
  239. _MATCH_PROPERTY = re.compile(r'^\[([^\]]*)\]: *\[([^\]]*)\]$')
  240. _GET_PID = ' && '.join((r'fields=( $(ps | grep -F %s) )',
  241. r'echo ${fields[1]}'))
  242. def __init__(self, serial, command_handler, adb_path=None, verbose=False):
  243. """Initialize this instance.
  244. Args:
  245. serial: Device serial number to connect to. If this is an empty
  246. string this class will use the first device connected if only one
  247. device is connected.
  248. command_handler: Callable which executes subprocesses. See
  249. execute_local_command().
  250. adb_path: Path to the adb executable. If this is None the PATH is
  251. searched.
  252. verbose: Whether to display all shell commands run by this class.
  253. Raises:
  254. Adb.Error: If multiple devices are connected and no device is selected,
  255. no devices are connected or ADB can't be found.
  256. """
  257. self.cached_properties = {}
  258. self.verbose = verbose
  259. self.command_handler = command_handler
  260. self.adb_path = (adb_path if adb_path else
  261. distutils.spawn.find_executable('adb'))
  262. if not self.adb_path:
  263. raise Adb.Error('Unable to find adb executable, '
  264. 'is the ADT platforms-tools directory in the PATH?')
  265. self.serial = serial
  266. def _run_command(self, command, command_args, error, add_serial, **kwargs):
  267. """Run an ADB command for a specific device.
  268. Args:
  269. command: Command to execute.
  270. command_args: Arguments to pass to the command.
  271. error: The message to print if the command fails.
  272. add_serial: Add the device serial number to ADB's arguments. This should
  273. only be used with command that operate on a single device.
  274. **kwargs: Keyword arguments passed to "command_handler".
  275. Returns:
  276. (stdout, stderr, kbdint) where stdout is a string containing the
  277. standard output stream and stderr is a string containing the
  278. standard error stream and kbdint is whether a keyboard interrupt
  279. occurred.
  280. Raises:
  281. CommandFailedError: If the command fails.
  282. """
  283. kwargs = dict(kwargs)
  284. kwargs['verbose'] = self.verbose
  285. args = []
  286. if add_serial and self.serial:
  287. args.extend(('-s', self.serial))
  288. args.append(command)
  289. args.extend(command_args)
  290. return self.command_handler(self.adb_path, args, error, **kwargs)
  291. def run_command(self, command, command_args, error, **kwargs):
  292. """Run an ADB command for a specific device.
  293. Args:
  294. command: Command to execute.
  295. command_args: Arguments to pass to the command.
  296. error: The message to print if the command fails.
  297. **kwargs: Keyword arguments passed to "command_handler".
  298. Returns:
  299. (stdout, stderr, kbdint) where stdout is a string containing the
  300. standard output stream and stderr is a string containing the
  301. standard error stream and kbdint is whether a keyboard interrupt
  302. occurred.
  303. Raises:
  304. CommandFailedError: If the command fails.
  305. """
  306. return self._run_command(command, command_args,
  307. '%s (device=%s)' % (error, str(self)), True,
  308. **kwargs)
  309. def run_global_command(self, command, command_args, error, **kwargs):
  310. """Run an ADB command that does not operate on an individual device.
  311. Args:
  312. command: Command to execute.
  313. command_args: Arguments to pass to the command.
  314. error: The message to print if the command fails.
  315. **kwargs: Keyword arguments passed to "command_handler".
  316. Returns:
  317. (stdout, stderr, kbdint) where stdout is a string containing the
  318. standard output stream and stderr is a string containing the
  319. standard error stream and kbdint is whether a keyboard interrupt
  320. occurred.
  321. Raises:
  322. CommandFailedError: If the command fails.
  323. """
  324. return self._run_command(command, command_args, error, False, **kwargs)
  325. def shell_command(self, command, error, **kwargs):
  326. """Run a shell command on the device associated with this instance.
  327. Args:
  328. command: Command to execute in the remote shell.
  329. error: The message to print if the command fails.
  330. **kwargs: Keyword arguments passed to "command_handler".
  331. Returns:
  332. (stdout, stderr, kbdint) where stdout is a string containing the
  333. standard output stream and stderr is a string containing the
  334. standard error stream and kbdint is whether a keyboard interrupt
  335. occurred.
  336. Raises:
  337. CommandFailedError: If the command fails.
  338. """
  339. kwargs = dict(kwargs)
  340. kwargs['verbose'] = self.verbose
  341. # ADB doesn't return status codes from shell commands to the host shell
  342. # so get the status code up from the shell using the standard error
  343. # stream.
  344. out, err, kbdint = self.run_command(
  345. 'shell', [command + r'; echo $? >&2'], error, **kwargs)
  346. out_lines = out.splitlines()
  347. # If a keyboard interrupt occurred and the caller wants to ignore the
  348. # interrupt status, ignore it.
  349. if kbdint and kwargs.get('keyboard_interrupt_success'):
  350. returncode = 0
  351. else:
  352. returncode = 1
  353. # Regardless of the destination stream on the Android device ADB
  354. # redirects everything to the standard error stream so this looks at the
  355. # last line of the stream to get the command status code.
  356. if out_lines:
  357. try:
  358. returncode = int(out_lines[-1])
  359. out_lines = out_lines[:-1]
  360. except ValueError:
  361. pass
  362. if returncode and not kwargs.get('display_output'):
  363. print out
  364. print >> sys.stderr, err
  365. raise CommandFailedError(error, returncode)
  366. return (os.linesep.join(out_lines), err, kbdint)
  367. @property
  368. def serial(self):
  369. """Serial number of the device associated with this class."""
  370. return self._serial
  371. @serial.setter
  372. def serial(self, serial):
  373. """Set the serial number of the device associated with this class.
  374. Args:
  375. serial: Serial number string.
  376. Raises:
  377. Adb.Error: If no devices are connected, the serial number isn't in the
  378. set of connected devices or no serial number is specified and more
  379. than one device is connected.
  380. """
  381. # Verify the serial number is valid for the set of connected devices.
  382. devices = self.get_devices()
  383. number_of_devices = len(devices)
  384. error_message = []
  385. if not number_of_devices:
  386. error_message.append('No Android devices are connected to this host.')
  387. elif serial and serial not in [d.split()[0] for d in devices if d]:
  388. error_message = ['%s is not connected to the host.' % serial,
  389. 'The connected devices are:']
  390. error_message.extend(devices)
  391. elif not serial and number_of_devices > 1:
  392. error_message = ['Multiple Android devices are connected to this host.',
  393. 'The connected devices are:']
  394. error_message.extend(devices)
  395. if error_message:
  396. raise Adb.Error(os.linesep.join(error_message))
  397. # Set the serial number and clear the cached properties.
  398. self._serial = serial
  399. self.cached_properties = {}
  400. def get_prop(self, android_property_name, use_cached=True):
  401. """Gets a property (getprop) from the device.
  402. Args:
  403. android_property_name: The property to get.
  404. use_cached: Whether to use a cached value of the property.
  405. Returns:
  406. The value of the retrieved property.
  407. Raises:
  408. CommandFailedError: If the command fails.
  409. """
  410. if not use_cached:
  411. self.cached_properties = {}
  412. if not self.cached_properties:
  413. out, _, _ = self.shell_command('getprop', 'Unable to get properties')
  414. for l in out.splitlines():
  415. m = Adb._MATCH_PROPERTY.match(l)
  416. if m:
  417. key, value = m.groups()
  418. self.cached_properties[key] = value
  419. return self.cached_properties.get(android_property_name)
  420. def get_supported_abis(self):
  421. """Gets the set of ABIs supported by the Android device.
  422. Returns:
  423. List of ABI strings.
  424. """
  425. return [v for v in [self.get_prop('ro.product.cpu.%s' % p)
  426. for p in ('abi', 'abi2')] if v]
  427. def get_version(self):
  428. """Gets the version of Android on the device.
  429. Returns:
  430. The android version number
  431. """
  432. return self.get_prop('ro.build.version.release')
  433. def get_model_and_name(self):
  434. """Gets the version of Android on the device.
  435. Returns:
  436. Tuple of android model and name.
  437. Raises:
  438. CommandFailedError: If the command fails.
  439. """
  440. return [self.get_prop('ro.product.%s' % p) for p in ['model', 'name']]
  441. def get_api_level(self):
  442. """Gets the API level of Android on the device.
  443. Returns:
  444. Integer API level.
  445. Raises:
  446. CommandFailedError: If the command fails.
  447. """
  448. return int(self.get_prop('ro.build.version.sdk'))
  449. def __str__(self):
  450. """Get a string representation of this device.
  451. Returns:
  452. Serial number of this device.
  453. """
  454. return self.serial if self.serial else '<default>'
  455. def get_devices(self):
  456. """Gets the numer of connected android devices.
  457. Returns:
  458. The number of connected android devices.
  459. Raises:
  460. CommandFailedError: An error occured running the command.
  461. """
  462. out, _, _ = self.run_global_command(
  463. 'devices', ['-l'], 'Unable to get the list of connected devices.')
  464. return Adb._MATCH_DEVICES.sub(r'', out).splitlines()
  465. def start_activity(self, package, activity):
  466. """Start an activity on the device.
  467. Args:
  468. package: Package containing the activity that will be started.
  469. activity: Name of the activity to start.
  470. Returns:
  471. The process id of the process for the package containing the activity
  472. if found.
  473. Raises:
  474. CommandFailedError: If the activity fails to start.
  475. Error: If it's possible to get the PID of the process.
  476. """
  477. package_activity = '%s/%s' % (package, activity)
  478. out, _, _ = self.shell_command(
  479. ' && '.join(['am start -S -n %s' % package_activity,
  480. Adb._GET_PID % package]),
  481. 'Unable to start Android application %s' % package_activity)
  482. try:
  483. return int(out.splitlines()[-1])
  484. except (ValueError, IndexError):
  485. raise Error(UNABLE_TO_GET_PROCESS_ID % package_activity)
  486. def get_package_pid(self, package):
  487. """Get the process ID of a package.
  488. Args:
  489. package: Package containing the activity that will be started.
  490. Returns:
  491. The process id of the process for the package containing the activity
  492. if found.
  493. Raises:
  494. CommandFailedError: If the activity fails to start.
  495. Error: If it's possible to get the PID of the process.
  496. """
  497. out, _, _ = self.shell_command(
  498. Adb._GET_PID % package, UNABLE_TO_GET_PROCESS_ID % package)
  499. try:
  500. return int(out.splitlines()[-1])
  501. except (ValueError, IndexError):
  502. raise Error(UNABLE_TO_GET_PROCESS_ID % package)
  503. def push(self, local_file, remote_path):
  504. """Push a local file to the device.
  505. Args:
  506. local_file: File to push to the device.
  507. remote_path: Path on the device.
  508. Raises:
  509. CommandFailedError: If the push fails.
  510. """
  511. self.run_command('push', [local_file, remote_path],
  512. 'Unable to push %s to %s' % (local_file, remote_path))
  513. def push_files(self, local_remote_paths):
  514. """Push a set of local files to remote paths on the device.
  515. Args:
  516. local_remote_paths: List of (local, remote) tuples where "local" is the
  517. local path to push to the device and "remote" is the target location
  518. on the device.
  519. Raises:
  520. CommandFailedError: If the push fails.
  521. """
  522. for local, remote in local_remote_paths:
  523. self.push(local, remote)
  524. def pull(self, remote_path, local_file):
  525. """Pull a remote file to the host.
  526. Args:
  527. remote_path: Path on the device.
  528. local_file: Path to the file on the host. If the directories to the
  529. local file don't exist, they're created.
  530. Raises:
  531. CommandFailedError: If the pull fails.
  532. """
  533. local_dir = os.path.dirname(local_file)
  534. if not os.path.exists(local_dir):
  535. os.makedirs(local_dir)
  536. self.run_command('pull', [remote_path, local_file],
  537. 'Unable to pull %s to %s' % (remote_path, local_file))
  538. def pull_files(self, remote_local_paths):
  539. """Pull a set of remote files to the host.
  540. Args:
  541. remote_local_paths: List of (remote, local) tuples where "remote" is the
  542. source location on the device and "local" is the host path to copy to.
  543. Raises:
  544. CommandFailedError: If the pull fails.
  545. """
  546. for remote, local in remote_local_paths:
  547. self.pull(remote, local)
  548. @staticmethod
  549. def get_package_data_directory(package_name):
  550. """Get the directory containing data for a package.
  551. Args:
  552. package_name: Name of a package installed on the device.
  553. Returns:
  554. Directory containing data for a package.
  555. """
  556. return '/data/data/%s' % package_name
  557. @staticmethod
  558. def get_package_file(package_name, package_file):
  559. """Get the path of a file in a package's data directory.
  560. Args:
  561. package_name: Name of a package installed on the device.
  562. package_file: Path of the file within the package data directory.
  563. Returns:
  564. Absolute path to the file in the package data directory.
  565. """
  566. return '/'.join(Adb.get_package_data_directory(package_name), package_file)
  567. def pull_package_file(self, package_name, package_file, output_file):
  568. """Pull a file from a package's directory.
  569. Args:
  570. package_name: Name of the package to pull the file from.
  571. package_file: Use Adb.get_package_file() to form the path.
  572. output_file: Local path to copy the remote file to.
  573. """
  574. self.shell_command('run-as %s chmod 666 %s' % (package_name, package_file),
  575. 'Unable to make %s readable.' % package_file)
  576. self.run_command('pull', [package_file, output_file],
  577. 'Unable to copy %s from device to %s.' % (package_file,
  578. output_file))
  579. class SignalHandler(object):
  580. """Signal handler which allows signals to be sent to the subprocess.
  581. Attributes:
  582. called: Whether the signal handler has been called.
  583. signal_number: Number of the signal being caught.
  584. signal_handler: Original handler of the signal, restored on restore().
  585. """
  586. def __init__(self):
  587. """Initialize the instance."""
  588. self.called = False
  589. self.signal_number = 0
  590. self.signal_handler = None
  591. def __call__(self, unused_signal, unused_frame):
  592. """Logs whether the signal handler has been called."""
  593. self.called = True
  594. def acquire(self, signal_number):
  595. """Override the specified signal handler with this instance.
  596. Args:
  597. signal_number: Signal to override with this instance.
  598. """
  599. assert not self.signal_handler
  600. self.signal_number = signal_number
  601. self.signal_handler = signal.signal(self.signal_number, self)
  602. def release(self):
  603. """Restore the signal handler associated with this instance."""
  604. assert self.signal_handler
  605. signal.signal(self.signal_number, self.signal_handler)
  606. self.signal_handler = None
  607. class PerfArgsCommand(object):
  608. """Properties of a perf command.
  609. Attributes:
  610. name: Name of the command.
  611. sub_commands: Dictionary of sub-commands in the form of
  612. PerfArgsCommand instances indexed by sub-command name.
  613. value_options: List of value options that need to be skipped when
  614. determining the sub-command.
  615. verbose: Whether the command supports the verbose option.
  616. remote: Whether the command needs to be executed on a remote device.
  617. real_command: Whether this is a real perf command.
  618. output_filename: Default output filename for this command or '' if
  619. the command doesn't write to a file.
  620. input_filename: Default input filename for this command or '' if
  621. the command doesn't read from a file.
  622. """
  623. def __init__(self, name, sub_commands=None, value_options=None,
  624. verbose=False, remote=False, real_command=True,
  625. output_filename='', input_filename=''):
  626. """Initialize this instance.
  627. Args:
  628. name: Name of the command.
  629. sub_commands: List of sub-commands in the form of
  630. PerfArgsCommand instances.
  631. value_options: List of value options that need to be skipped when
  632. determining the sub-command.
  633. verbose: Whether the command supports the verbose option.
  634. remote: Whether the command needs to be executed on a remote device.
  635. real_command: Whether this is a real perf command.
  636. output_filename: Default output filename for this command or '' if
  637. the command doesn't write to a file.
  638. input_filename: Default input filename for this command or '' if
  639. the command doesn't read from a file.
  640. """
  641. self.name = name
  642. self.sub_commands = (dict([(cmd.name, cmd) for cmd in sub_commands]) if
  643. sub_commands else {})
  644. self.value_options = value_options if value_options else []
  645. self.verbose = verbose
  646. self.remote = remote
  647. self.real_command = real_command
  648. self.input_filename = input_filename
  649. self.output_filename = output_filename
  650. def __str__(self):
  651. """Get the name of the command.
  652. Returns:
  653. Name of the command.
  654. """
  655. return self.name
  656. class PerfArgs(object):
  657. """Class which parses and processes arguments to perf.
  658. Attributes:
  659. initial_args: Arguments the instance is initialized with.
  660. args: Arguments that have been modified by methods of this class.
  661. command: Primary perf command as a PerfArgsCommand instance.
  662. sub_command: PerfArgsCommand instance of the secondary command
  663. if provided, None otherwise.
  664. Class Attributes:
  665. SUPPORTED_COMMANDS: List of PerfArgsCommand instances, one for each
  666. command that *should* work with perf on Android. Not all commands have
  667. been tested
  668. SUPPORTED_COMMANDS_DICT: Dictionary populated from SUPPORTED_COMMANDS.
  669. """
  670. class Error(Exception):
  671. """Thrown if a problem is found parsing perf arguments."""
  672. pass
  673. SUPPORTED_COMMANDS = [
  674. PerfArgsCommand('annotate', verbose=True, input_filename='perf.data'),
  675. # May not be compiled in.
  676. PerfArgsCommand('archive', remote=True),
  677. # May not be compiled in.
  678. PerfArgsCommand('bench', remote=True),
  679. PerfArgsCommand('buildid-cache', verbose=True),
  680. PerfArgsCommand('buildid-list', verbose=True,
  681. input_filename='perf.data'),
  682. PerfArgsCommand('diff', verbose=True),
  683. PerfArgsCommand('evlist', input_filename='perf.data'),
  684. PerfArgsCommand('help'),
  685. PerfArgsCommand('inject', verbose=True),
  686. PerfArgsCommand('kmem',
  687. sub_commands=(PerfArgsCommand('record'),
  688. PerfArgsCommand('stat', remote=True)),
  689. value_options=('-i', '--input', '-s', '--sort',
  690. '-l', '--line'),
  691. input_filename='perf.data'),
  692. PerfArgsCommand('list', remote=True),
  693. PerfArgsCommand(
  694. 'lock',
  695. sub_commands=(PerfArgsCommand('record', remote=True,
  696. output_filename='perf.data'),
  697. PerfArgsCommand('trace', input_filename='perf.data'),
  698. PerfArgsCommand('report', input_filename='perf.data')),
  699. value_options=('-i', '--input'), verbose=True),
  700. PerfArgsCommand('probe', verbose=True, remote=True),
  701. PerfArgsCommand('record', verbose=True, remote=True,
  702. output_filename='perf.data'),
  703. PerfArgsCommand('report', verbose=True, input_filename='perf.data'),
  704. PerfArgsCommand('sched',
  705. sub_commands=(PerfArgsCommand('record', remote=True),
  706. PerfArgsCommand('latency'),
  707. PerfArgsCommand('map'),
  708. PerfArgsCommand('replay'),
  709. PerfArgsCommand('trace')),
  710. value_options=('-i', '--input'), verbose=True,
  711. input_filename='perf.data'),
  712. PerfArgsCommand('script',
  713. sub_commands=(PerfArgsCommand('record', remote=True),
  714. PerfArgsCommand('report')),
  715. value_options=('-s', '--script', '-g', '--gen-script',
  716. '-i', '--input', '-k', '--vmlinux',
  717. '--kallsyms', '--symfs'), verbose=True,
  718. input_filename='perf.data'),
  719. PerfArgsCommand('stat', output_filename='perf.data'),
  720. # May not be compiled in.
  721. PerfArgsCommand('test'),
  722. PerfArgsCommand('timechart',
  723. sub_commands=(PerfArgsCommand('record'),),
  724. value_options=('-i', '--input', '-o', '--output',
  725. '-w', '--width', '-p', '--process',
  726. '--symfs'),
  727. output_filename='output.svg',
  728. input_filename='perf.data'),
  729. PerfArgsCommand('top', verbose=True),
  730. # Specific to this script.
  731. PerfArgsCommand('visualize', real_command=False,
  732. input_filename='perf.data')]
  733. SUPPORTED_COMMANDS_DICT = dict([(cmd.name, cmd)
  734. for cmd in SUPPORTED_COMMANDS])
  735. def __init__(self, args, verbose):
  736. """Initialize the instance.
  737. Args:
  738. args: List of strings stored in initial_args.
  739. verbose: Whether verbose output is enabled.
  740. Raises:
  741. PerfArgs.Error: If a perf command isn't supported.
  742. """
  743. self.initial_args = args
  744. self.args = list(args)
  745. self.man_to_builtin_help()
  746. command_arg = self.args[0] if self.args else 'help'
  747. self.command = PerfArgs.SUPPORTED_COMMANDS_DICT.get(command_arg)
  748. if not self.command:
  749. raise PerfArgs.Error('Unsupported perf command %s' % command_arg)
  750. if self.command.verbose and verbose:
  751. self.args.append('--verbose')
  752. self.sub_command = self.get_sub_command()
  753. def get_sub_command(self):
  754. """Get the sub-command for the current command if applicable.
  755. Returns:
  756. PerfArgsCommand instance for the sub-command of the current command. If
  757. a sub-command isn't found None is returned.
  758. """
  759. if len(self.args) > 2:
  760. index = 1
  761. arg = self.args[1]
  762. while index < len(self.args):
  763. arg = self.args[index]
  764. if not arg.startswith('-'):
  765. break
  766. if arg in self.command.value_options:
  767. index += 1
  768. index += 1
  769. return self.command.sub_commands.get(arg)
  770. return None
  771. def requires_root(self):
  772. """Determines whether the perf command requires a rooted device.
  773. Returns:
  774. True if the command requires root, False otherwise.
  775. """
  776. if self.command.name == 'top' and not [
  777. arg for arg in self.args[1:] if arg in ('-p', '-t', '-u')]:
  778. return True
  779. return False
  780. def requires_remote(self):
  781. """Determine whether the perf command needs to run on a remote device.
  782. Returns:
  783. True if perf should be run on an Android device, False otherwise.
  784. """
  785. return self.command.remote or (self.sub_command and
  786. self.sub_command.remote)
  787. def insert_process_option(self, pid):
  788. """Inserts a process option into the argument list.
  789. Inserts a process option into the argument list if the command accepts
  790. a process ID.
  791. Args:
  792. pid: Process ID to add to the argument list.
  793. """
  794. if (self.command.name in ('record', 'stat', 'top') or
  795. (self.command.name == 'script' and
  796. self.sub_command and self.sub_command.name == 'record')):
  797. self.args.extend(('-p', str(pid)))
  798. def get_help_enabled(self):
  799. """Determine whether help display is requested in the arguments.
  800. Returns:
  801. True if help should be displayed, False otherwise.
  802. """
  803. return [arg for arg in self.args if arg in ('-h', '--help', 'help')]
  804. def man_to_builtin_help(self):
  805. """Convert perf arguments in the form "HELP COMMAND" to "COMMAND -h".
  806. Man pages are not provided with the binaries associated with this
  807. distribution so requests for them will fail. This function converts
  808. requests for man pages to arguments that result in retrieving the built-in
  809. documentation from the perf binaries.
  810. """
  811. args = self.args
  812. out_args = []
  813. index = 0
  814. while index < len(args):
  815. arg = args[index]
  816. if arg == 'help' and index + 1 < len(args):
  817. out_args.append(args[index + 1])
  818. out_args.append('-h')
  819. index += 1
  820. elif arg == '--help' and index + 1 == len(args):
  821. out_args.append('-h')
  822. else:
  823. out_args.append(arg)
  824. index += 1
  825. # Convert top level help argument into a form perf understands.
  826. if [arg for arg in out_args[0:1] if arg in ('-h', '--help')]:
  827. out_args = ['help']
  828. self.args = out_args
  829. def insert_symfs_dir(self, symbols_dir):
  830. """Insert symbols directory into perf arguments if it's not specified.
  831. Args:
  832. symbols_dir: Directory that contains symbols for perf data.
  833. """
  834. if not symbols_dir or self.command.name not in (
  835. 'annotate', 'diff', 'report', 'script', 'timechart', 'visualize'):
  836. return
  837. if '--symfs' in self.args:
  838. return
  839. out_args = list(self.args)
  840. out_args.extend(('--symfs', symbols_dir))
  841. self.args = out_args
  842. def parse_value_option(self, options):
  843. """Parse an argument with a value from the current argument list.
  844. Args:
  845. options: List of equivalent option strings (e.g '-o' and '--output') that
  846. are followed by the value to be retrieved.
  847. Returns:
  848. The index of the value argument in the 'args' attribute or -1 if it's
  849. not found.
  850. """
  851. index = -1
  852. for i, arg in enumerate(self.args):
  853. if arg in options and i < len(self.args) - 1:
  854. index = i + 1
  855. break
  856. return index
  857. def get_default_output_filename(self):
  858. """Get the default output filename for the current command.
  859. Returns:
  860. String containing the default output filename for the current command
  861. if the command results in an output file, empty string otherwise.
  862. """
  863. for command in (self.command, self.sub_command):
  864. if command and command.output_filename:
  865. return command.output_filename
  866. return ''
  867. def get_output_filename(self, remote_output_filename=''):
  868. """Parse output filename from perf arguments.
  869. Args:
  870. remote_output_filename: If this is a non-zero length string it replaces
  871. the current output filename in the arguments.
  872. Returns:
  873. Original output filename string.
  874. """
  875. output_filename = self.get_default_output_filename()
  876. if not output_filename:
  877. return ''
  878. index = self.parse_value_option(['-o'])
  879. if index >= 0:
  880. output_filename = self.args[index]
  881. if remote_output_filename:
  882. self.args[index] = remote_output_filename
  883. elif remote_output_filename:
  884. self.args.extend(('-o', remote_output_filename))
  885. return output_filename
  886. def get_default_input_filename(self):
  887. """Get the default input filename for the current command.
  888. Returns:
  889. String containing the default input filename for the current command
  890. if the command results in an input file, empty string otherwise.
  891. """
  892. for command in (self.command, self.sub_command):
  893. if command and command.input_filename:
  894. return command.input_filename
  895. return ''
  896. def get_input_filename(self):
  897. """Parse input filename from perf arguments.
  898. Returns:
  899. Input filename string if found in the arguments or the default input
  900. filename for the command.
  901. """
  902. index = self.parse_value_option(['-i'])
  903. return (self.args[index] if index >= 0 else
  904. self.get_default_input_filename())
  905. def process_remote_args(self, remote_output_filename,
  906. call_graph_recording, timestamp_recording):
  907. """Process arguments specifically for remote commands.
  908. Args:
  909. remote_output_filename: Output filename on the remote device.
  910. call_graph_recording: Enable recording of call graphs.
  911. timestamp_recording: Enable recording of time stamps.
  912. Returns:
  913. The local output filename string or an empty string if this doesn't
  914. reference the record command.
  915. """
  916. if self.command.name not in ('record', 'top', 'stat'):
  917. return ''
  918. # Use -m 4 due to certain devices not having mmap data pages.
  919. if self.command.name == 'record':
  920. self.args.extend(('-m', '4'))
  921. if call_graph_recording:
  922. self.args.append('-g')
  923. if timestamp_recording:
  924. self.args.append('-T')
  925. return self.get_output_filename(remote_output_filename)
  926. class ThreadedReader(threading.Thread):
  927. """Reads a file like object into a string from a thread.
  928. This also optionally writes data read to an output file.
  929. Attributes:
  930. read_file: File to read.
  931. output_file: If this isn't None, data read from read_file will be written
  932. to this file.
  933. read_lines: List of line strings read from the file.
  934. """
  935. def __init__(self, read_file, output_file):
  936. """Initialize this instance.
  937. Args:
  938. read_file: File to read.
  939. output_file: If this isn't None, data read from read_file will be written
  940. to this file.
  941. """
  942. super(ThreadedReader, self).__init__()
  943. self.read_file = read_file
  944. self.output_file = output_file
  945. self.read_lines = []
  946. def run(self):
  947. """Capture output from read_file into read_string."""
  948. while True:
  949. line = self.read_file.readline()
  950. if not line:
  951. break
  952. self.read_lines.append(line)
  953. if self.output_file:
  954. self.output_file.write(line)
  955. def __str__(self):
  956. """Get the string read from the file.
  957. Returns:
  958. String read from the file.
  959. """
  960. return ''.join(self.read_lines)
  961. class CommandThread(threading.Thread):
  962. """Runs a command in a separate thread.
  963. Attributes:
  964. command_handler: Callable which implements the same interface as
  965. execute_command() used to run the command from this thread.
  966. executable: String path to the executable to run.
  967. executable_args: List of string arguments to pass to the executable.
  968. error: Error string to pass to the command_handler.
  969. kwargs: Keyword arguments to pass to the command handler.
  970. stdout: String containing the standard output of the executed command.
  971. stderr: String containing the standard error output of the executed
  972. command.
  973. returncode: Return code of the command.
  974. """
  975. def __init__(self, command_handler, executable, executable_args, error,
  976. **kwargs):
  977. """Initialize the instance.
  978. Args:
  979. command_handler: Callable which implements the same interface as
  980. execute_command() used to run the command from this thread.
  981. executable: String path to the executable to run.
  982. executable_args: List of string arguments to pass to the executable.
  983. error: Error string to pass to the command_handler.
  984. **kwargs: Keyword arguments to pass to the command handler.
  985. """
  986. super(CommandThread, self).__init__()
  987. self.command_handler = command_handler
  988. self.executable = executable
  989. self.executable_args = executable_args
  990. self.error = error
  991. self.stdout = ''
  992. self.stderr = ''
  993. self.returncode = 0
  994. self.kwargs = kwargs
  995. def run(self):
  996. """Execute the command."""
  997. # Signals can only be caught from the main thread so disable capture.
  998. kwargs = dict(self.kwargs)
  999. kwargs['catch_sigint'] = False
  1000. try:
  1001. self.stdout, self.stderr, _ = self.command_handler(
  1002. self.executable, self.executable_args, self.error, **kwargs)
  1003. except CommandFailedError as e:
  1004. self.returncode = e.returncode
  1005. class ProgressDisplay(object):
  1006. """Displays a simple percentage progress display.
  1007. Args:
  1008. previous_progress: Value of the progress display the last time it was
  1009. displayed.
  1010. interval: How often to update the progress display e.g 0.1 will
  1011. update the display each time the difference between the current
  1012. progress value and previous_progress exceeds 0.1.
  1013. """
  1014. def __init__(self, previous_progress=0.0, interval=0.1):
  1015. """Initialize the instance.
  1016. Args:
  1017. previous_progress: Value of the progress display the last time it was
  1018. displayed.
  1019. interval: How often to update the progress display e.g 0.1 will
  1020. update the display each time the difference between the current
  1021. progress value and previous_progress exceeds 0.1.
  1022. """
  1023. self.previous_progress = previous_progress
  1024. self.interval = interval
  1025. def update(self, progress):
  1026. """Display a basic percentage progress display.
  1027. Args:
  1028. progress: Progress value to display, 0.1 == 10% etc.
  1029. """
  1030. if progress - self.previous_progress > self.interval or int(progress) == 1:
  1031. self.previous_progress = progress
  1032. sys.stderr.write('\r%d%%' % int(progress * 100.0))
  1033. sys.stderr.flush()
  1034. if int(progress) == 1:
  1035. sys.stderr.write(os.linesep)
  1036. class PerfIp(object):
  1037. """Perf instruction pointer.
  1038. Attributes:
  1039. ip: Instruction pointer.
  1040. symbol: Symbol at the address.
  1041. dso: Object (shared library, executable etc.) symbol was located in.
  1042. """
  1043. def __init__(self, ip, symbol, dso):
  1044. """Initialize the instance.
  1045. Args:
  1046. ip: Instruction pointer.
  1047. symbol: Symbol at the address.
  1048. dso: Object (shared library, executable etc.) symbol was located in.
  1049. """
  1050. self.ip = ip
  1051. self.symbol = symbol
  1052. self.dso = dso
  1053. class PerfRecordSample(object):
  1054. """Subset of a perf record sample.
  1055. Attributes:
  1056. file_offset: Offset of the sample in the source file.
  1057. event_type: Perf event type (should be PERF_RECORD_SAMPLE).
  1058. pid: ID of the process sampled.
  1059. tid: ID of the thread sampled.
  1060. ip: Instruction pointer at the time of the sample.
  1061. period: Period of the sample, if this was a recorded at a fixed frequency
  1062. this will be 1.
  1063. command: Name of the executable sampled.
  1064. time: Time sample was taken.
  1065. event: Type of record event.
  1066. stack: List of PerfIp instances which represent the stack of this sample.
  1067. """
  1068. def __init__(self, file_offset, event_type, pid, tid, ip, period,
  1069. command, sample_time, event):
  1070. """Initialize the instance.
  1071. Args:
  1072. file_offset: Offset of the sample in the source file.
  1073. event_type: Perf event type (should be PERF_RECORD_SAMPLE).
  1074. pid: ID of the process sampled.
  1075. tid: ID of the thread sampled.
  1076. ip: Instruction pointer at the time of the sample.
  1077. period: Period of the sample, if this was a recorded at a fixed frequency
  1078. this will be 1.
  1079. command: Name of the executable sampled.
  1080. sample_time: Time sample was taken.
  1081. event: Type of record event.
  1082. """
  1083. self.file_offset = file_offset
  1084. self.event_type = event_type
  1085. self.pid = pid
  1086. self.tid = tid
  1087. self.ip = ip
  1088. self.period = period
  1089. self.command = command
  1090. self.time = sample_time
  1091. self.event = event
  1092. self.stack = []
  1093. def version_to_tuple(version):
  1094. """Convert a version to a tuple of ints.
  1095. Args:
  1096. version: Version to convert
  1097. Returns:
  1098. Tuple of ints
  1099. """
  1100. return tuple([int(elem) for elem in version.split('.')])
  1101. def is_version_less_than(version1, version2):
  1102. """Comare to version strings.
  1103. Args:
  1104. version1: The first version to compare
  1105. version2: The second version to compare
  1106. Returns:
  1107. True if version1 < version2 and false otherwise.
  1108. """
  1109. return version_to_tuple(version1) < version_to_tuple(version2)
  1110. def get_package_name_from_manifest(manifest_filename):
  1111. """Gets the name of the apk package to profile from the Manifest.
  1112. Args:
  1113. manifest_filename: The name of the AndroidManifest file to search through.
  1114. Returns:
  1115. (package_name, activity_name) tuple where package_name is the name of the
  1116. package and activity is the main activity from the first application in
  1117. the package.
  1118. Raises:
  1119. Error: If it's not possible to parse the manifest.
  1120. """
  1121. if not os.path.isfile(manifest_filename):
  1122. raise Error('Cannot find Manifest %s, please specify the directory '
  1123. 'where the manifest is located with --apk-directory.' % (
  1124. manifest_filename))
  1125. xml = minidom.parse(manifest_filename)
  1126. manifest_tag = xml.getElementsByTagName('manifest')[0]
  1127. package_name = manifest_tag.getAttribute('package')
  1128. application_tag = manifest_tag.getElementsByTagName('application')[0]
  1129. for activity_tag in application_tag.getElementsByTagName('activity'):
  1130. for intent_filter_tag in activity_tag.getElementsByTagName(
  1131. 'intent-filter'):
  1132. for action_tag in intent_filter_tag.getElementsByTagName('action'):
  1133. if (action_tag.getAttribute('android:name') ==
  1134. 'android.intent.action.MAIN'):
  1135. activity = activity_tag.getAttribute('android:name')
  1136. return (package_name, activity)
  1137. def get_host_os_name_architecture():
  1138. """Get the OS name for the host and the architecture.
  1139. Returns:
  1140. (os_name, architectures) tuple where os_name is a string that contains the
  1141. name of the OS and architectures is a list of supported processor
  1142. architectures, in the form used by the AOSP build system.
  1143. Raises:
  1144. Error: If the operating system isn't recognized.
  1145. """
  1146. system_name = platform.system()
  1147. for regexp, os_name in HOST_SYSTEM_TO_OS_NAME:
  1148. if regexp.match(system_name):
  1149. return (os_name, HOST_MACHINE_TYPE_TO_ARCHITECTURE[platform.machine()])
  1150. raise Error('Unknown OS %s' % system_name)
  1151. def get_target_architectures(adb_device):
  1152. """Get the architecture of the target device.
  1153. Args:
  1154. adb_device: The device to query.
  1155. Returns:
  1156. List of compatible architecture strings in the form used by the AOSP build
  1157. system.
  1158. """
  1159. architectures = []
  1160. for abi in adb_device.get_supported_abis():
  1161. architectures.extend(ANDROID_ABI_TO_ARCHITECTURE[abi])
  1162. # Remove duplicates from the returned list.
  1163. unsorted_architectures = set(architectures)
  1164. sorted_architectures = []
  1165. for arch in architectures:
  1166. if arch in unsorted_architectures:
  1167. unsorted_architectures.remove(arch)
  1168. sorted_architectures.append(arch)
  1169. return sorted_architectures
  1170. def find_target_binary(name, adb_device):
  1171. """Find the path of the specified target (Android) binary.
  1172. Args:
  1173. name: The name of the binary to find.
  1174. adb_device: Device connected to the host.
  1175. Returns:
  1176. The path of the binary.
  1177. Raises:
  1178. BinaryNotFoundError: If the specified binary isn't found.
  1179. """
  1180. arch_paths = []
  1181. if adb_device:
  1182. target_architectures = get_target_architectures(adb_device)
  1183. for api_level in range(adb_device.get_api_level(),
  1184. PERF_MIN_API_LEVEL - 1, -1):
  1185. arch_paths.extend([os.path.join('android-%d' % api_level,
  1186. '-'.join(('arch', arch)))
  1187. for arch in target_architectures])
  1188. arch_paths.append('')
  1189. for arch_path in arch_paths:
  1190. for search_path in TARGET_BINARY_SEARCH_PATHS:
  1191. binary_path = os.path.join(search_path, arch_path, name)
  1192. if os.path.exists(binary_path):
  1193. return binary_path
  1194. raise BinaryNotFoundError('Unable to find Android %s binary %s' % (
  1195. arch_paths[0], name))
  1196. def get_host_executable_extensions():
  1197. """Get a list of executable file extensions.
  1198. Returns:
  1199. A list of executable file extensions.
  1200. """
  1201. # On Windows search for filenames that have executable extensions.
  1202. exe_extensions = ['']
  1203. if platform.system() == 'Windows':
  1204. extensions = os.getenv('PATHEXT')
  1205. if extensions:
  1206. exe_extensions.extend(extensions.split(os.pathsep))
  1207. return exe_extensions
  1208. def find_host_binary(name, adb_device=None):
  1209. """Find the path of the specified host binary.
  1210. Args:
  1211. name: The name of the binary to find.
  1212. adb_device: Device connected to the host, if this is None this function
  1213. will search for device specific binaries in the most recent API
  1214. directory.