def ProcessCommonOptions(args):
  """Processes and handles all common options."""
  run_tests_helper.SetLogLevel(args.verbose_count)
  constants.SetBuildType(args.build_type)
  if args.build_directory:
    constants.SetBuildDirectory(args.build_directory)
  if args.output_directory:
    constants.SetOutputDirectory(args.output_directory)

  devil_custom_deps = None
  if args.adb_path:
    devil_custom_deps = {
      'adb': {
        devil_env.GetPlatform(): [args.adb_path]
      }
    }

  devil_chromium.Initialize(
      output_directory=constants.GetOutDirectory(),
      custom_deps=devil_custom_deps)

  # Some things such as Forwarder require ADB to be in the environment path.
  adb_dir = os.path.dirname(constants.GetAdbPath())
  if adb_dir and adb_dir not in os.environ['PATH'].split(os.pathsep):
    os.environ['PATH'] = adb_dir + os.pathsep + os.environ['PATH']
示例#2
0
    def _UnmapDevicePortLocked(device_port, device):
        """Internal method used by UnmapDevicePort().

    Note that the global lock must be acquired before calling this method.
    """
        instance = Forwarder._GetInstanceLocked(None)
        serial = str(device)
        serial_with_port = (serial, device_port)
        if not serial_with_port in instance._device_to_host_port_map:
            logging.error('Trying to unmap non-forwarded port %d' %
                          device_port)
            return
        redirection_command = [
            '--adb=' + constants.GetAdbPath(), '--serial-id=' + serial,
            '--unmap',
            str(device_port)
        ]
        logging.info('Undo forwarding using command: %s', redirection_command)
        (exit_code, output
         ) = cmd_helper.GetCmdStatusAndOutput([instance._host_forwarder_path] +
                                              redirection_command)
        if exit_code != 0:
            logging.error(
                '%s exited with %d:\n%s' %
                (instance._host_forwarder_path, exit_code, '\n'.join(output)))
        host_port = instance._device_to_host_port_map[serial_with_port]
        del instance._device_to_host_port_map[serial_with_port]
        del instance._host_to_device_port_map[host_port]
示例#3
0
def StartShell(context, arguments, stdout=None, on_application_stop=None):
    """
  Starts the mojo shell, passing it the given arguments.

  If stdout is not None, it should be a valid argument for subprocess.Popen.
  """
    STDOUT_PIPE = "/data/data/%s/stdout.fifo" % MOJO_SHELL_PACKAGE_NAME

    cmd = [
        constants.GetAdbPath(), 'shell', 'am', 'start', '-W', '-S', '-a',
        'android.intent.action.VIEW', '-n',
        '%s/.MojoShellActivity' % MOJO_SHELL_PACKAGE_NAME
    ]

    parameters = ['--origin=http://127.0.0.1:%d/' % context.device_port]
    if stdout or on_application_stop:
        context.device.RunShellCommand('rm %s' % STDOUT_PIPE)
        parameters.append('--fifo-path=%s' % STDOUT_PIPE)
        _ReadFifo(context, STDOUT_PIPE, stdout, on_application_stop)
    parameters += arguments

    if parameters:
        encodedParameters = json.dumps(parameters)
        cmd += ['--es', 'encodedParameters', encodedParameters]

    with open(os.devnull, 'w') as devnull:
        subprocess.Popen(cmd, stdout=devnull).wait()
示例#4
0
def CanDiscoverDevices():
    """Returns true if devices are discoverable via adb."""
    adb_path = constants.GetAdbPath()
    if os.path.isabs(adb_path) and not os.path.exists(adb_path):
        return False
    try:
        with open(os.devnull, 'w') as devnull:
            adb_process = subprocess.Popen(['adb', 'devices'],
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           stdin=devnull)
            stdout = adb_process.communicate()[0]
        if re.search(re.escape('????????????\tno permissions'),
                     stdout) != None:
            logging.warn('adb devices gave a permissions error. '
                         'Consider running adb as root:')
            logging.warn('  adb kill-server')
            logging.warn('  sudo `which adb` devices\n\n')
        return True
    except OSError:
        pass
    try:
        os.environ['PATH'] = os.pathsep.join(
            [os.path.dirname(adb_path), os.environ['PATH']])
        device_utils.DeviceUtils.HealthyDevices(None)
        return True
    except (device_errors.CommandFailedError,
            device_errors.CommandTimeoutError, OSError):
        return False
