response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Reset the connection to the physical device through USB. Returns whether
or not the reset succeeded. | def reset_device_connection():
"""Reset the connection to the physical device through USB. Returns whether
or not the reset succeeded."""
if environment.is_android_cuttlefish():
restart_cuttlefish_device()
else:
# Physical device. Try restarting usb.
reset_usb()
# Check device status.
state = get_device_state()
if state != 'device':
logs.log_warn('Device state is %s, unable to recover using usb reset/'
'cuttlefish reconnect.' % str(state))
return False
return True |
Return the ip address of cuttlefish device. | def get_cuttlefish_device_ip():
"""Return the ip address of cuttlefish device."""
try:
return socket.gethostbyname('cuttlefish')
except socket.gaierror:
logs.log_fatal_and_exit('Unable to get cvd ip address on cuttlefish host.')
return None |
Set the ANDROID_SERIAL to cuttlefish ip and port. | def set_cuttlefish_device_serial():
"""Set the ANDROID_SERIAL to cuttlefish ip and port."""
device_serial = '%s:%d' % (get_cuttlefish_device_ip(), CUTTLEFISH_CVD_PORT)
environment.set_value('ANDROID_SERIAL', device_serial)
logs.log('Set cuttlefish device serial: %s' % device_serial) |
Return the target for cuttlefish ssh connection. | def get_cuttlefish_ssh_target():
"""Return the target for cuttlefish ssh connection."""
return f'{CUTTLEFISH_USER}@{get_cuttlefish_device_ip()}' |
Gets a device path to be cached and used by reset_usb. | def get_device_path():
"""Gets a device path to be cached and used by reset_usb."""
def _get_usb_devices():
"""Returns a list of device objects containing a serial and USB path."""
usb_list_cmd = 'lsusb -v'
output = execute_command(usb_list_cmd, timeout=RECOVERY_CMD_TIMEOUT)
if output is None:
logs.log_error('Failed to populate usb devices using lsusb, '
'host restart might be needed.')
bad_state_reached()
devices = []
path = None
for line in output.splitlines():
match = LSUSB_BUS_RE.match(line)
if match:
path = '/dev/bus/usb/%s/%s' % (match.group(1), match.group(2))
continue
match = LSUSB_SERIAL_RE.match(line)
if path and match and match.group(1):
serial = match.group(1)
devices.append(DEVICE(serial, path))
return devices
def _get_device_path_for_serial():
"""Return device path. Assumes a simple ANDROID_SERIAL."""
devices = _get_usb_devices()
for device in devices:
if device_serial == device.serial:
return device.path
return None
def _get_device_path_for_usb():
"""Returns a device path.
Assumes ANDROID_SERIAL in the form "usb:<identifier>"."""
# Android serial may reference a usb device rather than a serial number.
device_id = device_serial[len('usb:'):]
bus_number = int(
open('/sys/bus/usb/devices/%s/busnum' % device_id).read().strip())
device_number = int(
open('/sys/bus/usb/devices/%s/devnum' % device_id).read().strip())
return '/dev/bus/usb/%03d/%03d' % (bus_number, device_number)
if environment.is_android_cuttlefish():
return None
device_serial = environment.get_value('ANDROID_SERIAL')
if device_serial.startswith('usb:'):
return _get_device_path_for_usb()
return _get_device_path_for_serial() |
Reset USB bus for a device serial. | def reset_usb():
"""Reset USB bus for a device serial."""
if environment.is_android_cuttlefish():
# Nothing to do here.
return True
# App Engine does not let us import this.
import fcntl
# We need to get latest device path since it could be changed in reboots or
# adb root restarts.
try:
device_path = get_device_path()
except OSError:
# We may reach this state if the device is no longer available.
device_path = None
if not device_path:
# Try pulling from cache (if available).
device_path = environment.get_value('DEVICE_PATH')
if not device_path:
logs.log_warn('No device path found, unable to reset usb.')
return False
try:
with open(device_path, 'w') as f:
fcntl.ioctl(f, USBDEVFS_RESET)
except:
logs.log_warn('Failed to reset usb.')
return False
# Wait for usb to recover.
wait_for_device(recover=False)
return True |
Reverts ASan device setup if installed. | def revert_asan_device_setup_if_needed():
"""Reverts ASan device setup if installed."""
if not environment.get_value('ASAN_DEVICE_SETUP'):
return
device_id = environment.get_value('ANDROID_SERIAL')
device_argument = '--device %s' % device_id
revert_argument = '--revert'
asan_device_setup_script_path = os.path.join(
environment.get_platform_resources_directory(), 'third_party',
'asan_device_setup.sh')
command = '%s %s %s' % (asan_device_setup_script_path, device_argument,
revert_argument)
execute_command(command, timeout=RECOVERY_CMD_TIMEOUT) |
Restart adbd and runs as root. | def run_as_root():
"""Restart adbd and runs as root."""
# Check if we are already running as root. If yes bail out.
if get_property('service.adb.root') == '1':
return
wait_for_device()
run_command('root')
wait_for_device() |
Run a command in adb shell. | def run_command(cmd,
log_output=False,
log_error=True,
timeout=None,
recover=True):
"""Run a command in adb shell."""
if isinstance(cmd, list):
cmd = ' '.join([str(i) for i in cmd])
if log_output:
logs.log('Running: adb %s' % cmd)
if not timeout:
timeout = ADB_TIMEOUT
output = execute_command(get_adb_command_line(cmd), timeout, log_error)
if not recover:
if log_output:
logs.log('Output: (%s)' % output)
return output
device_not_found_string_with_serial = DEVICE_NOT_FOUND_STRING.format(
serial=environment.get_value('ANDROID_SERIAL'))
if (output in [
DEVICE_HANG_STRING, DEVICE_OFFLINE_STRING,
device_not_found_string_with_serial
]):
logs.log_warn('Unable to query device, resetting device connection.')
if reset_device_connection():
# Device has successfully recovered, re-run command to get output.
# Continue execution and validate output next for |None| condition.
output = execute_command(get_adb_command_line(cmd), timeout, log_error)
else:
output = DEVICE_HANG_STRING
if output is DEVICE_HANG_STRING:
# Handle the case where our command execution hung. This is usually when
# device goes into a bad state and only way to recover is to restart it.
logs.log_warn('Unable to query device, restarting device to recover.')
hard_reset()
# Wait until we've booted and try the command again.
wait_until_fully_booted()
output = execute_command(get_adb_command_line(cmd), timeout, log_error)
if log_output:
logs.log('Output: (%s)' % output)
return output |
Run adb shell command (with root if needed). | def run_shell_command(cmd,
log_output=False,
log_error=True,
root=False,
timeout=None,
recover=True):
"""Run adb shell command (with root if needed)."""
def _escape_specials(command):
return command.replace('\\', '\\\\').replace('"', '\\"')
if isinstance(cmd, list):
cmd = ' '.join([str(i) for i in cmd])
if cmd[0] not in ['"', "'"]:
cmd = '"{}"'.format(_escape_specials(cmd))
if root:
root_cmd_prefix = 'su root sh -c '
# The arguments to adb shell need to be quoted, so if we're using
# su root sh -c, quote the combined command
full_cmd = 'shell \'{}{}\''.format(root_cmd_prefix, cmd)
else:
full_cmd = 'shell {}'.format(cmd)
return run_command(
full_cmd,
log_output=log_output,
log_error=log_error,
timeout=timeout,
recover=recover) |
Run a command in fastboot shell. | def run_fastboot_command(cmd, log_output=True, log_error=True, timeout=None):
"""Run a command in fastboot shell."""
if environment.is_android_cuttlefish():
# We can't run fastboot commands on Android cuttlefish instances.
return None
if isinstance(cmd, list):
cmd = ' '.join([str(i) for i in cmd])
if log_output:
logs.log('Running: fastboot %s' % cmd)
if not timeout:
timeout = ADB_TIMEOUT
output = execute_command(get_fastboot_command_line(cmd), timeout, log_error)
return output |
Sets up ADB binary for use. | def setup_adb():
"""Sets up ADB binary for use."""
adb_binary_path = get_adb_path()
# Make sure that ADB env var is set.
if not environment.get_value('ADB'):
environment.set_value('ADB', adb_binary_path) |
Stops shell. | def start_shell():
"""Stops shell."""
# Make sure we are running as root.
run_as_root()
run_shell_command('start')
wait_until_fully_booted() |
Stops shell. | def stop_shell():
"""Stops shell."""
# Make sure we are running as root.
run_as_root()
run_shell_command('stop') |
Return time in seconds since last reboot. | def time_since_last_reboot():
"""Return time in seconds since last reboot."""
uptime_string = run_shell_command(['cat', '/proc/uptime']).split(
' ', maxsplit=1)[0]
try:
return float(uptime_string)
except ValueError:
# Sometimes, adb can just hang or return null output. In these cases, just
# return infinity uptime value.
return float('inf') |
Waits indefinitely for the device to come online. | def wait_for_device(recover=True):
"""Waits indefinitely for the device to come online."""
run_command(
'wait-for-device', timeout=WAIT_FOR_DEVICE_TIMEOUT, recover=recover) |
Wait until device is fully booted or timeout expires. | def wait_until_fully_booted():
"""Wait until device is fully booted or timeout expires."""
def boot_completed():
expected = '1'
result = run_shell_command('getprop sys.boot_completed', log_error=False)
return result == expected
def drive_ready():
expected = '0'
result = run_shell_command('\'test -d "/"; echo $?\'', log_error=False)
return result == expected
def package_manager_ready():
expected = 'package:/system/framework/framework-res.apk'
result = run_shell_command('pm path android', log_error=False)
if not result:
return False
# Ignore any extra messages before or after the result we want.
return expected in result.splitlines()
# Make sure we are not already recursing inside this function.
if utils.is_recursive_call():
return False
# Wait until device is online.
wait_for_device()
start_time = time.time()
is_boot_completed = False
is_drive_ready = False
is_package_manager_ready = False
while time.time() - start_time < REBOOT_TIMEOUT:
# TODO(mbarbella): Investigate potential optimizations.
# The package manager check should also work for shell restarts.
if not is_drive_ready:
is_drive_ready = drive_ready()
if not is_package_manager_ready:
is_package_manager_ready = package_manager_ready()
if not is_boot_completed:
is_boot_completed = boot_completed()
if is_drive_ready and is_package_manager_ready and is_boot_completed:
return True
time.sleep(BOOT_WAIT_INTERVAL)
factory_reset()
if environment.is_android_emulator():
#Device may be in recovery mode
hard_reset()
logs.log_fatal_and_exit(
'Device failed to finish boot. Reset to factory settings and exited.')
# Not reached.
return False |
Write command line file with command line argument for the application. | def write_command_line_file(command_line, app_path):
"""Write command line file with command line argument for the application."""
command_line_path = environment.get_value('COMMAND_LINE_PATH')
if not command_line_path:
return
# Algorithm for filtering current command line.
# 1. Remove |APP_PATH| from front.
# 2. Add 'chrome ' to start.
# 3. Strip for whitespaces at start and end.
command_line_without_app_path = command_line.replace('%s ' % app_path, '')
command_line_file_contents = 'chrome %s' % (
command_line_without_app_path.strip())
write_data_to_file(command_line_file_contents, command_line_path) |
Writes content to file. | def write_data_to_file(contents, file_path):
"""Writes content to file."""
# If this is a file in /system, we need to remount /system as read-write and
# after file is written, revert it back to read-only.
is_system_file = file_path.startswith('/system')
if is_system_file:
remount()
# Write file with desired contents.
run_shell_command("\"echo -n '%s' | su root dd of=%s\"" % (contents.replace(
'"', '\\"'), file_path))
# Make command line file is readable.
run_shell_command('chmod 0644 %s' % file_path, root=True)
if is_system_file:
reboot()
wait_until_fully_booted() |
Disable known packages that crash on gesture fuzzing. | def disable_packages_that_crash_with_gestures():
"""Disable known packages that crash on gesture fuzzing."""
for package in PACKAGES_THAT_CRASH_WITH_GESTURES:
adb.run_shell_command(['pm', 'disable-user', package], log_error=False) |
Get command to launch application with an optional testcase path. | def get_launch_command(app_args, testcase_path, testcase_file_url):
"""Get command to launch application with an optional testcase path."""
application_launch_command = environment.get_value('APP_LAUNCH_COMMAND')
if not application_launch_command:
return ''
package_name = get_package_name() or ''
application_launch_command = application_launch_command.replace(
'%APP_ARGS%', app_args)
application_launch_command = application_launch_command.replace(
'%DEVICE_TESTCASES_DIR%', constants.DEVICE_TESTCASES_DIR)
application_launch_command = application_launch_command.replace(
'%PKG_NAME%', package_name)
application_launch_command = application_launch_command.replace(
'%TESTCASE%', testcase_path)
application_launch_command = application_launch_command.replace(
'%TESTCASE_FILE_URL%', testcase_file_url)
return application_launch_command |
Return package name. | def get_package_name(apk_path=None):
"""Return package name."""
# See if our environment is already set with this info.
package_name = environment.get_value('PKG_NAME')
if package_name:
return package_name
# See if we have the apk available to derive this info.
if not apk_path:
# Try getting apk path from APP_PATH.
apk_path = environment.get_value('APP_PATH')
if not apk_path:
return None
# Make sure that apk has the correct extension.
if not apk_path.endswith('.apk'):
return None
# Try retrieving package name using aapt.
aapt_binary_path = os.path.join(
environment.get_platform_resources_directory(), 'aapt')
aapt_command = '%s dump badging %s' % (aapt_binary_path, apk_path)
output = adb.execute_command(aapt_command, timeout=AAPT_CMD_TIMEOUT)
match = re.match('.*package: name=\'([^\']+)\'', output, re.DOTALL)
if not match:
return None
return match.group(1) |
Install a package from an apk path. | def install(package_apk_path):
"""Install a package from an apk path."""
return adb.run_command(['install', '-r', package_apk_path]) |
Checks if the app is installed. | def is_installed(package_name):
"""Checks if the app is installed."""
output = adb.run_shell_command(['pm', 'list', 'packages'])
package_names = [line.split(':')[-1] for line in output.splitlines()]
return package_name in package_names |
Reset to original clean state and kills pending instances. | def reset():
"""Reset to original clean state and kills pending instances."""
package_name = get_package_name()
if not package_name:
return
# Make sure package is actually installed.
if not is_installed(package_name):
return
# Clean package state.
adb.run_shell_command(['pm', 'clear', package_name])
# Re-grant storage permissions.
adb.run_shell_command(
['pm', 'grant', package_name, 'android.permission.READ_EXTERNAL_STORAGE'])
adb.run_shell_command([
'pm', 'grant', package_name, 'android.permission.WRITE_EXTERNAL_STORAGE'
]) |
Stop application and cleanup state. | def stop():
"""Stop application and cleanup state."""
package_name = get_package_name()
if not package_name:
return
# Device can get silently restarted in case of OOM. So, we would need to
# restart our shell as root in order to kill the application.
adb.run_as_root()
adb.kill_processes_and_children_matching_name(package_name)
# Chrome specific cleanup.
if package_name.endswith('.chrome'):
cache_dirs_absolute_paths = [
'/data/data/%s/%s' % (package_name, i) for i in CHROME_CACHE_DIRS
]
adb.run_shell_command(
['rm', '-rf', ' '.join(cache_dirs_absolute_paths)], root=True) |
Uninstall a package given a name. | def uninstall(package_name):
"""Uninstall a package given a name."""
return adb.run_command(['uninstall', package_name]) |
Waits for package optimization to finish. | def wait_until_optimization_complete():
"""Waits for package optimization to finish."""
start_time = time.time()
while time.time() - start_time < PACKAGE_OPTIMIZATION_TIMEOUT:
package_optimization_finished = 'dex2oat' not in adb.get_ps_output()
if package_optimization_finished:
return
logs.log('Waiting for package optimization to finish.')
time.sleep(PACKAGE_OPTIMIZATION_INTERVAL) |
Return device's battery and temperature levels. | def get_battery_level_and_temperature():
"""Return device's battery and temperature levels."""
output = adb.run_shell_command(['dumpsys', 'battery'])
# Get battery level.
m_battery_level = re.match(r'.*level: (\d+).*', output, re.DOTALL)
if not m_battery_level:
logs.log_error('Error occurred while getting battery status.')
return None
# Get battery temperature.
m_battery_temperature = re.match(r'.*temperature: (\d+).*', output, re.DOTALL)
if not m_battery_temperature:
logs.log_error('Error occurred while getting battery temperature.')
return None
level = int(m_battery_level.group(1))
temperature = float(m_battery_temperature.group(1)) / 10.0
return {'level': level, 'temperature': temperature} |
Check battery and make sure it is charged beyond minimum level and
temperature thresholds. | def wait_until_good_state():
"""Check battery and make sure it is charged beyond minimum level and
temperature thresholds."""
# Battery levels are not applicable on GCE.
if environment.is_android_cuttlefish() or settings.is_automotive():
return
# Make sure device is online.
adb.wait_for_device()
# Skip battery check if done recently.
last_battery_check_time = persistent_cache.get_value(
LAST_BATTERY_CHECK_TIME_KEY,
constructor=datetime.datetime.utcfromtimestamp)
if last_battery_check_time and not dates.time_has_expired(
last_battery_check_time, seconds=BATTERY_CHECK_INTERVAL):
return
# Initialize variables.
battery_level_threshold = environment.get_value('LOW_BATTERY_LEVEL_THRESHOLD',
LOW_BATTERY_LEVEL_THRESHOLD)
battery_temperature_threshold = environment.get_value(
'MAX_BATTERY_TEMPERATURE_THRESHOLD', MAX_BATTERY_TEMPERATURE_THRESHOLD)
device_restarted = False
while True:
battery_information = get_battery_level_and_temperature()
if battery_information is None:
logs.log_error('Failed to get battery information, skipping check.')
return
battery_level = battery_information['level']
battery_temperature = battery_information['temperature']
logs.log('Battery information: level (%d%%), temperature (%.1f celsius).' %
(battery_level, battery_temperature))
if (battery_level >= battery_level_threshold and
battery_temperature <= battery_temperature_threshold):
persistent_cache.set_value(LAST_BATTERY_CHECK_TIME_KEY, time.time())
return
logs.log('Battery in bad battery state, putting device in sleep mode.')
if not device_restarted:
adb.reboot()
device_restarted = True
# Change thresholds to expected levels (only if they were below minimum
# thresholds).
if battery_level < battery_level_threshold:
battery_level_threshold = EXPECTED_BATTERY_LEVEL
if battery_temperature > battery_temperature_threshold:
battery_temperature_threshold = EXPECTED_BATTERY_TEMPERATURE
# Stopping shell should help with shutting off a lot of services that would
# otherwise use up the battery. However, we need to turn it back on to get
# battery status information.
adb.stop_shell()
time.sleep(BATTERY_CHARGE_INTERVAL)
adb.start_shell() |
Add test account to work with GmsCore, etc. | def add_test_accounts_if_needed():
"""Add test account to work with GmsCore, etc."""
last_test_account_check_time = persistent_cache.get_value(
constants.LAST_TEST_ACCOUNT_CHECK_KEY,
constructor=datetime.datetime.utcfromtimestamp)
needs_test_account_update = (
last_test_account_check_time is None or dates.time_has_expired(
last_test_account_check_time,
seconds=ADD_TEST_ACCOUNT_CHECK_INTERVAL))
if not needs_test_account_update:
return
config = db_config.get()
if not config:
return
test_account_email = config.test_account_email
test_account_password = config.test_account_password
if not test_account_email or not test_account_password:
return
adb.run_as_root()
wifi.configure(force_enable=True)
if not app.is_installed(ADD_TEST_ACCOUNT_PKG_NAME):
logs.log('Installing helper apk for adding test account.')
android_directory = environment.get_platform_resources_directory()
add_test_account_apk_path = os.path.join(android_directory,
ADD_TEST_ACCOUNT_APK_NAME)
app.install(add_test_account_apk_path)
logs.log('Trying to add test account.')
output = adb.run_shell_command(
'am instrument -e account %s -e password %s -w %s' %
(test_account_email, test_account_password, ADD_TEST_ACCOUNT_CALL_PATH),
timeout=ADD_TEST_ACCOUNT_TIMEOUT)
if not output or test_account_email not in output:
logs.log('Failed to add test account, probably due to wifi issues.')
return
logs.log('Test account added successfully.')
persistent_cache.set_value(constants.LAST_TEST_ACCOUNT_CHECK_KEY, time.time()) |
Clear temp directories. | def clear_temp_directories():
"""Clear temp directories."""
adb.remove_directory(constants.DEVICE_DOWNLOAD_DIR, recreate=True)
adb.remove_directory(constants.DEVICE_TMP_DIR, recreate=True)
adb.remove_directory(constants.DEVICE_FUZZING_DIR, recreate=True) |
Clears testcase directory. | def clear_testcase_directory():
"""Clears testcase directory."""
adb.remove_directory(constants.DEVICE_TESTCASES_DIR, recreate=True) |
Configures device settings for test environment. | def configure_device_settings():
"""Configures device settings for test environment."""
adb.run_as_root()
# The following line filled with magic numbers will set media volume to 0
# 3 is the 3rd function in the IAudioServiceList and the following
# i32's specify 32 bit integer arguments to the function
adb.run_shell_command('service call audio 3 i32 3 i32 0 i32 1')
# FIXME: We shouldn't need repeat invocation of this. We need to do this
# in case previous invocations of any of the below commands failed.
# Write our test environment settings in content database.
settings.set_content_setting('com.google.settings/partner',
'use_location_for_services', 0)
settings.set_content_setting('settings/global', 'assisted_gps_enabled', 0)
settings.set_content_setting('settings/global',
'development_settings_enabled', 0)
settings.set_content_setting('settings/global', 'stay_on_while_plugged_in', 3)
settings.set_content_setting('settings/global', 'send_action_app_error', 0)
settings.set_content_setting('settings/global',
'verifier_verify_adb_installs', 0)
settings.set_content_setting('settings/global', 'wifi_scan_always_enabled', 0)
settings.set_content_setting('settings/secure', 'anr_show_background', 0)
settings.set_content_setting('settings/secure', 'doze_enabled', 0)
settings.set_content_setting('settings/secure', 'location_providers_allowed',
'')
settings.set_content_setting('settings/secure', 'lockscreen.disabled', 1)
settings.set_content_setting('settings/secure', 'screensaver_enabled', 0)
settings.set_content_setting('settings/system', 'accelerometer_rotation', 0)
settings.set_content_setting('settings/system', 'auto_time', 0)
settings.set_content_setting('settings/system', 'auto_timezone', 0)
settings.set_content_setting('settings/system', 'lockscreen.disabled', 1)
settings.set_content_setting('settings/system', 'notification_light_pulse', 0)
settings.set_content_setting('settings/system', 'screen_brightness_mode', 0)
settings.set_content_setting('settings/system', 'screen_brightness', 1)
settings.set_content_setting('settings/system', 'user_rotation', 0)
# On certain device/Android configurations we need to disable the lock screen
# in a different database. Additionally, the password type must be set to 0.
settings.set_database_setting(LOCKSCREEN_DB, LOCKSCREEN_TABLE_NAME,
'lockscreen.disabled', 1)
settings.set_database_setting(LOCKSCREEN_DB, LOCKSCREEN_TABLE_NAME,
'lockscreen.password_type', 0)
settings.set_database_setting(LOCKSCREEN_DB, LOCKSCREEN_TABLE_NAME,
'lockscreen.password_type_alternate', 0)
app.disable_packages_that_crash_with_gestures()
# Create a list of property name and names to be used in local.prop file.
local_properties_settings_list = copy.deepcopy(LOCAL_PROP_SETTINGS)
# Add debugging flags to local settings list so that they persist across
# reboots.
local_properties_settings_list += get_debug_props_and_values()
# Write the local properties file settings.
local_properties_file_contents = '\n'.join(local_properties_settings_list)
adb.write_data_to_file(local_properties_file_contents, LOCAL_PROP_PATH) |
Modifies system build properties in /system/build.prop for better boot
speed and power use. | def configure_system_build_properties():
"""Modifies system build properties in /system/build.prop for better boot
speed and power use."""
adb.run_as_root()
# Check md5 checksum of build.prop to see if already updated,
# in which case exit. If build.prop does not exist, something
# is very wrong with the device, so bail.
old_md5 = persistent_cache.get_value(constants.BUILD_PROP_MD5_KEY)
current_md5 = adb.get_file_checksum(BUILD_PROP_PATH)
if current_md5 is None:
logs.log_error('Unable to find %s on device.' % BUILD_PROP_PATH)
return
if old_md5 == current_md5:
return
# Pull to tmp file.
bot_tmp_directory = environment.get_value('BOT_TMPDIR')
old_build_prop_path = os.path.join(bot_tmp_directory, 'old.prop')
adb.run_command(['pull', BUILD_PROP_PATH, old_build_prop_path])
if not os.path.exists(old_build_prop_path):
logs.log_error('Unable to fetch %s from device.' % BUILD_PROP_PATH)
return
# Write new build.prop.
new_build_prop_path = os.path.join(bot_tmp_directory, 'new.prop')
old_build_prop_file_content = open(old_build_prop_path)
new_build_prop_file_content = open(new_build_prop_path, 'w')
new_content_notification = '### CHANGED OR ADDED PROPERTIES ###'
for line in old_build_prop_file_content:
property_name = line.split('=')[0].strip()
if property_name in BUILD_PROPERTIES:
continue
if new_content_notification in line:
continue
new_build_prop_file_content.write(line)
new_build_prop_file_content.write(new_content_notification + '\n')
for flag, value in BUILD_PROPERTIES.items():
new_build_prop_file_content.write('%s=%s\n' % (flag, value))
old_build_prop_file_content.close()
new_build_prop_file_content.close()
# Keep verified boot disabled for M and higher releases. This makes it easy
# to modify system's app_process to load asan libraries.
build_version = settings.get_build_version()
if is_build_at_least(build_version, 'M'):
adb.run_as_root()
adb.run_command('disable-verity')
reboot()
# Make /system writable.
adb.run_as_root()
adb.remount()
# Remove seccomp policies (on N and higher) as ASan requires extra syscalls.
if is_build_at_least(build_version, 'N'):
policy_files = adb.run_shell_command(
['find', '/system/etc/seccomp_policy/', '-type', 'f'])
for policy_file in policy_files.splitlines():
adb.run_shell_command(['rm', policy_file.strip()])
# Push new build.prop and backup to device.
logs.log('Pushing new build properties file on device.')
adb.run_command(['push', '-p', old_build_prop_path, BUILD_PROP_BACKUP_PATH])
adb.run_command(['push', '-p', new_build_prop_path, BUILD_PROP_PATH])
adb.run_shell_command(['chmod', '644', BUILD_PROP_PATH])
# Set persistent cache key containing and md5sum.
current_md5 = adb.get_file_checksum(BUILD_PROP_PATH)
persistent_cache.set_value(constants.BUILD_PROP_MD5_KEY, current_md5) |
Return debug property names and values based on |ENABLE_DEBUG_CHECKS|
flag. | def get_debug_props_and_values():
"""Return debug property names and values based on |ENABLE_DEBUG_CHECKS|
flag."""
debug_props_and_values_list = []
enable_debug_checks = environment.get_value('ENABLE_DEBUG_CHECKS', False)
logs.log('Debug flags set to %s.' % str(enable_debug_checks))
# Keep system and applications level asserts disabled since these can lead to
# potential battery depletion issues.
debug_props_and_values_list += [
'dalvik.vm.enableassertions=',
'debug.assert=0',
]
# JNI checks. See this link for more information.
# http://android-developers.blogspot.com/2011/07/debugging-android-jni-with-checkjni.html.
check_jni_flag = (
enable_debug_checks or environment.get_value('ENABLE_CHECK_JNI', False))
debug_props_and_values_list += [
'dalvik.vm.checkjni=%s' % str(check_jni_flag).lower(),
'debug.checkjni=%d' % int(check_jni_flag),
]
is_build_supported = is_build_at_least(settings.get_build_version(), 'N')
debug_malloc_enabled = (
enable_debug_checks and is_build_supported and
not settings.get_sanitizer_tool_name())
# https://android.googlesource.com/platform/bionic/+/master/libc/malloc_debug/README.md
if debug_malloc_enabled:
# FIXME: 'free_track' is very crashy. Skip for now.
debug_malloc_string = 'fill guard'
debug_props_and_values_list += [
'libc.debug.malloc.options=%s' % debug_malloc_string
]
return debug_props_and_values_list |
Prepares android device for app install. | def initialize_device():
"""Prepares android device for app install."""
if environment.is_engine_fuzzer_job() or environment.is_kernel_fuzzer_job():
# These steps are not applicable to libFuzzer and syzkaller jobs and can
# brick a device on trying to configure device build settings.
return
adb.setup_adb()
# General device configuration settings.
configure_system_build_properties()
configure_device_settings()
add_test_accounts_if_needed()
# Setup AddressSanitizer if needed.
sanitizer.setup_asan_if_needed()
# Reboot device as above steps would need it and also it brings device in a
# good state.
reboot()
# Make sure we are running as root after restart.
adb.run_as_root()
# Other configuration tasks (only to done after reboot).
wifi.configure()
setup_host_and_device_forwarder_if_needed()
settings.change_se_linux_to_permissive_mode()
app.wait_until_optimization_complete()
ui.clear_notifications()
ui.unlock_screen() |
Set common environment variables for easy access. | def initialize_environment():
"""Set common environment variables for easy access."""
environment.set_value('BUILD_FINGERPRINT', settings.get_build_fingerprint())
environment.set_value('BUILD_VERSION', settings.get_build_version())
environment.set_value('DEVICE_CODENAME', settings.get_device_codename())
environment.set_value('DEVICE_PATH', adb.get_device_path())
environment.set_value('PLATFORM_ID', settings.get_platform_id())
environment.set_value('PRODUCT_BRAND', settings.get_product_brand())
environment.set_value('SANITIZER_TOOL_NAME',
settings.get_sanitizer_tool_name())
environment.set_value('SECURITY_PATCH_LEVEL',
settings.get_security_patch_level())
environment.set_value('LOG_TASK_TIMES', True) |
Install application package if it does not exist on device
or if force_update is set. | def install_application_if_needed(apk_path, force_update):
"""Install application package if it does not exist on device
or if force_update is set."""
# Make sure that apk exists and has non-zero size. Otherwise, it means we
# are using a system package that we just want to fuzz, but not care about
# installation.
if (not apk_path or not os.path.exists(apk_path) or
not os.path.getsize(apk_path)):
return
# If we don't have a package name, we can't uninstall the app. This is needed
# for installation workflow.
package_name = app.get_package_name()
if not package_name:
return
# Add |REINSTALL_APP_BEFORE_EACH_TASK| to force update decision.
reinstall_app_before_each_task = environment.get_value(
'REINSTALL_APP_BEFORE_EACH_TASK', False)
force_update = force_update or reinstall_app_before_each_task
# Install application if it is not found in the device's
# package list or force_update flag has been set.
if force_update or not app.is_installed(package_name):
app.uninstall(package_name)
app.install(apk_path)
if not app.is_installed(package_name):
logs.log_error(
'Package %s was not installed successfully.' % package_name)
return
logs.log('Package %s is successfully installed using apk %s.' %
(package_name, apk_path))
app.reset() |
Returns whether or not |current_version| is at least as new as
|other_version|. | def is_build_at_least(current_version, other_version):
"""Returns whether or not |current_version| is at least as new as
|other_version|."""
if current_version is None:
return False
# Special-cases for master builds.
if current_version == 'MASTER':
# If the current build is master, we consider it at least as new as any
# other.
return True
if other_version == 'MASTER':
# Since this build is not master, it is not at least as new as master.
return False
return current_version >= other_version |
Pushes testcases from local fuzz directory onto device. | def push_testcases_to_device():
"""Pushes testcases from local fuzz directory onto device."""
# Attempt to ensure that the local state is the same as the state on the
# device by clearing existing files on device before pushing.
clear_testcase_directory()
local_testcases_directory = environment.get_value('FUZZ_INPUTS')
if not os.listdir(local_testcases_directory):
# Directory is empty, nothing to push.
logs.log('No testcases to copy to device, skipping.')
return
adb.copy_local_directory_to_remote(local_testcases_directory,
constants.DEVICE_TESTCASES_DIR) |
Reboots device and clear config state. | def reboot():
"""Reboots device and clear config state."""
# Make sure to clear logcat before reboot occurs. In case of kernel crashes,
# we use the log before reboot, so it is good to clear it when we are doing
# the reboot explicitly.
logger.clear_log()
# Reboot.
logs.log('Rebooting device.')
adb.reboot()
# Wait for boot to complete.
adb.wait_until_fully_booted() |
Sets up http(s) forwarding between device and host. | def setup_host_and_device_forwarder_if_needed():
"""Sets up http(s) forwarding between device and host."""
# Get list of ports to map.
http_port_1 = environment.get_value('HTTP_PORT_1', 8000)
http_port_2 = environment.get_value('HTTP_PORT_2', 8080)
ports = [http_port_1, http_port_2]
# Reverse map socket connections from device to host machine.
for port in ports:
port_string = 'tcp:%d' % port
adb.run_command(['reverse', port_string, port_string]) |
Prepares the device and updates the build if necessary. | def update_build(apk_path, force_update=True, should_initialize_device=True):
"""Prepares the device and updates the build if necessary."""
# Prepare device for app install.
if should_initialize_device:
initialize_device()
# On Android, we may need to write a command line file. We do this in
# advance so that we do not have to write this to the device multiple
# times.
# TODO(mbarbella): Platforms code should not depend on bot.
from clusterfuzz._internal.bot import testcase_manager
testcase_manager.get_command_line_for_application(
write_command_line_file=True)
# Install the app if it does not exist.
install_application_if_needed(apk_path, force_update=force_update) |
Executes request and retries on failure. | def execute_request_with_retries(request):
"""Executes request and retries on failure."""
result = None
for _ in range(MAX_RETRIES):
try:
result = request.execute()
break
except Exception as e:
logs.log_error(f'Error calling endpoint {request.uri}: Error {e}')
return result |
Download one artifact. | def download_artifact(client, bid, target, attempt_id, name, output_directory,
output_filename):
"""Download one artifact."""
logs.log('reached download_artifact')
logs.log('artifact to download: %s' % name)
logs.log('output_directory: %s' % output_directory)
logs.log('output_filename: %s' % output_filename)
artifact_query = client.buildartifact().get(
buildId=bid, target=target, attemptId=attempt_id, resourceId=name)
artifact = execute_request_with_retries(artifact_query)
if artifact is None:
logs.log_error(
'Artifact unreachable with name %s, target %s and build id %s.' %
(name, target, bid))
return False
# Lucky us, we always have the size.
size = int(artifact['size'])
chunksize = -1
if size >= DEFAULT_CHUNK_SIZE:
chunksize = DEFAULT_CHUNK_SIZE
# Just like get, except get_media.
dl_request = client.buildartifact().get_media(
buildId=bid, target=target, attemptId=attempt_id, resourceId=name)
if output_filename:
file_name = output_filename
else:
file_name = name.replace('signed/', '')
output_path = os.path.join(output_directory, file_name)
# If the artifact already exists, then bail out.
if os.path.exists(output_path) and os.path.getsize(output_path) == size:
logs.log('Artifact %s already exists, skipping download.' % name)
return output_path
logs.log('Downloading artifact %s.' % name)
output_dir = os.path.dirname(output_path)
logs.log('Output dir: %s' % output_dir)
if not os.path.exists(output_dir):
logs.log(f'Creating directory {output_dir}')
os.mkdir(output_dir)
with io.FileIO(output_path, mode='wb') as file_handle:
downloader = apiclient.http.MediaIoBaseDownload(
file_handle, dl_request, chunksize=chunksize)
done = False
while not done:
status, done = downloader.next_chunk()
if status:
size_completed = int(status.resumable_progress)
percent_completed = (size_completed * 100.0) / size
logs.log('%.1f%% complete.' % percent_completed)
return output_path |
Return list of artifacts for a given build. | def get_artifacts_for_build(client, bid, target, attempt_id='latest'):
"""Return list of artifacts for a given build."""
request = client.buildartifact().list(
buildId=bid, target=target, attemptId=attempt_id)
request_str = (f'{request.uri}, {request.method}, '
f'{request.body}, {request.methodId}')
artifacts = []
results = []
while request:
result = execute_request_with_retries(request)
if not result:
break
results.append(result)
if result and 'artifacts' in result:
for artifact in result['artifacts']:
artifacts.append(artifact)
request = client.buildartifact().list_next(request, result)
if not artifacts:
logs.log_error(f'No artifact found for target {target}, build id {bid}.\n'
f'request {request_str}, results {results}')
adb.bad_state_reached()
return artifacts |
Return client with connection to build apiary. | def get_client():
"""Return client with connection to build apiary."""
# Connect using build apiary service account credentials.
build_apiary_service_account_private_key = db_config.get_value(
'build_apiary_service_account_private_key')
if not build_apiary_service_account_private_key:
logs.log(
'Android build apiary credentials are not set, skip artifact fetch.')
return None
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json.loads(build_apiary_service_account_private_key),
scopes='https://www.googleapis.com/auth/androidbuild.internal')
client = apiclient.discovery.build(
'androidbuildinternal',
'v3',
credentials=credentials,
static_discovery=False)
return client |
Return stable artifact for cuttlefish branch and target. | def get_stable_build_info():
"""Return stable artifact for cuttlefish branch and target."""
logs.log('Reached get_stable_build_info')
stable_build_info = STABLE_CUTTLEFISH_BUILD
try:
build_info_data = storage.read_data(DEFAULT_STABLE_CUTTLEFISH_BUILD_INFO)
if build_info_data:
logs.log('Loading stable cuttlefish image from %s' %
DEFAULT_STABLE_CUTTLEFISH_BUILD_INFO)
stable_build_info = json.loads(build_info_data)
except Exception as e:
logs.log_error(
'Error loading remote data: %s!\nUsing default build info!' % e)
logs.log('Using stable cuttlefish image - %s' % stable_build_info)
return stable_build_info |
Return latest artifact for a branch and target. | def get_latest_artifact_info(branch, target, signed=False):
"""Return latest artifact for a branch and target."""
client = get_client()
if not client:
return None
# TODO(https://github.com/google/clusterfuzz/issues/3950)
# After stabilizing the Cuttlefish image, revert this
if environment.is_android_cuttlefish():
return get_stable_build_info()
request = client.build().list( # pylint: disable=no-member
buildType='submitted',
branch=branch,
target=target,
successful=True,
maxResults=1,
signed=signed)
request_str = (f'{request.uri}, {request.method}, '
f'{request.body}, {request.methodId}')
builds = execute_request_with_retries(request)
if not builds:
logs.log_error(f'No build found for target {target}, branch {branch}, '
f'request: {request_str}.')
return None
build = builds['builds'][0]
bid = build['buildId']
target = build['target']['name']
return {'bid': bid, 'branch': branch, 'target': target} |
Return artifact for a given build id, target and file regex. | def get(bid, target, regex, output_directory, output_filename=None):
"""Return artifact for a given build id, target and file regex."""
client = get_client()
if not client:
return None
# Run the script to fetch the artifact.
return run_script(
client=client,
bid=bid,
target=target,
regex=regex,
output_directory=output_directory,
output_filename=output_filename) |
Download artifacts as specified. | def run_script(client, bid, target, regex, output_directory, output_filename):
"""Download artifacts as specified."""
artifacts = get_artifacts_for_build(
client=client, bid=bid, target=target, attempt_id='latest')
if not artifacts:
logs.log_error('Artifact could not be fetched for target %s, build id %s.' %
(target, bid))
return False
regex = re.compile(regex)
result = []
for artifact in artifacts:
artifact_name = artifact['name']
# Exclude signature files.
if artifact_name.endswith('.SIGN_INFO'):
continue
if regex.match(artifact_name):
loop_result = download_artifact(
client=client,
bid=bid,
target=target,
attempt_id='latest',
name=artifact_name,
output_directory=output_directory,
output_filename=output_filename)
if loop_result is not None:
result.append(loop_result)
return result |
Download the latest build artifact for the given branch and target. | def download_latest_build(build_info, image_regexes, image_directory):
"""Download the latest build artifact for the given branch and target."""
# Check if our local build matches the latest build. If not, we will
# download it.
build_id = build_info['bid']
target = build_info['target']
logs.log('target stored in current build_info: %s.' % target)
last_build_info = persistent_cache.get_value(constants.LAST_FLASH_BUILD_KEY)
logs.log('last_build_info take from persisten cache: %s.' % last_build_info)
if last_build_info and last_build_info['bid'] == build_id:
return
# Clean up the images directory first.
shell.remove_directory(image_directory, recreate=True)
for image_regex in image_regexes:
image_file_paths = fetch_artifact.get(build_id, target, image_regex,
image_directory)
if not image_file_paths:
logs.log_error('Failed to download artifact %s for '
'branch %s and target %s.' %
(image_file_paths, build_info['branch'], target))
return
for file_path in image_file_paths:
if file_path.endswith('.zip') or file_path.endswith('.tar.gz'):
with archive.open(file_path) as reader:
reader.extract_all(image_directory) |
Wipes user data, resetting the device to original factory state. | def flash_to_latest_build_if_needed():
"""Wipes user data, resetting the device to original factory state."""
if environment.get_value('LOCAL_DEVELOPMENT'):
# Don't reimage local development devices.
return
run_timeout = environment.get_value('RUN_TIMEOUT')
if run_timeout:
# If we have a run timeout, then we are already scheduled to bail out and
# will be probably get re-imaged. E.g. using frameworks like Tradefed.
return
# Check if a flash is needed based on last recorded flash time.
last_flash_time = persistent_cache.get_value(
constants.LAST_FLASH_TIME_KEY,
constructor=datetime.datetime.utcfromtimestamp)
needs_flash = last_flash_time is None or dates.time_has_expired(
last_flash_time, seconds=FLASH_INTERVAL)
if not needs_flash:
return
is_google_device = settings.is_google_device()
if is_google_device is None:
logs.log_error('Unable to query device. Reimaging failed.')
adb.bad_state_reached()
elif not is_google_device:
# We can't reimage these, skip.
logs.log('Non-Google device found, skipping reimage.')
return
# Check if both |BUILD_BRANCH| and |BUILD_TARGET| environment variables
# are set. If not, we don't have enough data for reimaging and hence
# we bail out.
branch = environment.get_value('BUILD_BRANCH')
target = environment.get_value('BUILD_TARGET')
if not target:
logs.log('BUILD_TARGET is not set.')
build_params = settings.get_build_parameters()
if build_params:
logs.log('build_params found on device: %s.' % build_params)
if environment.is_android_cuttlefish():
target = build_params.get('target') + FLASH_DEFAULT_BUILD_TARGET
logs.log('is_android_cuttlefish() returned True. Target: %s.' % target)
else:
target = build_params.get('target') + '-userdebug'
logs.log('is_android_cuttlefish() returned False. Target: %s.' % target)
# Cache target in environment. This is also useful for cases when
# device is bricked and we don't have this information available.
environment.set_value('BUILD_TARGET', target)
else:
logs.log('build_params not found.')
if not branch or not target:
logs.log_warn(
'BUILD_BRANCH and BUILD_TARGET are not set, skipping reimage.')
return
image_directory = environment.get_value('IMAGES_DIR')
logs.log('image_directory: %s' % str(image_directory))
if not image_directory:
logs.log('no image_directory set, setting to default')
image_directory = FLASH_DEFAULT_IMAGES_DIR
logs.log('image_directory: %s' % image_directory)
build_info = fetch_artifact.get_latest_artifact_info(branch, target)
if not build_info:
logs.log_error('Unable to fetch information on latest build artifact for '
'branch %s and target %s.' % (branch, target))
return
if environment.is_android_cuttlefish():
download_latest_build(build_info, FLASH_CUTTLEFISH_REGEXES, image_directory)
adb.recreate_cuttlefish_device()
adb.connect_to_cuttlefish_device()
else:
download_latest_build(build_info, FLASH_IMAGE_REGEXES, image_directory)
# We do one device flash at a time on one host, otherwise we run into
# failures and device being stuck in a bad state.
flash_lock_key_name = 'flash:%s' % socket.gethostname()
if not locks.acquire_lock(flash_lock_key_name, by_zone=True):
logs.log_error('Failed to acquire lock for reimaging, exiting.')
return
logs.log('Reimaging started.')
logs.log('Rebooting into bootloader mode.')
for _ in range(FLASH_RETRIES):
adb.run_as_root()
adb.run_command(['reboot-bootloader'])
time.sleep(FLASH_REBOOT_BOOTLOADER_WAIT)
adb.run_fastboot_command(['oem', 'off-mode-charge', '0'])
adb.run_fastboot_command(['-w', 'reboot-bootloader'])
for partition, partition_image_filename in FLASH_IMAGE_FILES:
partition_image_file_path = os.path.join(image_directory,
partition_image_filename)
adb.run_fastboot_command(
['flash', partition, partition_image_file_path])
if partition in ['bootloader', 'radio']:
adb.run_fastboot_command(['reboot-bootloader'])
# Disable ramdump to avoid capturing ramdumps during kernel crashes.
# This causes device lockup of several minutes during boot and we intend
# to analyze them ourselves.
adb.run_fastboot_command(['oem', 'ramdump', 'disable'])
adb.run_fastboot_command('reboot')
time.sleep(FLASH_REBOOT_WAIT)
if adb.get_device_state() == 'device':
break
logs.log_error('Reimaging failed, retrying.')
locks.release_lock(flash_lock_key_name, by_zone=True)
if adb.get_device_state() != 'device':
logs.log_error('Unable to find device. Reimaging failed.')
adb.bad_state_reached()
logs.log('Reimaging finished.')
# Reset all of our persistent keys after wipe.
persistent_cache.delete_value(constants.BUILD_PROP_MD5_KEY)
persistent_cache.delete_value(constants.LAST_TEST_ACCOUNT_CHECK_KEY)
persistent_cache.set_value(constants.LAST_FLASH_BUILD_KEY, build_info)
persistent_cache.set_value(constants.LAST_FLASH_TIME_KEY, time.time()) |
Return a random gesture seed from monkey framework natively supported by
Android OS. | def get_random_gestures(_):
"""Return a random gesture seed from monkey framework natively supported by
Android OS."""
random_seed = random.getrandbits(32)
gesture = 'monkey,%s' % str(random_seed)
return [gesture] |
Run the provided interaction gestures. | def run_gestures(gestures, *_):
"""Run the provided interaction gestures."""
package_name = os.getenv('PKG_NAME')
if not package_name:
# No package to send gestures to, bail out.
return
if len(gestures) != 1 or not gestures[0].startswith('monkey'):
# Bad gesture string, bail out.
return
monkey_seed = gestures[0].split(',')[-1]
adb.run_shell_command([
'monkey', '-p', package_name, '-s', monkey_seed, '--throttle',
str(MONKEY_THROTTLE_DELAY), '--ignore-security-exceptions',
str(NUM_MONKEY_EVENTS)
]) |
Sometimes kernel paths start with
/buildbot/src/partner-android/BRANCH/private/PROJ. We want to remove all
of this. | def _get_clean_kernel_path(path):
"""Sometimes kernel paths start with
/buildbot/src/partner-android/BRANCH/private/PROJ. We want to remove all
of this."""
# Remove the stuff before 'private', since it is build-server dependent
# and not part of the final URL.
if '/private/' in path:
path_parts = path.split('/')
path_parts = path_parts[path_parts.index('private') + 2:]
return '/'.join(path_parts)
return path |
Add source links data to kernel stack frames. | def get_kernel_stack_frame_link(stack_frame, kernel_prefix, kernel_hash):
"""Add source links data to kernel stack frames."""
match = LLVM_SYMBOLIZER_STACK_FRAME_PATH_LINE_REGEX.search(stack_frame)
if not match:
# If this stack frame does not contain a path and line, bail out.
return stack_frame
path = _get_clean_kernel_path(match.group(1))
line = match.group(3)
kernel_prefix = utils.strip_from_left(kernel_prefix, 'kernel/private/')
display_path = f'{kernel_prefix}/{path}:{line}'
# If we have a column number, lets add it to the display path.
if match.group(4):
display_path += match.group(4)
kernel_url_info = (r'http://go/pakernel/{prefix}/+/{hash}/{path}#{line};'
r'{display_path};').format(
prefix=kernel_prefix,
hash=kernel_hash,
path=path,
line=line,
display_path=display_path)
link_added_stack_frame = LLVM_SYMBOLIZER_STACK_FRAME_PATH_LINE_REGEX.sub(
kernel_url_info, stack_frame)
return link_added_stack_frame |
Find the prefix and full hash in the repo_data based on the partial. | def _get_prefix_and_full_hash(repo_data, kernel_partial_hash):
"""Find the prefix and full hash in the repo_data based on the partial."""
kernel_partial_hash_lookup = 'u\'%s' % kernel_partial_hash
for line in repo_data.splitlines():
if kernel_partial_hash_lookup in line:
prefix, full_hash = line.split(' ', 1)
return prefix, full_hash.strip('u\'')
return None, None |
Downloads repo.prop and returns the data based on build_id and target. | def _get_repo_prop_data(build_id, target):
"""Downloads repo.prop and returns the data based on build_id and target."""
symbols_directory = os.path.join(
environment.get_value('SYMBOLS_DIR'), 'kernel')
repro_filename = symbols_downloader.get_repo_prop_archive_filename(
build_id, target)
# Grab repo.prop, it is not on the device nor in the build_dir.
symbols_downloader.download_kernel_repo_prop_if_needed(symbols_directory)
local_repo_path = utils.find_binary_path(symbols_directory, repro_filename)
if local_repo_path and os.path.exists(local_repo_path):
return utils.read_data_from_file(local_repo_path, eval_data=False).decode()
return None |
Download repo.prop and return the full hash and prefix. | def get_kernel_prefix_and_full_hash():
"""Download repo.prop and return the full hash and prefix."""
kernel_partial_hash, build_id = get_kernel_hash_and_build_id()
target = get_kernel_name()
if not build_id or not target:
logs.log_error('Could not get kernel parameters, exiting.')
return None
android_kernel_repo_data = _get_repo_prop_data(build_id, target)
if android_kernel_repo_data:
return _get_prefix_and_full_hash(android_kernel_repo_data,
kernel_partial_hash)
return None, None |
Returns the kernel name for the device, since some kernels are shared. | def get_kernel_name():
"""Returns the kernel name for the device, since some kernels are shared."""
product_name = settings.get_product_name()
build_product = settings.get_build_product()
# Strip _kasan off of the end as we will add it later if needed.
utils.strip_from_right(product_name, '_kasan')
# Some devices have a different kernel name than product_name, if so use the
# kernel name.
return constants.PRODUCT_TO_KERNEL.get(build_product, product_name) |
Returns the (partial_hash, build_id) of the kernel. | def get_kernel_hash_and_build_id():
"""Returns the (partial_hash, build_id) of the kernel."""
version_string = settings.get_kernel_version_string()
match = re.match(LINUX_VERSION_REGEX, version_string)
if match:
return match.group(2), match.group(3)
return None |
Clear log. | def clear_log():
"""Clear log."""
adb.run_as_root()
adb.run_shell_command(['stop', 'logd'])
adb.run_shell_command(['start', 'logd'])
time.sleep(0.1)
adb.run_command(['logcat', '-c']) |
Returns true if we consider this line in logs. | def is_line_valid(line):
"""Returns true if we consider this line in logs."""
if re.match(r'^[-]+ beginning of', line):
return False
is_chromium_resource_load = 'NotifyBeforeURLRequest' in line
# Discard noisy debug and verbose output.
# http://developer.android.com/tools/debugging/debugging-log.html.
at_least_info_level = not (line.startswith('D/') or line.startswith('V/'))
return is_chromium_resource_load or at_least_info_level |
Filters log output. Removes debug info, etc and normalize output. | def filter_log_output(output):
"""Filters log output. Removes debug info, etc and normalize output."""
if not output:
return ''
filtered_output = ''
last_process_tuple = (None, None)
for line in output.splitlines():
if not is_line_valid(line):
continue
# To parse frames like:
# E/v8 (18890): Error installing extension 'v8/LoadTimes'.
# {log_level}/{process_name}({process_id}): {message}
m_line = re.match(r'^[VDIWEFS]/(.+)\(\s*(\d+)\)[:](.*)$', line)
if not m_line:
logs.log_error('Failed to parse logcat line: %s' % line)
continue
process_name = m_line.group(1).strip()
process_id = int(m_line.group(2))
filtered_line = m_line.group(3).rstrip()[1:]
# Process Android crash stack frames and convert into sanitizer format.
m_crash_state = re.match(r'\s*#([0-9]+)\s+pc\s+([xX0-9a-fA-F]+)\s+(.+)',
filtered_line)
if m_crash_state:
frame_no = int(m_crash_state.group(1))
frame_address = m_crash_state.group(2)
frame_binary = m_crash_state.group(3).strip()
# Ignore invalid frames, helps to prevent errors
# while symbolizing.
if '<unknown>' in frame_binary:
continue
# Normalize frame address.
if not frame_address.startswith('0x'):
frame_address = '0x%s' % frame_address
# Separate out the function argument.
frame_binary = (frame_binary.split(' '))[0]
# Normalize line into the same sanitizer tool format.
filtered_line = (' #%d %s (%s+%s)' % (frame_no, frame_address,
frame_binary, frame_address))
# Process Chrome crash stack frames and convert into sanitizer format.
# Stack frames don't have paranthesis around frame binary and address, so
# add it explicitly to allow symbolizer to catch it.
m_crash_state = re.match(
r'\s*#([0-9]+)\s+([xX0-9a-fA-F]+)\s+([^(]+\+[xX0-9a-fA-F]+)$',
filtered_line)
if m_crash_state:
frame_no = int(m_crash_state.group(1))
frame_address = m_crash_state.group(2)
frame_binary_and_address = m_crash_state.group(3).strip()
filtered_line = (' #%d %s (%s)' % (frame_no, frame_address,
frame_binary_and_address))
# Add process number if changed.
current_process_tuple = (process_name, process_id)
if current_process_tuple != last_process_tuple:
filtered_output += '--------- %s (%d):\n' % (process_name, process_id)
last_process_tuple = current_process_tuple
filtered_output += filtered_line + '\n'
return filtered_output |
Return log data without noise and some normalization. | def log_output(additional_flags=''):
"""Return log data without noise and some normalization."""
output = adb.run_command('logcat -d -v brief %s *:V' % additional_flags)
return filter_log_output(output) |
Return log data from last reboot without noise and some normalization. | def log_output_before_last_reboot():
"""Return log data from last reboot without noise and some normalization."""
return log_output(additional_flags='-L') |
Return LD_LIBRARY_PATH setting for memory tools, None otherwise. | def get_ld_library_path_for_memory_tools():
"""Return LD_LIBRARY_PATH setting for memory tools, None otherwise."""
tool = settings.get_sanitizer_tool_name()
if tool:
return constants.DEVICE_SANITIZER_DIR
tool = settings.is_mte_build()
if tool:
return constants.DEVICE_MTE_DIR
return None |
Return path for the sanitizer options file. | def get_options_file_path(sanitizer_tool_name):
"""Return path for the sanitizer options file."""
# If this a full sanitizer system build, then update the options file in
# /system, else just put it in device temp directory.
sanitizer_directory = ('/system' if settings.get_sanitizer_tool_name() else
constants.DEVICE_TMP_DIR)
sanitizer_filename = SANITIZER_TOOL_TO_FILE_MAPPINGS.get(
sanitizer_tool_name.lower())
if sanitizer_filename is None:
logs.log_error('Unsupported sanitizer: ' + sanitizer_tool_name)
return None
return os.path.join(sanitizer_directory, sanitizer_filename) |
Set sanitizer options on the disk file. | def set_options(sanitizer_tool_name, sanitizer_options):
"""Set sanitizer options on the disk file."""
sanitizer_options_file_path = get_options_file_path(sanitizer_tool_name)
if not sanitizer_options_file_path:
return
adb.write_data_to_file(sanitizer_options, sanitizer_options_file_path) |
Set up asan on device. | def setup_asan_if_needed():
"""Set up asan on device."""
if not environment.get_value('ASAN_DEVICE_SETUP'):
# Only do this step if explicitly enabled in the job type. This cannot be
# determined from libraries in application directory since they can go
# missing in a bad build, so we want to catch that.
return
if settings.get_sanitizer_tool_name():
# If this is a sanitizer build, no need to setup ASAN (incompatible).
return
app_directory = environment.get_value('APP_DIR')
if not app_directory:
# No app directory -> No ASAN runtime library. No work to do, bail out.
return
# Initialize variables.
android_directory = environment.get_platform_resources_directory()
device_id = environment.get_value('ANDROID_SERIAL')
# Execute the script.
logs.log('Executing ASan device setup script.')
asan_device_setup_script_path = os.path.join(android_directory, 'third_party',
'asan_device_setup.sh')
extra_options_arg = 'include_if_exists=' + get_options_file_path('asan')
asan_device_setup_script_args = [
'--lib', app_directory, '--device', device_id, '--extra-options',
extra_options_arg
]
process = new_process.ProcessRunner(asan_device_setup_script_path,
asan_device_setup_script_args)
result = process.run_and_wait()
if result.return_code:
logs.log_error('Failed to setup ASan on device.', output=result.output)
return
logs.log(
'ASan device setup script successfully finished, waiting for boot.',
output=result.output)
# Wait until fully booted as otherwise shell restart followed by a quick
# reboot can trigger data corruption in /data/data.
adb.wait_until_fully_booted() |
Switch SELinux to permissive mode for working around local file access and
other issues. | def change_se_linux_to_permissive_mode():
"""Switch SELinux to permissive mode for working around local file access and
other issues."""
adb.run_shell_command(['setenforce', '0']) |
Return build's fingerprint. | def get_build_fingerprint():
"""Return build's fingerprint."""
return adb.get_property('ro.build.fingerprint') |
Return the build flavor. | def get_build_flavor():
"""Return the build flavor."""
return adb.get_property('ro.build.flavor') |
Return build_id, target and type from the device's fingerprint | def get_build_parameters():
"""Return build_id, target and type from the device's fingerprint"""
build_fingerprint = environment.get_value('BUILD_FINGERPRINT',
get_build_fingerprint())
build_fingerprint_match = BUILD_FINGERPRINT_REGEX.match(build_fingerprint)
if not build_fingerprint_match:
return None
build_id = build_fingerprint_match.group('build_id')
target = build_fingerprint_match.group('target')
build_type = build_fingerprint_match.group('type')
return {'build_id': build_id, 'target': target, 'type': build_type} |
Return the build version of the system as a character.
K = Kitkat, L = Lollipop, M = Marshmellow, MASTER = Master. | def get_build_version():
"""Return the build version of the system as a character.
K = Kitkat, L = Lollipop, M = Marshmellow, MASTER = Master.
"""
build_version = adb.get_property('ro.build.id')
if not build_version:
return None
if build_version == 'MASTER':
return build_version
match = re.match('^([A-Z])', build_version)
if not match:
return None
return match.group(1) |
Return cpu architecture. | def get_cpu_arch():
"""Return cpu architecture."""
return adb.get_property('ro.product.cpu.abi') |
Return the device codename. | def get_device_codename():
"""Return the device codename."""
serial = environment.get_value('ANDROID_SERIAL')
devices_output = adb.run_command(['devices', '-l'])
serial_pattern = r'(^|\s){serial}\s'.format(serial=re.escape(serial))
serial_regex = re.compile(serial_pattern)
for line in devices_output.splitlines():
values = line.strip().split()
if not serial_regex.search(line):
continue
for value in values:
if not value.startswith('device:'):
continue
device_codename = value.split(':')[-1]
if device_codename:
return device_codename
# Unable to get code name.
return '' |
Return a string as |android:{codename}_{sanitizer}:{build_version}|. | def get_platform_id():
"""Return a string as |android:{codename}_{sanitizer}:{build_version}|."""
platform_id = 'android'
# Add codename and sanitizer tool information.
platform_id += ':%s' % get_device_codename()
sanitizer_tool_name = get_sanitizer_tool_name()
if sanitizer_tool_name:
platform_id += '_%s' % sanitizer_tool_name
# Add build version.
build_version = get_build_version()
if build_version:
platform_id += ':%s' % build_version
return platform_id |
Return product's brand. | def get_product_brand():
"""Return product's brand."""
return adb.get_property('ro.product.brand') |
Return product's name. | def get_product_name():
"""Return product's name."""
return adb.get_property('ro.product.name') |
Return product's model. | def get_product_model():
"""Return product's model."""
return adb.get_property('ro.product.model') |
Return builds's product. | def get_build_product():
"""Return builds's product."""
return adb.get_property('ro.build.product') |
Return sanitizer tool name e.g. ASAN if found on device. | def get_sanitizer_tool_name():
"""Return sanitizer tool name e.g. ASAN if found on device."""
build_flavor = get_build_flavor()
if 'hwasan' in build_flavor:
return 'hwasan'
if 'kasan' in build_flavor:
return 'kasan'
if 'asan' in build_flavor:
return 'asan'
return None |
Return True if device is using Memory Tagging Extension. | def is_mte_build():
"""Return True if device is using Memory Tagging Extension."""
build_flavor = get_build_flavor()
return 'mte' in build_flavor |
Return the security patch level reported by the device. | def get_security_patch_level():
"""Return the security patch level reported by the device."""
return adb.get_property('ro.build.version.security_patch') |
Return true if this is a google branded device. | def is_google_device():
"""Return true if this is a google branded device."""
# If a build branch is already set, then this is a Google device. No need to
# query device which can fail if the device is failing on recovery mode.
build_branch = environment.get_value('BUILD_BRANCH')
if build_branch:
return True
product_brand = environment.get_value('PRODUCT_BRAND', get_product_brand())
if product_brand is None:
return None
return product_brand in ('google', 'generic') |
Returns if we are running in Android Automotive OS, currently only for
Osprey or Seahawk. | def is_automotive():
"""Returns if we are running in Android Automotive OS, currently only for
Osprey or Seahawk."""
product_model = get_product_model()
return product_model in ('Osprey', 'Seahawk') |
Set a device content setting. The input is not sanitized, so make sure to
use with trusted input key and value pair only. | def set_content_setting(table, key, value):
"""Set a device content setting. The input is not sanitized, so make sure to
use with trusted input key and value pair only."""
def _get_type_binding(value):
"""Return binding type for content setting."""
if isinstance(value, bool):
return 'b'
if isinstance(value, float):
return 'f'
if isinstance(value, int):
return 'i'
# Default to string.
return 's'
content_setting_command = (
'content insert --uri content://%s --bind name:s:%s --bind value:%s:%s' %
(table, key, _get_type_binding(value), str(value)))
adb.run_shell_command(content_setting_command) |
Update a key in a database. The input is not sanitized, so make sure to use
with trusted input key and value pair only. | def set_database_setting(database_path, table, key, value):
"""Update a key in a database. The input is not sanitized, so make sure to use
with trusted input key and value pair only."""
sql_command_string = ('"UPDATE %s SET value=\'%s\' WHERE name=\'%s\'"') % (
table, str(value), key)
adb.run_shell_command(['sqlite3', database_path, sql_command_string]) |
Return True if we should continue to download symbols. | def should_download_symbols():
"""Return True if we should continue to download symbols."""
# For local testing, we do not have access to the cloud storage bucket with
# the symbols. In this case, just bail out. We have archived symbols for
# google builds only.
return (not environment.get_value('LOCAL_DEVELOPMENT') and
settings.is_google_device()) |
Downloads artifact to actifacts_archive_path if needed | def download_artifact_if_needed(
build_id, artifact_directory, artifact_archive_path,
targets_with_type_and_san, artifact_file_name, output_filename_override):
"""Downloads artifact to actifacts_archive_path if needed"""
# Delete existing symbols directory first.
shell.remove_directory(artifact_directory, recreate=True)
for target_with_type_and_san in targets_with_type_and_san:
# Fetch the artifact now.
fetch_artifact.get(build_id, target_with_type_and_san, artifact_file_name,
artifact_directory, output_filename_override)
if os.path.exists(artifact_archive_path):
break |
Downloads the repo.prop for a branch | def download_repo_prop_if_needed(symbols_directory, build_id, cache_target,
targets_with_type_and_san, cache_type):
"""Downloads the repo.prop for a branch"""
artifact_file_name = 'repo.prop'
symbols_archive_filename = get_repo_prop_archive_filename(
build_id, cache_target)
output_filename_override = symbols_archive_filename
# We create our own build_params for cache
build_params = {
'build_id': build_id,
'target': cache_target,
'type': cache_type
}
build_params_check_path = os.path.join(symbols_directory,
'.cached_build_params')
if check_symbols_cached(build_params_check_path, build_params):
return
symbols_archive_path = os.path.join(symbols_directory,
symbols_archive_filename)
download_artifact_if_needed(build_id, symbols_directory, symbols_archive_path,
targets_with_type_and_san, artifact_file_name,
output_filename_override)
if not os.path.exists(symbols_archive_path):
logs.log_error('Unable to locate repo.prop %s.' % symbols_archive_path)
return
# Store the artifact for later use or for use by other bots.
utils.write_data_to_file(build_params, build_params_check_path) |
Downloads the repo.prop for the kernel of a device | def download_kernel_repo_prop_if_needed(symbols_directory):
"""Downloads the repo.prop for the kernel of a device"""
if not should_download_symbols():
return
# For Android kernel we want to get the repro.prop
# Note: kasan and non-kasan kernel should have the same repo.prop for a given
# build_id.
_, build_id = kernel_utils.get_kernel_hash_and_build_id()
target = kernel_utils.get_kernel_name()
if not build_id or not target:
logs.log_error('Could not get kernel parameters, exiting.')
return
tool_suffix = environment.get_value('SANITIZER_TOOL_NAME')
# Some kernels are just 'kernel', some are kernel_target
if tool_suffix:
targets_with_type_and_san = [
f'kernel_{tool_suffix}', f'kernel_{tool_suffix}_{target}'
]
else:
targets_with_type_and_san = ['kernel', f'kernel_{target}']
download_repo_prop_if_needed(symbols_directory, build_id, target,
targets_with_type_and_san, 'kernel') |
Download system libraries from |SYMBOLS_URL| and cache locally. | def download_system_symbols_if_needed(symbols_directory):
"""Download system libraries from |SYMBOLS_URL| and cache locally."""
if not should_download_symbols():
return
# Get the build fingerprint parameters.
build_params = settings.get_build_parameters()
if not build_params:
logs.log_error('Unable to determine build parameters.')
return
build_params_check_path = os.path.join(symbols_directory,
'.cached_build_params')
if check_symbols_cached(build_params_check_path, build_params):
return
build_id = build_params.get('build_id')
target = build_params.get('target')
build_type = build_params.get('type')
if environment.is_android():
build_type = constants.RELEASE_CONFIGURATION + '-' + build_type
if not build_id or not target or not build_type:
logs.log_error('Null build parameters found, exiting.')
return
symbols_archive_filename = f'{target}-symbols-{build_id}.zip'
artifact_file_name = symbols_archive_filename
output_filename_override = None
# Include type and sanitizer information in the target.
tool_suffix = environment.get_value('SANITIZER_TOOL_NAME')
target_with_type_and_san = f'{target}-{build_type}'
if tool_suffix and not tool_suffix in target_with_type_and_san:
target_with_type_and_san += f'_{tool_suffix}'
targets_with_type_and_san = [target_with_type_and_san]
symbols_archive_path = os.path.join(symbols_directory,
symbols_archive_filename)
download_artifact_if_needed(build_id, symbols_directory, symbols_archive_path,
targets_with_type_and_san, artifact_file_name,
output_filename_override)
if not os.path.exists(symbols_archive_path):
logs.log_error(
'Unable to locate symbols archive %s.' % symbols_archive_path)
return
with archive.open(symbols_archive_path) as reader:
reader.extract_all(symbols_directory, trusted=True)
shell.remove_file(symbols_archive_path)
utils.write_data_to_file(build_params, build_params_check_path) |
Downloads and extracts Trusted App ELF files | def download_trusty_symbols_if_needed(symbols_directory, app_name, bid):
"""Downloads and extracts Trusted App ELF files"""
ab_target = ''
device = settings.get_build_parameters().get('target')
if device in ['cheetah', 'panther']:
ab_target = 'cloudripper-fuzz-test-debug'
if device in ['oriole', 'raven', 'bluejay']:
ab_target = 'slider-fuzz-test-debug'
branch = 'polygon-trusty-whitechapel-master'
if not bid:
bid = fetch_artifact.get_latest_artifact_info(branch, ab_target)['bid']
artifact_filename = f'{ab_target}-{bid}.syms.zip'
symbols_archive_path = os.path.join(symbols_directory, artifact_filename)
download_artifact_if_needed(bid, symbols_directory, symbols_archive_path,
[ab_target], artifact_filename, None)
with zipfile.ZipFile(symbols_archive_path, 'r') as symbols_zipfile:
for filepath in symbols_zipfile.namelist():
if f'{app_name}.syms.elf' in filepath:
symbols_zipfile.extract(filepath, symbols_directory)
os.rename(f'{symbols_directory}/{filepath}',
f'{symbols_directory}/{app_name}.syms.elf')
if 'lk.elf' == filepath:
symbols_zipfile.extract(filepath, symbols_directory) |
Look for binary on build server or on device. | def _get_binary_from_build_or_device(binary_path):
"""Look for binary on build server or on device."""
# Initialize some helper variables.
symbols_directory = environment.get_value('SYMBOLS_DIR')
binary_filename = os.path.basename(binary_path)
# We didn't find the library locally in the build directory.
# Try finding the library in the local system library cache.
download_system_symbols_if_needed(symbols_directory)
local_binary_path = utils.find_binary_path(symbols_directory, binary_path)
if local_binary_path:
return local_binary_path
# Try pulling in the binary directly from the device into the
# system library cache directory.
local_binary_path = os.path.join(symbols_directory, binary_filename)
adb.run_command('pull %s %s' % (binary_path, local_binary_path))
if os.path.exists(local_binary_path):
return local_binary_path
return None |
Filter binary path to provide local copy. | def filter_binary_path(binary_path):
"""Filter binary path to provide local copy."""
# LKL fuzzer name is not full path.
if environment.is_android():
# Skip symbolization when running it on bad entries like [stack:XYZ].
if not binary_path.startswith('/') or '(deleted)' in binary_path:
return ''
# Initialize some helper variables.
build_directory = environment.get_value('BUILD_DIR')
# Try to find the library in the build directory first.
local_binary_path = utils.find_binary_path(build_directory, binary_path)
if local_binary_path:
return local_binary_path
# We should only download from the build server if we are Android.
if environment.is_android():
local_binary_path = _get_binary_from_build_or_device(binary_path)
if local_binary_path:
return local_binary_path
# Unable to find library.
logs.log_error('Unable to find library %s for symbolization.' % binary_path)
return '' |
Clear all pending notifications. | def clear_notifications():
"""Clear all pending notifications."""
adb.run_shell_command(['service', 'call', 'notification', '1']) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.