• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2
3"""Script to generate Chromium's Abseil .def files at roll time.
4
5This script generates //third_party/abseil-app/absl/symbols_*.def at Abseil
6roll time.
7
8Since Abseil doesn't export symbols, Chromium is forced to consider all
9Abseil's symbols as publicly visible. On POSIX it is possible to use
10-fvisibility=default but on Windows a .def file with all the symbols
11is needed.
12
13Unless you are on a Windows machine, you need to set up your Chromium
14checkout for cross-compilation by following the instructions at
15https://chromium.googlesource.com/chromium/src.git/+/main/docs/win_cross.md.
16If you are on Windows, you may need to tweak this script to run, e.g. by
17changing "gn" to "gn.bat", changing "llvm-nm" to the name of your copy of
18llvm-nm, etc.
19"""
20
21import fnmatch
22import logging
23import os
24import re
25import subprocess
26import sys
27import tempfile
28import time
29
30# Matches a mangled symbol that has 'absl' in it, this should be a good
31# enough heuristic to select Abseil symbols to list in the .def file.
32ABSL_SYM_RE = re.compile(r'0* [BT] (?P<symbol>(\?+)[^\?].*absl.*)')
33if sys.platform == 'win32':
34  # Typical dumpbin /symbol lines look like this:
35  # 04B 0000000C SECT14 notype       Static       | ?$S1@?1??SetCurrent
36  # ThreadIdentity@base_internal@absl@@YAXPAUThreadIdentity@12@P6AXPAX@Z@Z@4IA
37  #  (unsigned int `void __cdecl absl::base_internal::SetCurrentThreadIdentity...
38  # We need to start on "| ?" and end on the first " (" (stopping on space would
39  # also work).
40  # This regex is identical inside the () characters except for the ? after .*,
41  # which is needed to prevent greedily grabbing the undecorated version of the
42  # symbols.
43  ABSL_SYM_RE = '.*External     \| (?P<symbol>(\?+)[^\?].*?absl.*?) \(.*'
44  # Typical exported symbols in dumpbin /directives look like:
45  #    /EXPORT:?kHexChar@numbers_internal@absl@@3QBDB,DATA
46  ABSL_EXPORTED_RE = '.*/EXPORT:(.*),.*'
47
48
49def _DebugOrRelease(is_debug):
50  return 'dbg' if is_debug else 'rel'
51
52
53def _GenerateDefFile(cpu, is_debug, extra_gn_args=[], suffix=None):
54  """Generates a .def file for the absl component build on the specified CPU."""
55  if extra_gn_args:
56    assert suffix != None, 'suffix is needed when extra_gn_args is used'
57
58  flavor = _DebugOrRelease(is_debug)
59  gn_args = [
60      'ffmpeg_branding = "Chrome"',
61      'is_component_build = true',
62      'is_debug = {}'.format(str(is_debug).lower()),
63      'proprietary_codecs = true',
64      'symbol_level = 0',
65      'target_cpu = "{}"'.format(cpu),
66      'target_os = "win"',
67  ]
68  gn_args.extend(extra_gn_args)
69
70  gn = 'gn'
71  autoninja = 'autoninja'
72  symbol_dumper = ['third_party/llvm-build/Release+Asserts/bin/llvm-nm']
73  if sys.platform == 'win32':
74    gn = 'gn.bat'
75    autoninja = 'autoninja.bat'
76    symbol_dumper = ['dumpbin', '/symbols']
77    import shutil
78    if not shutil.which('dumpbin'):
79      logging.error('dumpbin not found. Run tools\win\setenv.bat.')
80      exit(1)
81  with tempfile.TemporaryDirectory() as out_dir:
82    logging.info('[%s - %s] Creating tmp out dir in %s', cpu, flavor, out_dir)
83    subprocess.check_call([gn, 'gen', out_dir, '--args=' + ' '.join(gn_args)],
84                          cwd=os.getcwd())
85    logging.info('[%s - %s] gn gen completed', cpu, flavor)
86    subprocess.check_call(
87        [autoninja, '-C', out_dir, 'third_party/abseil-cpp:absl_component_deps'],
88        cwd=os.getcwd())
89    logging.info('[%s - %s] autoninja completed', cpu, flavor)
90
91    obj_files = []
92    for root, _dirnames, filenames in os.walk(
93        os.path.join(out_dir, 'obj', 'third_party', 'abseil-cpp')):
94      matched_files = fnmatch.filter(filenames, '*.obj')
95      obj_files.extend((os.path.join(root, f) for f in matched_files))
96
97    logging.info('[%s - %s] Found %d object files.', cpu, flavor, len(obj_files))
98
99    absl_symbols = set()
100    dll_exports = set()
101    if sys.platform == 'win32':
102      for f in obj_files:
103        # Track all of the functions exported with __declspec(dllexport) and
104        # don't list them in the .def file - double-exports are not allowed. The
105        # error is "lld-link: error: duplicate /export option".
106        exports_out = subprocess.check_output(['dumpbin', '/directives', f], cwd=os.getcwd())
107        for line in exports_out.splitlines():
108          line = line.decode('utf-8')
109          match = re.match(ABSL_EXPORTED_RE, line)
110          if match:
111            dll_exports.add(match.groups()[0])
112    for f in obj_files:
113      stdout = subprocess.check_output(symbol_dumper + [f], cwd=os.getcwd())
114      for line in stdout.splitlines():
115        try:
116          line = line.decode('utf-8')
117        except UnicodeDecodeError:
118          # Due to a dumpbin bug there are sometimes invalid utf-8 characters in
119          # the output. This only happens on an unimportant line so it can
120          # safely and silently be skipped.
121          # https://developercommunity.visualstudio.com/content/problem/1091330/dumpbin-symbols-produces-randomly-wrong-output-on.html
122          continue
123        match = re.match(ABSL_SYM_RE, line)
124        if match:
125          symbol = match.group('symbol')
126          assert symbol.count(' ') == 0, ('Regex matched too much, probably got '
127                                          'undecorated name as well')
128          # Avoid getting names exported with dllexport, to avoid
129          # "lld-link: error: duplicate /export option" on symbols such as:
130          # ?kHexChar@numbers_internal@absl@@3QBDB
131          if symbol in dll_exports:
132            continue
133          # Avoid to export deleting dtors since they trigger
134          # "lld-link: error: export of deleting dtor" linker errors, see
135          # crbug.com/1201277.
136          if symbol.startswith('??_G'):
137            continue
138          absl_symbols.add(symbol)
139
140    logging.info('[%s - %s] Found %d absl symbols.', cpu, flavor, len(absl_symbols))
141
142    if extra_gn_args:
143      def_file = os.path.join('third_party', 'abseil-cpp',
144                              'symbols_{}_{}_{}.def'.format(cpu, flavor, suffix))
145    else:
146      def_file = os.path.join('third_party', 'abseil-cpp',
147                             'symbols_{}_{}.def'.format(cpu, flavor))
148
149    with open(def_file, 'w', newline='') as f:
150      f.write('EXPORTS\n')
151      for s in sorted(absl_symbols):
152        f.write('    {}\n'.format(s))
153
154    # Hack, it looks like there is a race in the directory cleanup.
155    time.sleep(10)
156
157  logging.info('[%s - %s] .def file successfully generated.', cpu, flavor)
158
159
160if __name__ == '__main__':
161  logging.getLogger().setLevel(logging.INFO)
162
163  if sys.version_info.major == 2:
164    logging.error('This script requires Python 3.')
165    exit(1)
166
167  if not os.getcwd().endswith('src') or not os.path.exists('chrome/browser'):
168    logging.error('Run this script from a chromium/src/ directory.')
169    exit(1)
170
171  _GenerateDefFile('x86', True)
172  _GenerateDefFile('x86', False)
173  _GenerateDefFile('x64', True)
174  _GenerateDefFile('x64', False)
175  _GenerateDefFile('x64', False, ['is_asan = true'], 'asan')
176  _GenerateDefFile('arm64', True)
177  _GenerateDefFile('arm64', False)
178