def Asan(args):
  env = os.environ.copy()
  env['ADB'] = args.adb

  try:
    with _LogDevicesOnFailure('Failed to set up the device.'):
      device = device_utils.DeviceUtils.HealthyDevices(
          device_arg=args.device)[0]
      disable_verity = device.build_version_sdk >= version_codes.MARSHMALLOW
      if disable_verity:
        device.EnableRoot()
        # TODO(crbug.com/790202): Stop logging output after diagnosing
        # issues on android-asan.
        verity_output = device.adb.DisableVerity()
        if verity_output:
          logging.info('disable-verity output:')
          for line in verity_output.splitlines():
            logging.info('  %s', line)
        device.Reboot()
      # Call EnableRoot prior to asan_device_setup.sh to ensure it doesn't
      # get tripped up by the root timeout.
      device.EnableRoot()
      setup_cmd = [_SCRIPT_PATH, '--lib', args.lib]
      if args.device:
        setup_cmd += ['--device', args.device]
      subprocess.check_call(setup_cmd, env=env)
      yield
  finally:
    with _LogDevicesOnFailure('Failed to tear down the device.'):
      device.EnableRoot()
      teardown_cmd = [_SCRIPT_PATH, '--revert']
      if args.device:
        teardown_cmd += ['--device', args.device]
      subprocess.check_call(teardown_cmd, env=env)
      if disable_verity:
        # TODO(crbug.com/790202): Stop logging output after diagnosing
        # issues on android-asan.
        verity_output = device.adb.EnableVerity()
        if verity_output:
          logging.info('enable-verity output:')
          for line in verity_output.splitlines():
            logging.info('  %s', line)
        device.Reboot()