File: path_util.py

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (207 lines) | stat: -rw-r--r-- 5,976 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# Copyright 2017 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Functions for getting paths to things."""

import abc
import logging
import os

_STATUS_DETECTED = 1
_STATUS_VERIFIED = 2

# Src root of SuperSize being run. Not to be confused with src root of the input
# binary being archived.
_TOOLS_SRC_ROOT = os.environ.get(
    'CHECKOUT_SOURCE_ROOT',
    os.path.abspath(
        os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
                     os.pardir)))


class _PathFinder:
  def __init__(self, name, value):
    self._status = _STATUS_DETECTED if value is not None else 0
    self._name = name
    self._value = value

  @abc.abstractmethod
  def Detect(self):
    pass

  @abc.abstractmethod
  def Verify(self):
    pass

  def Tentative(self):
    if self._status < _STATUS_DETECTED:
      self._value = self.Detect()
      logging.debug('Detected --%s=%s', self._name, self._value)
      self._status = _STATUS_DETECTED
    return self._value

  def Finalized(self):
    if self._status < _STATUS_VERIFIED:
      self.Tentative()
      self.Verify()
      logging.info('Using --%s=%s', self._name, self._value)
      self._status = _STATUS_VERIFIED
    return self._value


class OutputDirectoryFinder(_PathFinder):
  def __init__(self, value=None, any_path_within_output_directory=None):
    super().__init__(name='output-directory', value=value)
    self._any_path_within_output_directory = any_path_within_output_directory

  def Detect(self):
    # Try and find build.ninja.
    abs_path = os.path.abspath(self._any_path_within_output_directory)
    while True:
      if os.path.exists(os.path.join(abs_path, 'build.ninja')):
        return os.path.relpath(abs_path)
      parent_dir = os.path.dirname(abs_path)
      if parent_dir == abs_path:
        break
      abs_path = parent_dir

    # See if CWD=output directory.
    if os.path.exists('build.ninja'):
      return '.'
    return None

  def Verify(self):
    if not self._value or not os.path.isdir(self._value):
      raise Exception(
          'Invalid --output-directory. Path not found: {}\n'
          'Use --no-output-directory to disable features that rely on it.'.
          format(self._value))

def GetSrcRootFromOutputDirectory(output_directory):
  """Returns the source root directory from output directory.

  Typical case: '/.../chromium/src/out/Release' -> '/.../chromium/src/'.
  Heuristic: Look for .gn in the current and successive parent directories.

  Args:
    output_directory: Starting point of search. This may be relative to CWD.

  Returns:
    Source root directory.
  """
  if output_directory:
    cur_dir = os.path.abspath(output_directory)
    while True:
      gn_path = os.path.join(cur_dir, '.gn')
      if os.path.isfile(gn_path):
        return cur_dir
      cur_dir, prev_dir = os.path.dirname(cur_dir), cur_dir
      if cur_dir == prev_dir:  # Reached root.
        break
  logging.warning('Cannot deduce src root from output directory. Falling back '
                  'to tools src root.')
  return _TOOLS_SRC_ROOT


def FromToolsSrcRoot(*args):
  ret = os.path.relpath(os.path.join(_TOOLS_SRC_ROOT, *args))
  # Need to maintain a trailing /.
  if args[-1].endswith(os.path.sep):
    ret += os.path.sep
  return ret


def _LlvmTool(name):
  default = FromToolsSrcRoot('third_party', 'llvm-build', 'Release+Asserts',
                             'bin', 'llvm-')
  actual = os.environ.get('SUPERSIZE_TOOL_PREFIX', default)
  # abspath since some executions use cwd= argument.
  return os.path.abspath(actual + name)


def CheckLlvmToolsAvailable():
  test_path = _LlvmTool('objdump')
  if not os.path.isfile(test_path):
    raise Exception(
        ('File not found: {}\nProbably need to run: '
         'tools/clang/scripts/update.py --package=objdump').format(test_path))


def GetCppFiltPath():
  return _LlvmTool('cxxfilt')


def GetDwarfdumpPath():
  return _LlvmTool('dwarfdump')


def GetNmPath():
  return _LlvmTool('nm')


def GetReadElfPath():
  return _LlvmTool('readelf')


def GetBcAnalyzerPath():
  return _LlvmTool('bcanalyzer')


def GetObjDumpPath():
  return _LlvmTool('objdump')


def GetDisassembleObjDumpPath(arch):
  path = None
  if arch == 'arm':
    path = FromToolsSrcRoot('third_party', 'android_toolchain', 'ndk',
                            'toolchains', 'arm-linux-androideabi-4.9',
                            'prebuilt', 'linux-x86_64', 'bin',
                            'arm-linux-androideabi-objdump')
  elif arch == 'arm64':
    path = FromToolsSrcRoot('third_party', 'android_toolchain', 'ndk',
                            'toolchains', 'aarch64-linux-android-4.9',
                            'prebuilt', 'linux-x86_64', 'bin',
                            'aarch64-linux-android-objdump')
  if path and os.path.exists(path):
    return path

  logging.warning('Falling back to llvm-objdump for arch %s', arch)
  return GetObjDumpPath()


def GetStripPath():
  # First look for the test-only "fakestrip" for the sake of tests.
  fake_strip = _LlvmTool('fakestrip')
  if os.path.exists(fake_strip):
    return fake_strip
  return _LlvmTool('strip')


def GetApkAnalyzerPath():
  default_path = FromToolsSrcRoot('third_party', 'android_build_tools',
                                  'apkanalyzer', 'apkanalyzer')
  return os.environ.get('SUPERSIZE_APK_ANALYZER', default_path)


def GetAapt2Path():
  default_path = FromToolsSrcRoot('third_party', 'android_build_tools', 'aapt2',
                                  'cipd', 'aapt2')
  return os.environ.get('SUPERSIZE_AAPT2', default_path)


def GetJavaHome():
  return FromToolsSrcRoot('third_party', 'jdk', 'current')


def GetJavaExec():
  return os.path.join(GetJavaHome(), 'bin', 'java')


def GetDefaultJsonConfigPath():
  return FromToolsSrcRoot('tools', 'binary_size', 'supersize.json')


def GetR8Path():
  return FromToolsSrcRoot('third_party', 'r8', 'lib', 'r8.jar')