示例#5
0
  def Map(port_pairs, device, tool=None):
    """Runs the forwarder.

    Args:
      port_pairs: A list of tuples (device_port, host_port) to forward. Note
                 that you can specify 0 as a device_port, in which case a
                 port will by dynamically assigned on the device. You can
                 get the number of the assigned port using the
                 DevicePortForHostPort method.
      device: A DeviceUtils instance.
      tool: Tool class to use to get wrapper, if necessary, for executing the
            forwarder (see valgrind_tools.py).

    Raises:
      Exception on failure to forward the port.
    """
    if not tool:
      tool = valgrind_tools.CreateTool(None, device)
    with _FileLock(Forwarder._LOCK_PATH):
      instance = Forwarder._GetInstanceLocked(tool)
      instance._InitDeviceLocked(device, tool)

      device_serial = str(device)
      redirection_commands = [
          ['--adb=' + constants.GetAdbPath(),
           '--serial-id=' + device_serial,
           '--map', str(device_port), str(host_port)]
          for device_port, host_port in port_pairs]
      logging.info('Forwarding using commands: %s', redirection_commands)

      for redirection_command in redirection_commands:
        try:
          (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
              [instance._host_forwarder_path] + redirection_command)
        except OSError as e:
          if e.errno == 2:
            raise Exception('Unable to start host forwarder. Make sure you have'
                            ' built host_forwarder.')
          else: raise
        if exit_code != 0:
          Forwarder._KillDeviceLocked(device, tool)
          # Log alive forwarders
          ps_out = device.RunShellCommand(['ps'])
          logging.info('Currently running device_forwarders:')
          for line in ps_out:
            if 'device_forwarder' in line:
              logging.info('    %s', line)
          raise Exception('%s exited with %d:\n%s' % (
              instance._host_forwarder_path, exit_code, '\n'.join(output)))
        tokens = output.split(':')
        if len(tokens) != 2:
          raise Exception('Unexpected host forwarder output "%s", '
                          'expected "device_port:host_port"' % output)
        device_port = int(tokens[0])
        host_port = int(tokens[1])
        serial_with_port = (device_serial, device_port)
        instance._device_to_host_port_map[serial_with_port] = host_port
        instance._host_to_device_port_map[host_port] = serial_with_port
        logging.info('Forwarding device port: %d to host port: %d.',
                     device_port, host_port)
示例#6
0
 def __init__(self, config):
     self.adb_path = constants.GetAdbPath()
     self.paths = Paths(config)
     self.device = None
     self.shell_args = []
     self.target_package = apk_helper.GetPackageName(self.paths.apk_path)
     self.temp_gdb_dir = None
     # This is used by decive_utils.Install to check if the apk needs updating.
     constants.SetOutputDirectory(self.paths.build_dir)
示例#7
0
 def _BuildAdbCmd(cls, args, device_serial, cpu_affinity=None):
   if cpu_affinity is not None:
     cmd = ['taskset', '-c', str(cpu_affinity)]
   else:
     cmd = []
   cmd.append(constants.GetAdbPath())
   if device_serial is not None:
     cmd.extend(['-s', device_serial])
   cmd.extend(args)
   return cmd
示例#8
0
def ShowLogs():
    """
  Displays the log for the mojo shell.

  Returns the process responsible for reading the logs.
  """
    logcat = subprocess.Popen(
        [constants.GetAdbPath(), 'logcat', '-s', ' '.join(LOGCAT_TAGS)],
        stdout=sys.stdout)
    atexit.register(_ExitIfNeeded, logcat)
    return logcat
示例#9
0
def ProcessCommonOptions(args):
    """Processes and handles all common options."""
    run_tests_helper.SetLogLevel(args.verbose_count)
    constants.SetBuildType(args.build_type)
    if args.build_directory:
        constants.SetBuildDirectory(args.build_directory)
    if args.output_directory:
        constants.SetOutputDirectory(args.output_directory)
    if args.adb_path:
        constants.SetAdbPath(args.adb_path)
    # Some things such as Forwarder require ADB to be in the environment path.
    adb_dir = os.path.dirname(constants.GetAdbPath())
    if adb_dir and adb_dir not in os.environ['PATH'].split(os.pathsep):
        os.environ['PATH'] = adb_dir + os.pathsep + os.environ['PATH']
示例#10
0
def ProcessCommonOptions(options, error_func):
    """Processes and handles all common options."""
    run_tests_helper.SetLogLevel(options.verbose_count)
    constants.SetBuildType(options.build_type)
    if options.build_directory:
        constants.SetBuildDirectory(options.build_directory)
    if options.output_directory:
        constants.SetOutputDirectort(options.output_directory)
    if options.adb_path:
        constants.SetAdbPath(options.adb_path)
    # Some things such as Forwarder require ADB to be in the environment path.
    adb_dir = os.path.dirname(constants.GetAdbPath())
    if adb_dir and adb_dir not in os.environ['PATH'].split(os.pathsep):
        os.environ['PATH'] = adb_dir + os.pathsep + os.environ['PATH']
    if options.environment not in constants.VALID_ENVIRONMENTS:
        error_func('--environment must be one of: %s' %
                   ', '.join(constants.VALID_ENVIRONMENTS))
