Debian Codegraph @

mesonbuild/scripts/symbolextractor.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2016 The Meson development team
3
4 # This script extracts the symbols of a given shared library
5 # into a file. If the symbols have not changed, the file is not
6 # touched. This information is used to skip link steps if the
7 # ABI has not changed.
8
9 # This file is basically a reimplementation of
10 # http://cgit.freedesktop.org/libreoffice/core/commit/?id=3213cd54b76bc80a6f0516aac75a48ff3b2ad67c
11 from __future__ import annotations
12
13 import typing as T
14 import os, sys
15 from .. import mesonlib
16 from .. import mlog
17 from ..mesonlib import Popen_safe
18 import argparse
19
20 parser = argparse.ArgumentParser()
21
22 parser.add_argument('--cross-host', default=None, dest='cross_host',
23 help='cross compilation host platform')
24 parser.add_argument('args', nargs='+')
25
26 TOOL_WARNING_FILE: str
27 RELINKING_WARNING = 'Relinking will always happen on source changes.'
28
29 def dummy_syms(outfilename: str) -> None:
30 """Just touch it so relinking happens always."""
31 with open(outfilename, 'w', encoding='utf-8'):
32 pass
33
34 def write_if_changed(text: str, outfilename: str) -> None:
35 try:
36 with open(outfilename, encoding='utf-8') as f:
37 oldtext = f.read()
38 if text == oldtext:
39 return
40 except FileNotFoundError:
41 pass
42 with open(outfilename, 'w', encoding='utf-8') as f:
43 f.write(text)
44
45 def print_tool_warning(tools: T.List[str], msg: str, stderr: T.Optional[str] = None) -> None:
46 if os.path.exists(TOOL_WARNING_FILE):
47 return
48 m = f'{tools!r} {msg}. {RELINKING_WARNING}'
49 if stderr:
50 m += '\n' + stderr
51 mlog.warning(m)
52 # Write it out so we don't warn again
53 with open(TOOL_WARNING_FILE, 'w', encoding='utf-8'):
54 pass
55
56 def get_tool(name: str) -> T.List[str]:
57 evar = name.upper()
58 if evar in os.environ:
59 import shlex
60 return shlex.split(os.environ[evar])
61 return [name]
62
63 def call_tool(name: str, args: T.List[str], **kwargs: T.Any) -> str:
64 tool = get_tool(name)
65 try:
66 p, output, e = Popen_safe(tool + args, **kwargs)
67 except FileNotFoundError:
68 print_tool_warning(tool, 'not found')
69 return None
70 except PermissionError:
71 print_tool_warning(tool, 'not usable')
72 return None
73 if p.returncode != 0:
74 print_tool_warning(tool, 'does not work', e)
75 return None
76 return output
77
78 def call_tool_nowarn(tool: T.List[str], **kwargs: T.Any) -> T.Tuple[str, str]:
79 try:
80 p, output, e = Popen_safe(tool, **kwargs)
81 except FileNotFoundError:
82 return None, '{!r} not found\n'.format(tool[0])
83 except PermissionError:
84 return None, '{!r} not usable\n'.format(tool[0])
85 if p.returncode != 0:
86 return None, e
87 return output, None
88
89 def gnu_syms(libfilename: str, outfilename: str) -> None:
90 # Get the name of the library
91 output = call_tool('readelf', ['-d', libfilename])
92 if not output:
93 dummy_syms(outfilename)
94 return
95 result = [x for x in output.split('\n') if 'SONAME' in x]
96 assert len(result) <= 1
97 # Get a list of all symbols exported
98 output = call_tool('nm', ['--dynamic', '--extern-only', '--defined-only',
99 '--format=posix', libfilename])
100 if not output:
101 dummy_syms(outfilename)
102 return
103 for line in output.split('\n'):
104 if not line:
105 continue
106 line_split = line.split()
107 entry = line_split[0:2]
108 # Store the size of symbols pointing to data objects so we relink
109 # when those change, which is needed because of copy relocations
110 # https://github.com/mesonbuild/meson/pull/7132#issuecomment-628353702
111 if line_split[1].upper() in {'B', 'G', 'D'} and len(line_split) >= 4:
112 entry += [line_split[3]]
113 result += [' '.join(entry)]
114 write_if_changed('\n'.join(result) + '\n', outfilename)
115
116 def solaris_syms(libfilename: str, outfilename: str) -> None:
117 # gnu_syms() works with GNU nm & readelf, not Solaris nm & elfdump
118 origpath = os.environ['PATH']
119 try:
120 os.environ['PATH'] = '/usr/gnu/bin:' + origpath
121 gnu_syms(libfilename, outfilename)
122 finally:
123 os.environ['PATH'] = origpath
124
125 def osx_syms(libfilename: str, outfilename: str) -> None:
126 # Get the name of the library
127 output = call_tool('otool', ['-l', libfilename])
128 if not output:
129 dummy_syms(outfilename)
130 return
131 arr = output.split('\n')
132 for (i, val) in enumerate(arr):
133 if 'LC_ID_DYLIB' in val:
134 match = i
135 break
136 result = [arr[match + 2], arr[match + 5]] # Libreoffice stores all 5 lines but the others seem irrelevant.
137 # Get a list of all symbols exported. `nm -g -U -P` is equivalent to, and more portable than,
138 # `nm --extern-only --defined-only --format=posix`; cctools-port only understands the one-character form,
139 # as does `nm` on very old macOS versions, (see meson#11131). `llvm-nm` understands both forms.
140 output = call_tool('nm', ['-g', '-U', '-P', libfilename])
141 if not output:
142 dummy_syms(outfilename)
143 return
144 result += [' '.join(x.split()[0:2]) for x in output.split('\n')]
145 write_if_changed('\n'.join(result) + '\n', outfilename)
146
147 def openbsd_syms(libfilename: str, outfilename: str) -> None:
148 # Get the name of the library
149 output = call_tool('readelf', ['-d', libfilename])
150 if not output:
151 dummy_syms(outfilename)
152 return
153 result = [x for x in output.split('\n') if 'SONAME' in x]
154 assert len(result) <= 1
155 # Get a list of all symbols exported
156 output = call_tool('nm', ['-D', '-P', '-g', libfilename])
157 if not output:
158 dummy_syms(outfilename)
159 return
160 # U = undefined (cope with the lack of --defined-only option)
161 result += [' '.join(x.split()[0:2]) for x in output.split('\n') if x and not x.endswith('U ')]
162 write_if_changed('\n'.join(result) + '\n', outfilename)
163
164 def freebsd_syms(libfilename: str, outfilename: str) -> None:
165 # Get the name of the library
166 output = call_tool('readelf', ['-d', libfilename])
167 if not output:
168 dummy_syms(outfilename)
169 return
170 result = [x for x in output.split('\n') if 'SONAME' in x]
171 assert len(result) <= 1
172 # Get a list of all symbols exported
173 output = call_tool('nm', ['--dynamic', '--extern-only', '--defined-only',
174 '--format=posix', libfilename])
175 if not output:
176 dummy_syms(outfilename)
177 return
178
179 result += [' '.join(x.split()[0:2]) for x in output.split('\n')]
180 write_if_changed('\n'.join(result) + '\n', outfilename)
181
182 def cygwin_syms(impfilename: str, outfilename: str) -> None:
183 # Get the name of the library
184 output = call_tool('dlltool', ['-I', impfilename])
185 if not output:
186 dummy_syms(outfilename)
187 return
188 result = [output]
189 # Get the list of all symbols exported
190 output = call_tool('nm', ['--extern-only', '--defined-only',
191 '--format=posix', impfilename])
192 if not output:
193 dummy_syms(outfilename)
194 return
195 for line in output.split('\n'):
196 if ' T ' not in line:
197 continue
198 result.append(line.split(maxsplit=1)[0])
199 write_if_changed('\n'.join(result) + '\n', outfilename)
200
201 def _get_implib_dllname(impfilename: str) -> T.Tuple[T.List[str], str]:
202 all_stderr = ''
203 # First try lib.exe, which is provided by MSVC. Then llvm-lib.exe, by LLVM
204 # for clang-cl.
205 #
206 # We cannot call get_tool on `lib` because it will look at the `LIB` env
207 # var which is the list of library paths MSVC will search for import
208 # libraries while linking.
209 for lib in (['lib'], get_tool('llvm-lib')):
210 output, e = call_tool_nowarn(lib + ['-list', '-nologo', impfilename])
211 if output:
212 # The output is a list of DLLs that each symbol exported by the import
213 # library is available in. We only build import libraries that point to
214 # a single DLL, so we can pick any of these. Pick the last one for
215 # simplicity. Also skip the last line, which is empty.
216 return output.split('\n')[-2:-1], None
217 all_stderr += e
218 # Next, try dlltool.exe which is provided by MinGW
219 output, e = call_tool_nowarn(get_tool('dlltool') + ['-I', impfilename])
220 if output:
221 return [output], None
222 all_stderr += e
223 return ([], all_stderr)
224
225 def _get_implib_exports(impfilename: str) -> T.Tuple[T.List[str], str]:
226 all_stderr = ''
227 # Force dumpbin.exe to use en-US so we can parse its output
228 env = os.environ.copy()
229 env['VSLANG'] = '1033'
230 output, e = call_tool_nowarn(get_tool('dumpbin') + ['-exports', impfilename], env=env)
231 if output:
232 lines = output.split('\n')
233 start = lines.index('File Type: LIBRARY')
234 end = lines.index(' Summary')
235 return lines[start:end], None
236 all_stderr += e
237 # Next, try llvm-nm.exe provided by LLVM, then nm.exe provided by MinGW
238 for nm in ('llvm-nm', 'nm'):
239 output, e = call_tool_nowarn(get_tool(nm) + ['--extern-only', '--defined-only',
240 '--format=posix', impfilename])
241 if output:
242 result = []
243 for line in output.split('\n'):
244 if ' T ' not in line or line.startswith('.text'):
245 continue
246 result.append(line.split(maxsplit=1)[0])
247 return result, None
248 all_stderr += e
249 return ([], all_stderr)
250
251 def windows_syms(impfilename: str, outfilename: str) -> None:
252 # Get the name of the library
253 result, e = _get_implib_dllname(impfilename)
254 if not result:
255 print_tool_warning(['lib', 'llvm-lib', 'dlltool'], 'do not work or were not found', e)
256 dummy_syms(outfilename)
257 return
258 # Get a list of all symbols exported
259 symbols, e = _get_implib_exports(impfilename)
260 if not symbols:
261 print_tool_warning(['dumpbin', 'llvm-nm', 'nm'], 'do not work or were not found', e)
262 dummy_syms(outfilename)
263 return
264 result += symbols
265 write_if_changed('\n'.join(result) + '\n', outfilename)
266
267 def os2_syms(impfilename: str, outfilename: str) -> None:
268 # Get a list of all symbols exported with the name of the library
269 all_stderr = ''
270 # First try nm.exe for aout .a
271 output, e = call_tool_nowarn(get_tool('nm') + ['-P', impfilename])
272 if output:
273 result = [x for x in output.split('\n') if ' E ' in x]
274 write_if_changed('\n'.join(result) + '\n', outfilename)
275 return
276 if e:
277 all_stderr += e
278 # Next try listomf.exe for omf .lib
279 output, e = call_tool_nowarn(get_tool('listomf') + ['-d', impfilename])
280 if output:
281 result = [x for x in output.split('\n') if ' IMPDEF ' in x]
282 write_if_changed('\n'.join(result) + '\n', outfilename)
283 return
284 if e:
285 all_stderr += e
286 print_tool_warning(['nm', 'listomf'], 'do not work or were not found', all_stderr)
287
288 def gen_symbols(libfilename: str, impfilename: str, outfilename: str, cross_host: str) -> None:
289 if cross_host is not None:
290 # In case of cross builds just always relink. In theory we could
291 # determine the correct toolset, but we would need to use the correct
292 # `nm`, `readelf`, etc, from the cross info which requires refactoring.
293 if cross_host == 'windows' and os.path.isfile(impfilename):
294 windows_syms(impfilename, outfilename)
295 else:
296 dummy_syms(outfilename)
297 elif mesonlib.is_linux() or mesonlib.is_hurd() or mesonlib.is_haiku():
298 gnu_syms(libfilename, outfilename)
299 elif mesonlib.is_osx():
300 osx_syms(libfilename, outfilename)
301 elif mesonlib.is_openbsd():
302 openbsd_syms(libfilename, outfilename)
303 elif mesonlib.is_freebsd():
304 freebsd_syms(libfilename, outfilename)
305 elif mesonlib.is_netbsd():
306 freebsd_syms(libfilename, outfilename)
307 elif mesonlib.is_windows():
308 if os.path.isfile(impfilename):
309 windows_syms(impfilename, outfilename)
310 else:
311 # No import library. Not sure how the DLL is being used, so just
312 # rebuild everything that links to it every time.
313 dummy_syms(outfilename)
314 elif mesonlib.is_cygwin():
315 if os.path.isfile(impfilename):
316 cygwin_syms(impfilename, outfilename)
317 else:
318 # No import library. Not sure how the DLL is being used, so just
319 # rebuild everything that links to it every time.
320 dummy_syms(outfilename)
321 elif mesonlib.is_sunos():
322 solaris_syms(libfilename, outfilename)
323 elif mesonlib.is_os2():
324 if os.path.isfile(impfilename):
325 os2_syms(impfilename, outfilename)
326 else:
327 # No import library. Not sure how the DLL is being used, so just
328 # rebuild everything that links to it every time.
329 dummy_syms(outfilename)
330 else:
331 if not os.path.exists(TOOL_WARNING_FILE):
332 mlog.warning('Symbol extracting has not been implemented for this '
333 'platform. ' + RELINKING_WARNING)
334 # Write it out so we don't warn again
335 with open(TOOL_WARNING_FILE, 'w', encoding='utf-8'):
336 pass
337 dummy_syms(outfilename)
338
339 def run(args: T.List[str]) -> int:
340 global TOOL_WARNING_FILE # pylint: disable=global-statement
341 options = parser.parse_args(args)
342 if len(options.args) != 4:
343 print('symbolextractor.py <shared library file> <import library> <output file>')
344 sys.exit(1)
345 privdir = os.path.join(options.args[0], 'meson-private')
346 TOOL_WARNING_FILE = os.path.join(privdir, 'symbolextractor_tool_warning_printed')
347 libfile = options.args[1]
348 impfile = options.args[2] # Only used on Windows
349 outfile = options.args[3]
350 gen_symbols(libfile, impfile, outfile, options.cross_host)
351 return 0
352
353 if __name__ == '__main__':
354 sys.exit(run(sys.argv[1:]))