1# Copyright 2024 Google LLC 2# 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6import os 7import subprocess 8import sys 9import time 10 11ADB = sys.argv[1] 12ASAN_SETUP = sys.argv[2] 13 14def wait_for_device(): 15 while True: 16 time.sleep(5) 17 print('Waiting for device') 18 subprocess.check_call([ADB, 'wait-for-device']) 19 bit1 = subprocess.check_output([ADB, 'shell', 'getprop', 20 'dev.bootcomplete']).decode('utf-8') 21 bit2 = subprocess.check_output([ADB, 'shell', 'getprop', 22 'sys.boot_completed']).decode('utf-8') 23 if '1' in bit1 and '1' in bit2: 24 print('Device detected') 25 break 26 27log = subprocess.check_output([ADB, 'root']).decode('utf-8') 28# check for message like 'adbd cannot run as root in production builds' 29print(log) 30if 'cannot' in log: 31 raise Exception('adb root failed') 32 33output = subprocess.check_output([ADB, 'disable-verity']).decode('utf-8') 34print(output) 35 36if 'already disabled' not in output: 37 print('Rebooting device') 38 subprocess.check_call([ADB, 'reboot']) 39 wait_for_device() 40 41def installASAN(revert=False): 42 # ASAN setup script is idempotent, either it installs it or 43 # says it's installed. Returns True on success, false otherwise. 44 out = subprocess.check_output([ADB, 'wait-for-device']).decode('utf-8') 45 print(out) 46 cmd = [ASAN_SETUP] 47 if revert: 48 cmd = [ASAN_SETUP, '--revert'] 49 process = subprocess.Popen(cmd, env={'ADB': ADB}, 50 stdout=subprocess.PIPE, stderr=subprocess.PIPE) 51 52 # this also blocks until command finishes 53 (stdout, stderr) = process.communicate() 54 print(stdout.decode('utf-8')) 55 print('Stderr: %s' % stderr.decode('utf-8')) 56 return process.returncode == 0 57 58if not installASAN(): 59 print('Trying to revert the ASAN install and then re-install') 60 # ASAN script sometimes has issues if it was interrupted or partially applied 61 # Try reverting it, then re-enabling it 62 if not installASAN(revert=True): 63 raise Exception('reverting ASAN install failed') 64 65 # Sleep because device does not reboot instantly 66 time.sleep(10) 67 68 if not installASAN(): 69 raise Exception('Tried twice to setup ASAN and failed.') 70 71# Sleep because device does not reboot instantly 72time.sleep(10) 73wait_for_device() 74# Sleep again to hopefully avoid error "secure_mkdirs failed: No such file or 75# directory" when pushing resources to the device. 76time.sleep(60) 77