示例#1
0
def CountStaticInitializers(so_path):
    def get_elf_section_size(readelf_stdout, section_name):
        # Matches: .ctors PROGBITS 000000000516add0 5169dd0 000010 00 WA 0 0 8
        match = re.search(r'\.%s.*$' % re.escape(section_name), readelf_stdout,
                          re.MULTILINE)
        if not match:
            return (False, -1)
        size_str = re.split(r'\W+', match.group(0))[5]
        return (True, int(size_str, 16))

    # Find the number of files with at least one static initializer.
    # First determine if we're 32 or 64 bit
    stdout = cmd_helper.GetCmdOutput(['readelf', '-h', so_path])
    elf_class_line = re.search('Class:.*$', stdout, re.MULTILINE).group(0)
    elf_class = re.split(r'\W+', elf_class_line)[1]
    if elf_class == 'ELF32':
        word_size = 4
    else:
        word_size = 8

    # Then find the number of files with global static initializers.
    # NOTE: this is very implementation-specific and makes assumptions
    # about how compiler and linker implement global static initializers.
    si_count = 0
    stdout = cmd_helper.GetCmdOutput(['readelf', '-SW', so_path])
    has_init_array, init_array_size = get_elf_section_size(
        stdout, 'init_array')
    if has_init_array:
        si_count = init_array_size / word_size
    si_count = max(si_count, 0)
    return si_count
def _GetReportMeta(utc_script_runtime_string, total_test_count):
    """Returns a dictionary of the report's metadata"""
    revision = cmd_helper.GetCmdOutput(['git', 'rev-parse', 'HEAD']).strip()
    raw_string = cmd_helper.GetCmdOutput(
        ['git', 'log', '--pretty=format:%at', '--max-count=1', 'HEAD'])
    time_string_search = re.search(_GIT_LOG_TIME_PATTERN, raw_string)
    if time_string_search is None:
        raise Exception(
            'Timestamp format incorrect, expected all digits, got %s' %
            raw_string)

    raw_string = cmd_helper.GetCmdOutput(
        ['git', 'log', '--pretty=format:%b', '--max-count=1', 'HEAD'])
    commit_pos_search = re.search(_GIT_LOG_MESSAGE_PATTERN, raw_string)
    if commit_pos_search is None:
        raise Exception(
            'Cr-Commit-Position is not found, potentially running with '
            'uncommited HEAD')
    commit_pos = int(commit_pos_search.group(1))

    utc_revision_time = datetime.datetime.utcfromtimestamp(
        int(time_string_search.group(0)))
    utc_revision_time = utc_revision_time.strftime(_EXPORT_TIME_FORMAT)
    logging.info('revision is %s, revision time is %s', revision,
                 utc_revision_time)

    return {
        'revision': revision,
        'commit_pos': commit_pos,
        'script_runtime': utc_script_runtime_string,
        'revision_time': utc_revision_time,
        'platform': 'android',
        'total_test_count': total_test_count
    }
def _ParseManifestAttributes(apk_path):
    # Check if the manifest specifies whether or not to extract native libs.
    skip_extract_lib = False
    output = cmd_helper.GetCmdOutput(
        [_AAPT_PATH.read(), 'd', 'xmltree', apk_path, 'AndroidManifest.xml'])
    m = re.search(r'extractNativeLibs\(.*\)=\(.*\)(\w)', output)
    if m:
        skip_extract_lib = not bool(int(m.group(1)))

    # Dex decompression overhead varies by Android version.
    m = re.search(r'android:minSdkVersion\(\w+\)=\(type \w+\)(\w+)\n', output)
    sdk_version = int(m.group(1), 16)
    # Pre-L: Dalvik - .odex file is simply decompressed/optimized dex file (~1x).
    # L, M: ART - .odex file is compiled version of the dex file (~4x).
    # N: ART - Uses Dalvik-like JIT for normal apps (~1x), full compilation for
    #    shared apps (~4x).
    # Actual multipliers calculated using "apk_operations.py disk-usage".
    # Will need to update multipliers once apk obfuscation is enabled.
    # E.g. with obfuscation, the 4.04 changes to 4.46.
    if sdk_version < 21:
        dex_multiplier = 1.16
    elif sdk_version < 24:
        dex_multiplier = 4.04
    elif 'Monochrome' in apk_path or 'WebView' in apk_path:
        dex_multiplier = 4.04  # compilation_filter=speed
    else:
        dex_multiplier = 1.17  # compilation_filter=speed-profile

    return dex_multiplier, skip_extract_lib
