blob: 6e56c5885a66f4a950f9c62c42f5090bc4f9d93c [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
Chris Redpathe8e945a2016-10-14 14:35:58 +0100156 ls_command = 'ls'
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100157
158 @property
159 def name(self):
160 return self.device
161
Sebastian Goscik8de24b52016-03-23 15:10:26 +0000162 @property
163 @memoized
164 def newline_separator(self):
Chris Redpathe8e945a2016-10-14 14:35:58 +0100165 output = adb_command(self.device,
166 "shell '({}); echo \"\n$?\"'".format(self.ls_command))
Sebastian Goscik8de24b52016-03-23 15:10:26 +0000167 if output.endswith('\r\n'):
168 return '\r\n'
169 elif output.endswith('\n'):
170 return '\n'
171 else:
172 raise DevlibError("Unknown line ending")
173
Chris Redpathe8e945a2016-10-14 14:35:58 +0100174 # Again, we need to handle boards where the default output format from ls is
175 # single column *and* boards where the default output is multi-column.
176 # We need to do this purely because the '-1' option causes errors on older
177 # versions of the ls tool in Android pre-v7.
178 def _setup_ls(self):
179 command = "shell '(ls -1); echo \"\n$?\"'"
180 output = adb_command(self.device, command, timeout=self.timeout)
181 lines = output.splitlines()
182 retval = lines[-1].strip()
183 if int(retval) == 0:
184 self.ls_command = 'ls -1'
185 else:
186 self.ls_command = 'ls'
187 logger.info("ls command is set to {}".format(self.ls_command))
188
Sergei Trofimov89256fd2016-05-17 14:00:01 +0100189 def __init__(self, device=None, timeout=None):
190 self.timeout = timeout if timeout is not None else self.default_timeout
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100191 if device is None:
192 device = adb_get_device(timeout=timeout)
193 self.device = device
194 adb_connect(self.device)
195 AdbConnection.active_connections[self.device] += 1
Chris Redpathe8e945a2016-10-14 14:35:58 +0100196 self._setup_ls()
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100197
198 def push(self, source, dest, timeout=None):
199 if timeout is None:
200 timeout = self.timeout
Sebastian Goscik1424ceb2016-02-15 15:27:19 +0000201 command = "push '{}' '{}'".format(source, dest)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100202 return adb_command(self.device, command, timeout=timeout)
203
204 def pull(self, source, dest, timeout=None):
205 if timeout is None:
206 timeout = self.timeout
Patrick Bellasic93e3d62015-11-25 11:19:08 +0000207 # Pull all files matching a wildcard expression
208 if os.path.isdir(dest) and \
Sebastian Goscikaab487c2016-02-15 15:21:40 +0000209 ('*' in source or '?' in source):
Chris Redpathe8e945a2016-10-14 14:35:58 +0100210 command = 'shell {} {}'.format(self.ls_command, source)
Patrick Bellasic93e3d62015-11-25 11:19:08 +0000211 output = adb_command(self.device, command, timeout=timeout)
212 for line in output.splitlines():
Brendan Jackmanee38a422016-11-18 17:48:48 +0000213 command = "pull '{}' '{}'".format(line.strip(), dest)
Patrick Bellasic93e3d62015-11-25 11:19:08 +0000214 adb_command(self.device, command, timeout=timeout)
215 return
Sebastian Goscik1424ceb2016-02-15 15:27:19 +0000216 command = "pull '{}' '{}'".format(source, dest)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100217 return adb_command(self.device, command, timeout=timeout)
218
219 def execute(self, command, timeout=None, check_exit_code=False, as_root=False):
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100220 return adb_shell(self.device, command, timeout, check_exit_code,
221 as_root, self.newline_separator)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100222
223 def background(self, command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, as_root=False):
224 return adb_background_shell(self.device, command, stdout, stderr, as_root)
225
226 def close(self):
227 AdbConnection.active_connections[self.device] -= 1
228 if AdbConnection.active_connections[self.device] <= 0:
229 adb_disconnect(self.device)
230 del AdbConnection.active_connections[self.device]
231
232 def cancel_running_command(self):
233 # adbd multiplexes commands so that they don't interfer with each
234 # other, so there is no need to explicitly cancel a running command
235 # before the next one can be issued.
236 pass
237
238
239def fastboot_command(command, timeout=None):
240 _check_env()
241 full_command = "fastboot {}".format(command)
242 logger.debug(full_command)
243 output, _ = check_output(full_command, timeout, shell=True)
244 return output
245
246
247def fastboot_flash_partition(partition, path_to_image):
248 command = 'flash {} {}'.format(partition, path_to_image)
249 fastboot_command(command)
250
251
252def adb_get_device(timeout=None):
253 """
254 Returns the serial number of a connected android device.
255
256 If there are more than one device connected to the machine, or it could not
257 find any device connected, :class:`devlib.exceptions.HostError` is raised.
258 """
259 # TODO this is a hacky way to issue a adb command to all listed devices
260
261 # The output of calling adb devices consists of a heading line then
262 # a list of the devices sperated by new line
263 # The last line is a blank new line. in otherwords, if there is a device found
264 # then the output length is 2 + (1 for each device)
265 start = time.time()
266 while True:
267 output = adb_command(None, "devices").splitlines() # pylint: disable=E1103
268 output_length = len(output)
269 if output_length == 3:
270 # output[1] is the 2nd line in the output which has the device name
271 # Splitting the line by '\t' gives a list of two indexes, which has
272 # device serial in 0 number and device type in 1.
273 return output[1].split('\t')[0]
274 elif output_length > 3:
275 message = '{} Android devices found; either explicitly specify ' +\
Sebastian Goscikaab487c2016-02-15 15:21:40 +0000276 'the device you want, or make sure only one is connected.'
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100277 raise HostError(message.format(output_length - 2))
278 else:
279 if timeout < time.time() - start:
280 raise HostError('No device is connected and available')
281 time.sleep(1)
282
283
284def adb_connect(device, timeout=None, attempts=MAX_ATTEMPTS):
285 _check_env()
Patrick Bellasif714dd32016-07-15 11:18:09 +0100286 # Connect is required only for ADB-over-IP
287 if "." not in device:
288 logger.debug('Device connected via USB, connect not required')
289 return
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100290 tries = 0
291 output = None
292 while tries <= attempts:
293 tries += 1
294 if device:
295 command = 'adb connect {}'.format(device)
296 logger.debug(command)
297 output, _ = check_output(command, shell=True, timeout=timeout)
298 if _ping(device):
299 break
300 time.sleep(10)
301 else: # did not connect to the device
302 message = 'Could not connect to {}'.format(device or 'a device')
303 if output:
304 message += '; got: "{}"'.format(output)
305 raise HostError(message)
306
307
308def adb_disconnect(device):
309 _check_env()
310 if not device:
311 return
Chris Redpath119fd7d2016-10-06 16:34:14 +0100312 if ":" in device and device in adb_list_devices():
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100313 command = "adb disconnect " + device
314 logger.debug(command)
315 retval = subprocess.call(command, stdout=open(os.devnull, 'wb'), shell=True)
316 if retval:
317 raise TargetError('"{}" returned {}'.format(command, retval))
318
319
320def _ping(device):
321 _check_env()
322 device_string = ' -s {}'.format(device) if device else ''
323 command = "adb{} shell \"ls / > /dev/null\"".format(device_string)
324 logger.debug(command)
325 result = subprocess.call(command, stderr=subprocess.PIPE, shell=True)
326 if not result:
327 return True
328 else:
329 return False
330
331
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100332def adb_shell(device, command, timeout=None, check_exit_code=False,
333 as_root=False, newline_separator='\r\n'): # NOQA
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100334 _check_env()
335 if as_root:
Sergei Trofimov171cc252015-12-14 17:21:47 +0000336 command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
Marc Bonnicib59f7c32016-11-01 17:17:04 +0000337 device_part = ['-s', device] if device else []
338 device_string = ' {} {}'.format(*device_part) if device_part else ''
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100339 full_command = 'adb{} shell "{}"'.format(device_string,
340 escape_double_quotes(command))
341 logger.debug(full_command)
342 if check_exit_code:
Marc Bonnicib59f7c32016-11-01 17:17:04 +0000343 adb_shell_command = '({}); echo \"\n$?\"'.format(command)
344 actual_command = ['adb'] + device_part + ['shell', adb_shell_command]
345 raw_output, error = check_output(actual_command, timeout, shell=False)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100346 if raw_output:
347 try:
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100348 output, exit_code, _ = raw_output.rsplit(newline_separator, 2)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100349 except ValueError:
Patrick Bellasic2329bd2016-03-28 12:29:45 +0100350 exit_code, _ = raw_output.rsplit(newline_separator, 1)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100351 output = ''
352 else: # raw_output is empty
353 exit_code = '969696' # just because
354 output = ''
355
356 exit_code = exit_code.strip()
357 if exit_code.isdigit():
358 if int(exit_code):
359 message = 'Got exit code {}\nfrom: {}\nSTDOUT: {}\nSTDERR: {}'
360 raise TargetError(message.format(exit_code, full_command, output, error))
361 elif AM_START_ERROR.findall(output):
362 message = 'Could not start activity; got the following:'
363 message += '\n{}'.format(AM_START_ERROR.findall(output)[0])
364 raise TargetError(message)
365 else: # not all digits
366 if AM_START_ERROR.findall(output):
367 message = 'Could not start activity; got the following:\n{}'
368 raise TargetError(message.format(AM_START_ERROR.findall(output)[0]))
369 else:
370 message = 'adb has returned early; did not get an exit code. '\
371 'Was kill-server invoked?'
372 raise TargetError(message)
373 else: # do not check exit code
374 output, _ = check_output(full_command, timeout, shell=True)
375 return output
376
377
378def adb_background_shell(device, command,
379 stdout=subprocess.PIPE,
380 stderr=subprocess.PIPE,
381 as_root=False):
382 """Runs the sepcified command in a subprocess, returning the the Popen object."""
383 _check_env()
384 if as_root:
385 command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
386 device_string = ' -s {}'.format(device) if device else ''
387 full_command = 'adb{} shell "{}"'.format(device_string, escape_double_quotes(command))
388 logger.debug(full_command)
389 return subprocess.Popen(full_command, stdout=stdout, stderr=stderr, shell=True)
390
391
392def adb_list_devices():
393 output = adb_command(None, 'devices')
394 devices = []
395 for line in output.splitlines():
396 parts = [p.strip() for p in line.split()]
397 if len(parts) == 2:
398 devices.append(AdbDevice(*parts))
399 return devices
400
401
402def adb_command(device, command, timeout=None):
403 _check_env()
404 device_string = ' -s {}'.format(device) if device else ''
405 full_command = "adb{} {}".format(device_string, command)
406 logger.debug(full_command)
407 output, _ = check_output(full_command, timeout, shell=True)
408 return output
409
410
411# Messy environment initialisation stuff...
412
413class _AndroidEnvironment(object):
414
415 def __init__(self):
416 self.android_home = None
417 self.platform_tools = None
418 self.adb = None
419 self.aapt = None
420 self.fastboot = None
421
422
423def _initialize_with_android_home(env):
424 logger.debug('Using ANDROID_HOME from the environment.')
425 env.android_home = android_home
426 env.platform_tools = os.path.join(android_home, 'platform-tools')
427 os.environ['PATH'] += os.pathsep + env.platform_tools
428 _init_common(env)
429 return env
430
431
432def _initialize_without_android_home(env):
Javi Merino7f32efc2015-12-15 13:43:56 +0000433 adb_full_path = which('adb')
434 if adb_full_path:
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100435 env.adb = 'adb'
436 else:
437 raise HostError('ANDROID_HOME is not set and adb is not in PATH. '
438 'Have you installed Android SDK?')
439 logger.debug('Discovering ANDROID_HOME from adb path.')
Javi Merino7f32efc2015-12-15 13:43:56 +0000440 env.platform_tools = os.path.dirname(adb_full_path)
Sergei Trofimov4e6afe92015-10-09 09:30:04 +0100441 env.android_home = os.path.dirname(env.platform_tools)
442 _init_common(env)
443 return env
444
445
446def _init_common(env):
447 logger.debug('ANDROID_HOME: {}'.format(env.android_home))
448 build_tools_directory = os.path.join(env.android_home, 'build-tools')
449 if not os.path.isdir(build_tools_directory):
450 msg = '''ANDROID_HOME ({}) does not appear to have valid Android SDK install
451 (cannot find build-tools)'''
452 raise HostError(msg.format(env.android_home))
453 versions = os.listdir(build_tools_directory)
454 for version in reversed(sorted(versions)):
455 aapt_path = os.path.join(build_tools_directory, version, 'aapt')
456 if os.path.isfile(aapt_path):
457 logger.debug('Using aapt for version {}'.format(version))
458 env.aapt = aapt_path
459 break
460 else:
461 raise HostError('aapt not found. Please make sure at least one Android '
462 'platform is installed.')
463
464
465def _check_env():
466 global android_home, platform_tools, adb, aapt # pylint: disable=W0603
467 if not android_home:
468 android_home = os.getenv('ANDROID_HOME')
469 if android_home:
470 _env = _initialize_with_android_home(_AndroidEnvironment())
471 else:
472 _env = _initialize_without_android_home(_AndroidEnvironment())
473 android_home = _env.android_home
474 platform_tools = _env.platform_tools
475 adb = _env.adb
476 aapt = _env.aapt