Debian Codegraph @

vendored-meson/meson/mesonbuild/linkers/detect.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2022 The Meson development team
3
4 from __future__ import annotations
5
6 from .base import RSPFileSyntax
7 from .. import mlog
8 from ..mesonlib import (
9 EnvironmentException,
10 Popen_safe, Popen_safe_logged, join_args, search_version
11 )
12
13 import re
14 import shlex
15 import typing as T
16
17 if T.TYPE_CHECKING:
18 from .linkers import DynamicLinker, GnuDynamicLinker
19 from ..environment import Environment
20 from ..compilers import Compiler
21 from ..mesonlib import MachineChoice
22
23 defaults: T.Dict[str, T.List[str]] = {}
24 defaults['static_linker'] = ['ar', 'gar']
25 defaults['vs_static_linker'] = ['lib']
26 defaults['clang_cl_static_linker'] = ['llvm-lib']
27 defaults['cuda_static_linker'] = ['nvlink']
28 defaults['gcc_static_linker'] = ['gcc-ar']
29 defaults['clang_static_linker'] = ['llvm-ar']
30
31 def __failed_to_detect_linker(compiler: T.List[str], args: T.List[str], stdout: str, stderr: str) -> 'T.NoReturn':
32 msg = 'Unable to detect linker for compiler `{}`\nstdout: {}\nstderr: {}'.format(
33 join_args(compiler + args), stdout, stderr)
34 raise EnvironmentException(msg)
35
36
37 def guess_win_linker(env: 'Environment', compiler: T.List[str], comp_class: T.Type['Compiler'],
38 comp_version: str, for_machine: MachineChoice, *,
39 use_linker_prefix: bool = True, invoked_directly: bool = True,
40 extra_args: T.Optional[T.List[str]] = None) -> 'DynamicLinker':
41 from . import linkers
42 env.add_lang_args(comp_class.language, comp_class, for_machine)
43
44 if invoked_directly or comp_class.get_argument_syntax() == 'msvc':
45 rsp_syntax = RSPFileSyntax.MSVC
46 else:
47 rsp_syntax = RSPFileSyntax.GCC
48
49 # Explicitly pass logo here so that we can get the version of link.exe
50 if not use_linker_prefix or comp_class.LINKER_PREFIX is None:
51 check_args = ['/logo', '--version']
52 elif isinstance(comp_class.LINKER_PREFIX, str):
53 check_args = [comp_class.LINKER_PREFIX + '/logo', comp_class.LINKER_PREFIX + '--version']
54 else: # list
55 check_args = comp_class.LINKER_PREFIX + ['/logo'] + comp_class.LINKER_PREFIX + ['--version']
56
57 check_args += env.coredata.get_external_link_args(for_machine, comp_class.language)
58
59 override: T.List[str] = []
60 value = env.lookup_binary_entry(for_machine, comp_class.language + '_ld')
61 if value is not None:
62 override = comp_class.use_linker_args(value[0], comp_version)
63 check_args += override
64 elif 'lld-link' in compiler:
65 override = comp_class.use_linker_args('lld-link', comp_version)
66 check_args += override
67
68 if extra_args is not None:
69 check_args.extend(extra_args)
70
71 p, o, _ = Popen_safe(compiler + check_args)
72 if 'LLD' in o.split('\n', maxsplit=1)[0]:
73 if 'compatible with GNU linkers' in o:
74 return linkers.LLVMDynamicLinker(
75 compiler, for_machine, comp_class.LINKER_PREFIX,
76 override, version=search_version(o))
77 elif not invoked_directly:
78 return linkers.ClangClDynamicLinker(
79 for_machine, override, exelist=compiler, prefix=comp_class.LINKER_PREFIX,
80 version=search_version(o), direct=False, machine=None,
81 rsp_syntax=rsp_syntax)
82
83 if value is not None and invoked_directly:
84 compiler = value
85 # We've already handled the non-direct case above
86
87 p, o, e = Popen_safe(compiler + check_args)
88 if 'LLD' in o.split('\n', maxsplit=1)[0]:
89 return linkers.ClangClDynamicLinker(
90 for_machine, [],
91 prefix=comp_class.LINKER_PREFIX if use_linker_prefix else [],
92 exelist=compiler, version=search_version(o), direct=invoked_directly,
93 rsp_syntax=rsp_syntax)
94 elif 'OPTLINK' in o:
95 # Optlink's stdout *may* begin with a \r character.
96 return linkers.OptlinkDynamicLinker(compiler, for_machine, version=search_version(o))
97 elif o.startswith('Microsoft') or e.startswith('Microsoft'):
98 out = o or e
99 match = re.search(r'.*(X86|X64|ARM|ARM64).*', out)
100 if match:
101 target = str(match.group(1))
102 else:
103 target = 'x86'
104
105 return linkers.MSVCDynamicLinker(
106 for_machine, [], machine=target, exelist=compiler,
107 prefix=comp_class.LINKER_PREFIX if use_linker_prefix else [],
108 version=search_version(out), direct=invoked_directly,
109 rsp_syntax=rsp_syntax)
110 elif 'GNU coreutils' in o:
111 import shutil
112 fullpath = shutil.which(compiler[0])
113 raise EnvironmentException(
114 f"Found GNU link.exe instead of MSVC link.exe in {fullpath}.\n"
115 "This link.exe is not a linker.\n"
116 "You may need to reorder entries to your %PATH% variable to resolve this.")
117 __failed_to_detect_linker(compiler, check_args, o, e)
118
119 def guess_nix_linker(env: 'Environment', compiler: T.List[str], comp_class: T.Type['Compiler'],
120 comp_version: str, for_machine: MachineChoice, *,
121 extra_args: T.Optional[T.List[str]] = None) -> 'DynamicLinker':
122 """Helper for guessing what linker to use on Unix-Like OSes.
123
124 :compiler: Invocation to use to get linker
125 :comp_class: The Compiler Type (uninstantiated)
126 :comp_version: The compiler version string
127 :for_machine: which machine this linker targets
128 :extra_args: Any additional arguments required (such as a source file)
129 """
130 from . import linkers
131 env.add_lang_args(comp_class.language, comp_class, for_machine)
132 extra_args = extra_args or []
133
134 system = env.machines[for_machine].system
135 ldflags = env.coredata.get_external_link_args(for_machine, comp_class.language)
136 extra_args += comp_class._unix_args_to_native(ldflags, env.machines[for_machine])
137
138 if isinstance(comp_class.LINKER_PREFIX, str):
139 check_args = [comp_class.LINKER_PREFIX + '--version'] + extra_args
140 else:
141 check_args = comp_class.LINKER_PREFIX + ['--version'] + extra_args
142
143 override: T.List[str] = []
144 value = env.lookup_binary_entry(for_machine, comp_class.language + '_ld')
145 if value is not None:
146 override = comp_class.use_linker_args(value[0], comp_version)
147 check_args += override
148
149 mlog.debug('-----')
150 p, o, e = Popen_safe_logged(compiler + check_args, msg='Detecting linker via')
151
152 v = search_version(o + e)
153 linker: DynamicLinker
154 if 'LLD' in o.split('\n', maxsplit=1)[0] or 'tiarmlnk' in e:
155 if isinstance(comp_class.LINKER_PREFIX, str):
156 cmd = compiler + override + [comp_class.LINKER_PREFIX + '-v'] + extra_args
157 else:
158 cmd = compiler + override + comp_class.LINKER_PREFIX + ['-v'] + extra_args
159 _, newo, newerr = Popen_safe_logged(cmd, msg='Detecting LLD linker via')
160
161 lld_cls: T.Type[DynamicLinker]
162 if 'ld64.lld' in newerr:
163 lld_cls = linkers.LLVMLD64DynamicLinker
164 else:
165 lld_cls = linkers.LLVMDynamicLinker
166
167 linker = lld_cls(
168 compiler, for_machine, comp_class.LINKER_PREFIX, override, system=system, version=v)
169 elif o.startswith("eld"):
170 linker = linkers.ELDDynamicLinker(
171 compiler, for_machine, comp_class.LINKER_PREFIX, override, version=v)
172 elif 'Snapdragon' in e and 'LLVM' in e:
173 linker = linkers.QualcommLLVMDynamicLinker(
174 compiler, for_machine, comp_class.LINKER_PREFIX, override, version=v)
175 elif e.startswith('lld-link: '):
176 # The LLD MinGW frontend didn't respond to --version before version 9.0.0,
177 # and produced an error message about failing to link (when no object
178 # files were specified), instead of printing the version number.
179 # Let's try to extract the linker invocation command to grab the version.
180
181 _, o, e = Popen_safe(compiler + check_args + ['-v'])
182
183 try:
184 linker_cmd = re.match(r'.*\n(.*?)\nlld-link: ', e, re.DOTALL).group(1)
185 linker_cmd = shlex.split(linker_cmd)[0]
186 except (AttributeError, IndexError, ValueError):
187 pass
188 else:
189 _, o, e = Popen_safe([linker_cmd, '--version'])
190 v = search_version(o)
191
192 linker = linkers.LLVMDynamicLinker(compiler, for_machine, comp_class.LINKER_PREFIX, override, version=v)
193 elif 'GNU' in o or 'GNU' in e:
194 gnu_cls: T.Type[GnuDynamicLinker]
195 # this is always the only thing on stdout, except for swift
196 # which may or may not redirect the linker stdout to stderr
197 if o.startswith('GNU gold') or e.startswith('GNU gold'):
198 gnu_cls = linkers.GnuGoldDynamicLinker
199 elif o.startswith('mold') or e.startswith('mold'):
200 gnu_cls = linkers.MoldDynamicLinker
201 else:
202 gnu_cls = linkers.GnuBFDDynamicLinker
203 linker = gnu_cls(compiler, for_machine, comp_class.LINKER_PREFIX, override, version=v)
204 elif 'Solaris' in e or 'Solaris' in o:
205 for line in (o+e).split('\n'):
206 if 'ld: Software Generation Utilities' in line:
207 v = line.split(':')[2].lstrip()
208 break
209 else:
210 v = 'unknown version'
211 linker = linkers.SolarisDynamicLinker(
212 compiler, for_machine, comp_class.LINKER_PREFIX, override,
213 version=v)
214 elif 'ld: 0706-012 The -- flag is not recognized' in e:
215 if isinstance(comp_class.LINKER_PREFIX, str):
216 _, _, e = Popen_safe(compiler + [comp_class.LINKER_PREFIX + '-V'] + extra_args)
217 else:
218 _, _, e = Popen_safe(compiler + comp_class.LINKER_PREFIX + ['-V'] + extra_args)
219 linker = linkers.AIXDynamicLinker(
220 compiler, for_machine, comp_class.LINKER_PREFIX, override,
221 version=search_version(e))
222 elif o.startswith('zig ld'):
223 linker = linkers.ZigCCDynamicLinker(
224 compiler, for_machine, comp_class.LINKER_PREFIX, override, version=v)
225 # detect xtools first, bug #10805
226 elif 'xtools-' in o.split('\n', maxsplit=1)[0]:
227 xtools = o.split(' ', maxsplit=1)[0]
228 v = xtools.split('-', maxsplit=2)[1]
229 linker = linkers.AppleDynamicLinker(
230 compiler, for_machine, comp_class.LINKER_PREFIX, override,
231 system=system, version=v
232 )
233 # detect linker on MacOS - must be after other platforms because the
234 # "(use -v to see invocation)" will match clang on other platforms,
235 # but the rest of the checks will fail and call __failed_to_detect_linker.
236 # First might be apple clang, second is for real gcc, the third is icc.
237 # Note that "ld: unknown option: " sometimes instead is "ld: unknown options:".
238 elif e.endswith('(use -v to see invocation)\n') or 'macosx_version' in e or 'ld: unknown option' in e:
239 if isinstance(comp_class.LINKER_PREFIX, str):
240 cmd = compiler + [comp_class.LINKER_PREFIX + '-v'] + extra_args
241 else:
242 cmd = compiler + comp_class.LINKER_PREFIX + ['-v'] + extra_args
243 _, newo, newerr = Popen_safe_logged(cmd, msg='Detecting Apple linker via')
244
245 for line in newerr.split('\n'):
246 if 'PROJECT:ld' in line or 'PROJECT:dyld' in line:
247 v = line.split('-')[1]
248 break
249 else:
250 __failed_to_detect_linker(compiler, check_args, o, e)
251 linker = linkers.AppleDynamicLinker(
252 compiler, for_machine, comp_class.LINKER_PREFIX, override,
253 system=system, version=v
254 )
255 else:
256 __failed_to_detect_linker(compiler, check_args, o, e)
257 return linker