示例#4
0
def _ParseManifestAttributes(apk_path):
  # Check if the manifest specifies whether or not to extract native libs.
  skip_extract_lib = False
  output = cmd_helper.GetCmdOutput([
      _AAPT_PATH.read(), 'd', 'xmltree', apk_path, 'AndroidManifest.xml'])
  m = re.search(r'extractNativeLibs\(.*\)=\(.*\)(\w)', output)
  if m:
    skip_extract_lib = not bool(int(m.group(1)))

  # Dex decompression overhead varies by Android version.
  m = re.search(r'android:minSdkVersion\(\w+\)=\(type \w+\)(\w+)\n', output)
  sdk_version = int(m.group(1), 16)
  # Pre-L: Dalvik - .odex file is simply decompressed/optimized dex file (~1x).
  # L, M: ART - .odex file is compiled version of the dex file (~3x).
  # N: ART - Uses Dalvik-like JIT for normal apps (~1x), full compilation for
  #    shared apps (~3x).
  if sdk_version < 21:
    dex_multiplier = 1
  elif sdk_version < 24:
    dex_multiplier = 3
  elif 'Monochrome' in apk_path or 'WebView' in apk_path:
    dex_multiplier = 3
  else:
    dex_multiplier = 1

  return dex_multiplier, skip_extract_lib
示例#5
0
def Dump(apk_path):
  """Dumps class and method information from a APK into a dict via dexdump.

  Args:
    apk_path: An absolute path to an APK file to dump.
  Returns:
    A dict in the following format:
      {
        <package_name>: {
          'classes': {
            <class_name>: {
              'methods': [<method_1>, <method_2>]
            }
          }
        }
      }
  """
  # TODO(mikecase): Support multi-dex
  try:
    dexfile_dir = tempfile.mkdtemp()
    # Python zipfile module is unable to unzip APKs.
    cmd_helper.RunCmd(['unzip', apk_path, 'classes.dex'], cwd=dexfile_dir)
    dexfile = os.path.join(dexfile_dir, 'classes.dex')
    output_xml = cmd_helper.GetCmdOutput([DEXDUMP_PATH, '-l', 'xml', dexfile])
    return _ParseRootNode(ElementTree.fromstring(output_xml))
  finally:
    shutil.rmtree(dexfile_dir)
示例#6
0
    def _GetSVNRevision(self, in_directory):
        """Returns the git/svn revision for the given directory.

    Args:
      in_directory: The directory relative to src.
    """
        def _is_git_directory(in_directory):
            """Returns true if the given directory is in a git repository.

      Args:
        in_directory: The directory path to be tested.
      """
            if os.path.exists(os.path.join(in_directory, '.git')):
                return True
            parent = os.path.dirname(in_directory)
            if parent in (host_paths.DIR_SOURCE_ROOT, in_directory):
                return False
            return _is_git_directory(parent)

        in_directory = os.path.join(host_paths.DIR_SOURCE_ROOT, in_directory)

        if not os.path.exists(os.path.join(in_directory, '.svn')):
            if _is_git_directory(in_directory):
                return repo_utils.GetGitHeadSHA1(in_directory)
            return ''

        output = cmd_helper.GetCmdOutput(['svn', 'info', '--xml'],
                                         cwd=in_directory)
        try:
            dom = xml.dom.minidom.parseString(output)
            return dom.getElementsByTagName('entry')[0].getAttribute(
                'revision')
        except xml.parsers.expat.ExpatError:
            return ''
        return ''