示例#11
0
    def Run():
        def _WaitForFifo():
            for _ in xrange(max_attempts):
                if context.device.FileExistsOnDevice(fifo_path):
                    return
                time.sleep(1)
            if on_fifo_closed:
                on_fifo_closed()
            raise Exception("Unable to find fifo.")

        _WaitForFifo()
        stdout_cat = subprocess.Popen(
            [constants.GetAdbPath(), 'shell', 'cat', fifo_path], stdout=pipe)
        atexit.register(_ExitIfNeeded, stdout_cat)
        stdout_cat.wait()
        if on_fifo_closed:
            on_fifo_closed()
示例#12
0
 def _RunAdbCmd(cls,
                arg_list,
                timeout=None,
                retries=None,
                check_error=True):
     cmd = [constants.GetAdbPath()] + arg_list
     exit_code, output = cmd_helper.GetCmdStatusAndOutputWithTimeout(
         cmd,
         timeout_retry.CurrentTimeoutThread().GetRemainingTime())
     if exit_code != 0:
         raise device_errors.AdbCommandFailedError(
             cmd, 'returned non-zero exit code %d and output %r' %
             (exit_code, output))
     # This catches some errors, including when the device drops offline;
     # unfortunately adb is very inconsistent with error reporting so many
     # command failures present differently.
     if check_error and output[:len('error:')] == 'error:':
         raise device_errors.AdbCommandFailedError(arg_list, output)
     return output
示例#13
0
 def _RunAdbCmd(cls,
                args,
                timeout=None,
                retries=None,
                device_serial=None,
                check_error=True):
     cmd = [constants.GetAdbPath()]
     if device_serial is not None:
         cmd.extend(['-s', device_serial])
     cmd.extend(args)
     status, output = cmd_helper.GetCmdStatusAndOutputWithTimeout(
         cmd,
         timeout_retry.CurrentTimeoutThread().GetRemainingTime())
     if status != 0:
         raise device_errors.AdbCommandFailedError(args, output, status,
                                                   device_serial)
     # This catches some errors, including when the device drops offline;
     # unfortunately adb is very inconsistent with error reporting so many
     # command failures present differently.
     if check_error and output.startswith('error:'):
         raise device_errors.AdbCommandFailedError(args, output)
     return output
示例#14
0
 def _BuildAdbCmd(cls, args, device_serial):
     cmd = [constants.GetAdbPath()]
     if device_serial is not None:
         cmd.extend(['-s', device_serial])
     cmd.extend(args)
     return cmd
示例#15
0
def main():
    logging.basicConfig()

    parser = argparse.ArgumentParser(usage=USAGE)

    debug_group = parser.add_mutually_exclusive_group()
    debug_group.add_argument('--debug',
                             help='Debug build (default)',
                             default=True,
                             action='store_true')
    debug_group.add_argument('--release',
                             help='Release build',
                             default=False,
                             dest='debug',
                             action='store_false')
    parser.add_argument('--no-url',
                        help='Allows not to provide a application URL',
                        action='store_true')
    launcher_args, args = parser.parse_known_args()

    paths = Paths(
        Config(target_os=Config.OS_ANDROID, is_debug=launcher_args.debug))
    constants.SetOutputDirectort(paths.build_dir)

    httpd = SocketServer.TCPServer(('127.0.0.1', 0),
                                   GetHandlerForPath(paths.build_dir))
    atexit.register(httpd.shutdown)
    port = httpd.server_address[1]

    http_thread = threading.Thread(target=httpd.serve_forever)
    http_thread.daemon = True
    http_thread.start()

    device = android_commands.AndroidCommands(
        android_commands.GetAttachedDevices()[0])
    device.EnableAdbRoot()

    atexit.register(forwarder.Forwarder.UnmapAllDevicePorts, device)
    forwarder.Forwarder.Map([(0, port)], device)
    device_port = forwarder.Forwarder.DevicePortForHostPort(port)

    cmd = ('am start'
           ' -W'
           ' -S'
           ' -a android.intent.action.VIEW'
           ' -n org.chromium.mojo_shell_apk/.MojoShellActivity')

    parameters = ['--origin=http://127.0.0.1:%d/' % device_port]

    url = None
    if launcher_args.no_url:
        parameters += args
    else:
        url = args[-1]
        parameters += args[:-1]

    cmd += ' --esa parameters \"%s\"' % ','.join(parameters)

    if url:
        cmd += ' -d %s' % url

    device.RunShellCommand('logcat -c')
    device.RunShellCommand(cmd)
    os.system("%s logcat -s %s" % (constants.GetAdbPath(), ' '.join(TAGS)))
    device.RunShellCommand("am force-stop org.chromium.mojo_shell_apk")
    return 0