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