示例#7
0
def CalculateHostMd5Sums(paths):
    """Calculates the MD5 sum value for all items in |paths|.

  Directories are traversed recursively and the MD5 sum of each file found is
  reported in the result.

  Args:
    paths: A list of host paths to md5sum.
  Returns:
    A dict mapping file paths to their respective md5sum checksums.
  """
    if isinstance(paths, basestring):
        paths = [paths]
    paths = list(paths)

    md5sum_bin_host_path = devil_env.config.FetchPath('md5sum_host')
    if not os.path.exists(md5sum_bin_host_path):
        raise IOError('File not built: %s' % md5sum_bin_host_path)
    out = ""
    for i in range(0, len(paths), _MAX_PATHS_PER_INVOCATION):
        mem_file = io.BytesIO()
        compressed = gzip.GzipFile(fileobj=mem_file, mode="wb")
        compressed.write(";".join([
            os.path.realpath(p) for p in paths[i:i + _MAX_PATHS_PER_INVOCATION]
        ]))
        compressed.close()
        compressed_paths = base64.b64encode(mem_file.getvalue())
        out += cmd_helper.GetCmdOutput(
            [md5sum_bin_host_path, "-gz", compressed_paths])

    return dict(zip(paths, out.splitlines()))
示例#8
0
 def _RunAdbShellCommand(self, command):
     # We use a separate interface to adb because the one from AndroidCommands
     # isn't re-entrant.
     # TODO(jbudorick) Look at providing a way to unhandroll this once the
     #                 adb rewrite has fully landed.
     device_param = (['-s', str(self._device)] if str(self._device) else [])
     cmd = ['adb'] + device_param + ['shell'] + command
     return cmd_helper.GetCmdOutput(cmd)
示例#9
0
def lsusb():
    """Call lsusb and return the parsed output."""
    lsusb_raw_output = cmd_helper.GetCmdOutput(['lsusb', '-v'])
    device = None
    devices = []
    depth_stack = []
    for line in lsusb_raw_output.splitlines():
        if not line:
            if device:
                devices.append(device)
            device = None
            continue

        if not device:
            m = _LSUSB_BUS_DEVICE_RE.match(line)
            if m:
                device = {'bus': m.group(1), 'device': m.group(2)}
                depth_stack = [device]
            continue

        indent_match = _INDENTATION_RE.match(line)
        if not indent_match:
            continue

        depth = 1 + len(indent_match.group(1)) / 2
        if depth > len(depth_stack):
            logging.error('lsusb parsing error: unexpected indentation: "%s"',
                          line)
            continue

        while depth < len(depth_stack):
            depth_stack.pop()

        cur = depth_stack[-1]

        m = _LSUSB_GROUP_RE.match(line)
        if m:
            new_group = {}
            cur[m.group(1)] = new_group
            depth_stack.append(new_group)
            continue

        m = _LSUSB_ENTRY_RE.match(line)
        if m:
            new_entry = {
                '_value': m.group(2),
                '_desc': m.group(3),
            }
            cur[m.group(1)] = new_entry
            depth_stack.append(new_entry)
            continue

        logging.error('lsusb parsing error: unrecognized line: "%s"', line)

    if device:
        devices.append(device)

    return devices
示例#10
0
def _CreateSectionNameSizeMap(so_path):
    stdout = cmd_helper.GetCmdOutput(['readelf', '-S', '--wide', so_path])
    section_sizes = {}
    # Matches  [ 2] .hash HASH 00000000006681f0 0001f0 003154 04   A  3   0  8
    for match in re.finditer(r'\[[\s\d]+\] (\..*)$', stdout, re.MULTILINE):
        items = match.group(1).split()
        section_sizes[items[0]] = int(items[4], 16)

    return section_sizes
示例#11
0
def GetGitHeadSHA1(in_directory):
    """Returns the git hash tag for the given directory.

  Args:
    in_directory: The directory where git is to be run.
  """
    command_line = ['git', 'log', '-1', '--pretty=format:%H']
    output = cmd_helper.GetCmdOutput(command_line, cwd=in_directory)
    return output[0:40]
示例#12
0
 def _read_trace_data(self):
     result = cmd_helper.GetCmdOutput(['cat', self._filename])
     mo = re.search(TRACE_START_REGEXP, result)
     if mo != None:
         data_start = mo.end(0)
     else:
         data_start = 0
     data = re.sub(ADB_IGNORE_REGEXP, '', result[data_start:])
     return self._preprocess_data(data)
示例#13
0
def get_device_serials():
    """Get the serial numbers of devices connected via adb.

  Only gets serial numbers of "active" devices (e.g. does not get serial
  numbers of devices which have not been authorized.)
  """
    cmdout = cmd_helper.GetCmdOutput(['adb', 'devices'])
    lines = [x.split() for x in cmdout.splitlines()[1:-1]]
    return [x[0] for x in lines if x[1] == 'device']
