• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5
6from recipe_engine import recipe_api
7from recipe_engine import recipe_test_api
8
9from . import default
10import subprocess  # TODO(borenet): No! Remove this.
11
12
13"""Android flavor, used for running code on Android."""
14
15
16class AndroidFlavor(default.DefaultFlavor):
17  def __init__(self, m, app_name):
18    super(AndroidFlavor, self).__init__(m, app_name)
19    self._ever_ran_adb = False
20    self.ADB_BINARY = '/usr/bin/adb.1.0.35'
21    self.ADB_PUB_KEY = '/home/chrome-bot/.android/adbkey'
22    if 'skia' not in self.m.vars.swarming_bot_id:
23      self.ADB_BINARY = '/opt/infra-android/tools/adb'
24      self.ADB_PUB_KEY = ('/home/chrome-bot/.android/'
25                          'chrome_infrastructure_adbkey')
26
27    # Data should go in android_data_dir, which may be preserved across runs.
28    android_data_dir = '/sdcard/revenge_of_the_skiabot/'
29    self.device_dirs = default.DeviceDirs(
30        bin_dir        = '/data/local/tmp/',
31        dm_dir         = android_data_dir + 'dm_out',
32        perf_data_dir  = android_data_dir + 'perf',
33        resource_dir   = android_data_dir + 'resources',
34        images_dir     = android_data_dir + 'images',
35        lotties_dir    = android_data_dir + 'lotties',
36        skp_dir        = android_data_dir + 'skps',
37        svg_dir        = android_data_dir + 'svgs',
38        mskp_dir       = android_data_dir + 'mskp',
39        tmp_dir        = android_data_dir,
40        texttraces_dir = android_data_dir + 'text_blob_traces')
41
42    # A list of devices we can't root.  If rooting fails and a device is not
43    # on the list, we fail the task to avoid perf inconsistencies.
44    self.cant_root = ['GalaxyS7_G930FD', 'GalaxyS9',
45                      'GalaxyS20', 'MotoG4', 'NVIDIA_Shield',
46                      'P30', 'Pixel4','Pixel4XL', 'Pixel5', 'TecnoSpark3Pro', 'JioNext']
47
48    # Maps device type -> CPU ids that should be scaled for nanobench.
49    # Many devices have two (or more) different CPUs (e.g. big.LITTLE
50    # on Nexus5x). The CPUs listed are the biggest cpus on the device.
51    # The CPUs are grouped together, so we only need to scale one of them
52    # (the one listed) in order to scale them all.
53    # E.g. Nexus5x has cpu0-3 as one chip and cpu4-5 as the other. Thus,
54    # if one wants to run a single-threaded application (e.g. nanobench), one
55    # can disable cpu0-3 and scale cpu 4 to have only cpu4 and 5 at the same
56    # frequency.  See also disable_for_nanobench.
57    self.cpus_to_scale = {
58      'Nexus5x': [4],
59      'Pixel': [2],
60      'Pixel2XL': [4]
61    }
62
63    # Maps device type -> CPU ids that should be turned off when running
64    # single-threaded applications like nanobench. The devices listed have
65    # multiple, differnt CPUs. We notice a lot of noise that seems to be
66    # caused by nanobench running on the slow CPU, then the big CPU. By
67    # disabling this, we see less of that noise by forcing the same CPU
68    # to be used for the performance testing every time.
69    self.disable_for_nanobench = {
70      'Nexus5x': range(0, 4),
71      'Pixel': range(0, 2),
72      'Pixel2XL': range(0, 4),
73      'Pixel6': range(4,8), # Only use the 4 small cores.
74    }
75
76    self.gpu_scaling = {
77      "Nexus5":  450000000,
78      "Nexus5x": 600000000,
79    }
80
81  def _adb(self, title, *cmd, **kwargs):
82    # The only non-infra adb steps (dm / nanobench) happen to not use _adb().
83    if 'infra_step' not in kwargs:
84      kwargs['infra_step'] = True
85
86    self._ever_ran_adb = True
87    # ADB seems to be occasionally flaky on every device, so always retry.
88    attempts = kwargs.pop('attempts', 3)
89
90    def wait_for_device(attempt):
91      self.m.run(self.m.step,
92                 'adb reconnect after failure of \'%s\' (attempt %d)' % (
93                     title, attempt),
94                 cmd=[self.ADB_BINARY, 'reconnect'],
95                 infra_step=True, timeout=30, abort_on_failure=False,
96                 fail_build_on_failure=False)
97      self.m.run(self.m.step,
98                 'wait for device after failure of \'%s\' (attempt %d)' % (
99                     title, attempt),
100                 cmd=[self.ADB_BINARY, 'wait-for-device'], infra_step=True,
101                 timeout=180, abort_on_failure=False,
102                 fail_build_on_failure=False)
103      self.m.run(self.m.step,
104                 'adb reconnect device after failure of \'%s\' (attempt %d)' % (
105                     title, attempt),
106                 cmd=[self.ADB_BINARY, 'reconnect', 'device'],
107                 infra_step=True, timeout=30, abort_on_failure=False,
108                 fail_build_on_failure=False)
109      self.m.run(self.m.step,
110                 'wait for device after failure of \'%s\' (attempt %d)' % (
111                     title, attempt),
112                 cmd=[self.ADB_BINARY, 'wait-for-device'], infra_step=True,
113                 timeout=180, abort_on_failure=False,
114                 fail_build_on_failure=False)
115
116    with self.m.context(cwd=self.m.path['start_dir'].join('skia')):
117      with self.m.env({'ADB_VENDOR_KEYS': self.ADB_PUB_KEY}):
118        return self.m.run.with_retry(self.m.step, title, attempts,
119                                     cmd=[self.ADB_BINARY]+list(cmd),
120                                     between_attempts_fn=wait_for_device,
121                                     **kwargs)
122
123  def _scale_for_dm(self):
124    device = self.m.vars.builder_cfg.get('model')
125    if (device in self.cant_root or
126        self.m.vars.internal_hardware_label):
127      return
128
129    # This is paranoia... any CPUs we disabled while running nanobench
130    # ought to be back online now that we've restarted the device.
131    for i in self.disable_for_nanobench.get(device, []):
132      self._set_cpu_online(i, 1) # enable
133
134    scale_up = self.cpus_to_scale.get(device, [0])
135    # For big.LITTLE devices, make sure we scale the LITTLE cores up;
136    # there is a chance they are still in powersave mode from when
137    # swarming slows things down for cooling down and charging.
138    if 0 not in scale_up:
139      scale_up.append(0)
140    for i in scale_up:
141      # AndroidOne doesn't support ondemand governor. hotplug is similar.
142      if device == 'AndroidOne':
143        self._set_governor(i, 'hotplug')
144      elif device in ['Pixel3a', 'Pixel4', 'Pixel4a', 'Wembley', 'Pixel6']:
145        # Pixel3a/4/4a have userspace powersave performance schedutil.
146        # performance seems like a reasonable choice.
147        self._set_governor(i, 'performance')
148      else:
149        self._set_governor(i, 'ondemand')
150
151  def _scale_for_nanobench(self):
152    device = self.m.vars.builder_cfg.get('model')
153    if (device in self.cant_root or
154      self.m.vars.internal_hardware_label):
155      return
156
157    # Set to 'powersave' for Pixel6.
158    for i in self.cpus_to_scale.get(device, [0]):
159      if device in ['Pixel6']:
160        self._set_governor(i, 'powersave')
161      else:
162        self._set_governor(i, 'userspace')
163        self._scale_cpu(i, 0.6)
164
165    for i in self.disable_for_nanobench.get(device, []):
166      self._set_cpu_online(i, 0) # disable
167
168    if device in self.gpu_scaling:
169      #https://developer.qualcomm.com/qfile/28823/lm80-p0436-11_adb_commands.pdf
170      # Section 3.2.1 Commands to put the GPU in performance mode
171      # Nexus 5 is  320000000 by default
172      # Nexus 5x is 180000000 by default
173      gpu_freq = self.gpu_scaling[device]
174      self.m.run.with_retry(self.m.python.inline,
175        "Lock GPU to %d (and other perf tweaks)" % gpu_freq,
176        3, # attempts
177        program="""
178import os
179import subprocess
180import sys
181import time
182ADB = sys.argv[1]
183freq = sys.argv[2]
184idle_timer = "10000"
185
186log = subprocess.check_output([ADB, 'root']).decode('utf-8')
187# check for message like 'adbd cannot run as root in production builds'
188print(log)
189if 'cannot' in log:
190  raise Exception('adb root failed')
191
192subprocess.check_output([ADB, 'shell', 'stop', 'thermald']).decode('utf-8')
193
194subprocess.check_output([ADB, 'shell', 'echo "%s" > '
195    '/sys/class/kgsl/kgsl-3d0/gpuclk' % freq]).decode('utf-8')
196
197actual_freq = subprocess.check_output([ADB, 'shell', 'cat '
198    '/sys/class/kgsl/kgsl-3d0/gpuclk']).decode('utf-8').strip()
199if actual_freq != freq:
200  raise Exception('Frequency (actual, expected) (%s, %s)'
201                  % (actual_freq, freq))
202
203subprocess.check_call([ADB, 'shell', 'echo "%s" > '
204    '/sys/class/kgsl/kgsl-3d0/idle_timer' % idle_timer])
205
206actual_timer = subprocess.check_output([ADB, 'shell', 'cat '
207    '/sys/class/kgsl/kgsl-3d0/idle_timer']).decode('utf-8').strip()
208if actual_timer != idle_timer:
209  raise Exception('idle_timer (actual, expected) (%s, %s)'
210                  % (actual_timer, idle_timer))
211
212for s in ['force_bus_on', 'force_rail_on', 'force_clk_on']:
213  subprocess.check_call([ADB, 'shell', 'echo "1" > '
214      '/sys/class/kgsl/kgsl-3d0/%s' % s])
215  actual_set = subprocess.check_output([ADB, 'shell', 'cat '
216      '/sys/class/kgsl/kgsl-3d0/%s' % s]).decode('utf-8').strip()
217  if actual_set != "1":
218    raise Exception('%s (actual, expected) (%s, 1)'
219                    % (s, actual_set))
220""",
221        args = [self.ADB_BINARY, gpu_freq],
222        infra_step=True,
223        timeout=30)
224
225  def _set_governor(self, cpu, gov):
226    self._ever_ran_adb = True
227    self.m.run.with_retry(self.m.python.inline,
228        "Set CPU %d's governor to %s" % (cpu, gov),
229        3, # attempts
230        program="""
231import os
232import subprocess
233import sys
234import time
235ADB = sys.argv[1]
236cpu = int(sys.argv[2])
237gov = sys.argv[3]
238
239log = subprocess.check_output([ADB, 'root']).decode('utf-8')
240# check for message like 'adbd cannot run as root in production builds'
241print(log)
242if 'cannot' in log:
243  raise Exception('adb root failed')
244
245subprocess.check_output([
246    ADB, 'shell',
247    'echo "%s" > /sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor' % (
248        gov, cpu)]).decode('utf-8')
249actual_gov = subprocess.check_output([
250    ADB, 'shell', 'cat /sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor' %
251        cpu]).decode('utf-8').strip()
252if actual_gov != gov:
253  raise Exception('(actual, expected) (%s, %s)'
254                  % (actual_gov, gov))
255""",
256        args = [self.ADB_BINARY, cpu, gov],
257        infra_step=True,
258        timeout=30)
259
260
261  def _set_cpu_online(self, cpu, value):
262    """Set /sys/devices/system/cpu/cpu{N}/online to value (0 or 1)."""
263    self._ever_ran_adb = True
264    msg = 'Disabling'
265    if value:
266      msg = 'Enabling'
267    self.m.run.with_retry(self.m.python.inline,
268        '%s CPU %d' % (msg, cpu),
269        3, # attempts
270        program="""
271import os
272import subprocess
273import sys
274import time
275ADB = sys.argv[1]
276cpu = int(sys.argv[2])
277value = int(sys.argv[3])
278
279log = subprocess.check_output([ADB, 'root']).decode('utf-8')
280# check for message like 'adbd cannot run as root in production builds'
281print(log)
282if 'cannot' in log:
283  raise Exception('adb root failed')
284
285# If we try to echo 1 to an already online cpu, adb returns exit code 1.
286# So, check the value before trying to write it.
287prior_status = subprocess.check_output([ADB, 'shell', 'cat '
288    '/sys/devices/system/cpu/cpu%d/online' % cpu]).decode('utf-8').strip()
289if prior_status == str(value):
290  print('CPU %d online already %d' % (cpu, value))
291  sys.exit()
292
293subprocess.check_call([ADB, 'shell', 'echo %s > '
294    '/sys/devices/system/cpu/cpu%d/online' % (value, cpu)])
295actual_status = subprocess.check_output([ADB, 'shell', 'cat '
296    '/sys/devices/system/cpu/cpu%d/online' % cpu]).decode('utf-8').strip()
297if actual_status != str(value):
298  raise Exception('(actual, expected) (%s, %d)'
299                  % (actual_status, value))
300""",
301        args = [self.ADB_BINARY, cpu, value],
302        infra_step=True,
303        timeout=30)
304
305
306  def _scale_cpu(self, cpu, target_percent):
307    self._ever_ran_adb = True
308    self.m.run.with_retry(self.m.python.inline,
309        'Scale CPU %d to %f' % (cpu, target_percent),
310        3, # attempts
311        program="""
312import os
313import subprocess
314import sys
315import time
316ADB = sys.argv[1]
317target_percent = float(sys.argv[2])
318cpu = int(sys.argv[3])
319log = subprocess.check_output([ADB, 'root']).decode('utf-8')
320# check for message like 'adbd cannot run as root in production builds'
321print(log)
322if 'cannot' in log:
323  raise Exception('adb root failed')
324
325root = '/sys/devices/system/cpu/cpu%d/cpufreq' %cpu
326
327# All devices we test on give a list of their available frequencies.
328available_freqs = subprocess.check_output([ADB, 'shell',
329    'cat %s/scaling_available_frequencies' % root]).decode('utf-8')
330
331# Check for message like '/system/bin/sh: file not found'
332if available_freqs and '/system/bin/sh' not in available_freqs:
333  available_freqs = sorted(
334      int(i) for i in available_freqs.strip().split())
335else:
336  raise Exception('Could not get list of available frequencies: %s' %
337                  available_freqs)
338
339maxfreq = available_freqs[-1]
340target = int(round(maxfreq * target_percent))
341freq = maxfreq
342for f in reversed(available_freqs):
343  if f <= target:
344    freq = f
345    break
346
347print('Setting frequency to %d' % freq)
348
349# If scaling_max_freq is lower than our attempted setting, it won't take.
350# We must set min first, because if we try to set max to be less than min
351# (which sometimes happens after certain devices reboot) it returns a
352# perplexing permissions error.
353subprocess.check_call([ADB, 'shell', 'echo 0 > '
354    '%s/scaling_min_freq' % root])
355subprocess.check_call([ADB, 'shell', 'echo %d > '
356    '%s/scaling_max_freq' % (freq, root)])
357subprocess.check_call([ADB, 'shell', 'echo %d > '
358    '%s/scaling_setspeed' % (freq, root)])
359time.sleep(5)
360actual_freq = subprocess.check_output([ADB, 'shell', 'cat '
361    '%s/scaling_cur_freq' % root]).decode('utf-8').strip()
362if actual_freq != str(freq):
363  raise Exception('(actual, expected) (%s, %d)'
364                  % (actual_freq, freq))
365""",
366        args = [self.ADB_BINARY, str(target_percent), cpu],
367        infra_step=True,
368        timeout=30)
369
370
371  def _asan_setup_path(self):
372    return self.m.vars.workdir.join(
373        'android_ndk_linux', 'toolchains', 'llvm', 'prebuilt', 'linux-x86_64',
374        'lib64', 'clang', '9.0.8', 'bin', 'asan_device_setup')
375
376
377  def install(self):
378    self._adb('mkdir ' + self.device_dirs.resource_dir,
379              'shell', 'mkdir', '-p', self.device_dirs.resource_dir)
380    if self.m.vars.builder_cfg.get('model') in ['GalaxyS20', 'GalaxyS9']:
381      # See skia:10184, should be moot once upgraded to Android 11?
382      self._adb('cp libGLES_mali.so to ' + self.device_dirs.bin_dir,
383                 'shell', 'cp',
384                '/vendor/lib64/egl/libGLES_mali.so',
385                self.device_dirs.bin_dir + 'libvulkan.so')
386    if 'ASAN' in self.m.vars.extra_tokens:
387      self._ever_ran_adb = True
388      self.m.run(self.m.python.inline, 'Setting up device to run ASAN',
389                 program="""
390import os
391import subprocess
392import sys
393import time
394ADB = sys.argv[1]
395ASAN_SETUP = sys.argv[2]
396
397def wait_for_device():
398  while True:
399    time.sleep(5)
400    print('Waiting for device')
401    subprocess.check_call([ADB, 'wait-for-device'])
402    bit1 = subprocess.check_output([ADB, 'shell', 'getprop',
403                                   'dev.bootcomplete']).decode('utf-8')
404    bit2 = subprocess.check_output([ADB, 'shell', 'getprop',
405                                   'sys.boot_completed']).decode('utf-8')
406    if '1' in bit1 and '1' in bit2:
407      print('Device detected')
408      break
409
410log = subprocess.check_output([ADB, 'root']).decode('utf-8')
411# check for message like 'adbd cannot run as root in production builds'
412print(log)
413if 'cannot' in log:
414  raise Exception('adb root failed')
415
416output = subprocess.check_output([ADB, 'disable-verity']).decode('utf-8')
417print(output)
418
419if 'already disabled' not in output:
420  print('Rebooting device')
421  subprocess.check_call([ADB, 'reboot'])
422  wait_for_device()
423
424def installASAN(revert=False):
425  # ASAN setup script is idempotent, either it installs it or
426  # says it's installed.  Returns True on success, false otherwise.
427  out = subprocess.check_output([ADB, 'wait-for-device']).decode('utf-8')
428  print(out)
429  cmd = [ASAN_SETUP]
430  if revert:
431    cmd = [ASAN_SETUP, '--revert']
432  process = subprocess.Popen(cmd, env={'ADB': ADB},
433                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
434
435  # this also blocks until command finishes
436  (stdout, stderr) = process.communicate()
437  print(stdout.decode('utf-8'))
438  print('Stderr: %s' % stderr.decode('utf-8'))
439  return process.returncode == 0
440
441if not installASAN():
442  print('Trying to revert the ASAN install and then re-install')
443  # ASAN script sometimes has issues if it was interrupted or partially applied
444  # Try reverting it, then re-enabling it
445  if not installASAN(revert=True):
446    raise Exception('reverting ASAN install failed')
447
448  # Sleep because device does not reboot instantly
449  time.sleep(10)
450
451  if not installASAN():
452    raise Exception('Tried twice to setup ASAN and failed.')
453
454# Sleep because device does not reboot instantly
455time.sleep(10)
456wait_for_device()
457# Sleep again to hopefully avoid error "secure_mkdirs failed: No such file or
458# directory" when pushing resources to the device.
459time.sleep(60)
460""",
461                 args = [self.ADB_BINARY, self._asan_setup_path()],
462                 infra_step=True,
463                 timeout=300,
464                 abort_on_failure=True)
465    if self.app_name:
466      if (self.app_name == 'nanobench'):
467        self._scale_for_nanobench()
468      else:
469        self._scale_for_dm()
470      app_path = self.host_dirs.bin_dir.join(self.app_name)
471      self._adb('push %s' % self.app_name,
472                'push', app_path, self.device_dirs.bin_dir)
473
474
475
476  def cleanup_steps(self):
477    if 'ASAN' in self.m.vars.extra_tokens:
478      self._ever_ran_adb = True
479      # Remove ASAN.
480      self.m.run(self.m.step,
481                 'wait for device before uninstalling ASAN',
482                 cmd=[self.ADB_BINARY, 'wait-for-device'], infra_step=True,
483                 timeout=180, abort_on_failure=False,
484                 fail_build_on_failure=False)
485      self.m.run(self.m.step, 'uninstall ASAN',
486                 cmd=[self._asan_setup_path(), '--revert'],
487                 infra_step=True, timeout=300,
488                 abort_on_failure=False, fail_build_on_failure=False)
489
490    if self._ever_ran_adb:
491      self.m.run(self.m.python.inline, 'dump log', program="""
492          import os
493          import subprocess
494          import sys
495          out = sys.argv[1]
496          log = subprocess.check_output([
497              '%s', 'logcat', '-d']).decode('utf-8', errors='ignore')
498          for line in log.split('\\n'):
499            tokens = line.split()
500            if len(tokens) == 11 and tokens[-7] == 'F' and tokens[-3] == 'pc':
501              addr, path = tokens[-2:]
502              local = os.path.join(out, os.path.basename(path))
503              if os.path.exists(local):
504                try:
505                  sym = subprocess.check_output([
506                      'addr2line', '-Cfpe', local, addr]).decode('utf-8')
507                  line = line.replace(addr, addr + ' ' + sym.strip())
508                except subprocess.CalledProcessError:
509                  pass
510            print(line)
511          """ % self.ADB_BINARY,
512          args=[self.host_dirs.bin_dir],
513          infra_step=True,
514          timeout=300,
515          abort_on_failure=False)
516
517    # Only quarantine the bot if the first failed step
518    # is an infra step. If, instead, we did this for any infra failures, we
519    # would do this too much. For example, if a Nexus 10 died during dm
520    # and the following pull step would also fail "device not found" - causing
521    # us to run the shutdown command when the device was probably not in a
522    # broken state; it was just rebooting.
523    if (self.m.run.failed_steps and
524        isinstance(self.m.run.failed_steps[0], recipe_api.InfraFailure)):
525      bot_id = self.m.vars.swarming_bot_id
526      self.m.file.write_text('Quarantining Bot',
527                             '/home/chrome-bot/%s.force_quarantine' % bot_id,
528                             ' ')
529
530    if self._ever_ran_adb:
531      self._adb('kill adb server', 'kill-server')
532
533  def step(self, name, cmd):
534    sh = '%s.sh' % cmd[0]
535    self.m.run.writefile(self.m.vars.tmp_dir.join(sh),
536        'set -x; LD_LIBRARY_PATH=%s %s%s; echo $? >%src' % (
537            self.device_dirs.bin_dir,
538            self.device_dirs.bin_dir, subprocess.list2cmdline(map(str, cmd)),
539            self.device_dirs.bin_dir))
540    self._adb('push %s' % sh,
541              'push', self.m.vars.tmp_dir.join(sh), self.device_dirs.bin_dir)
542
543    self._adb('clear log', 'logcat', '-c')
544    self.m.python.inline('%s' % cmd[0], """
545    import subprocess
546    import sys
547    bin_dir = sys.argv[1]
548    sh      = sys.argv[2]
549    subprocess.check_call(['%s', 'shell', 'sh', bin_dir + sh])
550    try:
551      sys.exit(int(subprocess.check_output([
552          '%s', 'shell', 'cat', bin_dir + 'rc']).decode('utf-8')))
553    except ValueError:
554      print("Couldn't read the return code.  Probably killed for OOM.")
555      sys.exit(1)
556    """ % (self.ADB_BINARY, self.ADB_BINARY),
557      args=[self.device_dirs.bin_dir, sh])
558
559  def copy_file_to_device(self, host, device):
560    self._adb('push %s %s' % (host, device), 'push', host, device)
561
562  def copy_directory_contents_to_device(self, host, device):
563    contents = self.m.file.glob_paths('ls %s/*' % host,
564                                      host, '*',
565                                      test_data=['foo.png', 'bar.jpg'])
566    args = contents + [device]
567    self._adb('push --sync %s/* %s' % (host, device), 'push', *args)
568
569  def copy_directory_contents_to_host(self, device, host):
570    # TODO(borenet): When all of our devices are on Android 6.0 and up, we can
571    # switch to using tar to zip up the results before pulling.
572    with self.m.step.nest('adb pull'):
573      tmp = self.m.path.mkdtemp('adb_pull')
574      self._adb('pull %s' % device, 'pull', device, tmp)
575      paths = self.m.file.glob_paths(
576          'list pulled files',
577          tmp,
578          self.m.path.basename(device) + self.m.path.sep + '*',
579          test_data=['%d.png' % i for i in (1, 2)])
580      for p in paths:
581        self.m.file.copy('copy %s' % self.m.path.basename(p), p, host)
582
583  def read_file_on_device(self, path, **kwargs):
584    rv = self._adb('read %s' % path,
585                   'shell', 'cat', path, stdout=self.m.raw_io.output(),
586                   **kwargs)
587    return rv.stdout.decode('utf-8').rstrip() if rv and rv.stdout else None
588
589  def remove_file_on_device(self, path):
590    self.m.run.with_retry(self.m.python.inline, 'rm %s' % path, 3, program="""
591        import subprocess
592        import sys
593
594        # Remove the path.
595        adb = sys.argv[1]
596        path = sys.argv[2]
597        print('Removing %s' % path)
598        cmd = [adb, 'shell', 'rm', '-rf', path]
599        print(' '.join(cmd))
600        subprocess.check_call(cmd)
601
602        # Verify that the path was deleted.
603        print('Checking for existence of %s' % path)
604        cmd = [adb, 'shell', 'ls', path]
605        print(' '.join(cmd))
606        try:
607          output = subprocess.check_output(
608              cmd, stderr=subprocess.STDOUT).decode('utf-8')
609        except subprocess.CalledProcessError as e:
610          output = e.output.decode('utf-8')
611        print('Output was:')
612        print('======')
613        print(output)
614        print('======')
615        if 'No such file or directory' not in output:
616          raise Exception('%s exists despite being deleted' % path)
617        """,
618        args=[self.ADB_BINARY, path],
619        infra_step=True)
620
621  def create_clean_device_dir(self, path):
622    self.remove_file_on_device(path)
623    self._adb('mkdir %s' % path, 'shell', 'mkdir', '-p', path)
624