blob: 93c1fdab01f57b13bf6180360c08b35f22c34800 [file] [log] [blame]
Sergei Trofimov4e6afe92015-10-09 09:30:04 +01001# Copyright 2013-2015 ARM Limited
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15
16
17"""
18Utility functions for working with Android devices through adb.
19
20"""
21# pylint: disable=E1103
22import os
23import time
24import subprocess
25import logging
26import re
27from collections import defaultdict
28
Sebastian Goscik8de24b52016-03-23 15:10:26 +000029from devlib.exception import TargetError, HostError, DevlibError
30from devlib.utils.misc import check_output, which, memoized
Sergei Trofimov4e6afe92015-10-09 09:30:04 +010031from devlib.utils.misc import escape_single_quotes, escape_double_quotes
32
33
34logger = logging.getLogger('android')
35
36MAX_ATTEMPTS = 5
37AM_START_ERROR = re.compile(r"Error: Activity class {[\w|.|/]*} does not exist")
38
39# See:
40# http://developer.android.com/guide/topics/manifest/uses-sdk-element.html#ApiLevels
41ANDROID_VERSION_MAP = {
Sebastian Goscik0c112892016-02-15 15:35:56 +000042 23: 'MARSHMALLOW',
Sergei Trofimov4e6afe92015-10-09 09:30:04 +010043 22: 'LOLLYPOP_MR1',
44 21: 'LOLLYPOP',
45 20: 'KITKAT_WATCH',
46 19: 'KITKAT',
47 18: 'JELLY_BEAN_MR2',
48 17: 'JELLY_BEAN_MR1',
49 16: 'JELLY_BEAN',
50 15: 'ICE_CREAM_SANDWICH_MR1',
51 14: 'ICE_CREAM_SANDWICH',
52 13: 'HONEYCOMB_MR2',
53 12: 'HONEYCOMB_MR1',
54 11: 'HONEYCOMB',
55 10: 'GINGERBREAD_MR1',
56 9: 'GINGERBREAD',
57 8: 'FROYO',
58 7: 'ECLAIR_MR1',
59 6: 'ECLAIR_0_1',
60 5: 'ECLAIR',
61 4: 'DONUT',
62 3: 'CUPCAKE',
63 2: 'BASE_1_1',
64 1: 'BASE',
65}
66
67
68# Initialized in functions near the botton of the file
69android_home = None
70platform_tools = None
71adb = None
72aapt = None
73fastboot = None
74
75
76class AndroidProperties(object):
77
78 def __init__(self, text):
79 self._properties = {}
80 self.parse(text)
81
82 def parse(self, text):
83 self._properties = dict(re.findall(r'\[(.*?)\]:\s+\[(.*?)\]', text))
84
85 def iteritems(self):
86 return self._properties.iteritems()
87
88 def __iter__(self):
89 return iter(self._properties)
90
91 def __getattr__(self, name):
92 return self._properties.get(name)
93
94 __getitem__ = __getattr__
95
96
97class AdbDevice(object):
98
99 def __init__(self, name, status):
100 self.name = name
101 self.status = status
102
103 def __cmp__(self, other):
104 if isinstance(other, AdbDevice):
105 return cmp(self.name, other.name)
106 else:
107 return cmp(self.name, other)
108
109 def __str__(self):
110 return 'AdbDevice({}, {})'.format(self.name, self.status)
111
112 __repr__ = __str__
113
114
115class ApkInfo(object):
116
117 version_regex = re.compile(r"name='(?P<name>[^']+)' versionCode='(?P<vcode>[^']+)' versionName='(?P<vname>[^']+)'")
118 name_regex = re.compile(r"name='(?P<name>[^']+)'")
119
120 def __init__(self, path=None):
121 self.path = path
122 self.package = None
123 self.activity = None
124 self.label = None
125 self.version_name = None
126 self.version_code = None
127 self.parse(path)
128
129 def parse(self, apk_path):
130 _check_env()
131 command = [aapt, 'dump', 'badging', apk_path]
132 logger.debug(' '.join(command))
133 output = subprocess.check_output(command)
134 for line in output.split('\n'):
135 if line.startswith('application-label:'):
136 self.label = line.split(':')[1].strip().replace('\'', '')
137 elif line.startswith('package:'):
138 match = self.version_regex.search(line)
139 if match:
140 self.package = match.group('name')
141 self.version_code = match.group('vcode')
142 self.version_name = match.group('vname')
143 elif line.startswith('launchable-activity:'):
144 match = self.name_regex.search(line)
145 self.activity = match.group('name')
146 else:
147 pass # not interested
148
149
150class AdbConnection(object):
151
152 # maintains the count of parallel active connections to a device, so that
153 # adb disconnect is not invoked untill all connections are closed
154 active_connections = defaultdict(int)
Sergei Trofimov89256fd2016-05-17 14:00:01 +0100155 default_timeout = 10
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100156
157 @property
158 def name(self):
159 return self.device
160
Sebastian Goscik8de24b52016-03-23 15:10:26 +0000161 @property
162 @memoized
163 def newline_separator(self):
164 output = adb_command(self.device, "shell '(ls); echo \"\n$?\"'")
165 if output.endswith('\r\n'):
166 return '\r\n'
167 elif output.endswith('\n'):
168 return '\n'
169 else:
170 raise DevlibError("Unknown line ending")
171
Sergei Trofimov89256fd2016-05-17 14:00:01 +0100172 def __init__(self, device=None, timeout=None):
173 self.timeout = timeout if timeout is not None else self.default_timeout
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100174 if device is None:
175 device = adb_get_device(timeout=timeout)
176 self.device = device
177 adb_connect(self.device)
178 AdbConnection.active_connections[self.device] += 1
179
180 def push(self, source, dest, timeout=None):
181 if timeout is None:
182 timeout = self.timeout
Sebastian Goscik1424ceb2016-02-15 15:27:19 +0000183 command = "push '{}' '{}'".format(source, dest)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100184 return adb_command(self.device, command, timeout=timeout)
185
186 def pull(self, source, dest, timeout=None):
187 if timeout is None:
188 timeout = self.timeout
Patrick Bellasic93e3d62015-11-25 11:19:08 +0000189 # Pull all files matching a wildcard expression
190 if os.path.isdir(dest) and \
Sebastian Goscikaab487c2016-02-15 15:21:40 +0000191 ('*' in source or '?' in source):
Patrick Bellasic93e3d62015-11-25 11:19:08 +0000192 command = 'shell ls {}'.format(source)
193 output = adb_command(self.device, command, timeout=timeout)
194 for line in output.splitlines():
Sebastian Goscik1424ceb2016-02-15 15:27:19 +0000195 command = "pull '{}' '{}'".format(line, dest)
Patrick Bellasic93e3d62015-11-25 11:19:08 +0000196 adb_command(self.device, command, timeout=timeout)
197 return
Sebastian Goscik1424ceb2016-02-15 15:27:19 +0000198 command = "pull '{}' '{}'".format(source, dest)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100199 return adb_command(self.device, command, timeout=timeout)
200
201 def execute(self, command, timeout=None, check_exit_code=False, as_root=False):
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100202 return adb_shell(self.device, command, timeout, check_exit_code,
203 as_root, self.newline_separator)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100204
205 def background(self, command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, as_root=False):
206 return adb_background_shell(self.device, command, stdout, stderr, as_root)
207
208 def close(self):
209 AdbConnection.active_connections[self.device] -= 1
210 if AdbConnection.active_connections[self.device] <= 0:
211 adb_disconnect(self.device)
212 del AdbConnection.active_connections[self.device]
213
214 def cancel_running_command(self):
215 # adbd multiplexes commands so that they don't interfer with each
216 # other, so there is no need to explicitly cancel a running command
217 # before the next one can be issued.
218 pass
219
220
221def fastboot_command(command, timeout=None):
222 _check_env()
223 full_command = "fastboot {}".format(command)
224 logger.debug(full_command)
225 output, _ = check_output(full_command, timeout, shell=True)
226 return output
227
228
229def fastboot_flash_partition(partition, path_to_image):
230 command = 'flash {} {}'.format(partition, path_to_image)
231 fastboot_command(command)
232
233
234def adb_get_device(timeout=None):
235 """
236 Returns the serial number of a connected android device.
237
238 If there are more than one device connected to the machine, or it could not
239 find any device connected, :class:`devlib.exceptions.HostError` is raised.
240 """
241 # TODO this is a hacky way to issue a adb command to all listed devices
242
243 # The output of calling adb devices consists of a heading line then
244 # a list of the devices sperated by new line
245 # The last line is a blank new line. in otherwords, if there is a device found
246 # then the output length is 2 + (1 for each device)
247 start = time.time()
248 while True:
249 output = adb_command(None, "devices").splitlines() # pylint: disable=E1103
250 output_length = len(output)
251 if output_length == 3:
252 # output[1] is the 2nd line in the output which has the device name
253 # Splitting the line by '\t' gives a list of two indexes, which has
254 # device serial in 0 number and device type in 1.
255 return output[1].split('\t')[0]
256 elif output_length > 3:
257 message = '{} Android devices found; either explicitly specify ' +\
Sebastian Goscikaab487c2016-02-15 15:21:40 +0000258 'the device you want, or make sure only one is connected.'
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100259 raise HostError(message.format(output_length - 2))
260 else:
261 if timeout < time.time() - start:
262 raise HostError('No device is connected and available')
263 time.sleep(1)
264
265
266def adb_connect(device, timeout=None, attempts=MAX_ATTEMPTS):
267 _check_env()
Patrick Bellasif714dd32016-07-15 11:18:09 +0100268 # Connect is required only for ADB-over-IP
269 if "." not in device:
270 logger.debug('Device connected via USB, connect not required')
271 return
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100272 tries = 0
273 output = None
274 while tries <= attempts:
275 tries += 1
276 if device:
277 command = 'adb connect {}'.format(device)
278 logger.debug(command)
279 output, _ = check_output(command, shell=True, timeout=timeout)
280 if _ping(device):
281 break
282 time.sleep(10)
283 else: # did not connect to the device
284 message = 'Could not connect to {}'.format(device or 'a device')
285 if output:
286 message += '; got: "{}"'.format(output)
287 raise HostError(message)
288
289
290def adb_disconnect(device):
291 _check_env()
292 if not device:
293 return
Chris Redpath119fd7d2016-10-06 16:34:14 +0100294 if ":" in device and device in adb_list_devices():
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100295 command = "adb disconnect " + device
296 logger.debug(command)
297 retval = subprocess.call(command, stdout=open(os.devnull, 'wb'), shell=True)
298 if retval:
299 raise TargetError('"{}" returned {}'.format(command, retval))
300
301
302def _ping(device):
303 _check_env()
304 device_string = ' -s {}'.format(device) if device else ''
305 command = "adb{} shell \"ls / > /dev/null\"".format(device_string)
306 logger.debug(command)
307 result = subprocess.call(command, stderr=subprocess.PIPE, shell=True)
308 if not result:
309 return True
310 else:
311 return False
312
313
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100314def adb_shell(device, command, timeout=None, check_exit_code=False,
315 as_root=False, newline_separator='\r\n'): # NOQA
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100316 _check_env()
317 if as_root:
Sergei Trofimov171cc252015-12-14 17:21:47 +0000318 command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100319 device_string = ' -s {}'.format(device) if device else ''
320 full_command = 'adb{} shell "{}"'.format(device_string,
321 escape_double_quotes(command))
322 logger.debug(full_command)
323 if check_exit_code:
Sergei Trofimovf52bf792015-12-11 17:18:18 +0000324 actual_command = "adb{} shell '({}); echo \"\n$?\"'".format(device_string,
Sergei Trofimov64261a62015-11-24 12:50:02 +0000325 escape_single_quotes(command))
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100326 raw_output, error = check_output(actual_command, timeout, shell=True)
327 if raw_output:
328 try:
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100329 output, exit_code, _ = raw_output.rsplit(newline_separator, 2)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100330 except ValueError:
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100331 exit_code, _ = raw_output.rsplit(newline_separator, 1)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100332 output = ''
333 else: # raw_output is empty
334 exit_code = '969696' # just because
335 output = ''
336
337 exit_code = exit_code.strip()
338 if exit_code.isdigit():
339 if int(exit_code):
340 message = 'Got exit code {}\nfrom: {}\nSTDOUT: {}\nSTDERR: {}'
341 raise TargetError(message.format(exit_code, full_command, output, error))
342 elif AM_START_ERROR.findall(output):
343 message = 'Could not start activity; got the following:'
344 message += '\n{}'.format(AM_START_ERROR.findall(output)[0])
345 raise TargetError(message)
346 else: # not all digits
347 if AM_START_ERROR.findall(output):
348 message = 'Could not start activity; got the following:\n{}'
349 raise TargetError(message.format(AM_START_ERROR.findall(output)[0]))
350 else:
351 message = 'adb has returned early; did not get an exit code. '\
352 'Was kill-server invoked?'
353 raise TargetError(message)
354 else: # do not check exit code
355 output, _ = check_output(full_command, timeout, shell=True)
356 return output
357
358
359def adb_background_shell(device, command,
360 stdout=subprocess.PIPE,
361 stderr=subprocess.PIPE,
362 as_root=False):
363 """Runs the sepcified command in a subprocess, returning the the Popen object."""
364 _check_env()
365 if as_root:
366 command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
367 device_string = ' -s {}'.format(device) if device else ''
368 full_command = 'adb{} shell "{}"'.format(device_string, escape_double_quotes(command))
369 logger.debug(full_command)
370 return subprocess.Popen(full_command, stdout=stdout, stderr=stderr, shell=True)
371
372
373def adb_list_devices():
374 output = adb_command(None, 'devices')
375 devices = []
376 for line in output.splitlines():
377 parts = [p.strip() for p in line.split()]
378 if len(parts) == 2:
379 devices.append(AdbDevice(*parts))
380 return devices
381
382
383def adb_command(device, command, timeout=None):
384 _check_env()
385 device_string = ' -s {}'.format(device) if device else ''
386 full_command = "adb{} {}".format(device_string, command)
387 logger.debug(full_command)
388 output, _ = check_output(full_command, timeout, shell=True)
389 return output
390
391
392# Messy environment initialisation stuff...
393
394class _AndroidEnvironment(object):
395
396 def __init__(self):
397 self.android_home = None
398 self.platform_tools = None
399 self.adb = None
400 self.aapt = None
401 self.fastboot = None
402
403
404def _initialize_with_android_home(env):
405 logger.debug('Using ANDROID_HOME from the environment.')
406 env.android_home = android_home
407 env.platform_tools = os.path.join(android_home, 'platform-tools')
408 os.environ['PATH'] += os.pathsep + env.platform_tools
409 _init_common(env)
410 return env
411
412
413def _initialize_without_android_home(env):
Javi Merino7f32efc2015-12-15 13:43:56 +0000414 adb_full_path = which('adb')
415 if adb_full_path:
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100416 env.adb = 'adb'
417 else:
418 raise HostError('ANDROID_HOME is not set and adb is not in PATH. '
419 'Have you installed Android SDK?')
420 logger.debug('Discovering ANDROID_HOME from adb path.')
Javi Merino7f32efc2015-12-15 13:43:56 +0000421 env.platform_tools = os.path.dirname(adb_full_path)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100422 env.android_home = os.path.dirname(env.platform_tools)
423 _init_common(env)
424 return env
425
426
427def _init_common(env):
428 logger.debug('ANDROID_HOME: {}'.format(env.android_home))
429 build_tools_directory = os.path.join(env.android_home, 'build-tools')
430 if not os.path.isdir(build_tools_directory):
431 msg = '''ANDROID_HOME ({}) does not appear to have valid Android SDK install
432 (cannot find build-tools)'''
433 raise HostError(msg.format(env.android_home))
434 versions = os.listdir(build_tools_directory)
435 for version in reversed(sorted(versions)):
436 aapt_path = os.path.join(build_tools_directory, version, 'aapt')
437 if os.path.isfile(aapt_path):
438 logger.debug('Using aapt for version {}'.format(version))
439 env.aapt = aapt_path
440 break
441 else:
442 raise HostError('aapt not found. Please make sure at least one Android '
443 'platform is installed.')
444
445
446def _check_env():
447 global android_home, platform_tools, adb, aapt # pylint: disable=W0603
448 if not android_home:
449 android_home = os.getenv('ANDROID_HOME')
450 if android_home:
451 _env = _initialize_with_android_home(_AndroidEnvironment())
452 else:
453 _env = _initialize_without_android_home(_AndroidEnvironment())
454 android_home = _env.android_home
455 platform_tools = _env.platform_tools
456 adb = _env.adb
457 aapt = _env.aapt