示例#14
0
  def git_status(self, path):
    """Returns canonical git status of file.

    Args:
      path: Path to file.
    Returns:
      Output of git status --porcelain.
    """
    with chdir(self._root_dir):
      output = cmd_helper.GetCmdOutput(['git', 'status', '--porcelain', path])
      return output
示例#15
0
def GetStaticInitializers(so_path):
    """Returns a list of static initializers found in the non-stripped library
     located at the provided path. Note that this function assumes that the
     library was compiled with GCC.
  """
    output = cmd_helper.GetCmdOutput(['nm', so_path])
    static_initializers = []
    for line in output:
        symbol_name = line.split(' ').pop().rstrip()
        if STATIC_INITIALIZER_SYMBOL_PREFIX in symbol_name:
            static_initializers.append(
                symbol_name.replace(STATIC_INITIALIZER_SYMBOL_PREFIX, ''))
    return static_initializers
示例#16
0
def _ParseManifestAttributes(apk_path):
    # Check if the manifest specifies whether or not to extract native libs.
    skip_extract_lib = False
    output = cmd_helper.GetCmdOutput(
        [_AAPT_PATH.read(), 'd', 'xmltree', apk_path, 'AndroidManifest.xml'])
    m = re.search(r'extractNativeLibs\(.*\)=\(.*\)(\w)', output)
    if m:
        skip_extract_lib = not bool(int(m.group(1)))

    # Dex decompression overhead varies by Android version.
    m = re.search(r'android:minSdkVersion\(\w+\)=\(type \w+\)(\w+)', output)
    sdk_version = int(m.group(1), 16)

    return sdk_version, skip_extract_lib
示例#17
0
def Dump(apk_path):
    """Dumps class and method information from a APK into a dict via dexdump.

  Args:
    apk_path: An absolute path to an APK file to dump.
  Returns:
    A dict in the following format:
      {
        <package_name>: {
          'classes': {
            <class_name>: {
              'methods': [<method_1>, <method_2>]
            }
          }
        }
      }
  """
    try:
        dexfile_dir = tempfile.mkdtemp()
        parsed_dex_files = []
        for dex_file in build_utils.ExtractAll(apk_path,
                                               dexfile_dir,
                                               pattern='*classes*.dex'):
            output_xml = cmd_helper.GetCmdOutput(
                [DEXDUMP_PATH, '-j', '-l', 'xml', dex_file])
            # Dexdump doesn't escape its XML output very well; decode it as utf-8 with
            # invalid sequences replaced, then remove forbidden characters and
            # re-encode it (as etree expects a byte string as input so it can figure
            # out the encoding itself from the XML declaration)
            BAD_XML_CHARS = re.compile(
                u'[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x84\x86-\x9f' +
                u'\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]')
            if sys.version_info[0] < 3:
                decoded_xml = output_xml.decode('utf-8', 'replace')
                clean_xml = BAD_XML_CHARS.sub(u'\ufffd', decoded_xml)
            else:
                # Line duplicated to avoid pylint redefined-variable-type error.
                clean_xml = BAD_XML_CHARS.sub(u'\ufffd', output_xml)
            parsed_dex_files.append(
                _ParseRootNode(
                    ElementTree.fromstring(clean_xml.encode('utf-8'))))
        return parsed_dex_files
    finally:
        shutil.rmtree(dexfile_dir)
示例#18
0
def SymbolizeMicroDump(stackwalker_binary_path, dump, symbols_path):
    """Runs stackwalker on microdump.

  Runs the stackwalker binary at stackwalker_binary_path on a given microdump
  using the symbols at symbols_path.

  Args:
    stackwalker_binary_path: Path to the stackwalker binary.
    dump: The microdump to run the stackwalker on.
    symbols_path: Path the the symbols file to use.

  Returns:
    Output from stackwalker tool.
  """
    with tempfile.NamedTemporaryFile() as tf:
        for l in dump:
            tf.write('%s\n' % l)
        cmd = [stackwalker_binary_path, tf.name, symbols_path]
        return cmd_helper.GetCmdOutput(cmd)
