Debian Codegraph @

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

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2022 The Meson development team
3 # Copyright © 2023 Intel Corporation
4
5 from __future__ import annotations
6
7 import abc
8 import os
9 import typing as T
10 import re
11
12 from .base import ArLikeLinker, RSPFileSyntax
13 from .. import mesonlib
14 from ..mesonlib import EnvironmentException, MesonException
15 from ..arglist import CompilerArgs
16
17 if T.TYPE_CHECKING:
18 from ..environment import Environment
19 from ..mesonlib import MachineChoice
20 from ..build import BuildTarget
21 from ..compilers import Compiler
22
23
24 class StaticLinker:
25
26 id: str
27
28 def __init__(self, exelist: T.List[str]):
29 self.exelist = exelist
30
31 def get_id(self) -> str:
32 return self.id
33
34 def get_exe(self) -> str:
35 return self.exelist[0]
36
37 def compiler_args(self, args: T.Optional[T.Iterable[str]] = None) -> CompilerArgs:
38 return CompilerArgs(self, args)
39
40 def can_linker_accept_rsp(self) -> bool:
41 """
42 Determines whether the linker can accept arguments using the @rsp syntax.
43 """
44 return mesonlib.is_windows()
45
46 def get_base_link_args(self,
47 target: 'BuildTarget',
48 linker: 'Compiler',
49 env: 'Environment') -> T.List[str]:
50 """Like compilers.get_base_link_args, but for the static linker."""
51 return []
52
53 def get_exelist(self) -> T.List[str]:
54 return self.exelist.copy()
55
56 def get_std_link_args(self, env: 'Environment', is_thin: bool) -> T.List[str]:
57 return []
58
59 def get_optimization_link_args(self, optimization_level: str) -> T.List[str]:
60 return []
61
62 def get_output_args(self, target: str) -> T.List[str]:
63 return []
64
65 def get_coverage_link_args(self) -> T.List[str]:
66 return []
67
68 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
69 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
70 return ([], set())
71
72 def thread_link_flags(self, env: 'Environment') -> T.List[str]:
73 return []
74
75 def openmp_flags(self, env: Environment) -> T.List[str]:
76 return []
77
78 def get_option_link_args(self, target: 'BuildTarget', env: 'Environment', subproject: T.Optional[str] = None) -> T.List[str]:
79 return []
80
81 @classmethod
82 def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]:
83 return args[:]
84
85 @classmethod
86 def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:
87 return args[:]
88
89 def get_link_debugfile_name(self, targetfile: str) -> T.Optional[str]:
90 return None
91
92 def get_link_debugfile_args(self, targetfile: str) -> T.List[str]:
93 # Static libraries do not have PDB files
94 return []
95
96 def get_always_args(self) -> T.List[str]:
97 return []
98
99 def get_linker_always_args(self) -> T.List[str]:
100 return []
101
102 def rsp_file_syntax(self) -> RSPFileSyntax:
103 """The format of the RSP file that this compiler supports.
104
105 If `self.can_linker_accept_rsp()` returns True, then this needs to
106 be implemented
107 """
108 assert not self.can_linker_accept_rsp(), f'{self.id} linker accepts RSP, but doesn\' provide a supported format, this is a bug'
109 raise EnvironmentException(f'{self.id} does not implement rsp format, this shouldn\'t be called')
110
111
112 class DynamicLinker(metaclass=abc.ABCMeta):
113
114 """Base class for dynamic linkers."""
115
116 _OPTIMIZATION_ARGS: T.Dict[str, T.List[str]] = {
117 'plain': [],
118 '0': [],
119 'g': [],
120 '1': [],
121 '2': [],
122 '3': [],
123 's': [],
124 }
125
126 @abc.abstractproperty
127 def id(self) -> str:
128 pass
129
130 def _apply_prefix(self, arg: T.Union[str, T.List[str]]) -> T.List[str]:
131 args = [arg] if isinstance(arg, str) else arg
132 if self.prefix_arg is None:
133 return args
134 elif isinstance(self.prefix_arg, str):
135 return [self.prefix_arg + arg for arg in args]
136 ret: T.List[str] = []
137 for arg in args:
138 ret += self.prefix_arg + [arg]
139 return ret
140
141 def __init__(self, exelist: T.List[str],
142 for_machine: mesonlib.MachineChoice, prefix_arg: T.Union[str, T.List[str]],
143 always_args: T.List[str], *, system: str = 'unknown system',
144 version: str = 'unknown version'):
145 self.exelist = exelist
146 self.for_machine = for_machine
147 self.system = system
148 self.version = version
149 self.prefix_arg = prefix_arg
150 self.always_args = always_args
151 self.machine: T.Optional[str] = None
152
153 def __repr__(self) -> str:
154 return '<{}: v{} `{}`>'.format(type(self).__name__, self.version, ' '.join(self.exelist))
155
156 def get_id(self) -> str:
157 return self.id
158
159 def get_exe(self) -> str:
160 return self.exelist[0]
161
162 def get_version_string(self) -> str:
163 return f'({self.id} {self.version})'
164
165 def get_exelist(self) -> T.List[str]:
166 return self.exelist.copy()
167
168 def get_accepts_rsp(self) -> bool:
169 # rsp files are only used when building on Windows because we want to
170 # avoid issues with quoting and max argument length
171 return mesonlib.is_windows()
172
173 def rsp_file_syntax(self) -> RSPFileSyntax:
174 """The format of the RSP file that this compiler supports.
175
176 If `self.can_linker_accept_rsp()` returns True, then this needs to
177 be implemented
178 """
179 return RSPFileSyntax.GCC
180
181 def get_always_args(self) -> T.List[str]:
182 return self.always_args.copy()
183
184 def get_lib_prefix(self) -> str:
185 return ''
186
187 # XXX: is use_ldflags a compiler or a linker attribute?
188
189 def get_option_args(self, target: 'BuildTarget', env: 'Environment', subproject: T.Optional[str] = None) -> T.List[str]:
190 return []
191
192 def get_option_link_args(self, target: 'BuildTarget', env: 'Environment', subproject: T.Optional[str] = None) -> T.List[str]:
193 return []
194
195 def has_multi_arguments(self, args: T.List[str], env: 'Environment') -> T.Tuple[bool, bool]:
196 raise EnvironmentException(f'Language {self.id} does not support has_multi_link_arguments.')
197
198 def get_debugfile_name(self, targetfile: str) -> T.Optional[str]:
199 '''Name of debug file written out (see below)'''
200 return None
201
202 def get_debugfile_args(self, targetfile: str) -> T.List[str]:
203 """Some compilers (MSVC) write debug into a separate file.
204
205 This method takes the target object path and returns a list of
206 commands to append to the linker invocation to control where that
207 file is written.
208 """
209 return []
210
211 def get_optimization_link_args(self, optimization_level: str) -> T.List[str]:
212 # We can override these in children by just overriding the
213 # _OPTIMIZATION_ARGS value.
214 return mesonlib.listify([self._apply_prefix(a) for a in self._OPTIMIZATION_ARGS[optimization_level]])
215
216 def get_std_shared_lib_args(self) -> T.List[str]:
217 return []
218
219 def get_std_shared_module_args(self, Target: 'BuildTarget') -> T.List[str]:
220 return self.get_std_shared_lib_args()
221
222 def get_pie_args(self) -> T.List[str]:
223 # TODO: this really needs to take a boolean and return the args to
224 # disable pie, otherwise it only acts to enable pie if pie *isn't* the
225 # default.
226 raise EnvironmentException(f'Linker {self.id} does not support position-independent executable')
227
228 def get_lto_args(self) -> T.List[str]:
229 return []
230
231 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
232 return []
233
234 def sanitizer_args(self, value: T.List[str]) -> T.List[str]:
235 return []
236
237 def get_asneeded_args(self) -> T.List[str]:
238 return []
239
240 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
241 raise EnvironmentException(
242 f'Linker {self.id} does not support link_whole')
243
244 def get_allow_undefined_args(self) -> T.List[str]:
245 raise EnvironmentException(
246 f'Linker {self.id} does not support allow undefined')
247
248 @abc.abstractmethod
249 def get_output_args(self, outputname: str) -> T.List[str]:
250 pass
251
252 def get_coverage_args(self) -> T.List[str]:
253 raise EnvironmentException(f"Linker {self.id} doesn't implement coverage data generation.")
254
255 @abc.abstractmethod
256 def get_search_args(self, dirname: str) -> T.List[str]:
257 pass
258
259 def export_dynamic_args(self, env: 'Environment') -> T.List[str]:
260 return []
261
262 def import_library_args(self, implibname: str) -> T.List[str]:
263 """The name of the outputted import library.
264
265 This implementation is used only on Windows by compilers that use GNU ld
266 """
267 return []
268
269 def thread_flags(self, env: 'Environment') -> T.List[str]:
270 return []
271
272 def no_undefined_args(self) -> T.List[str]:
273 """Arguments to error if there are any undefined symbols at link time.
274
275 This is the inverse of get_allow_undefined_args().
276
277 TODO: A future cleanup might merge this and
278 get_allow_undefined_args() into a single method taking a
279 boolean
280 """
281 return []
282
283 def fatal_warnings(self) -> T.List[str]:
284 """Arguments to make all warnings errors."""
285 return []
286
287 def headerpad_args(self) -> T.List[str]:
288 # Only used by the Apple linker
289 return []
290
291 def get_win_subsystem_args(self, value: str) -> T.List[str]:
292 # Only used if supported by the dynamic linker and
293 # only when targeting Windows
294 return []
295
296 def bitcode_args(self) -> T.List[str]:
297 raise MesonException('This linker does not support bitcode bundles')
298
299 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
300 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
301 return ([], set())
302
303 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
304 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
305 return []
306
307 def get_archive_name(self, filename: str) -> str:
308 #Only used by AIX.
309 return str()
310
311 def get_command_to_archive_shlib(self) -> T.List[str]:
312 #Only used by AIX.
313 return []
314
315
316 if T.TYPE_CHECKING:
317 StaticLinkerBase = StaticLinker
318 DynamicLinkerBase = DynamicLinker
319 else:
320 StaticLinkerBase = DynamicLinkerBase = object
321
322
323 class VisualStudioLikeLinker(StaticLinkerBase):
324 always_args = ['/NOLOGO']
325
326 def __init__(self, machine: str):
327 self.machine = machine
328
329 def get_always_args(self) -> T.List[str]:
330 return self.always_args.copy()
331
332 def get_linker_always_args(self) -> T.List[str]:
333 return self.always_args.copy()
334
335 def get_output_args(self, target: str) -> T.List[str]:
336 args: T.List[str] = []
337 if self.machine:
338 args += ['/MACHINE:' + self.machine]
339 args += ['/OUT:' + target]
340 return args
341
342 @classmethod
343 def unix_args_to_native(cls, args: T.List[str]) -> T.List[str]:
344 from ..compilers.c import VisualStudioCCompiler
345 return VisualStudioCCompiler.unix_args_to_native(args)
346
347 @classmethod
348 def native_args_to_unix(cls, args: T.List[str]) -> T.List[str]:
349 from ..compilers.c import VisualStudioCCompiler
350 return VisualStudioCCompiler.native_args_to_unix(args)
351
352 def rsp_file_syntax(self) -> RSPFileSyntax:
353 return RSPFileSyntax.MSVC
354
355
356 class VisualStudioLinker(VisualStudioLikeLinker, StaticLinker):
357
358 """Microsoft's lib static linker."""
359
360 id = 'lib'
361
362 def __init__(self, exelist: T.List[str], machine: str):
363 StaticLinker.__init__(self, exelist)
364 VisualStudioLikeLinker.__init__(self, machine)
365
366
367 class IntelVisualStudioLinker(VisualStudioLikeLinker, StaticLinker):
368
369 """Intel's xilib static linker."""
370
371 id = 'xilib'
372
373 def __init__(self, exelist: T.List[str], machine: str):
374 StaticLinker.__init__(self, exelist)
375 VisualStudioLikeLinker.__init__(self, machine)
376
377
378 class ArLinker(ArLikeLinker, StaticLinker):
379 id = 'ar'
380
381 def __init__(self, for_machine: mesonlib.MachineChoice, exelist: T.List[str]):
382 super().__init__(exelist)
383 stdo = mesonlib.Popen_safe(self.exelist + ['-h'])[1]
384 # Enable deterministic builds if they are available.
385 stdargs = 'csr'
386 thinargs = ''
387 if '[D]' in stdo:
388 stdargs += 'D'
389 if '[T]' in stdo:
390 thinargs = 'T'
391 self.std_args = [stdargs]
392 self.std_thin_args = [stdargs + thinargs]
393 self.can_rsp = '@<' in stdo
394 self.for_machine = for_machine
395
396 def can_linker_accept_rsp(self) -> bool:
397 return self.can_rsp
398
399 def get_std_link_args(self, env: 'Environment', is_thin: bool) -> T.List[str]:
400 # Thin archives are a GNU extension not supported by the system linkers
401 # on Mac OS X, Solaris, or illumos, so don't build them on those OSes.
402 # OS X ld rejects with: "file built for unknown-unsupported file format"
403 # illumos/Solaris ld rejects with: "unknown file type"
404 if is_thin and not env.machines[self.for_machine].is_darwin() \
405 and not env.machines[self.for_machine].is_sunos():
406 return self.std_thin_args
407 else:
408 return self.std_args
409
410
411 class AppleArLinker(ArLinker):
412
413 # mostly this is used to determine that we need to call ranlib
414
415 id = 'applear'
416
417
418 class ArmarLinker(ArLikeLinker, StaticLinker):
419 id = 'armar'
420
421
422 class DLinker(StaticLinker):
423 def __init__(self, exelist: T.List[str], arch: str, *, rsp_syntax: RSPFileSyntax = RSPFileSyntax.GCC):
424 super().__init__(exelist)
425 self.id = exelist[0]
426 self.arch = arch
427 self.__rsp_syntax = rsp_syntax
428
429 def get_std_link_args(self, env: 'Environment', is_thin: bool) -> T.List[str]:
430 return ['-lib']
431
432 def get_output_args(self, target: str) -> T.List[str]:
433 return ['-of=' + target]
434
435 def get_linker_always_args(self) -> T.List[str]:
436 if mesonlib.is_windows():
437 if self.arch == 'x86_64':
438 return ['-m64']
439 elif self.arch == 'x86_mscoff' and self.id == 'dmd':
440 return ['-m32mscoff']
441 return ['-m32']
442 return []
443
444 def rsp_file_syntax(self) -> RSPFileSyntax:
445 return self.__rsp_syntax
446
447
448 class CcrxLinker(StaticLinker):
449
450 def __init__(self, exelist: T.List[str]):
451 super().__init__(exelist)
452 self.id = 'rlink'
453
454 def can_linker_accept_rsp(self) -> bool:
455 return False
456
457 def get_output_args(self, target: str) -> T.List[str]:
458 return [f'-output={target}']
459
460 def get_linker_always_args(self) -> T.List[str]:
461 return ['-nologo', '-form=library']
462
463
464 class Xc16Linker(StaticLinker):
465
466 def __init__(self, exelist: T.List[str]):
467 super().__init__(exelist)
468 self.id = 'xc16-ar'
469
470 def can_linker_accept_rsp(self) -> bool:
471 return False
472
473 def get_output_args(self, target: str) -> T.List[str]:
474 return [f'{target}']
475
476 def get_linker_always_args(self) -> T.List[str]:
477 return ['rcs']
478
479 class CompCertLinker(StaticLinker):
480
481 def __init__(self, exelist: T.List[str]):
482 super().__init__(exelist)
483 self.id = 'ccomp'
484
485 def can_linker_accept_rsp(self) -> bool:
486 return False
487
488 def get_output_args(self, target: str) -> T.List[str]:
489 return [f'-o{target}']
490
491
492 class TILinker(StaticLinker):
493
494 def __init__(self, exelist: T.List[str]):
495 super().__init__(exelist)
496 self.id = 'ti-ar'
497
498 def can_linker_accept_rsp(self) -> bool:
499 return False
500
501 def get_output_args(self, target: str) -> T.List[str]:
502 return [f'{target}']
503
504 def get_linker_always_args(self) -> T.List[str]:
505 return ['-r']
506
507
508 class C2000Linker(TILinker):
509 # Required for backwards compat with projects created before ti-cgt support existed
510 id = 'ar2000'
511
512 class C6000Linker(TILinker):
513 id = 'ar6000'
514
515
516 class AIXArLinker(ArLikeLinker, StaticLinker):
517 id = 'aixar'
518 std_args = ['-csr', '-Xany']
519
520
521 class MetrowerksStaticLinker(StaticLinker):
522
523 def can_linker_accept_rsp(self) -> bool:
524 return True
525
526 def get_linker_always_args(self) -> T.List[str]:
527 return ['-library']
528
529 def get_output_args(self, target: str) -> T.List[str]:
530 return ['-o', target]
531
532 def rsp_file_syntax(self) -> RSPFileSyntax:
533 return RSPFileSyntax.GCC
534
535
536 class MetrowerksStaticLinkerARM(MetrowerksStaticLinker):
537 id = 'mwldarm'
538
539
540 class MetrowerksStaticLinkerEmbeddedPowerPC(MetrowerksStaticLinker):
541 id = 'mwldeppc'
542
543 class TaskingStaticLinker(StaticLinker):
544 id = 'tasking'
545
546 def __init__(self, exelist: T.List[str]):
547 super().__init__(exelist)
548
549 def can_linker_accept_rsp(self) -> bool:
550 return True
551
552 def rsp_file_syntax(self) -> RSPFileSyntax:
553 return RSPFileSyntax.TASKING
554
555 def get_output_args(self, target: str) -> T.List[str]:
556 return ['-n', target]
557
558 def get_linker_always_args(self) -> T.List[str]:
559 return ['-r']
560
561 def prepare_rpaths(raw_rpaths: T.Tuple[str, ...], build_dir: str, from_dir: str) -> T.List[str]:
562 # The rpaths we write must be relative if they point to the build dir,
563 # because otherwise they have different length depending on the build
564 # directory. This breaks reproducible builds.
565 internal_format_rpaths = [evaluate_rpath(p, build_dir, from_dir) for p in raw_rpaths]
566 ordered_rpaths = order_rpaths(internal_format_rpaths)
567 return ordered_rpaths
568
569
570 def order_rpaths(rpath_list: T.List[str]) -> T.List[str]:
571 # We want rpaths that point inside our build dir to always override
572 # those pointing to other places in the file system. This is so built
573 # binaries prefer our libraries to the ones that may lie somewhere
574 # in the file system, such as /lib/x86_64-linux-gnu.
575 #
576 # The correct thing to do here would be C++'s std::stable_partition.
577 # Python standard library does not have it, so replicate it with
578 # sort, which is guaranteed to be stable.
579 return sorted(rpath_list, key=os.path.isabs)
580
581
582 def evaluate_rpath(p: str, build_dir: str, from_dir: str) -> str:
583 if p == from_dir:
584 return '' # relpath errors out in this case
585 elif os.path.isabs(p):
586 return p # These can be outside of build dir.
587 else:
588 return os.path.relpath(os.path.join(build_dir, p), os.path.join(build_dir, from_dir))
589
590
591 class PosixDynamicLinkerMixin(DynamicLinkerBase):
592
593 """Mixin class for POSIX-ish linkers.
594
595 This is obviously a pretty small subset of the linker interface, but
596 enough dynamic linkers that meson supports are POSIX-like but not
597 GNU-like that it makes sense to split this out.
598 """
599
600 def get_output_args(self, outputname: str) -> T.List[str]:
601 return ['-o', outputname]
602
603 def get_std_shared_lib_args(self) -> T.List[str]:
604 return ['-shared']
605
606 def get_search_args(self, dirname: str) -> T.List[str]:
607 return ['-L' + dirname]
608
609 def sanitizer_args(self, value: T.List[str]) -> T.List[str]:
610 return []
611
612
613 class GnuLikeDynamicLinkerMixin(DynamicLinkerBase):
614
615 """Mixin class for dynamic linkers that provides gnu-like interface.
616
617 This acts as a base for the GNU linkers (bfd and gold), LLVM's lld, and
618 other linkers like GNU-ld.
619 """
620
621 if T.TYPE_CHECKING:
622 for_machine = MachineChoice.HOST
623 def _apply_prefix(self, arg: T.Union[str, T.List[str]]) -> T.List[str]: ...
624
625 _OPTIMIZATION_ARGS: T.Dict[str, T.List[str]] = {
626 'plain': [],
627 '0': [],
628 'g': [],
629 '1': [],
630 '2': [],
631 '3': ['-O1'],
632 's': [],
633 }
634
635 _SUBSYSTEMS: T.Dict[str, str] = {
636 "native": "1",
637 "windows": "windows",
638 "console": "console",
639 "posix": "7",
640 "efi_application": "10",
641 "efi_boot_service_driver": "11",
642 "efi_runtime_driver": "12",
643 "efi_rom": "13",
644 "boot_application": "16",
645 }
646
647 def get_accepts_rsp(self) -> bool:
648 return True
649
650 def get_pie_args(self) -> T.List[str]:
651 return ['-pie']
652
653 def get_asneeded_args(self) -> T.List[str]:
654 return self._apply_prefix('--as-needed')
655
656 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
657 if not args:
658 return args
659 return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive')
660
661 def get_allow_undefined_args(self) -> T.List[str]:
662 return self._apply_prefix('--allow-shlib-undefined')
663
664 def get_lto_args(self) -> T.List[str]:
665 return ['-flto']
666
667 def sanitizer_args(self, value: T.List[str]) -> T.List[str]:
668 if not value:
669 return value
670 return [f'-fsanitize={",".join(value)}']
671
672 def get_coverage_args(self) -> T.List[str]:
673 return ['--coverage']
674
675 def export_dynamic_args(self, env: 'Environment') -> T.List[str]:
676 m = env.machines[self.for_machine]
677 if m.is_windows() or m.is_cygwin():
678 return self._apply_prefix('--export-all-symbols')
679 return self._apply_prefix('-export-dynamic')
680
681 def import_library_args(self, implibname: str) -> T.List[str]:
682 return self._apply_prefix('--out-implib=' + implibname)
683
684 def thread_flags(self, env: 'Environment') -> T.List[str]:
685 if env.machines[self.for_machine].is_haiku():
686 return []
687 return ['-pthread']
688
689 def no_undefined_args(self) -> T.List[str]:
690 return self._apply_prefix('--no-undefined')
691
692 def fatal_warnings(self) -> T.List[str]:
693 return self._apply_prefix('--fatal-warnings')
694
695 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
696 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
697 m = env.machines[self.for_machine]
698 if m.is_windows() or m.is_cygwin():
699 # For PE/COFF the soname argument has no effect
700 return []
701 sostr = '' if soversion is None else '.' + soversion
702 return self._apply_prefix(f'-soname,{prefix}{shlib_name}.{suffix}{sostr}')
703
704 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
705 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
706 m = env.machines[self.for_machine]
707 if m.is_windows() or m.is_cygwin():
708 return ([], set())
709 rpath_paths = target.determine_rpath_dirs()
710 if not rpath_paths and not target.install_rpath and not target.build_rpath and not extra_paths:
711 return ([], set())
712 args: T.List[str] = []
713 origin_placeholder = '$ORIGIN'
714 processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir)
715 # Need to deduplicate rpaths, as macOS's install_name_tool
716 # is *very* allergic to duplicate -delete_rpath arguments
717 # when calling depfixer on installation.
718 all_paths = mesonlib.OrderedSet([os.path.join(origin_placeholder, p) for p in processed_rpaths])
719 rpath_dirs_to_remove: T.Set[bytes] = set()
720 for p in all_paths:
721 rpath_dirs_to_remove.add(p.encode('utf8'))
722 # Build_rpath is used as-is (it is usually absolute).
723 if target.build_rpath != '':
724 all_paths.add(target.build_rpath)
725 for p in target.build_rpath.split(':'):
726 rpath_dirs_to_remove.add(p.encode('utf8'))
727 if extra_paths:
728 all_paths.update(extra_paths)
729
730 # TODO: should this actually be "for (dragonfly|open)bsd"?
731 if mesonlib.is_dragonflybsd() or mesonlib.is_openbsd():
732 # This argument instructs the compiler to record the value of
733 # ORIGIN in the .dynamic section of the elf. On Linux this is done
734 # by default, but is not on dragonfly/openbsd for some reason. Without this
735 # $ORIGIN in the runtime path will be undefined and any binaries
736 # linked against local libraries will fail to resolve them.
737 args.extend(self._apply_prefix('-z,origin'))
738
739 # In order to avoid relinking for RPATH removal, the binary needs to contain just
740 # enough space in the ELF header to hold the final installation RPATH.
741 paths = ':'.join(all_paths)
742 paths_length = len(paths.encode('utf-8'))
743 install_rpath_length = len(target.install_rpath.encode('utf-8'))
744 if paths_length < install_rpath_length:
745 padding = 'X' * (install_rpath_length - paths_length)
746 if not paths:
747 paths = padding
748 else:
749 paths = paths + ':' + padding
750 args.extend(self._apply_prefix('-rpath,' + paths))
751
752 # TODO: should this actually be "for solaris/sunos"?
753 # NOTE: Remove the zigcc check once zig support "-rpath-link"
754 # See https://github.com/ziglang/zig/issues/18713
755 if mesonlib.is_sunos() or self.id == 'ld.zigcc':
756 return (args, rpath_dirs_to_remove)
757
758 # Rpaths to use while linking must be absolute. These are not
759 # written to the binary. Needed only with GNU ld, and only for
760 # versions before 2.28:
761 # https://sourceware.org/bugzilla/show_bug.cgi?id=20535
762 # https://sourceware.org/bugzilla/show_bug.cgi?id=16936
763 # Not needed on Windows or other platforms that don't use RPATH
764 # https://github.com/mesonbuild/meson/issues/1897
765 #
766 # In 2.28 and on, $ORIGIN tokens inside of -rpath are respected,
767 # so we do not need to duplicate it in -rpath-link.
768 #
769 # In addition, this linker option tends to be quite long and some
770 # compilers have trouble dealing with it. That's why we will include
771 # one option per folder, like this:
772 #
773 # -Wl,-rpath-link,/path/to/folder1 -Wl,-rpath,/path/to/folder2 ...
774 #
775 # ...instead of just one single looooong option, like this:
776 #
777 # -Wl,-rpath-link,/path/to/folder1:/path/to/folder2:...
778 if self.id in {'ld.bfd', 'ld.gold'} and mesonlib.version_compare(self.version, '<2.28'):
779 for p in rpath_paths:
780 args.extend(self._apply_prefix('-rpath-link,' + os.path.join(build_dir, p)))
781
782 return (args, rpath_dirs_to_remove)
783
784 def get_win_subsystem_args(self, value: str) -> T.List[str]:
785 # MinGW only directly supports a couple of the possible
786 # PE application types. The raw integer works as an argument
787 # as well, and is always accepted, so we manually map the
788 # other types here. List of all types:
789 # https://github.com/wine-mirror/wine/blob/3ded60bd1654dc689d24a23305f4a93acce3a6f2/include/winnt.h#L2492-L2507
790 versionsuffix = None
791 if ',' in value:
792 value, versionsuffix = value.split(',', 1)
793 newvalue = self._SUBSYSTEMS.get(value)
794 if newvalue is not None:
795 if versionsuffix is not None:
796 newvalue += f':{versionsuffix}'
797 args = [f'--subsystem,{newvalue}']
798 else:
799 raise mesonlib.MesonBugException(f'win_subsystem: {value!r} not handled in MinGW linker. This should not be possible.')
800
801 return self._apply_prefix(args)
802
803
804 class AppleDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
805
806 """Apple's ld implementation."""
807
808 id = 'ld64'
809
810 def get_asneeded_args(self) -> T.List[str]:
811 return self._apply_prefix('-dead_strip_dylibs')
812
813 def get_allow_undefined_args(self) -> T.List[str]:
814 # iOS doesn't allow undefined symbols when linking
815 if self.system == 'ios':
816 return []
817 else:
818 return self._apply_prefix('-undefined,dynamic_lookup')
819
820 def get_std_shared_module_args(self, target: 'BuildTarget') -> T.List[str]:
821 if self.system == 'ios':
822 return ['-dynamiclib']
823 else:
824 return ['-bundle'] + self.get_allow_undefined_args()
825
826 def get_pie_args(self) -> T.List[str]:
827 return []
828
829 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
830 result: T.List[str] = []
831 for a in args:
832 result.extend(self._apply_prefix('-force_load'))
833 result.append(a)
834 return result
835
836 def get_coverage_args(self) -> T.List[str]:
837 return ['--coverage']
838
839 def sanitizer_args(self, value: T.List[str]) -> T.List[str]:
840 if not value:
841 return value
842 return [f'-fsanitize={",".join(value)}']
843
844 def no_undefined_args(self) -> T.List[str]:
845 # We used to emit -undefined,error, but starting with Xcode 15 /
846 # Sonoma, doing so triggers "ld: warning: -undefined error is
847 # deprecated". Given that "-undefined error" is documented to be the
848 # linker's default behaviour, this warning seems ill advised. However,
849 # it does create a lot of noise. As "-undefined error" is the default
850 # behaviour, the least bad way to deal with this seems to be to just
851 # not emit anything here. Of course that only works as long as nothing
852 # else injects -undefined dynamic_lookup, or such. Complain to Apple.
853 return []
854
855 def headerpad_args(self) -> T.List[str]:
856 return self._apply_prefix('-headerpad_max_install_names')
857
858 def bitcode_args(self) -> T.List[str]:
859 return self._apply_prefix('-bitcode_bundle')
860
861 def fatal_warnings(self) -> T.List[str]:
862 return self._apply_prefix('-fatal_warnings')
863
864 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
865 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
866 install_name = ['@rpath/', prefix, shlib_name]
867 if soversion is not None:
868 install_name.append('.' + soversion)
869 install_name.append('.' + suffix)
870 args = ['-install_name', ''.join(install_name)]
871 if darwin_versions:
872 args.extend(['-compatibility_version', darwin_versions[0],
873 '-current_version', darwin_versions[1]])
874 return args
875
876 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
877 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
878 rpath_paths = target.determine_rpath_dirs()
879 if not rpath_paths and not target.install_rpath and not target.build_rpath and not extra_paths:
880 return ([], set())
881 args: T.List[str] = []
882 rpath_dirs_to_remove: T.Set[bytes] = set()
883 # @loader_path is the equivalent of $ORIGIN on macOS
884 # https://stackoverflow.com/q/26280738
885 origin_placeholder = '@loader_path'
886 processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir)
887 all_paths = mesonlib.OrderedSet([os.path.join(origin_placeholder, p) for p in processed_rpaths])
888 if target.build_rpath != '':
889 all_paths.update(target.build_rpath.split(':'))
890 if extra_paths:
891 all_paths.update(extra_paths)
892 for rp in all_paths:
893 rpath_dirs_to_remove.add(rp.encode('utf8'))
894 args.extend(self._apply_prefix('-rpath,' + rp))
895
896 return (args, rpath_dirs_to_remove)
897
898 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
899 return ["-Wl,-cache_path_lto," + path]
900
901 def export_dynamic_args(self, env: 'Environment') -> T.List[str]:
902 if mesonlib.version_compare(self.version, '>=224.1'):
903 return self._apply_prefix('-export_dynamic')
904 return []
905
906
907 class LLVMLD64DynamicLinker(AppleDynamicLinker):
908
909 id = 'ld64.lld'
910
911
912 class GnuDynamicLinker(GnuLikeDynamicLinkerMixin, PosixDynamicLinkerMixin, DynamicLinker):
913
914 """Representation of GNU ld.bfd and ld.gold."""
915
916
917 class GnuGoldDynamicLinker(GnuDynamicLinker):
918
919 id = 'ld.gold'
920
921 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
922 return ['-Wl,-plugin-opt,cache-dir=' + path]
923
924
925 class GnuBFDDynamicLinker(GnuDynamicLinker):
926
927 id = 'ld.bfd'
928
929
930 class MoldDynamicLinker(GnuDynamicLinker):
931
932 id = 'ld.mold'
933
934 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
935 return ['-Wl,--thinlto-cache-dir=' + path]
936
937
938 class LLVMDynamicLinker(GnuLikeDynamicLinkerMixin, PosixDynamicLinkerMixin, DynamicLinker):
939
940 """Representation of LLVM's ld.lld linker.
941
942 This is only the gnu-like linker, not the apple like or link.exe like
943 linkers.
944 """
945
946 id = 'ld.lld'
947
948 def __init__(self, exelist: T.List[str],
949 for_machine: mesonlib.MachineChoice, prefix_arg: T.Union[str, T.List[str]],
950 always_args: T.List[str], *, system: str = 'unknown system',
951 version: str = 'unknown version'):
952 super().__init__(exelist, for_machine, prefix_arg, always_args, system=system, version=version)
953
954 # Some targets don't seem to support this argument (windows, wasm, ...)
955 self.has_allow_shlib_undefined = self._supports_flag('--allow-shlib-undefined', always_args)
956 # These aren't supported by TI Arm Clang
957 self.has_as_needed = self._supports_flag('--as-needed', always_args)
958 self.has_no_undefined = self._supports_flag('--no-undefined', always_args)
959
960 def _supports_flag(self, flag: str, always_args: T.List[str]) -> bool:
961 _, _, e = mesonlib.Popen_safe(self.exelist + always_args + self._apply_prefix(flag))
962 return (
963 # Versions < 9 do not have a quoted argument
964 (f'unknown argument: {flag}' not in e) and
965 (f"unknown argument: '{flag}'" not in e) and
966 # TI Arm Clang uses a different message
967 (f'invalid option: {flag}' not in e)
968 )
969
970 def get_allow_undefined_args(self) -> T.List[str]:
971 if self.has_allow_shlib_undefined:
972 return self._apply_prefix('--allow-shlib-undefined')
973 return []
974
975 def get_asneeded_args(self) -> T.List[str]:
976 if self.has_as_needed:
977 return self._apply_prefix('--as-needed')
978 return []
979
980 def no_undefined_args(self) -> T.List[str]:
981 if self.has_no_undefined:
982 return self._apply_prefix('--no-undefined')
983 return []
984
985 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
986 return ['-Wl,--thinlto-cache-dir=' + path]
987
988 def get_win_subsystem_args(self, value: str) -> T.List[str]:
989 # lld does not support a numeric subsystem value
990 version = None
991 if ',' in value:
992 value, version = value.split(',', 1)
993 if value in self._SUBSYSTEMS:
994 if version is not None:
995 value += f':{version}'
996 return self._apply_prefix([f'--subsystem,{value}'])
997 else:
998 raise mesonlib.MesonBugException(f'win_subsystem: {value} not handled in lld linker. This should not be possible.')
999
1000
1001 class ZigCCDynamicLinker(LLVMDynamicLinker):
1002 id = 'ld.zigcc'
1003
1004 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
1005 return []
1006
1007
1008 class WASMDynamicLinker(GnuLikeDynamicLinkerMixin, PosixDynamicLinkerMixin, DynamicLinker):
1009
1010 """Emscripten's wasm-ld."""
1011
1012 id = 'ld.wasm'
1013
1014 def get_allow_undefined_args(self) -> T.List[str]:
1015 return ['-sERROR_ON_UNDEFINED_SYMBOLS=0']
1016
1017 def no_undefined_args(self) -> T.List[str]:
1018 return ['-sERROR_ON_UNDEFINED_SYMBOLS=1']
1019
1020 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1021 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1022 raise MesonException(f'{self.id} does not support shared libraries.')
1023
1024 def get_asneeded_args(self) -> T.List[str]:
1025 return []
1026
1027 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
1028 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
1029 return ([], set())
1030
1031
1032 class CcrxDynamicLinker(DynamicLinker):
1033
1034 """Linker for Renesas CCrx compiler."""
1035
1036 id = 'rlink'
1037
1038 def __init__(self, for_machine: mesonlib.MachineChoice,
1039 *, version: str = 'unknown version'):
1040 super().__init__(['rlink.exe'], for_machine, '', [],
1041 version=version)
1042
1043 def get_accepts_rsp(self) -> bool:
1044 return False
1045
1046 def get_lib_prefix(self) -> str:
1047 return '-lib='
1048
1049 def get_std_shared_lib_args(self) -> T.List[str]:
1050 return []
1051
1052 def get_output_args(self, outputname: str) -> T.List[str]:
1053 return [f'-output={outputname}']
1054
1055 def get_search_args(self, dirname: str) -> 'T.NoReturn':
1056 raise OSError('rlink.exe does not have a search dir argument')
1057
1058 def get_allow_undefined_args(self) -> T.List[str]:
1059 return []
1060
1061 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1062 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1063 return []
1064
1065
1066 class Xc16DynamicLinker(DynamicLinker):
1067
1068 """Linker for Microchip XC16 compiler."""
1069
1070 id = 'xc16-gcc'
1071
1072 def __init__(self, for_machine: mesonlib.MachineChoice,
1073 *, version: str = 'unknown version'):
1074 super().__init__(['xc16-gcc'], for_machine, '', [],
1075 version=version)
1076
1077 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1078 if len(args) < 2:
1079 return args
1080 return self._apply_prefix('--start-group') + args + self._apply_prefix('--end-group')
1081
1082 def get_accepts_rsp(self) -> bool:
1083 return False
1084
1085 def get_lib_prefix(self) -> str:
1086 return ''
1087
1088 def get_std_shared_lib_args(self) -> T.List[str]:
1089 return []
1090
1091 def get_output_args(self, outputname: str) -> T.List[str]:
1092 return [f'-o{outputname}']
1093
1094 def get_search_args(self, dirname: str) -> 'T.NoReturn':
1095 raise OSError('xc16-gcc does not have a search dir argument')
1096
1097 def get_allow_undefined_args(self) -> T.List[str]:
1098 return []
1099
1100 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1101 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1102 return []
1103
1104 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
1105 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
1106 return ([], set())
1107
1108 class CompCertDynamicLinker(DynamicLinker):
1109
1110 """Linker for CompCert C compiler."""
1111
1112 id = 'ccomp'
1113
1114 def __init__(self, for_machine: mesonlib.MachineChoice,
1115 *, version: str = 'unknown version'):
1116 super().__init__(['ccomp'], for_machine, '', [],
1117 version=version)
1118
1119 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1120 if not args:
1121 return args
1122 return self._apply_prefix('-Wl,--whole-archive') + args + self._apply_prefix('-Wl,--no-whole-archive')
1123
1124 def get_accepts_rsp(self) -> bool:
1125 return False
1126
1127 def get_lib_prefix(self) -> str:
1128 return ''
1129
1130 def get_std_shared_lib_args(self) -> T.List[str]:
1131 return []
1132
1133 def get_output_args(self, outputname: str) -> T.List[str]:
1134 return [f'-o{outputname}']
1135
1136 def get_search_args(self, dirname: str) -> T.List[str]:
1137 return [f'-L{dirname}']
1138
1139 def get_allow_undefined_args(self) -> T.List[str]:
1140 return []
1141
1142 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1143 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1144 raise MesonException(f'{self.id} does not support shared libraries.')
1145
1146 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
1147 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
1148 return ([], set())
1149
1150 class TIDynamicLinker(DynamicLinker):
1151
1152 """Linker for Texas Instruments compiler family."""
1153
1154 id = 'ti'
1155
1156 def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice,
1157 *, version: str = 'unknown version'):
1158 super().__init__(exelist, for_machine, '', [],
1159 version=version)
1160
1161 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1162 if len(args) < 2:
1163 return args
1164 return self._apply_prefix('--start-group') + args + self._apply_prefix('--end-group')
1165
1166 def get_accepts_rsp(self) -> bool:
1167 return False
1168
1169 def get_lib_prefix(self) -> str:
1170 return '-l='
1171
1172 def get_std_shared_lib_args(self) -> T.List[str]:
1173 return []
1174
1175 def get_output_args(self, outputname: str) -> T.List[str]:
1176 return ['-z', f'--output_file={outputname}']
1177
1178 def get_search_args(self, dirname: str) -> 'T.NoReturn':
1179 raise OSError('TI compilers do not have a search dir argument')
1180
1181 def get_allow_undefined_args(self) -> T.List[str]:
1182 return []
1183
1184 def get_always_args(self) -> T.List[str]:
1185 return []
1186
1187
1188 class C2000DynamicLinker(TIDynamicLinker):
1189 # Required for backwards compat with projects created before ti-cgt support existed
1190 id = 'cl2000'
1191
1192 class C6000DynamicLinker(TIDynamicLinker):
1193 id = 'cl6000'
1194
1195
1196 class ArmDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
1197
1198 """Linker for the ARM compiler."""
1199
1200 id = 'armlink'
1201
1202 def __init__(self, for_machine: mesonlib.MachineChoice,
1203 *, version: str = 'unknown version'):
1204 super().__init__(['armlink'], for_machine, '', [],
1205 version=version)
1206
1207 def get_accepts_rsp(self) -> bool:
1208 return False
1209
1210 def get_std_shared_lib_args(self) -> 'T.NoReturn':
1211 raise MesonException('The Arm Linkers do not support shared libraries')
1212
1213 def get_allow_undefined_args(self) -> T.List[str]:
1214 return []
1215
1216
1217 class ArmClangDynamicLinker(ArmDynamicLinker):
1218
1219 """Linker used with ARM's clang fork.
1220
1221 The interface is similar enough to the old ARM ld that it inherits and
1222 extends a few things as needed.
1223 """
1224
1225 def export_dynamic_args(self, env: 'Environment') -> T.List[str]:
1226 return ['--export_dynamic']
1227
1228 def import_library_args(self, implibname: str) -> T.List[str]:
1229 return ['--symdefs=' + implibname]
1230
1231 class QualcommLLVMDynamicLinker(LLVMDynamicLinker):
1232
1233 """ARM Linker from Snapdragon LLVM ARM Compiler."""
1234
1235 id = 'ld.qcld'
1236
1237 class ELDDynamicLinker(GnuLikeDynamicLinkerMixin, PosixDynamicLinkerMixin, DynamicLinker):
1238
1239 """Qualcomm's opensource embedded linker"""
1240
1241 id = 'ld.eld'
1242
1243
1244 class NAGDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
1245
1246 """NAG Fortran linker, ld via gcc indirection.
1247
1248 Using nagfor -Wl,foo passes option foo to a backend gcc invocation.
1249 (This linking gathers the correct objects needed from the nagfor runtime
1250 system.)
1251 To pass gcc -Wl,foo options (i.e., to ld) one must apply indirection
1252 again: nagfor -Wl,-Wl,,foo
1253 """
1254
1255 id = 'nag'
1256
1257 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
1258 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
1259 rpath_paths = target.determine_rpath_dirs()
1260 if not rpath_paths and not target.install_rpath and not target.build_rpath and not extra_paths:
1261 return ([], set())
1262 args: T.List[str] = []
1263 origin_placeholder = '$ORIGIN'
1264 processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir)
1265 all_paths = mesonlib.OrderedSet([os.path.join(origin_placeholder, p) for p in processed_rpaths])
1266 if target.build_rpath != '':
1267 all_paths.add(target.build_rpath)
1268 if extra_paths:
1269 all_paths.update(extra_paths)
1270 for rp in all_paths:
1271 args.extend(self._apply_prefix('-Wl,-Wl,,-rpath,,' + rp))
1272
1273 return (args, set())
1274
1275 def get_allow_undefined_args(self) -> T.List[str]:
1276 return []
1277
1278 def get_std_shared_lib_args(self) -> T.List[str]:
1279 from ..compilers.fortran import NAGFortranCompiler
1280 return NAGFortranCompiler.get_nagfor_quiet(self.version) + ['-Wl,-shared']
1281
1282
1283 class PGIDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
1284
1285 """PGI linker."""
1286
1287 id = 'pgi'
1288
1289 def get_allow_undefined_args(self) -> T.List[str]:
1290 return []
1291
1292 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1293 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1294 return []
1295
1296 def get_std_shared_lib_args(self) -> T.List[str]:
1297 # PGI -shared is Linux only.
1298 if mesonlib.is_windows():
1299 return ['-Bdynamic', '-Mmakedll']
1300 elif mesonlib.is_linux():
1301 return ['-shared']
1302 return []
1303
1304 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
1305 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
1306 if not env.machines[self.for_machine].is_windows():
1307 rpath_paths = target.determine_rpath_dirs()
1308 return (['-R' + os.path.join(build_dir, p) for p in rpath_paths], set())
1309 return ([], set())
1310
1311 NvidiaHPC_DynamicLinker = PGIDynamicLinker
1312
1313
1314 class PGIStaticLinker(StaticLinker):
1315 def __init__(self, exelist: T.List[str]):
1316 super().__init__(exelist)
1317 self.id = 'ar'
1318 self.std_args = ['-r']
1319
1320 def get_std_link_args(self, env: 'Environment', is_thin: bool) -> T.List[str]:
1321 return self.std_args
1322
1323 def get_output_args(self, target: str) -> T.List[str]:
1324 return [target]
1325
1326 NvidiaHPC_StaticLinker = PGIStaticLinker
1327
1328
1329 class VisualStudioLikeLinkerMixin(DynamicLinkerBase):
1330
1331 """Mixin class for dynamic linkers that act like Microsoft's link.exe."""
1332
1333 if T.TYPE_CHECKING:
1334 for_machine = MachineChoice.HOST
1335 def _apply_prefix(self, arg: T.Union[str, T.List[str]]) -> T.List[str]: ...
1336
1337 _OPTIMIZATION_ARGS: T.Dict[str, T.List[str]] = {
1338 'plain': [],
1339 '0': [],
1340 'g': [],
1341 '1': [],
1342 '2': [],
1343 # The otherwise implicit REF and ICF linker optimisations are disabled by
1344 # /DEBUG. REF implies ICF.
1345 '3': ['/OPT:REF'],
1346 's': ['/INCREMENTAL:NO', '/OPT:REF'],
1347 }
1348
1349 def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice,
1350 prefix_arg: T.Union[str, T.List[str]], always_args: T.List[str], *,
1351 version: str = 'unknown version', direct: bool = True, machine: str = 'x86',
1352 rsp_syntax: RSPFileSyntax = RSPFileSyntax.MSVC):
1353 # There's no way I can find to make mypy understand what's going on here
1354 super().__init__(exelist, for_machine, prefix_arg, always_args, version=version)
1355 self.machine = machine
1356 self.direct = direct
1357 self.rsp_syntax = rsp_syntax
1358
1359 def invoked_by_compiler(self) -> bool:
1360 return not self.direct
1361
1362 def get_output_args(self, outputname: str) -> T.List[str]:
1363 return self._apply_prefix(['/MACHINE:' + self.machine, '/OUT:' + outputname])
1364
1365 def get_always_args(self) -> T.List[str]:
1366 parent = super().get_always_args()
1367 return self._apply_prefix('/nologo') + parent
1368
1369 def get_search_args(self, dirname: str) -> T.List[str]:
1370 return self._apply_prefix('/LIBPATH:' + dirname)
1371
1372 def get_std_shared_lib_args(self) -> T.List[str]:
1373 return self._apply_prefix('/DLL')
1374
1375 def get_debugfile_name(self, targetfile: str) -> str:
1376 return targetfile
1377
1378 def get_debugfile_args(self, targetfile: str) -> T.List[str]:
1379 return self._apply_prefix(['/DEBUG', '/PDB:' + self.get_debugfile_name(targetfile)])
1380
1381 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1382 # Only since VS2015
1383 args = mesonlib.listify(args)
1384 l: T.List[str] = []
1385 for a in args:
1386 l.extend(self._apply_prefix('/WHOLEARCHIVE:' + a))
1387 return l
1388
1389 def get_allow_undefined_args(self) -> T.List[str]:
1390 return []
1391
1392 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1393 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1394 return []
1395
1396 def import_library_args(self, implibname: str) -> T.List[str]:
1397 """The command to generate the import library."""
1398 return self._apply_prefix(['/IMPLIB:' + implibname])
1399
1400 def rsp_file_syntax(self) -> RSPFileSyntax:
1401 return self.rsp_syntax
1402
1403 def get_pie_args(self) -> T.List[str]:
1404 return []
1405
1406
1407 class MSVCDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
1408
1409 """Microsoft's Link.exe."""
1410
1411 id = 'link'
1412
1413 def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *,
1414 exelist: T.Optional[T.List[str]] = None,
1415 prefix: T.Union[str, T.List[str]] = '',
1416 machine: str = 'x86', version: str = 'unknown version',
1417 direct: bool = True, rsp_syntax: RSPFileSyntax = RSPFileSyntax.MSVC):
1418 super().__init__(exelist or ['link.exe'], for_machine,
1419 prefix, always_args, machine=machine, version=version, direct=direct,
1420 rsp_syntax=rsp_syntax)
1421
1422 def get_always_args(self) -> T.List[str]:
1423 return self._apply_prefix(['/release']) + super().get_always_args()
1424
1425 def get_win_subsystem_args(self, value: str) -> T.List[str]:
1426 return self._apply_prefix([f'/SUBSYSTEM:{value.upper()}'])
1427
1428 def fatal_warnings(self) -> T.List[str]:
1429 return ['-WX']
1430
1431
1432 class ClangClDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
1433
1434 """Clang's lld-link.exe."""
1435
1436 id = 'lld-link'
1437
1438 def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *,
1439 exelist: T.Optional[T.List[str]] = None,
1440 prefix: T.Union[str, T.List[str]] = '',
1441 machine: str = 'x86', version: str = 'unknown version',
1442 direct: bool = True, rsp_syntax: RSPFileSyntax = RSPFileSyntax.MSVC):
1443 super().__init__(exelist or ['lld-link.exe'], for_machine,
1444 prefix, always_args, machine=machine, version=version, direct=direct,
1445 rsp_syntax=rsp_syntax)
1446
1447 def get_output_args(self, outputname: str) -> T.List[str]:
1448 # If we're being driven indirectly by clang just skip /MACHINE
1449 # as clang's target triple will handle the machine selection
1450 if self.machine is None:
1451 return self._apply_prefix([f"/OUT:{outputname}"])
1452
1453 return super().get_output_args(outputname)
1454
1455 def get_win_subsystem_args(self, value: str) -> T.List[str]:
1456 return self._apply_prefix([f'/SUBSYSTEM:{value.upper()}'])
1457
1458 def get_thinlto_cache_args(self, path: str) -> T.List[str]:
1459 return ["/lldltocache:" + path]
1460
1461 def fatal_warnings(self) -> T.List[str]:
1462 return ['-WX']
1463
1464
1465 class XilinkDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
1466
1467 """Intel's Xilink.exe."""
1468
1469 id = 'xilink'
1470
1471 def __init__(self, for_machine: mesonlib.MachineChoice, always_args: T.List[str], *,
1472 exelist: T.Optional[T.List[str]] = None,
1473 prefix: T.Union[str, T.List[str]] = '',
1474 machine: str = 'x86', version: str = 'unknown version',
1475 direct: bool = True):
1476 super().__init__(['xilink.exe'], for_machine, '', always_args, version=version)
1477
1478 def get_win_subsystem_args(self, value: str) -> T.List[str]:
1479 return self._apply_prefix([f'/SUBSYSTEM:{value.upper()}'])
1480
1481
1482 class SolarisDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
1483
1484 """Sys-V derived linker used on Solaris and OpenSolaris."""
1485
1486 id = 'ld.solaris'
1487
1488 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1489 if not args:
1490 return args
1491 return self._apply_prefix('--whole-archive') + args + self._apply_prefix('--no-whole-archive')
1492
1493 def get_pie_args(self) -> T.List[str]:
1494 # Available in Solaris 11.2 and later
1495 pc, stdo, stde = mesonlib.Popen_safe(self.exelist + self._apply_prefix('-zhelp'))
1496 for line in (stdo + stde).split('\n'):
1497 if '-z type' in line:
1498 if 'pie' in line:
1499 return ['-z', 'type=pie']
1500 break
1501 return []
1502
1503 def get_asneeded_args(self) -> T.List[str]:
1504 return self._apply_prefix(['-z', 'ignore'])
1505
1506 def no_undefined_args(self) -> T.List[str]:
1507 return ['-z', 'defs']
1508
1509 def get_allow_undefined_args(self) -> T.List[str]:
1510 return ['-z', 'nodefs']
1511
1512 def fatal_warnings(self) -> T.List[str]:
1513 return ['-z', 'fatal-warnings']
1514
1515 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
1516 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
1517 rpath_paths = target.determine_rpath_dirs()
1518 if not rpath_paths and not target.install_rpath and not target.build_rpath and not extra_paths:
1519 return ([], set())
1520 processed_rpaths = prepare_rpaths(rpath_paths, build_dir, from_dir)
1521 all_paths = mesonlib.OrderedSet([os.path.join('$ORIGIN', p) for p in processed_rpaths])
1522 rpath_dirs_to_remove: T.Set[bytes] = set()
1523 for p in all_paths:
1524 rpath_dirs_to_remove.add(p.encode('utf8'))
1525 if target.build_rpath != '':
1526 all_paths.add(target.build_rpath)
1527 for p in target.build_rpath.split(':'):
1528 rpath_dirs_to_remove.add(p.encode('utf8'))
1529 if extra_paths:
1530 all_paths.update(extra_paths)
1531
1532 # In order to avoid relinking for RPATH removal, the binary needs to contain just
1533 # enough space in the ELF header to hold the final installation RPATH.
1534 paths = ':'.join(all_paths)
1535 paths_length = len(paths.encode('utf-8'))
1536 install_rpath_length = len(target.install_rpath.encode('utf-8'))
1537 if paths_length < install_rpath_length:
1538 padding = 'X' * (install_rpath_length - paths_length)
1539 if not paths:
1540 paths = padding
1541 else:
1542 paths = paths + ':' + padding
1543 return (self._apply_prefix(f'-rpath,{paths}'), rpath_dirs_to_remove)
1544
1545 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1546 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1547 sostr = '' if soversion is None else '.' + soversion
1548 return self._apply_prefix(f'-soname,{prefix}{shlib_name}.{suffix}{sostr}')
1549
1550
1551 class AIXDynamicLinker(PosixDynamicLinkerMixin, DynamicLinker):
1552
1553 """Sys-V derived linker used on AIX"""
1554
1555 id = 'ld.aix'
1556
1557 def get_always_args(self) -> T.List[str]:
1558 return self._apply_prefix(['-bnoipath', '-bbigtoc']) + super().get_always_args()
1559
1560 def no_undefined_args(self) -> T.List[str]:
1561 return self._apply_prefix(['-bernotok'])
1562
1563 def get_allow_undefined_args(self) -> T.List[str]:
1564 return self._apply_prefix(['-berok'])
1565
1566 def get_archive_name(self, filename: str) -> str:
1567 # In AIX we allow the shared library name to have the lt_version and so_version.
1568 # But the archive name must just be .a .
1569 # For Example shared object can have the name libgio.so.0.7200.1 but the archive
1570 # must have the name libgio.a having libgio.a (libgio.so.0.7200.1) in the
1571 # archive. This regular expression is to do the same.
1572 filename = re.sub('[.][a]([.]?([0-9]+))*([.]?([a-z]+))*', '.a', filename.replace('.so', '.a'))
1573 return filename
1574
1575 def get_command_to_archive_shlib(self) -> T.List[str]:
1576 # Archive shared library object and remove the shared library object,
1577 # since it already exists in the archive.
1578 command = ['ar', '-r', '-s', '-v', '$out', '$in', '&&', 'rm', '-f', '$in']
1579 return command
1580
1581 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1582 # AIX's linker always links the whole archive: "The ld command
1583 # processes all input files in the same manner, whether they are
1584 # archives or not."
1585 return args
1586
1587 def build_rpath_args(self, env: Environment, build_dir: str, from_dir: str,
1588 target: BuildTarget, extra_paths: T.Optional[T.List[str]] = None) -> T.Tuple[T.List[str], T.Set[bytes]]:
1589 all_paths: mesonlib.OrderedSet[str] = mesonlib.OrderedSet()
1590 # install_rpath first, followed by other paths, and the system path last
1591 if target.install_rpath != '':
1592 all_paths.add(target.install_rpath)
1593 if target.build_rpath != '':
1594 all_paths.add(target.build_rpath)
1595 for p in target.determine_rpath_dirs():
1596 all_paths.add(os.path.join(build_dir, p))
1597 # We should consider allowing the $LIBPATH environment variable
1598 # to override sys_path.
1599 sys_path = env.get_compiler_system_lib_dirs(self.for_machine)
1600 if len(sys_path) == 0:
1601 # get_compiler_system_lib_dirs doesn't support our compiler.
1602 # Use the default system library path
1603 all_paths.update(['/usr/lib', '/lib'])
1604 else:
1605 # Include the compiler's default library paths, but filter out paths that don't exist
1606 for p in sys_path:
1607 if os.path.isdir(p):
1608 all_paths.add(p)
1609 if extra_paths:
1610 all_paths.update(extra_paths)
1611 return (self._apply_prefix('-blibpath:' + ':'.join(all_paths)), set())
1612
1613 def thread_flags(self, env: 'Environment') -> T.List[str]:
1614 return ['-pthread']
1615
1616
1617 class OptlinkDynamicLinker(VisualStudioLikeLinkerMixin, DynamicLinker):
1618
1619 """Digital Mars dynamic linker for windows."""
1620
1621 id = 'optlink'
1622
1623 def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice,
1624 *, version: str = 'unknown version'):
1625 # Use optlink instead of link so we don't interfere with other link.exe
1626 # implementations.
1627 super().__init__(exelist, for_machine, '', [], version=version)
1628
1629 def get_allow_undefined_args(self) -> T.List[str]:
1630 return []
1631
1632 def get_debugfile_args(self, targetfile: str) -> T.List[str]:
1633 # Optlink does not generate pdb files.
1634 return []
1635
1636 def get_always_args(self) -> T.List[str]:
1637 return []
1638
1639
1640 class CudaLinker(PosixDynamicLinkerMixin, DynamicLinker):
1641 """Cuda linker (nvlink)"""
1642
1643 id = 'nvlink'
1644
1645 @staticmethod
1646 def parse_version() -> str:
1647 version_cmd = ['nvlink', '--version']
1648 try:
1649 _, out, _ = mesonlib.Popen_safe(version_cmd)
1650 except OSError:
1651 return 'unknown version'
1652 # Output example:
1653 # nvlink: NVIDIA (R) Cuda linker
1654 # Copyright (c) 2005-2018 NVIDIA Corporation
1655 # Built on Sun_Sep_30_21:09:22_CDT_2018
1656 # Cuda compilation tools, release 10.0, V10.0.166
1657 # we need the most verbose version output. Luckily starting with V
1658 return out.strip().rsplit('V', maxsplit=1)[-1]
1659
1660 def get_accepts_rsp(self) -> bool:
1661 # nvcc does not support response files
1662 return False
1663
1664 def get_lib_prefix(self) -> str:
1665 # nvcc doesn't recognize Meson's default .a extension for static libraries on
1666 # Windows and passes it to cl as an object file, resulting in 'warning D9024 :
1667 # unrecognized source file type 'xxx.a', object file assumed'.
1668 #
1669 # nvcc's --library= option doesn't help: it takes the library name without the
1670 # extension and assumes that the extension on Windows is .lib; prefixing the
1671 # library with -Xlinker= seems to work.
1672 #
1673 # On Linux, we have to use rely on -Xlinker= too, since nvcc/nvlink chokes on
1674 # versioned shared libraries:
1675 #
1676 # nvcc fatal : Don't know what to do with 'subprojects/foo/libbar.so.0.1.2'
1677 #
1678 from ..compilers.cuda import CudaCompiler
1679 return CudaCompiler.LINKER_PREFIX
1680
1681 def fatal_warnings(self) -> T.List[str]:
1682 return ['--warning-as-error']
1683
1684 def get_allow_undefined_args(self) -> T.List[str]:
1685 return []
1686
1687 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1688 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1689 return []
1690
1691
1692 class MetrowerksLinker(DynamicLinker):
1693
1694 def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice,
1695 *, version: str = 'unknown version'):
1696 super().__init__(exelist, for_machine, '', [],
1697 version=version)
1698
1699 def fatal_warnings(self) -> T.List[str]:
1700 return ['-w', 'error']
1701
1702 def get_allow_undefined_args(self) -> T.List[str]:
1703 return []
1704
1705 def get_accepts_rsp(self) -> bool:
1706 return True
1707
1708 def get_linker_always_args(self) -> T.List[str]:
1709 return []
1710
1711 def get_output_args(self, outputname: str) -> T.List[str]:
1712 return ['-o', outputname]
1713
1714 def get_search_args(self, dirname: str) -> T.List[str]:
1715 return self._apply_prefix('-L' + dirname)
1716
1717 def invoked_by_compiler(self) -> bool:
1718 return False
1719
1720 def get_soname_args(self, env: 'Environment', prefix: str, shlib_name: str,
1721 suffix: str, soversion: str, darwin_versions: T.Tuple[str, str]) -> T.List[str]:
1722 raise MesonException(f'{self.id} does not support shared libraries.')
1723
1724
1725 class MetrowerksLinkerARM(MetrowerksLinker):
1726 id = 'mwldarm'
1727
1728
1729 class MetrowerksLinkerEmbeddedPowerPC(MetrowerksLinker):
1730 id = 'mwldeppc'
1731
1732 class TaskingLinker(DynamicLinker):
1733 id = 'tasking'
1734
1735 _OPTIMIZATION_ARGS: T.Dict[str, T.List[str]] = {
1736 'plain': [],
1737 '0': ['-O0'],
1738 'g': ['-O1'], # There is no debug specific level, O1 is recommended by the compiler
1739 '1': ['-O1'],
1740 '2': ['-O2'],
1741 '3': ['-O2'], # There is no 3rd level optimization for the linker
1742 's': ['-Os'],
1743 }
1744
1745 def __init__(self, exelist: T.List[str], for_machine: mesonlib.MachineChoice,
1746 *, version: str = 'unknown version'):
1747 super().__init__(exelist, for_machine, '', [],
1748 version=version)
1749
1750 def get_accepts_rsp(self) -> bool:
1751 return True
1752
1753 def get_lib_prefix(self) -> str:
1754 return ""
1755
1756 def get_allow_undefined_args(self) -> T.List[str]:
1757 return []
1758
1759 def invoked_by_compiler(self) -> bool:
1760 return True
1761
1762 def get_search_args(self, dirname: str) -> T.List[str]:
1763 return self._apply_prefix('-L' + dirname)
1764
1765 def get_output_args(self, outputname: str) -> T.List[str]:
1766 return ['-o', outputname]
1767
1768 def get_lto_args(self) -> T.List[str]:
1769 return ['--mil-link']
1770
1771 def rsp_file_syntax(self) -> RSPFileSyntax:
1772 return RSPFileSyntax.TASKING
1773
1774 def fatal_warnings(self) -> T.List[str]:
1775 """Arguments to make all warnings errors."""
1776 return self._apply_prefix('--warnings-as-errors')
1777
1778 def get_link_whole_for(self, args: T.List[str]) -> T.List[str]:
1779 args = mesonlib.listify(args)
1780 l: T.List[str] = []
1781 for a in args:
1782 l.extend(self._apply_prefix('-Wl--whole-archive=' + a))
1783 return l