示例#19
0
def _ParseManifestAttributes(apk_path):
    # Check if the manifest specifies whether or not to extract native libs.
    output = cmd_helper.GetCmdOutput(
        [_AAPT_PATH.read(), 'd', 'xmltree', apk_path, 'AndroidManifest.xml'])

    def parse_attr(name):
        # android:extractNativeLibs(0x010104ea)=(type 0x12)0x0
        # android:extractNativeLibs(0x010104ea)=(type 0x12)0xffffffff
        # dist:onDemand=(type 0x12)0xffffffff
        m = re.search(name + r'(?:\(.*?\))?=\(type .*?\)(\w+)', output)
        return m and int(m.group(1), 16)

    skip_extract_lib = bool(parse_attr('android:extractNativeLibs'))
    sdk_version = parse_attr('android:minSdkVersion')
    is_feature_split = parse_attr('android:isFeatureSplit')
    # Can use <dist:on-demand>, or <module dist:onDemand="true">.
    on_demand = parse_attr('dist:onDemand') or 'dist:on-demand' in output
    on_demand = bool(on_demand and is_feature_split)

    return sdk_version, skip_extract_lib, on_demand
示例#20
0
def CalculateHostMd5Sums(paths):
    """Calculates the MD5 sum value for all items in |paths|.

  Directories are traversed recursively and the MD5 sum of each file found is
  reported in the result.

  Args:
    paths: A list of host paths to md5sum.
  Returns:
    A dict mapping file paths to their respective md5sum checksums.
  """
    if isinstance(paths, basestring):
        paths = [paths]

    md5sum_bin_host_path = devil_env.config.FetchPath('md5sum_host')
    if not os.path.exists(md5sum_bin_host_path):
        raise IOError('File not built: %s' % md5sum_bin_host_path)
    out = cmd_helper.GetCmdOutput([md5sum_bin_host_path] + [p for p in paths])

    return _ParseMd5SumOutput(out.splitlines())
示例#21
0
def Dump(apk_path):
    """Dumps class and method information from a APK into a dict via dexdump.

  Args:
    apk_path: An absolute path to an APK file to dump.
  Returns:
    A dict in the following format:
      {
        <package_name>: {
          'classes': {
            <class_name>: {
              'methods': [<method_1>, <method_2>]
            }
          }
        }
      }
  """
    # TODO(mikecase): Support multi-dex
    try:
        dexfile_dir = tempfile.mkdtemp()
        # Python zipfile module is unable to unzip APKs.
        cmd_helper.RunCmd(['unzip', apk_path, 'classes.dex'], cwd=dexfile_dir)
        dexfile = os.path.join(dexfile_dir, 'classes.dex')
        output_xml = cmd_helper.GetCmdOutput(
            [DEXDUMP_PATH, '-l', 'xml', dexfile])
        # Dexdump doesn't escape its XML output very well; decode it as utf-8 with
        # invalid sequences replaced, then remove forbidden characters and
        # re-encode it (as etree expects a byte string as input so it can figure
        # out the encoding itself from the XML declaration)
        BAD_XML_CHARS = re.compile(
            u'[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x84\x86-\x9f' +
            u'\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]')
        decoded_xml = output_xml.decode('utf-8', 'replace')
        clean_xml = BAD_XML_CHARS.sub(u'\ufffd', decoded_xml)
        return _ParseRootNode(ElementTree.fromstring(
            clean_xml.encode('utf-8')))
    finally:
        shutil.rmtree(dexfile_dir)
示例#22
0
def _GetCommList():
  return cmd_helper.GetCmdOutput('ls /dev', shell=True)
示例#23
0
 def testSingleQuote_doExpand(self):
     test_string = 'hello $TEST_VAR'
     cmd = 'TEST_VAR=world; echo %s' % cmd_helper.DoubleQuote(test_string)
     self.assertEquals('hello world',
                       cmd_helper.GetCmdOutput(cmd, shell=True).rstrip())
示例#24
0
def main(argv):
  # ANDROID_SDK_ROOT needs to be set to the location of the SDK used to launch
  # the emulator to find the system images upon launch.
  emulator_sdk = constants.ANDROID_SDK_ROOT
  os.environ['ANDROID_SDK_ROOT'] = emulator_sdk

  arg_parser = argparse.ArgumentParser(description='AVD script.')
  sub_parsers = arg_parser.add_subparsers(title='subparser', dest='command')
  sub_parsers.add_parser(
      'kill', help='Shutdown all existing emulators')
  sub_parsers.add_parser(
      'delete', help='Deleting all the avd files')
  run_parser = sub_parsers.add_parser('run', help='Run emulators')
  run_parser.add_argument('--name', help='Optinaly, name of existing AVD to '
                          'launch. If not specified, AVD\'s will be created')
  run_parser.add_argument('-n', '--num', dest='emulator_count',
                          help='Number of emulators to launch (default is 1).',
                          type=int, default='1')
  run_parser.add_argument('--abi', default='x86',
                          help='Platform of emulators to launch (x86 default)')
  run_parser.add_argument('--api-level', dest='api_level',
                          help='API level for the image',
                          type=int, default=constants.ANDROID_SDK_VERSION)
  run_parser.add_argument('--sdcard-size', dest='sdcard_size',
                          default=emulator.DEFAULT_SDCARD_SIZE,
                          help='Set sdcard size of the emulators'
                          ' e.g. --sdcard-size=512M')
  run_parser.add_argument('--partition-size', dest='partition_size',
                          default=emulator.DEFAULT_STORAGE_SIZE,
                          help='Default internal storage size'
                          ' e.g. --partition-size=1024M')
  run_parser.add_argument('--launch-without-kill', action='store_false',
                          dest='kill_and_launch', default=True,
                          help='Kill all emulators at launch')

  arguments = arg_parser.parse_args(argv[1:])

  logging.root.setLevel(logging.INFO)

  if arguments.command == 'kill':
    logging.info('Killing all existing emulator and existing the program')
    emulator.KillAllEmulators()
    return
  if arguments.command == 'delete':
    emulator.DeleteAllTempAVDs()
    return

  # Check if SDK exist in ANDROID_SDK_ROOT
  if not install_emulator_deps.CheckSDK():
    raise Exception('Emulator SDK not installed in %s'
                     % constants.ANDROID_SDK_ROOT)

  # Check if KVM is enabled for x86 AVD's and check for x86 system images.
  # TODO(andrewhayden) Since we can fix all of these with install_emulator_deps
  # why don't we just run it?
  if arguments.abi == 'x86':
    if not install_emulator_deps.CheckKVM():
      logging.critical('ERROR: KVM must be enabled in BIOS, and installed. '
                       'Enable KVM in BIOS and run install_emulator_deps.py')
      return 1
    elif not install_emulator_deps.CheckX86Image(arguments.api_level):
      logging.critical('ERROR: System image for x86 AVD not installed. Run '
                       'install_emulator_deps.py')
      return 1

  # If AVD is specified, check that the SDK has the required target. If not,
  # check that the SDK has the desired target for the temporary AVD's.
  api_level = arguments.api_level
  if arguments.name:
    android = os.path.join(constants.ANDROID_SDK_ROOT, 'tools',
                           'android')
    avds_output = cmd_helper.GetCmdOutput([android, 'list', 'avd'])
    names = re.findall(r'Name: (\w+)', avds_output)
    api_levels = re.findall(r'API level (\d+)', avds_output)
    try:
      avd_index = names.index(arguments.name)
    except ValueError:
      logging.critical('ERROR: Specified AVD %s does not exist.',
                       arguments.name)
      return 1
    api_level = int(api_levels[avd_index])

  if not install_emulator_deps.CheckSDKPlatform(api_level):
    logging.critical('ERROR: Emulator SDK missing required target for API %d. '
                     'Run install_emulator_deps.py.')
    return 1

  if arguments.name:
    emulator.LaunchEmulator(
        arguments.name,
        arguments.abi,
        kill_and_launch=arguments.reset_and_launch,
        sdcard_size=arguments.sdcard_size,
        storage_size=arguments.partition_size
    )
  else:
    emulator.LaunchTempEmulators(
        arguments.emulator_count,
        arguments.abi,
        arguments.api_level,
        kill_and_launch=arguments.kill_and_launch,
        sdcard_size=arguments.sdcard_size,
        storage_size=arguments.partition_size,
        wait_for_boot=True
    )
示例#25
0
def GetStaticInitializers(so_path):
    output = cmd_helper.GetCmdOutput(
        [_DUMP_STATIC_INITIALIZERS_PATH, '-d', so_path])
    return output.splitlines()
def GetStaticInitializers(so_path, tool_prefix):
    output = cmd_helper.GetCmdOutput(
        [_DUMP_STATIC_INITIALIZERS_PATH, '-d', so_path, '-t', tool_prefix])
    summary = re.search(r'Found \d+ static initializers in (\d+) files.',
                        output)
    return output.splitlines()[:-1], int(summary.group(1))
示例#27
0
def _GetTtyUSBInfo(tty_string):
  cmd = ['udevadm', 'info', '--name=/dev/' + tty_string, '--attribute-walk']
  return cmd_helper.GetCmdOutput(cmd)
示例#28
0
def _RunReadelf(so_path, options, tool_prefix=''):
    return cmd_helper.GetCmdOutput([tool_prefix + 'readelf'] + options +
                                   [so_path])
示例#29
0
def raw_lsusb():
    return cmd_helper.GetCmdOutput(['lsusb'])
示例#30
0
def main(argv):
    # ANDROID_SDK_ROOT needs to be set to the location of the SDK used to launch
    # the emulator to find the system images upon launch.
    emulator_sdk = os.path.join(constants.EMULATOR_SDK_ROOT, 'sdk')
    os.environ['ANDROID_SDK_ROOT'] = emulator_sdk

    opt_parser = optparse.OptionParser(description='AVD script.')
    opt_parser.add_option(
        '--name',
        help='Optinaly, name of existing AVD to '
        'launch. If not specified, new AVD\'s will be created')
    opt_parser.add_option('-n',
                          '--num',
                          dest='emulator_count',
                          help='Number of emulators to launch (default is 1).',
                          type='int',
                          default='1')
    opt_parser.add_option(
        '--abi',
        default='x86',
        help='Platform of emulators to launch (x86 default).')
    opt_parser.add_option(
        '--api-level',
        dest='api_level',
        help='API level for the image, e.g. 19 for Android 4.4',
        type='int',
        default=constants.ANDROID_SDK_VERSION)

    options, _ = opt_parser.parse_args(argv[1:])

    logging.basicConfig(level=logging.INFO,
                        format='# %(asctime)-15s: %(message)s')
    logging.root.setLevel(logging.INFO)

    # Check if KVM is enabled for x86 AVD's and check for x86 system images.
    # TODO(andrewhayden) Since we can fix all of these with install_emulator_deps
    # why don't we just run it?
    if options.abi == 'x86':
        if not install_emulator_deps.CheckKVM():
            logging.critical(
                'ERROR: KVM must be enabled in BIOS, and installed. '
                'Enable KVM in BIOS and run install_emulator_deps.py')
            return 1
        elif not install_emulator_deps.CheckX86Image(options.api_level):
            logging.critical(
                'ERROR: System image for x86 AVD not installed. Run '
                'install_emulator_deps.py')
            return 1

    if not install_emulator_deps.CheckSDK():
        logging.critical('ERROR: Emulator SDK not installed. Run '
                         'install_emulator_deps.py.')
        return 1

    # If AVD is specified, check that the SDK has the required target. If not,
    # check that the SDK has the desired target for the temporary AVD's.
    api_level = options.api_level
    if options.name:
        android = os.path.join(constants.EMULATOR_SDK_ROOT, 'sdk', 'tools',
                               'android')
        avds_output = cmd_helper.GetCmdOutput([android, 'list', 'avd'])
        names = re.findall(r'Name: (\w+)', avds_output)
        api_levels = re.findall(r'API level (\d+)', avds_output)
        try:
            avd_index = names.index(options.name)
        except ValueError:
            logging.critical('ERROR: Specified AVD %s does not exist.',
                             options.name)
            return 1
        api_level = int(api_levels[avd_index])

    if not install_emulator_deps.CheckSDKPlatform(api_level):
        logging.critical(
            'ERROR: Emulator SDK missing required target for API %d. '
            'Run install_emulator_deps.py.')
        return 1

    if options.name:
        emulator.LaunchEmulator(options.name, options.abi)
    else:
        emulator.LaunchTempEmulators(options.emulator_count, options.abi,
                                     options.api_level, True)