Debian Codegraph @

mesonbuild/build.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2017 The Meson development team
3
4 from __future__ import annotations
5 from collections import defaultdict, deque, OrderedDict
6 from dataclasses import dataclass, field
7 from functools import lru_cache
8 import abc
9 import copy
10 import hashlib
11 import itertools, pathlib
12 import os
13 import pickle
14 import re
15 import textwrap
16 import typing as T
17
18 from . import coredata
19 from . import dependencies
20 from . import mlog
21 from . import programs
22 from .environment import MachineMap
23 from .mesonlib import (
24 HoldableObject, SecondLevelHolder, SimpleABC, SubProject,
25 File, MesonException, MachineChoice, ThreeMachineChoice, PerMachine,
26 OrderedSet, classify_unity_sources, ROOT_SUBPROJECT,
27 get_filenames_templates_dict, substitute_values, has_path_sep,
28 is_parent_path, relpath, PerMachineDefaultable,
29 MesonBugException, EnvironmentVariables, pickle_load, lazy_property,
30 unwrap,
31 )
32 from .options import OptionKey
33
34 from .compilers import (
35 is_header, is_object, is_source, clink_langs, sort_clink,
36 is_known_suffix, detect_static_linker, LANGUAGES_USING_LDFLAGS,
37 get_base_compile_args
38 )
39 from .interpreterbase import FeatureNew, FeatureDeprecated
40
41 if T.TYPE_CHECKING:
42 from typing_extensions import Literal, Self, TypeAlias, TypedDict
43
44 from .arglist import CompilerArgs
45 from .environment import Environment
46 from ._typing import ImmutableListProtocol
47 from .backend.backends import Backend
48 from .compilers.compilers import Compiler, CompilerDict, Language
49 from .compilers.rust import RustCompiler
50 from .interpreter.interpreter import CustomTargetSources, SourceOutputs, Interpreter
51 from .interpreter.interpreterobjects import Test, Doctest
52 from .interpreter.kwargs import TargetDepends
53 from .linkers import StaticLinker
54 from .mesonlib import ExecutableSerialisation, FileMode, FileOrString, InstallScript
55 from .mparser import BaseNode
56 from .options import ElementaryOptionValues
57
58 TargetSources: TypeAlias = T.Union['File', 'GeneratedTypes']
59 CommandTypes: TypeAlias = T.Union['programs.Program', 'BuildTargetTypes', File, str]
60 GeneratedTypes: TypeAlias = T.Union['CustomTarget', 'CustomTargetIndex', 'GeneratedList']
61 LibTypes: TypeAlias = T.Union['SharedLibrary', 'StaticLibrary', 'CustomTarget', 'CustomTargetIndex']
62 LinkableTargetTypes: TypeAlias = T.Union['SharedLibrary', 'StaticLibrary', 'CustomTarget', 'CustomTargetIndex', 'Executable']
63 BuildTargetTypes: TypeAlias = T.Union['BuildTarget', 'CustomTarget', 'CustomTargetIndex']
64 StaticTargetTypes: TypeAlias = T.Union['StaticLibrary', 'CustomTarget', 'CustomTargetIndex']
65 ObjectTypes: TypeAlias = T.Union['File', 'ExtractedObjects']
66 AnyTargetType: TypeAlias = T.Union['Target', 'CustomTargetIndex']
67 RustCrateType: TypeAlias = Literal['bin', 'lib', 'rlib', 'dylib', 'cdylib', 'staticlib', 'proc-macro']
68 _LibraryType: TypeAlias = Literal['auto', 'shared', 'static']
69
70 class DFeatures(TypedDict):
71
72 unittest: bool
73 debug: T.List[T.Union[str, int]]
74 import_dirs: T.List[IncludeDirs]
75 versions: T.List[T.Union[str, int]]
76
77 class BuildTargetKeywordArguments(TypedDict, total=False):
78
79 # The use of Sequence[str] here is intentional to get the generally
80 # undesirable behavior of Sequence[str]
81
82 build_by_default: bool
83 build_rpath: str
84 build_subdir: T.Optional[str]
85 c_pch: T.Optional[T.Tuple[str, T.Optional[str]]]
86 cpp_pch: T.Optional[T.Tuple[str, T.Optional[str]]]
87 d_debug: T.List[T.Union[str, int]]
88 d_import_dirs: T.List[IncludeDirs]
89 d_module_versions: T.List[T.Union[str, int]]
90 d_unittest: bool
91 dependencies: T.List[dependencies.Dependency]
92 depend_files: T.List[File]
93 extra_files: T.List[File]
94 gnu_symbol_visibility: Literal['default', 'internal', 'hidden', 'protected', 'inlineshidden', '']
95 implicit_include_directories: bool
96 include_directories: T.List[IncludeDirs]
97 install: bool
98 install_dir: T.List[T.Union[str, bool]]
99 install_mode: FileMode
100 install_rpath: str
101 install_tag: T.List[T.Optional[str]]
102 language_args: T.DefaultDict[Language, T.List[str]]
103 link_args: T.List[str]
104 link_early_args: T.List[str]
105 link_depends: T.List[T.Union[File, BuildTargetTypes]]
106 link_language: Language
107 link_whole: T.List[StaticTargetTypes]
108 link_with: T.List[LinkableTargetTypes]
109 name_prefix: T.Optional[str]
110 name_suffix: T.Optional[str]
111 native: MachineChoice
112 override_options: T.Dict[str, ElementaryOptionValues]
113 resources: T.List[str]
114 swift_interoperability_mode: Literal['c', 'cpp']
115 swift_module_name: str
116 rust_crate_type: RustCrateType
117 rust_dependency_map: T.Dict[str, str]
118 vala_gir: T.Optional[str]
119 install_vala_gir: bool
120 install_vala_gir_dir: T.Optional[str]
121 vala_header: T.Optional[str]
122 install_vala_header: bool
123 install_vala_header_dir: T.Optional[str]
124 vala_vapi: T.Optional[str]
125 install_vala_vapi: bool
126 install_vala_vapi_dir: T.Optional[str]
127
128 _allow_no_sources: bool
129
130 class ExecutableKeywordArguments(BuildTargetKeywordArguments, total=False):
131
132 android_exe_type: T.Optional[Literal['application', 'executable']]
133 implib: T.Optional[str]
134 export_dynamic: bool
135 pie: bool
136 vs_module_defs: T.Union[File, CustomTarget, CustomTargetIndex]
137 win_subsystem: str
138
139 class SharedModuleKeywordArguments(BuildTargetKeywordArguments, total=False):
140
141 vs_module_defs: T.Union[File, CustomTarget, CustomTargetIndex]
142 win_subsystem: str
143
144 class SharedLibraryKeywordArguments(SharedModuleKeywordArguments, total=False):
145
146 version: str
147 soversion: str
148 darwin_versions: T.Tuple[str, str]
149 shortname: str
150
151 class StaticLibraryKeywordArguments(BuildTargetKeywordArguments, total=False):
152
153 pic: bool
154 prelink: bool
155
156 class JarKeywordArguments(BuildTargetKeywordArguments, total=False):
157
158 java_args: T.List[str]
159 java_resources: T.Optional[StructuredSources]
160 main_class: str
161
162
163 _T = T.TypeVar('_T')
164
165 DEFAULT_STATIC_LIBRARY_NAMES: T.Mapping[str, T.Tuple[str, str]] = {
166 'unix': ('lib', 'a'),
167 'windows': ('', 'lib'),
168 'darwin': ('lib', 'a'),
169 'cygwin': ('lib', 'a'),
170 }
171
172 DEFAULT_SHARED_LIBRARY_NAMES: T.Mapping[str, T.Tuple[str, str, str]] = {
173 'unix': ('lib', 'so', ''),
174 'windows': ('', 'dll', 'dll.lib'),
175 'darwin': ('lib', 'dylib', ''),
176 'cygwin': ('cyg', 'dll', 'dll.a'),
177 }
178
179 def _process_install_tag(install_tag: T.Optional[T.List[T.Optional[str]]],
180 num_outputs: int) -> T.List[T.Optional[str]]:
181 _install_tag: T.List[T.Optional[str]]
182 if not install_tag:
183 _install_tag = [None] * num_outputs
184 elif len(install_tag) == 1:
185 _install_tag = install_tag * num_outputs
186 else:
187 _install_tag = install_tag
188 return _install_tag
189
190
191 @lru_cache(maxsize=None)
192 def get_target_macos_dylib_install_name(ld: SharedLibrary) -> str:
193 name = ['@rpath/', ld.prefix, ld.name]
194 if ld.soversion is not None:
195 name.append('.' + ld.soversion)
196 name.append('.dylib')
197 return ''.join(name)
198
199
200 class InvalidArguments(MesonException):
201 pass
202
203 @dataclass(eq=False)
204 class DependencyOverride(HoldableObject):
205 dep: dependencies.Dependency
206 node: 'BaseNode'
207 explicit: bool = True
208
209 @dataclass(eq=False)
210 class Headers(HoldableObject):
211 sources: T.List[File]
212 install_subdir: T.Optional[str]
213 custom_install_dir: T.Optional[str]
214 custom_install_mode: 'FileMode'
215 subproject: SubProject
216 follow_symlinks: T.Optional[bool] = None
217 install_tag: T.Optional[str] = None
218
219 def __post_init__(self) -> None:
220 if self.install_tag is None:
221 self.install_tag = 'devel'
222
223 # TODO: we really don't need any of these methods, but they're preserved to
224 # keep APIs relying on them working.
225
226 def set_install_subdir(self, subdir: str) -> None:
227 self.install_subdir = subdir
228
229 def get_install_subdir(self) -> T.Optional[str]:
230 return self.install_subdir
231
232 def get_sources(self) -> T.List[File]:
233 return self.sources
234
235 def get_custom_install_dir(self) -> T.Optional[str]:
236 return self.custom_install_dir
237
238 def get_custom_install_mode(self) -> 'FileMode':
239 return self.custom_install_mode
240
241
242 @dataclass(eq=False)
243 class Man(HoldableObject):
244 sources: T.List[File]
245 custom_install_dir: T.Optional[str]
246 custom_install_mode: 'FileMode'
247 subproject: SubProject
248 locale: T.Optional[str]
249 install_tag: T.Optional[str] = None
250
251 def get_custom_install_dir(self) -> T.Optional[str]:
252 return self.custom_install_dir
253
254 def get_custom_install_mode(self) -> 'FileMode':
255 return self.custom_install_mode
256
257 def get_sources(self) -> T.List['File']:
258 return self.sources
259
260
261 @dataclass(eq=False)
262 class EmptyDir(HoldableObject):
263 path: str
264 install_mode: 'FileMode'
265 subproject: SubProject
266 install_tag: T.Optional[str] = None
267
268
269 @dataclass(eq=False)
270 class InstallDir(HoldableObject):
271 source_subdir: str
272 installable_subdir: str
273 install_dir: str
274 install_dir_name: str
275 install_mode: 'FileMode'
276 exclude: T.Tuple[T.Set[str], T.Set[str]]
277 strip_directory: bool
278 subproject: SubProject
279 from_source_dir: bool = True
280 install_tag: T.Optional[str] = None
281 follow_symlinks: T.Optional[bool] = None
282
283 @dataclass(eq=False)
284 class DepManifest:
285 version: str
286 license: T.List[str]
287 license_files: T.List[T.Tuple[str, File]]
288 subproject: SubProject
289
290 def license_mapping(self) -> T.List[T.Tuple[str, str]]:
291 ret = []
292 for ifilename, name in self.license_files:
293 fname = os.path.join(*(x for x in pathlib.PurePath(os.path.normpath(name.fname)).parts if x != '..'))
294 ret.append((ifilename, os.path.join(name.subdir, fname)))
295 return ret
296
297 def to_json(self) -> T.Dict[str, T.Union[str, T.List[str]]]:
298 return {
299 'version': self.version,
300 'license': self.license,
301 'license_files': [l[1] for l in self.license_mapping()],
302 }
303
304
305 @dataclass(eq=False)
306 class BuildProject:
307 name: str
308 version: str
309 subproject: SubProject
310 # orig_for_machine in BuildProject and BuildTarget is used to choose
311 # between "native: true" and "native: false" global arguments
312 # proj.o_f_m target.o_f_m global arguments used
313 # BUILD HOST BUILD ("native: true")
314 # BUILD BUILD BUILD ("native: true")
315 # HOST HOST HOST ("native: false")
316 # HOST BUILD BUILD ("native: true")
317 orig_for_machine: MachineChoice
318 for_machine: MachineChoice
319 project_args: PerMachine[T.Dict[Language, T.List[str]]] = field(default_factory=lambda: PerMachine({}, {}))
320 project_link_args: PerMachine[T.Dict[Language, T.List[str]]] = field(default_factory=lambda: PerMachine({}, {}))
321
322 @lazy_property
323 def prefix(self) -> str:
324 return 'build.' if self.for_machine is MachineChoice.BUILD else ''
325
326
327 # literally everything isn't dataclass stuff
328 class Build:
329 """A class that holds the status of one build including
330 all dependencies and so on.
331 """
332
333 def __init__(self, environment: Environment):
334 self.for_machine = MachineChoice.HOST
335 self.version = coredata.version
336 self._def_files: T.Optional[T.List[str]] = None
337 self.project_name = 'name of master project'
338 self.project_version: T.Optional[str] = None
339 self.environment = environment
340 self.projects: PerMachine[T.Dict[SubProject, BuildProject]] = PerMachine({}, {})
341 self.targets: dict[str, Target] = {}
342 self.targetnames: T.Set[T.Tuple[str, str]] = set() # Set of executable names and their subdir
343 self.global_args: PerMachine[T.Dict[Language, T.List[str]]] = PerMachine({}, {})
344 self.global_link_args: PerMachine[T.Dict[Language, T.List[str]]] = PerMachine({}, {})
345 self.tests: T.List['Test'] = []
346 self.benchmarks: T.List['Test'] = []
347 self.headers: T.List[Headers] = []
348 self.man: T.List[Man] = []
349 self.emptydir: T.List[EmptyDir] = []
350 self.data: T.List[Data] = []
351 self.symlinks: T.List[SymlinkData] = []
352 self.static_linker: PerMachine[T.Optional[StaticLinker]] = PerMachine(None, None)
353 self.subproject_dir = ''
354 self.install_scripts: T.List[InstallScript] = []
355 self.postconf_scripts: T.List['ExecutableSerialisation'] = []
356 self.dist_scripts: T.List['ExecutableSerialisation'] = []
357 self.install_dirs: T.List[InstallDir] = []
358 self.dep_manifest_name: T.Optional[str] = None
359 self.dep_manifest: T.Dict[str, DepManifest] = {}
360 self.test_setups: T.Dict[str, TestSetup] = {}
361 self.test_setup_default_name: str | None = None
362 self.find_overrides: PerMachine[T.Dict[str, programs.Program]] = PerMachineDefaultable.default(
363 environment.is_cross_build(), {}, {})
364 # The list of all programs that have been searched for.
365 self.searched_programs: PerMachine[T.Set[str]] = PerMachineDefaultable.default(
366 environment.is_cross_build(), set(), set())
367
368 # If we are doing a cross build we need two caches, if we're doing a
369 # build == host compilation the both caches should point to the same place.
370 self.stdlibs: PerMachine[T.Dict[str, dependencies.Dependency]] = PerMachineDefaultable.default(
371 environment.is_cross_build(), {}, {})
372 self.dependency_overrides: PerMachine[T.Dict[T.Tuple, DependencyOverride]] = PerMachineDefaultable.default(
373 environment.is_cross_build(), {}, {})
374
375 self.devenv: T.List[EnvironmentVariables] = []
376 self.machine_map = self.environment.machine_map
377 self.modules: T.Set[str] = set()
378 """Used to track which modules are enabled in all subprojects.
379
380 Needed for tracking whether a modules options needs to be exposed to the user.
381 """
382
383 @property
384 def def_files(self) -> T.List[str]:
385 if self._def_files is None:
386 raise MesonBugException('build.def_files has not been set yet')
387 return self._def_files
388
389 @def_files.setter
390 def def_files(self, value: T.List[str]) -> None:
391 if self._def_files is not None:
392 raise MesonBugException('build.def_files already set')
393 self._def_files = value
394
395 def get_build_targets(self) -> OrderedDict[str, BuildTarget]:
396 build_targets = OrderedDict()
397 for name, t in self.targets.items():
398 if isinstance(t, BuildTarget):
399 build_targets[name] = t
400 return build_targets
401
402 def get_custom_targets(self) -> OrderedDict[str, CustomTarget]:
403 custom_targets = OrderedDict()
404 for name, t in self.targets.items():
405 if isinstance(t, CustomTarget):
406 custom_targets[name] = t
407 return custom_targets
408
409 def copy(self) -> Build:
410 other = Build.__new__(Build)
411 for k, v in self.__dict__.items():
412 other.__dict__[k] = copy.copy(v)
413 return other
414
415 def copy_for_build_machine(self) -> Build:
416 """Create a build-only copy for build machine subprojects.
417
418 Build-only subprojects run with host==build configuration so that get_compiler(),
419 dependency() etc. look up the native (non-cross) environments. However, note
420 that the environment is still a cross one so that the build-machine options,
421 dependencies, etc. are looked up.
422 """
423 new = self.copy()
424 new.machine_map = MachineMap(self.machine_map.build, self.machine_map.build,
425 ThreeMachineChoice(self.machine_map.host))
426 new.for_machine = MachineChoice.BUILD
427 return new
428
429 def merge(self, other: Build) -> None:
430 for k, v in other.__dict__.items():
431 # This one is modified for build-only configs, but it is
432 # local. No need to copy it.
433 if k == 'machine_map':
434 continue
435 # These are not modified in subprojects
436 if k in {'global_args', 'global_link_args'}:
437 continue
438
439 if isinstance(v, PerMachine):
440 dest = self.__dict__[k]
441 if dest.host is dest.build:
442 dest.host = v.build
443 elif v.host is not v.build:
444 dest.host = v.host
445 dest.build = v.build
446 else:
447 self.__dict__[k] = v
448
449 def ensure_static_linker(self, compiler: Compiler) -> None:
450 for_machine = self.machine_map[compiler.for_machine]
451 if self.static_linker[for_machine] is None and compiler.needs_static_linker():
452 self.static_linker[for_machine] = detect_static_linker(self.environment, compiler)
453 if self.machine_map.build is self.machine_map.host:
454 self.static_linker.build = self.static_linker.host
455
456 def get_project(self) -> str:
457 return self.projects.host[ROOT_SUBPROJECT].name
458
459 def get_subproject_dir(self) -> str:
460 return self.subproject_dir
461
462 def get_targets(self) -> dict[str, Target]:
463 return self.targets
464
465 def get_tests(self) -> T.List['Test']:
466 return self.tests
467
468 def get_benchmarks(self) -> T.List['Test']:
469 return self.benchmarks
470
471 def get_headers(self) -> T.List['Headers']:
472 return self.headers
473
474 def get_man(self) -> T.List['Man']:
475 return self.man
476
477 def get_data(self) -> T.List['Data']:
478 return self.data
479
480 def get_symlinks(self) -> T.List['SymlinkData']:
481 return self.symlinks
482
483 def get_emptydir(self) -> T.List['EmptyDir']:
484 return self.emptydir
485
486 def get_install_subdirs(self) -> T.List['InstallDir']:
487 return self.install_dirs
488
489 def get_global_args(self, compiler: 'Compiler', target: BuildTarget) -> T.List[str]:
490 # for build-machine subprojects, even "native: false" targets use
491 # the global build-machine arguments (using the host machine would
492 # make no sense when cross compiling)
493 args_machine = MachineChoice.BUILD \
494 if target.build_project.orig_for_machine is MachineChoice.BUILD \
495 else target.orig_for_machine
496
497 d = self.global_args[args_machine]
498 return d.get(compiler.get_language(), [])
499
500 def get_project_args(self, compiler: 'Compiler', target: BuildTarget) -> T.List[str]:
501 d = target.build_project
502 args = d.project_args[target.orig_for_machine]
503 if not args:
504 return []
505 return args.get(compiler.get_language(), [])
506
507 def get_global_link_args(self, compiler: 'Compiler', target: BuildTarget) -> T.List[str]:
508 args_machine = MachineChoice.BUILD \
509 if target.build_project.orig_for_machine is MachineChoice.BUILD \
510 else target.orig_for_machine
511
512 d = self.global_link_args[args_machine]
513 return d.get(compiler.get_language(), [])
514
515 def get_project_link_args(self, compiler: 'Compiler', target: BuildTarget) -> T.List[str]:
516 d = target.build_project
517 link_args = d.project_link_args[target.orig_for_machine]
518 if not link_args:
519 return []
520
521 return link_args.get(compiler.get_language(), [])
522
523 def get_static_linker(self, target: BuildTarget) -> StaticLinker:
524 archiver = self.static_linker[target.for_machine]
525 if archiver is None:
526 raise MesonBugException(f'Required static_linker for {target.for_machine} not found')
527 return archiver
528
529 @dataclass(eq=False)
530 class IncludeDirs(HoldableObject):
531
532 """Internal representation of an include_directories call.
533
534 :param curdir: The directory from which this IncludeDirs is declared
535 :param incdirs: The paths relative to curdir the include
536 :param is_system: Should these be treated as `-isystem` (true) or `-I
537 :param extra_build_dirs: Extra build directories to include
538 """
539
540 curdir: str
541 incdirs: T.List[str]
542 is_system: bool
543 build_project: BuildProject
544 extra_build_dirs: T.List[str] = field(default_factory=list)
545
546 def abs_string_list(self, sourcedir: str, builddir: str) -> T.List[str]:
547 """Convert IncludeDirs object to a list of absolute string paths.
548
549 :param sourcedir: The absolute source directory
550 :param builddir: The absolute build directory, option, build dir will not
551 be added if this is unset
552 :returns: A list of strings (without compiler argument)
553 """
554 bsubdir = self.build_project.prefix + self.curdir
555
556 strlist: T.List[str] = []
557 for idir in self.incdirs:
558 strlist.append(os.path.join(sourcedir, self.curdir, idir))
559 strlist.append(os.path.join(builddir, bsubdir, idir))
560 for idir in self.extra_build_dirs:
561 strlist.append(os.path.join(builddir, bsubdir, idir))
562 return strlist
563
564 def rel_string_list(self, build_to_src: str, build_root: T.Optional[str] = None) -> T.List[str]:
565 """Convert IncludeDirs object to a list of relative string paths.
566
567 :param build_to_src: The relative path from the build dir to source dir
568 :param build_root: The absolute build root. When provided, build
569 directories that have not been created will be ignored. Default: None.
570 :return: A list if strings (without compiler argument)
571 """
572 strlist: T.List[str] = []
573 bsubdir = self.build_project.prefix + self.curdir
574
575 for idirs, add_src in [(self.incdirs, True), (self.extra_build_dirs, False)]:
576 for idir in idirs:
577 bld_dir = os.path.normpath(os.path.join(bsubdir, idir))
578 if build_root is None or os.path.isdir(os.path.join(build_root, bld_dir)):
579 strlist.append(bld_dir)
580 if add_src:
581 strlist.append(os.path.normpath(os.path.join(build_to_src, self.curdir, idir)))
582
583 return strlist
584
585
586 @dataclass(eq=False)
587 class ExtractedObjects(HoldableObject):
588 '''
589 Holds a list of sources for which the objects must be extracted
590 '''
591 target: 'BuildTarget'
592 srclist: T.List[File] = field(default_factory=list)
593 genlist: T.List['GeneratedTypes'] = field(default_factory=list)
594 objlist: T.List[ObjectTypes] = field(default_factory=list)
595 recursive: bool = True
596 pch: bool = False
597
598 def __repr__(self) -> str:
599 r = '<{0} {1!r}: {2}>'
600 return r.format(self.__class__.__name__, self.target.name, self.srclist)
601
602 @staticmethod
603 def get_sources(sources: T.Sequence['File'], generated_sources: T.Sequence['GeneratedTypes']) -> T.List['FileOrString']:
604 # Merge sources and generated sources
605 ret: T.List[FileOrString] = list(sources)
606 for gensrc in generated_sources:
607 for s in gensrc.get_outputs():
608 # We cannot know the path where this source will be generated,
609 # but all we need here is the file extension to determine the
610 # compiler.
611 ret.append(s)
612
613 # Filter out headers and all non-source files
614 return [s for s in ret if is_source(s)]
615
616 def classify_all_sources(self, sources: T.Sequence[File], generated_sources: T.Sequence['GeneratedTypes']) -> T.Dict['Compiler', T.List['FileOrString']]:
617 sources_ = self.get_sources(sources, generated_sources)
618 return classify_unity_sources(self.target.compilers.values(), sources_)
619
620 def check_unity_compatible(self) -> None:
621 # Figure out if the extracted object list is compatible with a Unity
622 # build. When we're doing a Unified build, we go through the sources,
623 # and create a single source file from each subset of the sources that
624 # can be compiled with a specific compiler. Then we create one object
625 # from each unified source file. So for each compiler we can either
626 # extra all its sources or none.
627 cmpsrcs = self.classify_all_sources(self.target.sources, self.target.generated)
628 extracted_cmpsrcs = self.classify_all_sources(self.srclist, self.genlist)
629
630 for comp, srcs in extracted_cmpsrcs.items():
631 if set(srcs) != set(cmpsrcs[comp]):
632 raise MesonException('Single object files cannot be extracted '
633 'in Unity builds. You can only extract all '
634 'the object files for each compiler at once.')
635
636
637 @dataclass(eq=False, order=False)
638 class StructuredSources(HoldableObject):
639
640 """A container for sources in languages that use filesystem hierarchy.
641
642 Languages like Rust and Cython rely on the layout of files in the filesystem
643 as part of the compiler implementation. This structure allows us to
644 represent the required filesystem layout.
645 """
646
647 sources: T.DefaultDict[str, T.List[TargetSources]] = field(
648 default_factory=lambda: defaultdict(list))
649
650 def __add__(self, other: StructuredSources) -> StructuredSources:
651 sources = self.sources.copy()
652 for k, v in other.sources.items():
653 sources[k].extend(v)
654 return StructuredSources(sources)
655
656 def __bool__(self) -> bool:
657 return bool(self.sources)
658
659 def as_list(self) -> T.List[TargetSources]:
660 return list(itertools.chain.from_iterable(self.sources.values()))
661
662 def needs_copy(self) -> bool:
663 """Do we need to create a structure in the build directory.
664
665 This allows us to avoid making copies if the structures exists in the
666 source dir. Which could happen in situations where a generated source
667 only exists in some configurations
668 """
669 for files in self.sources.values():
670 for f in files:
671 if isinstance(f, File):
672 if f.is_built:
673 return True
674 else:
675 return True
676 return False
677
678
679 @dataclass(eq=False)
680 class Target(HoldableObject, metaclass=SimpleABC):
681
682 typename: T.ClassVar[str]
683
684 name: str
685 subdir: str
686 build_by_default: bool
687 for_machine: MachineChoice
688 environment: Environment
689 build_project: BuildProject
690 install: bool = False
691 build_always_stale: bool = False
692 extra_files: T.List[File] = field(default_factory=list)
693 build_subdir: str = ''
694 depend_files: T.List[File] = field(default_factory=list)
695
696 @abc.abstractmethod
697 def type_suffix(self) -> str:
698 pass
699
700 def __post_init__(self) -> None:
701 # XXX: this should happen in the interpreter
702 if has_path_sep(self.name):
703 # Fix failing test 53 when this becomes an error.
704 mlog.warning(textwrap.dedent(f'''\
705 Target "{self.name}" has a path separator in its name.
706 This is not supported, it can cause unexpected failures and will become
707 a hard error in the future.'''))
708 self.builddir = self.build_project.prefix + self.subdir
709 if self.build_subdir:
710 self.builddir = os.path.join(self.builddir, self.build_subdir)
711
712 # dataclass comparators?
713 def __lt__(self, other: object) -> bool:
714 if not isinstance(other, Target):
715 return NotImplemented
716 return self.get_id() < other.get_id()
717
718 def __le__(self, other: object) -> bool:
719 if not isinstance(other, Target):
720 return NotImplemented
721 return self.get_id() <= other.get_id()
722
723 def __gt__(self, other: object) -> bool:
724 if not isinstance(other, Target):
725 return NotImplemented
726 return self.get_id() > other.get_id()
727
728 def __ge__(self, other: object) -> bool:
729 if not isinstance(other, Target):
730 return NotImplemented
731 return self.get_id() >= other.get_id()
732
733 def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
734 raise NotImplementedError
735
736 def get_basename(self) -> str:
737 return self.name
738
739 def get_subdir(self) -> str:
740 return self.subdir
741
742 def get_typename(self) -> str:
743 return self.typename
744
745 def get_build_subdir(self) -> str:
746 return self.build_subdir
747
748 def get_builddir(self) -> str:
749 return self.builddir
750
751 def get_target(self) -> Self:
752 return self
753
754 @staticmethod
755 def _get_id_hash(target_id: str) -> str:
756 # We don't really need cryptographic security here.
757 # Small-digest hash function with unlikely collision is good enough.
758 h = hashlib.sha256()
759 h.update(target_id.encode(encoding='utf-8', errors='replace'))
760 # This ID should be case-insensitive and should work in Visual Studio,
761 # e.g. it should not start with leading '-'.
762 return h.hexdigest()[:7]
763
764 @staticmethod
765 def construct_id_from_path(subdir: str, name: str, type_suffix: str) -> str:
766 """Construct target ID from subdir, name and type suffix.
767
768 This helper function is made public mostly for tests."""
769 # This ID must also be a valid file name on all OSs.
770 # It should also avoid shell metacharacters for obvious
771 # reasons. '@' is not used as often as '_' in source code names.
772 # In case of collisions consider using checksums.
773 # FIXME replace with assert when slash in names is prohibited
774 name_part = name.replace('/', '@').replace('\\', '@')
775 assert not has_path_sep(type_suffix)
776 my_id = name_part + type_suffix
777 if subdir:
778 subdir_part = Target._get_id_hash(subdir)
779 # preserve myid for better debuggability
780 return subdir_part + '@@' + my_id
781 return my_id
782
783 @lazy_property
784 def subproject(self) -> SubProject:
785 return self.build_project.subproject
786
787 @lazy_property
788 def id(self) -> str:
789 return self.construct_id_from_path(
790 self.builddir, self.name, self.type_suffix())
791
792 def get_id(self) -> str:
793 return self.id
794
795 def is_linkable_target(self) -> bool:
796 return False
797
798 def get_outputs(self) -> T.List[str]:
799 return []
800
801 def should_install(self) -> bool:
802 return False
803
804 class BuildTarget(Target):
805 rust_crate_type: RustCrateType
806
807 # This set contains all the languages a linker can link natively
808 # without extra flags. For instance, nvcc (cuda) can link C++
809 # without injecting -lc++/-lstdc++, see
810 # https://github.com/mesonbuild/meson/issues/10570
811 _MASK_LANGS: T.FrozenSet[T.Tuple[str, str]] = frozenset([
812 # (language, linker)
813 ('cpp', 'cuda'),
814 ])
815
816 def __init__(
817 self,
818 name: str,
819 subdir: str,
820 orig_for_machine: MachineChoice,
821 sources: T.List['SourceOutputs'],
822 structured_sources: T.Optional[StructuredSources],
823 objects: T.Sequence[ObjectTypes | GeneratedTypes],
824 environment: Environment,
825 compilers: CompilerDict,
826 build_project: BuildProject,
827 kwargs: BuildTargetKeywordArguments):
828 super().__init__(name, subdir, kwargs.get('build_by_default', True),
829 kwargs['native'], environment,
830 install=kwargs.get('install', False),
831 build_subdir=kwargs.get('build_subdir', ''),
832 build_project=build_project)
833 self.orig_for_machine = orig_for_machine
834 self.original_kwargs = kwargs
835 # all_compilers is a reference to Interpreter.compilers, as such we
836 # cannot mutate it inside build. Use a Mapping to get help from the
837 # static type checker
838 self.all_compilers: T.Mapping[Language, Compiler] = compilers
839 self.compilers: CompilerDict = {}
840 self.objects: T.List[ObjectTypes] = []
841 self.structured_sources = structured_sources
842 self.external_deps: T.List[dependencies.Dependency] = []
843 self.include_dirs: T.List['IncludeDirs'] = []
844 self.link_language: T.Optional[Language] = kwargs.get('link_language')
845 self.link_targets: T.List[LinkableTargetTypes] = []
846 self.link_whole_targets: T.List[StaticTargetTypes] = []
847 self.depend_files = kwargs.get('depend_files', [])
848 self.link_depends = kwargs.get('link_depends', [])
849 self.added_deps: T.Set[dependencies.Dependency] = set()
850 self.name_prefix_set = False
851 self.name_suffix_set = False
852 self.filename = 'no_name'
853 self.doctests: T.Optional[Doctest] = None
854 # The debugging information file this target will generate
855 self.debug_filename: str | None = None
856 # The list of all files outputted by this target. Useful in cases such
857 # as Vala which generates .vapi and .h besides the compiled output.
858 self.outputs = [self.filename]
859 self.pch: T.Dict[Language, T.Optional[T.Tuple[str, T.Optional[str]]]] = {}
860 self.extra_args = kwargs.get('language_args', T.cast('T.DefaultDict[Language, list[str]]', defaultdict(list)))
861 self.sources: T.List[File] = []
862 # If the same source is defined multiple times, use it only once.
863 self.seen_sources: T.Set[File] = set()
864 self.generated: T.List['GeneratedTypes'] = []
865 self.extra_files: T.List[File] = []
866 self.d_features: DFeatures = {
867 'debug': kwargs.get('d_debug', []),
868 'import_dirs': kwargs.get('d_import_dirs', []),
869 'versions': kwargs.get('d_module_versions', []),
870 'unittest': kwargs.get('d_unittest', False),
871 }
872 self.pic = False
873 self.pie = False
874 self.both_lib: T.Optional[T.Union[StaticLibrary, SharedLibrary]] = None
875 # Track build_rpath entries so we can remove them at install time
876 self.rpath_dirs_to_remove: T.Set[bytes] = set()
877 self.vala_header: T.Optional[str] = None
878 self.vala_vapi: T.Optional[str] = None
879 self.vala_gir: T.Optional[str] = None
880 self.process_sourcelist(sources)
881 # Objects can be:
882 # 1. Preexisting objects provided by the user with the `objects:` kwarg
883 # 2. Compiled objects created by and extracted from another target
884 self.process_objectlist(objects)
885
886 if not self.build_by_default and kwargs.get('install', False):
887 # For backward compatibility, if build_by_default is not explicitly
888 # set, use the value of 'install' if it's enabled.
889 self.build_by_default = True
890
891 self.raw_overrides = kwargs.get('override_options', {})
892
893 self.pch['c'] = kwargs.get('c_pch')
894 self.pch['cpp'] = kwargs.get('cpp_pch')
895
896 self.link_args = kwargs.get('link_args', [])
897 for l in self.link_args:
898 if '-Wl,-rpath' in l or l.startswith('-rpath'):
899 mlog.warning(textwrap.dedent('''\
900 Please do not define rpath with a linker argument, use install_rpath
901 or build_rpath properties instead.
902 This will become a hard error in a future Meson release.
903 '''))
904 self.link_early_args = kwargs.get('link_early_args', [])
905 # Target-specific include dirs must be added BEFORE include dirs from
906 # internal deps (added inside self.add_deps()) to override them.
907 self.add_include_dirs(kwargs.get('include_directories', []))
908 # Add dependencies (which also have include_directories)
909 self.add_deps(kwargs.get('dependencies', []))
910
911 self.has_custom_install_dir = False
912 i = kwargs.get('install_dir', [])
913 install_dir = i[0] if i else True
914 default_install_dir = self.get_default_install_dir()[0]
915 if install_dir is True:
916 install_dir = default_install_dir
917 elif install_dir != default_install_dir:
918 self.has_custom_install_dir = True
919 self.install_dir: T.List[T.Union[str, T.Literal[False]]] = [install_dir]
920 self.install_mode = kwargs.get('install_mode', None)
921 self.install_tag: T.List[T.Optional[str]] = kwargs.get('install_tag') or [None]
922 self.extra_files = kwargs.get('extra_files', [])
923 self.install_rpath: str = kwargs.get('install_rpath', '')
924 self.build_rpath = kwargs.get('build_rpath', '')
925 self.resources = kwargs.get('resources', [])
926 name_prefix = kwargs.get('name_prefix')
927 if name_prefix is not None:
928 self.prefix = name_prefix
929 self.name_prefix_set = True
930 name_suffix = kwargs.get('name_suffix')
931 if name_suffix is not None:
932 self.suffix = name_suffix
933 self.name_suffix_set = True
934 self.implicit_include_directories = kwargs.get('implicit_include_directories', True)
935 self.gnu_symbol_visibility = kwargs.get('gnu_symbol_visibility', '')
936 self.rust_dependency_map = kwargs.get('rust_dependency_map', {})
937
938 self.swift_interoperability_mode = kwargs.get('swift_interoperability_mode', 'c')
939 self.swift_module_name = kwargs.get('swift_module_name') or self.name
940 self.missing_languages = self.process_compilers()
941 self.single_compile_base_args: T.Dict[Compiler, ImmutableListProtocol[str]] = {}
942
943 # self.link_targets and self.link_whole_targets contains libraries from
944 # dependencies (see add_deps()). They have not been processed yet because
945 # we have to call process_compilers() first and we need to process libraries
946 # from link_with and link_whole first.
947 # See https://github.com/mesonbuild/meson/pull/11957#issuecomment-1629243208.
948 link_targets = self._extract_link_with(kwargs)
949 link_whole_targets = self._extract_link_whole(kwargs)
950 self.link_targets.clear()
951 self.link_whole_targets.clear()
952 self.link(link_targets)
953 self.link_whole(link_whole_targets)
954 self._set_vala_args(kwargs)
955
956 if not any([[src for src in self.sources if not is_header(src)], self.generated, self.objects,
957 self.link_whole_targets, self.structured_sources, kwargs.pop('_allow_no_sources', False)]):
958 mlog.warning(f'Build target {name} has no sources. '
959 'This was never supposed to be allowed but did because of a bug, '
960 'support will be removed in a future release of Meson')
961 self.validate_cross()
962 self.check_module_linking()
963
964 @lazy_property
965 def id(self) -> str:
966 name = self.name
967 if self.name_suffix_set:
968 name += '.' + self.suffix
969 return self.construct_id_from_path(
970 self.builddir, name, self.type_suffix())
971
972 def _set_vala_args(self, kwargs: BuildTargetKeywordArguments) -> None:
973 if self.uses_vala():
974 self.vala_header = kwargs.get('vala_header') or self.name + '.h'
975 inst = kwargs.get('install_vala_header', False)
976 if inst is True:
977 dir_ = kwargs.get('install_vala_header_dir') or self.environment.get_includedir()
978 self.install_dir.append(dir_)
979 else:
980 self.install_dir.append(False)
981
982 self.vala_vapi = kwargs.get('vala_vapi') or self.name + '.vapi'
983 inst = kwargs.get('install_vala_vapi', False)
984 if inst is True:
985 dir_ = kwargs.get('install_vala_vapi_dir') or os.path.join(self.environment.get_datadir(), 'vala', 'vapi')
986 self.install_dir.append(dir_)
987 else:
988 self.install_dir.append(False)
989
990 self.vala_gir = kwargs.get('vala_gir')
991 if self.vala_gir:
992 inst = kwargs.get('install_vala_gir', False)
993 if inst is True:
994 assert self.vala_gir is not None, 'Installing Vala GIR without generating one?'
995 dir_ = kwargs.get('install_vala_gir_dir') or os.path.join(self.environment.get_datadir(), 'gir-1.0')
996 self.install_dir.append(dir_)
997 elif self.vala_gir is not None:
998 self.install_dir.append(False)
999
1000 def post_init(self) -> None:
1001 ''' Initialisations and checks requiring the final list of compilers to be known
1002 '''
1003 self.validate_sources()
1004 if self.uses_rust():
1005 if self.link_language and self.link_language != 'rust':
1006 raise MesonException('cannot build Rust sources with a different link_language')
1007 if self.structured_sources:
1008 # TODO: the interpreter should be able to generate a better error message?
1009 if any((s.endswith('.rs') for s in self.sources)) or \
1010 any(any((s.endswith('.rs') for s in g.get_outputs())) for g in self.generated):
1011 raise MesonException('cannot mix Rust structured sources and unstructured sources')
1012
1013 # relocation-model=pic is rustc's default and Meson does not
1014 # currently have a way to disable PIC.
1015 self.pic = True
1016 self.pie = True
1017 else:
1018 if self.structured_sources:
1019 raise MesonException('structured sources are only supported in Rust targets')
1020
1021 if self.is_linkable_target():
1022 if self.vala_header is not None:
1023 self.outputs.append(self.vala_header)
1024 self.install_tag.append('devel')
1025 if self.vala_vapi is not None:
1026 self.outputs.append(self.vala_vapi)
1027 self.install_tag.append('devel')
1028 if self.vala_gir is not None:
1029 self.outputs.append(self.vala_gir)
1030 self.install_tag.append('devel')
1031
1032 for compiler in self.compilers.values():
1033 self.single_compile_base_args[compiler] = self._generate_single_compile_base_args(compiler)
1034
1035 def __repr__(self) -> str:
1036 repr_str = "<{0} {1}: {2}>"
1037 return repr_str.format(self.__class__.__name__, self.get_id(), self.filename)
1038
1039 def __str__(self) -> str:
1040 return f"{self.name}"
1041
1042 def validate_cross(self) -> None:
1043 if self.build_project.for_machine is MachineChoice.BUILD:
1044 if self.for_machine is MachineChoice.HOST:
1045 raise MesonBugException('Tried to build a target for the host machine in a build-only subproject.')
1046 if self.install:
1047 raise MesonBugException('Tried to build an installable target in a build-only subproject.')
1048
1049 if self.for_machine is MachineChoice.BUILD and self.install:
1050 if self.environment.is_cross_build():
1051 raise InvalidArguments('Tried to install a target for the build machine in a cross build.')
1052 else:
1053 mlog.warning('Installing target build for the build machine. This will fail in a cross build.')
1054
1055 def process_objectlist(self, objects: T.Iterable[ObjectTypes | GeneratedTypes]) -> None:
1056 assert isinstance(objects, list)
1057 deprecated_non_objects = []
1058 for s in objects:
1059 if isinstance(s, (File, ExtractedObjects)):
1060 self.objects.append(s)
1061 if not isinstance(s, ExtractedObjects) and not is_object(s):
1062 deprecated_non_objects.append(s)
1063 elif isinstance(s, (CustomTarget, CustomTargetIndex, GeneratedList)):
1064 non_objects = [o for o in s.get_outputs() if not is_object(o)]
1065 if non_objects:
1066 raise InvalidArguments(f'Generated file {non_objects[0]} in the \'objects\' kwarg is not an object.')
1067 self.generated.append(s)
1068 else:
1069 raise InvalidArguments(f'Bad object of type {type(s).__name__!r} in target {self.name!r}.')
1070 if deprecated_non_objects:
1071 FeatureDeprecated.single_use(f'Source file {deprecated_non_objects[0]} in the \'objects\' kwarg is not an object.',
1072 '1.3.0', self.subproject)
1073
1074 def process_sourcelist(self, sources: T.Iterable['SourceOutputs']) -> None:
1075 """Split sources into generated and static sources.
1076
1077 Sources can be:
1078 1. Preexisting source files in the source tree (static)
1079 2. Preexisting sources generated by configure_file in the build tree.
1080 (static as they are only regenerated if meson itself is regenerated)
1081 3. Sources files generated by another target or a Generator (generated)
1082 """
1083 for s in sources:
1084 if isinstance(s, File):
1085 if s not in self.seen_sources:
1086 self.sources.append(s)
1087 self.seen_sources.add(s)
1088 elif isinstance(s, (CustomTarget, CustomTargetIndex, GeneratedList)):
1089 self.generated.append(s)
1090
1091 def process_compilers_late(self) -> None:
1092 """Processes additional compilers after kwargs have been evaluated.
1093
1094 This can add extra compilers that might be required by keyword
1095 arguments, such as link_with or dependencies. It will also try to guess
1096 which compiler to use if one hasn't been selected already.
1097 """
1098 for lang in self.missing_languages:
1099 try:
1100 self.compilers[lang] = self.all_compilers[lang]
1101 except KeyError:
1102 # It is intentional not to update self.all_compilers here, since
1103 # that is a reference to Interpreter.compilers, which should
1104 # only contain the compilers enabled explicilty by the project
1105
1106 is_error: bool = True
1107
1108 # In the case of cython it's possible that we have an
1109 # implementation detail language
1110 if self.uses_cython() and lang == self.environment.coredata.get_option_for_target(self, 'cython_language'):
1111 self.compilers[lang] = self.environment.coredata.compilers[self.for_machine][lang]
1112 is_error = False
1113
1114 # C++ is an implementation detail of Cuda, and may not be
1115 # explicitly enabled.
1116 if self.uses_cuda() and lang == 'cpp':
1117 self.compilers[lang] = self.environment.coredata.compilers[self.for_machine][lang]
1118 is_error = False
1119
1120 if is_error:
1121 raise
1122
1123 # did user override clink_langs for this target?
1124 link_langs = (self.link_language, ) if self.link_language else clink_langs
1125
1126 if self.link_language:
1127 if self.link_language not in self.all_compilers:
1128 m = f'Target {self.name} requires {self.link_language} compiler not part of the project'
1129 raise MesonException(m)
1130 if self.link_language not in self.compilers and self.pch.get(self.link_language, None):
1131 self.compilers[self.link_language] = self.all_compilers[self.link_language]
1132
1133 # If this library is linked against another library we need to consider
1134 # the languages of those libraries as well.
1135 if self.link_targets or self.link_whole_targets:
1136 for t in itertools.chain(self.link_targets, self.link_whole_targets):
1137 if isinstance(t, (CustomTarget, CustomTargetIndex)):
1138 continue # We can't know anything about these.
1139 target_langs = [t.link_language] if t.link_language else list(t.compilers)
1140 for lang in target_langs:
1141 # Rust is always linked through a C-ABI target, so do not add
1142 # the compiler here
1143 if lang != 'rust' and lang in link_langs:
1144 if lang not in self.compilers:
1145 try:
1146 self.compilers[lang] = t.all_compilers[lang]
1147 except KeyError:
1148 # The language needed might be provided by a
1149 # subproject, and will not be in this project's
1150 # compiler set
1151 self.compilers[lang] = self.environment.coredata.compilers[self.for_machine][lang]
1152
1153 if not self.compilers:
1154 # No source files or parent targets, target consists of only object
1155 # files of unknown origin. Just add the first clink compiler
1156 # that we have and hope that it can link these objects
1157
1158 # TODO: pyright understands this, mypy doesn't
1159 for lang in T.cast('T.Iterable[Language]', reversed(link_langs)):
1160 if lang in self.all_compilers:
1161 self.compilers[lang] = self.all_compilers[lang]
1162 break
1163
1164 # Now that we have the final list of compilers we can sort it according
1165 # to clink_langs and do sanity checks.
1166 self.compilers = OrderedDict(sorted(self.compilers.items(),
1167 key=lambda t: sort_clink(t[0])))
1168 self.post_init()
1169
1170 def process_compilers(self) -> T.List[Language]:
1171 '''
1172 Populate self.compilers, which is the list of compilers that this
1173 target will use for compiling all its sources.
1174 We also add compilers that were used by extracted objects to simplify
1175 dynamic linker determination.
1176 Returns a list of missing languages that we can add implicitly, such as
1177 C/C++ compiler for cython.
1178 '''
1179 missing_languages: T.List[Language] = []
1180 if not any([self.sources, self.generated, self.objects, self.structured_sources]):
1181 return missing_languages
1182 # Preexisting sources
1183 sources: T.List['FileOrString'] = list(self.sources)
1184 generated = self.generated.copy()
1185
1186 if self.structured_sources:
1187 for v in self.structured_sources.sources.values():
1188 for src in v:
1189 if isinstance(src, File):
1190 sources.append(src)
1191 else:
1192 generated.append(src)
1193
1194 # All generated sources
1195 for gensrc in generated:
1196 for s in gensrc.get_outputs():
1197 # Generated objects can't be compiled, so don't use them for
1198 # compiler detection. If our target only has generated objects,
1199 # we will fall back to using the first c-like compiler we find,
1200 # which is what we need.
1201 if not is_object(s):
1202 sources.append(s)
1203
1204 for d in self.external_deps:
1205 for s in d.sources:
1206 if isinstance(s, File):
1207 sources.append(s)
1208
1209 # Sources that were used to create our extracted objects
1210 for o in self.objects:
1211 if not isinstance(o, ExtractedObjects):
1212 continue
1213 compsrcs = o.classify_all_sources(o.srclist, [])
1214 for comp in compsrcs:
1215 # Don't add Vala sources since that will pull in the Vala
1216 # compiler even though we will never use it since we are
1217 # dealing with compiled C code.
1218 if comp.language == 'vala':
1219 continue
1220 if comp.language not in self.compilers:
1221 self.compilers[comp.language] = comp
1222 if sources:
1223 # For each source, try to add one compiler that can compile it.
1224 #
1225 # If it has a suffix that belongs to a known language, we must have
1226 # a compiler for that language.
1227 #
1228 # Otherwise, it's ok if no compilers can compile it, because users
1229 # are expected to be able to add arbitrary non-source files to the
1230 # sources list
1231 for s in sources:
1232 for lang, compiler in self.all_compilers.items():
1233 if compiler.can_compile(s):
1234 if lang not in self.compilers:
1235 self.compilers[lang] = compiler
1236 break
1237 else:
1238 if is_known_suffix(s) and not is_header(s):
1239 path = pathlib.Path(str(s)).as_posix()
1240 m = f'No {self.for_machine.get_lower_case_name()} machine compiler for {path!r}'
1241 raise MesonException(m)
1242
1243 # If all our sources are Vala, our target also needs the C compiler but
1244 # it won't get added above.
1245 if 'vala' in self.compilers and 'c' not in self.compilers:
1246 self.compilers['c'] = self.all_compilers['c']
1247 if 'cython' in self.compilers:
1248 _value = self.environment.coredata.get_option_for_target(self, 'cython_language')
1249 assert isinstance(_value, str), 'for mypy'
1250 value = T.cast('Language', _value)
1251 try:
1252 self.compilers[value] = self.all_compilers[value]
1253 except KeyError:
1254 # This might be an implementation detail (C or C++)
1255 #
1256 # It is intentional not to update self.all_compilers here, since
1257 # that is a reference to Interpreter.compilers, which should
1258 # only contain the compilers enabled explicilty by the project
1259 try:
1260 self.compilers[value] = self.environment.coredata.compilers[self.for_machine][value]
1261 except KeyError:
1262 missing_languages.append(value)
1263
1264 return missing_languages
1265
1266 def validate_sources(self) -> None:
1267 if len(self.compilers) > 1 and any(lang in self.compilers for lang in ['cs', 'java']):
1268 langs = ', '.join(self.compilers.keys())
1269 raise InvalidArguments(f'Cannot mix those languages into a target: {langs}')
1270
1271 def extract_objects(self, srclist: T.List[TargetSources], is_unity: bool) -> ExtractedObjects:
1272 sources_set = set(self.sources)
1273 generated_set = set(self.generated)
1274
1275 obj_src: T.List['File'] = []
1276 obj_gen: T.List['GeneratedTypes'] = []
1277 for src in srclist:
1278 if isinstance(src, (str, File)):
1279 if src not in sources_set:
1280 raise MesonException(f'Tried to extract unknown source {src}.')
1281 obj_src.append(src)
1282 elif isinstance(src, (CustomTarget, CustomTargetIndex, GeneratedList)):
1283 FeatureNew.single_use('Generated sources for extract_objects', '0.61.0', self.subproject)
1284 target = src.target if isinstance(src, CustomTargetIndex) else src
1285 if src not in generated_set and target not in generated_set:
1286 raise MesonException(f'Tried to extract unknown source {target.get_basename()}.')
1287 obj_gen.append(src)
1288 else:
1289 raise MesonException(f'Object extraction arguments must be strings, Files or targets (got {type(src).__name__}).')
1290 eobjs = ExtractedObjects(self, obj_src, obj_gen)
1291 if is_unity:
1292 eobjs.check_unity_compatible()
1293 return eobjs
1294
1295 def extract_all_objects(self, recursive: bool = True) -> ExtractedObjects:
1296 return ExtractedObjects(self, self.sources, self.generated, self.objects,
1297 recursive, pch=True)
1298
1299 @lru_cache(maxsize=None)
1300 def get_all_link_deps(self) -> ImmutableListProtocol[BuildTargetTypes]:
1301 """ Get all shared libraries dependencies
1302 This returns all shared libraries in the entire dependency tree. Those
1303 are libraries needed at runtime which is different from the set needed
1304 at link time, see get_dependencies() for that.
1305 """
1306 result: OrderedSet[BuildTargetTypes] = OrderedSet()
1307 nonresults: T.Set[BuildTargetTypes] = set()
1308 stack: T.Deque[BuildTargetTypes] = deque()
1309 stack.appendleft(self)
1310 while stack:
1311 t = stack.pop()
1312 if t in result or t in nonresults:
1313 continue
1314 if isinstance(t, CustomTargetIndex):
1315 stack.appendleft(t.target)
1316 continue
1317 if isinstance(t, SharedLibrary):
1318 result.add(t)
1319 else:
1320 nonresults.add(t)
1321 if isinstance(t, BuildTarget):
1322 stack.extendleft((t2 for t2 in t.link_targets if t2 not in nonresults))
1323 stack.extendleft((t2 for t2 in t.link_whole_targets if t2 not in nonresults))
1324 return list(result)
1325
1326 @lru_cache(maxsize=None)
1327 def get_all_linked_targets(self) -> ImmutableListProtocol[BuildTargetTypes]:
1328 """Get all targets that have been linked with this one.
1329
1330 This is useful for cases where we need to analyze these links, such as
1331 for module information.
1332
1333 This includes static libraries and static libraries linked with static
1334 libraries. This differs from :method:`get_all_link_deps` in that it does
1335 add static libs, and differs from `:method:`get_dependencies`, which
1336 does not look for targets that are not directly linked, such as those
1337 that are added with `link_whole`.
1338
1339 :returns: An immutable list of BuildTargets
1340 """
1341 result: OrderedSet[BuildTargetTypes] = OrderedSet()
1342 stack: T.Deque[BuildTargetTypes] = deque()
1343 stack.extendleft(self.link_targets)
1344 stack.extendleft(self.link_whole_targets)
1345 while stack:
1346 t = stack.pop()
1347 if t in result:
1348 continue
1349 if isinstance(t, CustomTargetIndex):
1350 stack.appendleft(t.target)
1351 continue
1352 if isinstance(t, BuildTarget):
1353 result.add(t)
1354 stack.extendleft(t.link_targets)
1355 stack.extendleft(t.link_whole_targets)
1356 assert self not in result, 'should not have self'
1357 return list(result)
1358
1359 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
1360 return self.get_transitive_link_deps_mapping(prefix)
1361
1362 @lru_cache(maxsize=None)
1363 def get_transitive_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
1364 result: T.Dict[str, str] = {}
1365 for i in itertools.chain(self.link_targets, self.link_whole_targets):
1366 mapping = i.get_link_deps_mapping(prefix)
1367 # we are merging two dictionaries, while keeping the earlier one dominant
1368 # use dict() both to copy and change type
1369 result_tmp = dict(mapping)
1370 result_tmp.update(result)
1371 result = result_tmp
1372 return result
1373
1374 @lru_cache(maxsize=None)
1375 def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
1376 result: OrderedSet[str] = OrderedSet()
1377 for i in self.link_targets:
1378 if not isinstance(i, StaticLibrary):
1379 result.add(i.get_builddir())
1380 result.update(i.get_link_dep_subdirs())
1381 return result
1382
1383 def get_single_compile_base_args(self, compiler: Compiler) -> CompilerArgs:
1384 # Return a mutable CompilerArgs populated from the cached immutable
1385 # arguments so that callers can safely modify it.
1386 return compiler.compiler_args(self.single_compile_base_args[compiler])
1387
1388 def _generate_single_compile_base_args(self, compiler: Compiler) -> ImmutableListProtocol[str]:
1389 # Create an empty commands list, and start adding arguments from
1390 # various sources in the order in which they must override each other
1391 commands = compiler.compiler_args()
1392 # Start with symbol visibility.
1393 commands += compiler.gnu_symbol_visibility_args(self.gnu_symbol_visibility)
1394 # Add compiler args for compiling this target derived from 'base' build
1395 # options passed on the command-line, in default_options, etc.
1396 # These have the lowest priority.
1397 commands += get_base_compile_args(self, compiler, self.environment)
1398 return list(commands) # Avoid call to iterable.flush_pre_post in CompilerArgs.__init__
1399
1400 def get_default_install_dir(self) -> T.Tuple[str, str]:
1401 return self.environment.get_libdir(), '{libdir}'
1402
1403 def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
1404 return self.install_dir
1405
1406 def get_custom_install_mode(self) -> T.Optional['FileMode']:
1407 return self.install_mode
1408
1409 def get_override(self, name: str) -> T.Optional[ElementaryOptionValues]:
1410 return self.raw_overrides.get(name, None)
1411
1412 @T.overload
1413 def _extract_pic_pie(self, kwargs: StaticLibraryKeywordArguments, arg: Literal['pic'],
1414 option: Literal['b_staticpic']) -> bool: ...
1415
1416 @T.overload
1417 def _extract_pic_pie(self, kwargs: T.Union[StaticLibraryKeywordArguments, ExecutableKeywordArguments],
1418 arg: Literal['pie'], option: Literal['b_pie']) -> bool: ...
1419
1420 def _extract_pic_pie(self, kwargs: T.Union[StaticLibraryKeywordArguments, ExecutableKeywordArguments],
1421 arg: Literal['pic', 'pie'], option: Literal['b_staticpic', 'b_pie']) -> bool:
1422 # You can't disable PIC on OS X. The compiler ignores -fno-PIC.
1423 # PIC is always on for Windows (all code is position-independent
1424 # since library loading is done differently)
1425 m = self.environment.machines[self.for_machine]
1426 if arg == 'pic' and (m.is_darwin() or m.is_windows()):
1427 return True
1428
1429 # Executables must be PIE on Android
1430 if arg == 'pie' and m.is_android():
1431 return True
1432
1433 # Check if we have -fPIC, -fpic, -fPIE, or -fpie in cflags
1434 all_flags = self.extra_args['c'] + self.extra_args['cpp']
1435 if '-f' + arg.lower() in all_flags or '-f' + arg.upper() in all_flags:
1436 mlog.warning(f"Use the '{arg}' kwarg instead of passing '-f{arg}' manually to {self.name!r}")
1437 return True
1438
1439 if (a := kwargs.get(arg)) is not None:
1440 assert isinstance(a, bool), 'for mypy'
1441 return a
1442
1443 k = OptionKey(option)
1444 if k in self.environment.coredata.optstore:
1445 val = self.environment.coredata.get_option_for_target(self, k)
1446 assert isinstance(val, bool), 'for mypy'
1447 return val
1448
1449 return False
1450
1451 def install_dir_names(self) -> T.List[T.Optional[str]]:
1452 install_dir_names: T.List[T.Optional[str]]
1453 if self.has_custom_install_dir:
1454 install_dir_names = [getattr(i, 'optname', None) for i in self.install_dir]
1455 else:
1456 default = self.get_default_install_dir()[1]
1457 install_dir_names = T.cast('T.List[T.Optional[str]]', [default]) * len(self.install_dir)
1458
1459 return install_dir_names
1460
1461 def get_filename(self) -> str:
1462 return self.filename
1463
1464 def get_debug_filename(self) -> T.Optional[str]:
1465 """
1466 The name of debuginfo file that will be created by the compiler
1467
1468 Returns None if the build won't create any debuginfo file
1469 """
1470 return self.debug_filename
1471
1472 def get_outputs(self) -> T.List[str]:
1473 return self.outputs
1474
1475 def get_extra_args(self, language: Language) -> T.List[str]:
1476 return self.extra_args[language]
1477
1478 @lru_cache(maxsize=None)
1479 def get_dependencies(self) -> OrderedSet[BuildTargetTypes]:
1480 # Get all targets needed for linking. This includes all link_with and
1481 # link_whole targets, and also all dependencies of static libraries
1482 # recursively. The algorithm here is closely related to what we do in
1483 # get_internal_static_libraries(): Installed static libraries include
1484 # objects from all their dependencies already.
1485 result: OrderedSet[BuildTargetTypes] = OrderedSet()
1486 visited: T.Set[T.Tuple[BuildTargetTypes, bool, bool]] = set()
1487 for t in itertools.chain(self.link_targets, self.link_whole_targets):
1488 if t not in result:
1489 result.add(t)
1490 if isinstance(t, (StaticLibrary, CustomTarget, CustomTargetIndex)):
1491 t.get_dependencies_recurse(result, visited, handled_by_rustc=self.uses_rust())
1492 return result
1493
1494 def get_dependencies_recurse(self, result: OrderedSet[BuildTargetTypes],
1495 visited: T.Set[T.Tuple[BuildTargetTypes, bool, bool]],
1496 include_internals: bool = True, handled_by_rustc: bool = False) -> None:
1497 # self is always a static library because we don't need to pull dependencies
1498 # of shared libraries. If self is installed (not internal) it already
1499 # include objects extracted from all its internal dependencies so we can
1500 # skip them.
1501 include_internals = include_internals and self.is_internal()
1502 key = (self, include_internals, handled_by_rustc)
1503 if key in visited:
1504 return
1505 visited.add(key)
1506
1507 for t in self.link_targets:
1508 uses_rust_abi = isinstance(t, BuildTarget) and t.uses_rust_abi()
1509 if not handled_by_rustc and uses_rust_abi:
1510 # Rules for including libraries via Rust rlibs and staticlibs are complex:
1511 # - proc-macro crates should be skipped completely when the build product
1512 # is not a Rust program, because only rustc knows that they are
1513 # special build-machine shared libraries
1514 # - rlibs must always be returned for Rust programs, because even though
1515 # the -l flag is implicitly added, the -L flag is not. ninjabackend.py
1516 # handles leaving out the -l flag
1517 # - rlibs are bundled into staticlibs and need not be in the command line of
1518 # non-Rust programs; this is the case when t is not added to result.
1519 # - C-ABI libraries included in link_with use -lstatic:-bundle, so even for
1520 # staticlibs we do need to recurse into rlibs and collect these non-bundled
1521 # libraries. So don't return, unlike for procedural macros
1522 if t.rust_crate_type == 'proc-macro':
1523 continue
1524
1525 elif not include_internals and t.is_internal():
1526 pass
1527
1528 else:
1529 result.add(t)
1530 if isinstance(t, StaticLibrary):
1531 t.get_dependencies_recurse(result, visited, include_internals, handled_by_rustc and uses_rust_abi)
1532 for t in self.link_whole_targets:
1533 uses_rust_abi = isinstance(t, BuildTarget) and t.uses_rust_abi()
1534 t.get_dependencies_recurse(result, visited, include_internals, handled_by_rustc and uses_rust_abi)
1535
1536 def get_sources(self) -> T.List[File]:
1537 return self.sources
1538
1539 def get_objects(self) -> T.List[ObjectTypes]:
1540 return self.objects
1541
1542 def get_generated_sources(self) -> T.List['GeneratedTypes']:
1543 return self.generated
1544
1545 def should_install(self) -> bool:
1546 return self.install
1547
1548 def has_pch(self) -> bool:
1549 return any(x is not None for x in self.pch.values())
1550
1551 def get_include_dirs(self) -> T.List['IncludeDirs']:
1552 return self.include_dirs
1553
1554 def add_deps(self, deps: T.List[dependencies.Dependency]) -> None:
1555 for dep in deps:
1556 if dep in self.added_deps:
1557 # Prefer to add dependencies to added_deps which have a name
1558 if dep.is_named():
1559 self.added_deps.remove(dep)
1560 self.added_deps.add(dep)
1561 continue
1562
1563 if isinstance(dep, dependencies.InternalDependency):
1564 # Those parts that are internal.
1565 self.process_sourcelist(dep.sources)
1566 self.extra_files.extend(f for f in dep.extra_files if f not in self.extra_files)
1567 self.add_include_dirs(dep.include_directories, dep.get_include_type())
1568 self.objects.extend(dep.objects)
1569 self.link_targets.extend(dep.libraries)
1570 self.link_whole_targets.extend(dep.whole_libraries)
1571 if dep.get_compile_args() or dep.get_link_args():
1572 # Those parts that are external.
1573 extpart = type(dep)(dep.version,
1574 compile_args=dep.get_compile_args(),
1575 link_args=dep.get_link_args(),
1576 name=dep.name)
1577 self.external_deps.append(extpart)
1578 # Deps of deps.
1579 self.add_deps(dep.ext_deps)
1580 else:
1581 if dep not in self.external_deps:
1582 self.external_deps.append(dep)
1583 self.process_sourcelist(dep.get_sources())
1584 self.add_deps(dep.ext_deps)
1585
1586 dep_d_features = dep.d_features
1587
1588 for feature in ('versions', 'import_dirs'):
1589 if feature in dep_d_features:
1590 self.d_features[feature].extend(dep_d_features[feature])
1591
1592 self.added_deps.add(dep)
1593
1594 def get_external_deps(self) -> T.List[dependencies.Dependency]:
1595 return self.external_deps
1596
1597 def is_internal(self) -> bool:
1598 return False
1599
1600 def link(self, targets: T.Iterable[LinkableTargetTypes]) -> None:
1601 for t in targets:
1602 self.check_can_link_together(t)
1603 self.link_targets.append(t)
1604
1605 def link_whole(
1606 self,
1607 targets: T.Iterable[StaticTargetTypes],
1608 promoted: bool = False) -> None:
1609 for t in targets:
1610 self.check_can_link_together(t)
1611 self.link_whole_targets.append(t)
1612
1613 @lru_cache(maxsize=None)
1614 def get_internal_static_libraries(self) -> OrderedSet[StaticTargetTypes]:
1615 result: OrderedSet[StaticTargetTypes] = OrderedSet()
1616 self.get_internal_static_libraries_recurse(result)
1617 return result
1618
1619 def get_internal_static_libraries_recurse(self, result: OrderedSet[StaticTargetTypes]) -> None:
1620 for t in self.link_targets:
1621 if t.is_internal() and t not in result:
1622 assert isinstance(t, (StaticLibrary, CustomTarget, CustomTargetIndex)), 'for mypy'
1623 result.add(t)
1624 t.get_internal_static_libraries_recurse(result)
1625 for t in self.link_whole_targets:
1626 if t.is_internal():
1627 t.get_internal_static_libraries_recurse(result)
1628
1629 def check_can_link_together(self, t: BuildTargetTypes) -> None:
1630 links_with_rust_abi = isinstance(t, BuildTarget) and t.uses_rust_abi()
1631 if not self.uses_rust() and links_with_rust_abi:
1632 raise InvalidArguments(f'Try to link Rust ABI library {t.name!r} with a non-Rust target {self.name!r}')
1633 if self.for_machine is not t.for_machine and (not links_with_rust_abi or t.rust_crate_type != 'proc-macro'):
1634 msg = f'Tried to mix a {t.for_machine} library ("{t.name}") with a {self.for_machine} target "{self.name}"'
1635 if self.environment.is_cross_build():
1636 raise InvalidArguments(msg + ' This is not possible in a cross build.')
1637 else:
1638 mlog.warning(msg + ' This will fail in cross build.')
1639
1640 def add_include_dirs(self, args: T.Sequence['IncludeDirs'], set_is_system: str = 'preserve') -> None:
1641 if set_is_system != 'preserve':
1642 is_system = set_is_system == 'system'
1643 self.include_dirs.extend([IncludeDirs(x.curdir, x.incdirs, is_system, x.build_project,
1644 x.extra_build_dirs) for x in args])
1645 else:
1646 self.include_dirs.extend(args)
1647
1648 def get_aliases(self) -> T.List[T.Tuple[str, str, str]]:
1649 return []
1650
1651 def get_langs_used_by_deps(self) -> T.List[Language]:
1652 '''
1653 Sometimes you want to link to a C++ library that exports C API, which
1654 means the linker must link in the C++ stdlib, and we must use a C++
1655 compiler for linking. The same is also applicable for objc/objc++, etc,
1656 so we can keep using clink_langs for the priority order.
1657
1658 See: https://github.com/mesonbuild/meson/issues/1653
1659 '''
1660 langs: T.List[Language] = []
1661
1662 # Check if any of the external libraries were written in this language
1663 for dep in self.external_deps:
1664 if dep.language is None:
1665 continue
1666 if dep.language not in langs:
1667 langs.append(dep.language)
1668 # Check if any of the internal libraries this target links to were
1669 # written in this language
1670 for t in itertools.chain(self.link_targets, self.link_whole_targets):
1671 if isinstance(t, (CustomTarget, CustomTargetIndex)):
1672 continue
1673 target_langs = [t.link_language] if t.link_language else list(t.compilers)
1674 for language in target_langs:
1675 if language == 'rust' and not t.uses_rust_abi():
1676 # All Rust dependencies must go through a C-ABI dependency, so ignore it
1677 continue
1678 if language not in langs:
1679 langs.append(language)
1680
1681 return langs
1682
1683 def get_prelinker(self) -> Compiler:
1684 if self.link_language:
1685 comp = self.all_compilers[self.link_language]
1686 return comp
1687 for l in T.cast('T.Tuple[Language, ...]', clink_langs):
1688 if l in self.compilers:
1689 try:
1690 prelinker = self.all_compilers[l]
1691 except KeyError:
1692 raise MesonException(
1693 f'Could not get a prelinker linker for build target {self.name!r}. '
1694 f'Requires a compiler for language "{l}", but that is not '
1695 'a project language.')
1696 return prelinker
1697 raise MesonException(f'Could not determine prelinker for {self.name!r}.')
1698
1699 def get_clink_dynamic_linker_and_stdlibs(self) -> T.Tuple['Compiler', T.List[str]]:
1700 '''
1701 We use the order of languages in `clink_langs` to determine which
1702 linker to use in case the target has sources compiled with multiple
1703 compilers. All languages other than those in this list have their own
1704 linker.
1705 Note that Vala outputs C code, so Vala sources can use any linker
1706 that can link compiled C. We don't actually need to add an exception
1707 for Vala here because of that.
1708 '''
1709 # If the user set the link_language, just return that.
1710 if self.link_language:
1711 comp = self.all_compilers[self.link_language]
1712 return comp, comp.language_stdlib_only_link_flags()
1713
1714 # Since dependencies could come from subprojects, they could have
1715 # languages we don't have in self.all_compilers. Use the global list of
1716 # all compilers here.
1717 all_compilers = self.environment.coredata.compilers[self.for_machine]
1718
1719 # Languages used by dependencies
1720 dep_langs = self.get_langs_used_by_deps()
1721
1722 # Pick a compiler based on the language priority-order
1723 for l in T.cast('T.Tuple[Language, ...]', clink_langs):
1724 if l in self.compilers or l in dep_langs:
1725 try:
1726 linker = all_compilers[l]
1727 except KeyError:
1728 raise MesonException(
1729 f'Could not get a dynamic linker for build target {self.name!r}. '
1730 f'Requires a linker for language "{l}", but that is not '
1731 'a project language.')
1732 stdlib_args: T.List[str] = self.get_used_stdlib_args(linker.language)
1733 # Type of var 'linker' is Compiler.
1734 # Pretty hard to fix because the return value is passed everywhere
1735 return linker, stdlib_args
1736
1737 # None of our compilers can do clink, this happens for example if the
1738 # target only has ASM sources. Pick the first capable compiler.
1739 for l in T.cast('T.Tuple[Language, ...]', clink_langs):
1740 try:
1741 comp = self.all_compilers[l]
1742 return comp, comp.language_stdlib_only_link_flags()
1743 except KeyError:
1744 pass
1745
1746 raise AssertionError(f'Could not get a dynamic linker for build target {self.name!r}')
1747
1748 def get_used_stdlib_args(self, link_language: Language) -> T.List[str]:
1749 all_compilers = self.environment.coredata.compilers[self.for_machine]
1750 all_langs = set(self.compilers).union(self.get_langs_used_by_deps())
1751 stdlib_args: T.List[str] = []
1752 for dl in all_langs:
1753 if dl != link_language and (dl, link_language) not in self._MASK_LANGS:
1754 # We need to use all_compilers here because
1755 # get_langs_used_by_deps could return a language from a
1756 # subproject
1757 stdlib_args.extend(all_compilers[dl].language_stdlib_only_link_flags())
1758 return stdlib_args
1759
1760 def uses_rust(self) -> bool:
1761 return 'rust' in self.compilers
1762
1763 def uses_rust_abi(self) -> bool:
1764 return self.uses_rust() and self.rust_crate_type in {'dylib', 'rlib', 'proc-macro'}
1765
1766 def uses_fortran(self) -> bool:
1767 return 'fortran' in self.compilers
1768
1769 def uses_cython(self) -> bool:
1770 return 'cython' in self.compilers
1771
1772 def uses_cuda(self) -> bool:
1773 return 'cuda' in self.compilers
1774
1775 def uses_vala(self) -> bool:
1776 return 'vala' in self.compilers
1777
1778 def uses_swift_cpp_interop(self) -> bool:
1779 return self.swift_interoperability_mode == 'cpp' and 'swift' in self.compilers
1780
1781 def get_using_msvc(self) -> bool:
1782 '''
1783 Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,
1784 and SharedLibrary for deciding when to use MSVC-specific file naming
1785 and debug filenames.
1786
1787 If at least some code is built with MSVC and the final library is
1788 linked with MSVC, we can be sure that some debug info will be
1789 generated. We only check the dynamic linker here because the static
1790 linker is guaranteed to be of the same type.
1791
1792 Interesting cases:
1793 1. The Vala compiler outputs C code to be compiled by whatever
1794 C compiler we're using, so all objects will still be created by the
1795 MSVC compiler.
1796 2. If the target contains only objects, process_compilers guesses and
1797 picks the first compiler that smells right.
1798 '''
1799 # Rustc can use msvc style linkers
1800 if self.uses_rust():
1801 compiler = self.all_compilers['rust']
1802 else:
1803 compiler, _ = self.get_clink_dynamic_linker_and_stdlibs()
1804 # Mixing many languages with MSVC is not supported yet so ignore stdlibs.
1805 return bool(compiler) and compiler.get_linker_id() in {'link', 'lld-link', 'xilink', 'optlink'}
1806
1807 def check_module_linking(self) -> None:
1808 '''
1809 Warn if shared modules are linked with target: (link_with) #2865
1810 '''
1811 for link_target in self.link_targets:
1812 if isinstance(link_target, SharedModule) and not link_target.force_soname:
1813 if self.environment.machines[self.for_machine].is_darwin():
1814 raise MesonException(
1815 f'target {self.name} links against shared module {link_target.name}. This is not permitted on OSX')
1816 elif self.environment.machines[self.for_machine].is_android() and isinstance(self, SharedModule):
1817 # Android requires shared modules that use symbols from other shared modules to
1818 # be linked before they can be dlopen()ed in the correct order. Not doing so
1819 # leads to a missing symbol error: https://github.com/android/ndk/issues/201
1820 link_target.force_soname = True
1821 else:
1822 mlog.deprecation(f'target {self.name} links against shared module {link_target.name}, which is incorrect.'
1823 '\n '
1824 f'This will be an error in meson 2.0, so please use shared_library() for {link_target.name} instead.'
1825 '\n '
1826 f'If shared_module() was used for {link_target.name} because it has references to undefined symbols,'
1827 '\n '
1828 'use shared_library() with `override_options: [\'b_lundef=false\']` instead.')
1829 link_target.force_soname = True
1830
1831 def process_vs_module_defs_kw(self, kwargs: ExecutableKeywordArguments | SharedModuleKeywordArguments) -> None:
1832 path = kwargs.get('vs_module_defs')
1833 if path is None:
1834 return
1835
1836 self.link_depends.append(path)
1837 if isinstance(path, File):
1838 # When passing a generated file.
1839 self.vs_module_defs = path
1840 else:
1841 # When passing output of a Custom Target
1842 self.vs_module_defs = File.from_built_file(path.get_builddir(), path.get_filename())
1843
1844 def _default_library_type(self) -> _LibraryType:
1845 bl_type = self.environment.coredata.optstore.get_value_for(OptionKey('default_both_libraries'))
1846 assert isinstance(bl_type, str), 'for mypy'
1847 return T.cast('_LibraryType', bl_type)
1848
1849 def _extract_link_with(self, kwargs: BuildTargetKeywordArguments) -> list[LinkableTargetTypes]:
1850 bl_type = self._default_library_type()
1851
1852 lib_list: list[LinkableTargetTypes] = []
1853 for lib in itertools.chain(kwargs.get('link_with', []), self.link_targets):
1854 if isinstance(lib, (CustomTarget, CustomTargetIndex)):
1855 lib_list.append(lib)
1856 else:
1857 lib_list.append(lib.get(bl_type))
1858 return lib_list
1859
1860 def _extract_link_whole(self, kwargs: BuildTargetKeywordArguments) -> list[StaticTargetTypes]:
1861 lib_list: list[StaticTargetTypes] = []
1862 for lib in itertools.chain(kwargs.get('link_whole', []), self.link_whole_targets):
1863 if isinstance(lib, BothLibraries):
1864 lib = lib.get('static')
1865 if not isinstance(lib, StaticLibrary):
1866 raise MesonBugException('Tried to statically link a non-static library. How did we get here?')
1867 lib_list.append(lib)
1868 else:
1869 lib_list.append(lib)
1870 return lib_list
1871
1872 def determine_rpath_dirs(self) -> T.Tuple[str, ...]:
1873 result: OrderedSet[str]
1874 if self.environment.coredata.optstore.get_value_for(OptionKey('layout')) == 'mirror':
1875 # Need a copy here
1876 result = OrderedSet(self.get_link_dep_subdirs())
1877 else:
1878 result = OrderedSet()
1879 result.add('meson-out')
1880 result.update(self.rpaths_for_non_system_absolute_shared_libraries())
1881 self.rpath_dirs_to_remove.update([d.encode('utf-8') for d in result])
1882 return tuple(result)
1883
1884 @lru_cache(maxsize=None)
1885 def rpaths_for_non_system_absolute_shared_libraries(self, exclude_system: bool = True) -> ImmutableListProtocol[str]:
1886 paths: OrderedSet[str] = OrderedSet()
1887 srcdir = self.environment.get_source_dir()
1888
1889 system_dirs = set()
1890 if exclude_system:
1891 for cc in self.compilers.values():
1892 system_dirs.update(cc.get_library_dirs())
1893
1894 external_rpaths = self.get_external_rpath_dirs()
1895 build_to_src = relpath(self.environment.get_source_dir(),
1896 self.environment.get_build_dir())
1897
1898 for dep in self.external_deps:
1899 if dep.type_name not in {'library', 'pkgconfig', 'cmake'}:
1900 continue
1901 for libpath in dep.link_args:
1902 if libpath.startswith('-'):
1903 continue
1904 # For all link args that are absolute paths to a library file, add RPATH args
1905 if not os.path.isabs(libpath):
1906 continue
1907 libdir, libname = os.path.split(libpath)
1908 # Windows doesn't support rpaths, but we use this function to
1909 # emulate rpaths by setting PATH
1910 # .dll is there for mingw gcc
1911 # .so's may be extended with version information, e.g. libxyz.so.1.2.3
1912 if not (
1913 libname.endswith(('.dll', '.lib', '.so', '.dylib'))
1914 or '.so.' in libname
1915 ):
1916 continue
1917
1918 # Don't remove rpaths specified in LDFLAGS.
1919 if libdir in external_rpaths:
1920 continue
1921 if system_dirs and os.path.normpath(libdir) in system_dirs:
1922 # No point in adding system paths.
1923 continue
1924
1925 if is_parent_path(srcdir, libdir):
1926 rel_to_src = libdir[len(srcdir) + 1:]
1927 assert not os.path.isabs(rel_to_src), f'rel_to_src: {rel_to_src} is absolute'
1928 paths.add(os.path.join(build_to_src, rel_to_src))
1929 else:
1930 paths.add(libdir)
1931 # Don't remove rpaths specified by the dependency
1932 paths.difference_update(self.get_rpath_dirs_from_link_args(dep.link_args))
1933 for i in itertools.chain(self.link_targets, self.link_whole_targets):
1934 if isinstance(i, BuildTarget):
1935 paths.update(i.rpaths_for_non_system_absolute_shared_libraries(exclude_system))
1936 return list(paths)
1937
1938 def get_external_rpath_dirs(self) -> T.Set[str]:
1939 args: T.List[str] = []
1940 for lang in LANGUAGES_USING_LDFLAGS:
1941 try:
1942 args += self.environment.coredata.get_external_link_args(self.for_machine, lang)
1943 except KeyError:
1944 pass
1945 return self.get_rpath_dirs_from_link_args(args)
1946
1947 # Match rpath formats:
1948 # -Wl,-rpath=
1949 # -Wl,-rpath,
1950 _rpath_regex = re.compile(r'-Wl,-rpath[=,]([^,]+)')
1951 # Match solaris style compat runpath formats:
1952 # -Wl,-R
1953 # -Wl,-R,
1954 _runpath_regex = re.compile(r'-Wl,-R[,]?([^,]+)')
1955 # Match symbols formats:
1956 # -Wl,--just-symbols=
1957 # -Wl,--just-symbols,
1958 _symbols_regex = re.compile(r'-Wl,--just-symbols[=,]([^,]+)')
1959
1960 @classmethod
1961 def get_rpath_dirs_from_link_args(cls, args: T.List[str]) -> T.Set[str]:
1962 dirs: T.Set[str] = set()
1963
1964 for arg in args:
1965 if not arg.startswith('-Wl,'):
1966 continue
1967
1968 rpath_match = cls._rpath_regex.match(arg)
1969 if rpath_match:
1970 for dir in rpath_match.group(1).split(':'):
1971 dirs.add(dir)
1972 runpath_match = cls._runpath_regex.match(arg)
1973 if runpath_match:
1974 for dir in runpath_match.group(1).split(':'):
1975 # The symbols arg is an rpath if the path is a directory
1976 if os.path.isdir(dir):
1977 dirs.add(dir)
1978 symbols_match = cls._symbols_regex.match(arg)
1979 if symbols_match:
1980 for dir in symbols_match.group(1).split(':'):
1981 # Prevent usage of --just-symbols to specify rpath
1982 if os.path.isdir(dir):
1983 raise MesonException(f'Invalid arg for --just-symbols, {dir} is a directory.')
1984 return dirs
1985
1986 def get_platform_scheme_name(self) -> str:
1987 m = self.environment.machines[self.for_machine]
1988 if m.is_cygwin():
1989 return 'cygwin'
1990 elif m.is_windows():
1991 return 'windows'
1992 elif m.is_darwin():
1993 return 'darwin'
1994 else:
1995 return 'unix'
1996
1997
1998 class LinkableTarget(metaclass=SimpleABC):
1999 @abc.abstractmethod
2000 def get(self, lib_type: _LibraryType) -> LinkableTargetTypes:
2001 """If applicable, return the shared or static "part" of this target.
2002 Otherwise, just return self."""
2003
2004
2005 class FileInTargetPrivateDir:
2006 """Represents a file with the path '/path/to/build/target_private_dir/fname'.
2007 target_private_dir is the return value of get_target_private_dir which is e.g. 'subdir/target.p'.
2008 """
2009
2010 def __init__(self, fname: str):
2011 self.fname = fname
2012
2013 def __str__(self) -> str:
2014 return self.fname
2015
2016 class FileMaybeInTargetPrivateDir:
2017 """Union between 'File' and 'FileInTargetPrivateDir'"""
2018
2019 def __init__(self, inner: T.Union[File, FileInTargetPrivateDir]):
2020 self.inner = inner
2021
2022 @property
2023 def fname(self) -> str:
2024 return self.inner.fname
2025
2026 def rel_to_builddir(self, build_to_src: str, target_private_dir: str) -> str:
2027 if isinstance(self.inner, FileInTargetPrivateDir):
2028 return os.path.join(target_private_dir, self.inner.fname)
2029 return self.inner.rel_to_builddir(build_to_src)
2030
2031 def absolute_path(self, srcdir: str, builddir: str) -> str:
2032 if isinstance(self.inner, FileInTargetPrivateDir):
2033 raise RuntimeError('Unreachable code')
2034 return self.inner.absolute_path(srcdir, builddir)
2035
2036 def __str__(self) -> str:
2037 return self.fname
2038
2039 class Generator(HoldableObject):
2040 def __init__(self, env: Environment,
2041 exe: programs.Program,
2042 arguments: T.List[str],
2043 output: T.List[str],
2044 # how2dataclass
2045 *,
2046 depfile: T.Optional[str] = None,
2047 capture: bool = False,
2048 depends: T.Optional[T.Sequence[TargetDepends]] = None,
2049 name: str = 'Generator'):
2050 self.environment = env
2051 self.exe = exe
2052 self.depfile = depfile
2053 self.capture = capture
2054 self.depends: T.List[TargetDepends] = list(depends or [])
2055 self.arglist = arguments
2056 self.outputs = output
2057 self.name = name
2058
2059 def __repr__(self) -> str:
2060 repr_str = "<{0}: {1}>"
2061 return repr_str.format(self.__class__.__name__, self.exe)
2062
2063 def get_exe(self) -> programs.Program:
2064 return self.exe
2065
2066 def get_base_outnames(self, inname: str) -> T.List[str]:
2067 plainname = os.path.basename(inname)
2068 basename = os.path.splitext(plainname)[0]
2069 bases = [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.outputs]
2070 return bases
2071
2072 def get_dep_outname(self, inname: str) -> str:
2073 if self.depfile is None:
2074 raise InvalidArguments('Tried to get dep name for rule that does not have dependency file defined.')
2075 plainname = os.path.basename(inname)
2076 basename = os.path.splitext(plainname)[0]
2077 return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
2078
2079 def get_arglist(self, inname: str) -> T.List[str]:
2080 plainname = os.path.basename(inname)
2081 basename = os.path.splitext(plainname)[0]
2082 return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.arglist]
2083
2084 def process_files(self, files: T.Iterable[TargetSources],
2085 subdir: str = '',
2086 preserve_path_from: T.Optional[str] = None,
2087 extra_args: T.Optional[T.List[str]] = None,
2088 env: T.Optional[EnvironmentVariables] = None,
2089 extra_depends: T.Optional[T.Sequence[TargetDepends]] = None) -> 'GeneratedList':
2090 output = GeneratedList(
2091 self,
2092 subdir,
2093 preserve_path_from,
2094 extra_args=extra_args if extra_args is not None else [],
2095 env=env if env is not None else EnvironmentVariables(),
2096 extra_depends=list(extra_depends) if extra_depends is not None else [])
2097
2098 for e in files:
2099 if isinstance(e, (CustomTarget, CustomTargetIndex)):
2100 output.depends.add(e)
2101 fs = [File.from_built_file(e.get_builddir(), f) for f in e.get_outputs()]
2102 elif isinstance(e, GeneratedList):
2103 if preserve_path_from:
2104 raise InvalidArguments("generator.process: 'preserve_path_from' is not allowed if one input is a 'generated_list'.")
2105 output.depends.add(e)
2106 output.add_files(FileMaybeInTargetPrivateDir(FileInTargetPrivateDir(f))
2107 for f in e.get_outputs())
2108 continue
2109 elif isinstance(e, str):
2110 fs = [File.from_source_file(self.environment.source_dir, subdir, e)]
2111 else:
2112 fs = [e]
2113
2114 for f in fs:
2115 if preserve_path_from:
2116 abs_f = f.absolute_path(self.environment.source_dir, self.environment.build_dir)
2117 if not is_parent_path(preserve_path_from, abs_f):
2118 raise InvalidArguments('generator.process: When using preserve_path_from, all input files must be in a subdirectory of the given dir.')
2119 f = FileMaybeInTargetPrivateDir(f)
2120 output.add_file(f)
2121 return output
2122
2123
2124 @dataclass(eq=False)
2125 class GeneratedList(HoldableObject):
2126
2127 """The output of generator.process."""
2128
2129 generator: Generator
2130 subdir: str
2131 preserve_path_from: T.Optional[str]
2132 extra_args: T.List[str]
2133 env: T.Optional[EnvironmentVariables]
2134 extra_depends: T.List[TargetDepends]
2135
2136 def __post_init__(self) -> None:
2137 self.name = self.generator.exe
2138 self.depends: T.Set[GeneratedTypes] = set()
2139 self.infilelist: T.List[FileMaybeInTargetPrivateDir] = []
2140 self.outfilelist: T.List[str] = []
2141 self.outmap: T.Dict[FileMaybeInTargetPrivateDir, T.List[str]] = {}
2142 self.depend_files: T.List[File] = []
2143
2144 if self.extra_args is None:
2145 self.extra_args: T.List[str] = []
2146
2147 if self.env is None:
2148 self.env: EnvironmentVariables = EnvironmentVariables()
2149
2150 if self.extra_depends is None:
2151 self.extra_depends: T.List[TargetDepends] = []
2152
2153 if isinstance(self.generator.exe, programs.Program):
2154 if not self.generator.exe.found():
2155 raise InvalidArguments('Tried to use not-found external program as generator')
2156 if isinstance(self.generator.exe, LocalProgram):
2157 t = self.generator.exe.get_target()
2158 if isinstance(t, File):
2159 self.depend_files.append(t)
2160 else:
2161 self.extra_depends.append(t)
2162 else:
2163 path = self.generator.exe.get_path()
2164 if os.path.isabs(path):
2165 # Can only add a dependency on an external program which we
2166 # know the absolute path of
2167 self.depend_files.append(File.from_absolute_file(path))
2168
2169 def get_preserved_path_segment(self, infile: FileMaybeInTargetPrivateDir) -> str:
2170 in_abs = infile.absolute_path(self.generator.environment.source_dir, self.generator.environment.build_dir)
2171 assert os.path.isabs(self.preserve_path_from)
2172 rel = os.path.relpath(in_abs, self.preserve_path_from)
2173 return os.path.dirname(rel)
2174
2175 def add_files(self, newfiles: T.Iterable[FileMaybeInTargetPrivateDir]) -> None:
2176 for f in newfiles:
2177 self.add_file(f)
2178
2179 def add_file(self, newfile: FileMaybeInTargetPrivateDir) -> None:
2180 self.infilelist.append(newfile)
2181 outfiles = self.generator.get_base_outnames(newfile.fname)
2182 if self.preserve_path_from:
2183 path_segment = self.get_preserved_path_segment(newfile)
2184 outfiles = [os.path.join(path_segment, of) for of in outfiles]
2185 self.outfilelist += outfiles
2186 self.outmap[newfile] = outfiles
2187
2188 def get_inputs(self) -> T.List[FileMaybeInTargetPrivateDir]:
2189 return self.infilelist
2190
2191 def get_outputs(self) -> T.List[str]:
2192 return self.outfilelist
2193
2194 def get_outputs_for(self, filename: FileMaybeInTargetPrivateDir) -> T.List[str]:
2195 return self.outmap[filename]
2196
2197 def get_generator(self) -> 'Generator':
2198 return self.generator
2199
2200 def get_extra_args(self) -> T.List[str]:
2201 return self.extra_args
2202
2203 def get_subdir(self) -> str:
2204 return self.subdir
2205
2206 def get_basename(self) -> str:
2207 return self.generator.name
2208
2209
2210 class Executable(BuildTarget, LinkableTarget):
2211 typename = 'executable'
2212
2213 def __init__(
2214 self,
2215 name: str,
2216 subdir: str,
2217 orig_for_machine: MachineChoice,
2218 sources: T.List['SourceOutputs'],
2219 structured_sources: T.Optional[StructuredSources],
2220 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2221 environment: Environment,
2222 compilers: CompilerDict,
2223 build_project: BuildProject,
2224 kwargs: ExecutableKeywordArguments):
2225 self.export_dynamic = kwargs.get('export_dynamic', False)
2226 self.rust_crate_type = kwargs.get('rust_crate_type', 'bin')
2227 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
2228 environment, compilers, build_project, kwargs)
2229 self.win_subsystem = kwargs.get('win_subsystem') or 'console'
2230 self.pie = self._extract_pic_pie(kwargs, 'pie', 'b_pie')
2231 # Check for export_dynamic
2232 self.implib_name = kwargs.get('implib')
2233 # Only linkwithable if using export_dynamic
2234 self.is_linkwithable = self.export_dynamic
2235
2236 self.vs_module_defs: T.Optional[File] = None
2237 self.process_vs_module_defs_kw(kwargs)
2238
2239 def _set_vala_args(self, kwargs: BuildTargetKeywordArguments) -> None:
2240 # These don't get generated if the executable doesn't have
2241 # export_dynamic set to true.
2242 if self.export_dynamic:
2243 super()._set_vala_args(kwargs)
2244
2245 def post_init(self) -> None:
2246 super().post_init()
2247 machine = self.environment.machines[self.for_machine]
2248 # Unless overridden, executables have no suffix or prefix. Except on
2249 # Windows and with C#/Mono executables where the suffix is 'exe'
2250 if not hasattr(self, 'prefix'):
2251 self.prefix = ''
2252 if not hasattr(self, 'suffix'):
2253 # Executable for Windows or C#/Mono
2254 if machine.is_windows() or machine.is_cygwin() or 'cs' in self.compilers:
2255 self.suffix = 'exe'
2256 elif machine.system.startswith('wasm') or machine.system == 'emscripten':
2257 self.suffix = 'js'
2258 elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('armclang') or
2259 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('armclang')):
2260 self.suffix = 'axf'
2261 elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('ccrx') or
2262 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('ccrx')):
2263 self.suffix = 'abs'
2264 elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('xc16')):
2265 self.suffix = 'elf'
2266 elif ('c' in self.compilers and self.compilers['c'].get_id() in {'ti', 'c2000', 'c6000'} or
2267 'cpp' in self.compilers and self.compilers['cpp'].get_id() in {'ti', 'c2000', 'c6000'}):
2268 self.suffix = 'out'
2269 elif ('c' in self.compilers and self.compilers['c'].get_id() in {'mwccarm', 'mwcceppc'} or
2270 'cpp' in self.compilers and self.compilers['cpp'].get_id() in {'mwccarm', 'mwcceppc'}):
2271 self.suffix = 'nef'
2272 elif ('c' in self.compilers and self.compilers['c'].get_id() == 'tasking'):
2273 self.suffix = 'elf'
2274 else:
2275 self.suffix = machine.get_exe_suffix()
2276 self.filename = self.name
2277 if self.prefix:
2278 self.filename = self.prefix + self.filename
2279 if self.suffix:
2280 self.filename += '.' + self.suffix
2281 self.outputs[0] = self.filename
2282
2283 # The import library this target will generate
2284 self.import_filename: str | None = None
2285 # The debugging information file this target will generate
2286 self.debug_filename: str | None = None
2287
2288 # If using export_dynamic, set the import library name
2289 if self.export_dynamic:
2290 implib_basename = self.implib_name or self.name + '.exe'
2291 if machine.is_windows() or machine.is_cygwin():
2292 if self.get_using_msvc():
2293 self.import_filename = f'{implib_basename}.lib'
2294 else:
2295 self.import_filename = f'lib{implib_basename}.a'
2296
2297 create_debug_file = (
2298 machine.is_windows()
2299 and ('cs' in self.compilers or self.uses_rust() or self.get_using_msvc())
2300 # .pdb file is created only when debug symbols are enabled
2301 and self.environment.coredata.optstore.get_value_for(OptionKey("debug"))
2302 )
2303 if create_debug_file:
2304 # If the target is has a standard exe extension (i.e. 'foo.exe'),
2305 # then the pdb name simply becomes 'foo.pdb'. If the extension is
2306 # something exotic, then include that in the name for uniqueness
2307 # reasons (e.g. 'foo_com.pdb').
2308 name = self.name
2309 if getattr(self, 'suffix', 'exe') != 'exe':
2310 name += '_' + self.suffix
2311 self.debug_filename = name + '.pdb'
2312
2313 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2314 """Base case used by BothLibraries"""
2315 return self
2316
2317 def get_default_install_dir(self) -> T.Tuple[str, str]:
2318 return self.environment.get_bindir(), '{bindir}'
2319
2320 def type_suffix(self) -> str:
2321 return "@exe"
2322
2323 def get_import_filename(self) -> T.Optional[str]:
2324 """
2325 The name of the import library that will be outputted by the compiler
2326
2327 Returns None if there is no import library required for this platform
2328 """
2329 return self.import_filename
2330
2331 def get_debug_filename(self) -> T.Optional[str]:
2332 """
2333 The name of debuginfo file that will be created by the compiler
2334
2335 Returns None if the build won't create any debuginfo file
2336 """
2337 return self.debug_filename
2338
2339 def is_linkable_target(self) -> bool:
2340 return self.is_linkwithable
2341
2342
2343 class StaticLibrary(BuildTarget, LinkableTarget):
2344 typename = 'static library'
2345
2346 def __init__(
2347 self,
2348 name: str,
2349 subdir: str,
2350 orig_for_machine: MachineChoice,
2351 sources: T.List['SourceOutputs'],
2352 structured_sources: T.Optional[StructuredSources],
2353 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2354 environment: Environment,
2355 compilers: CompilerDict,
2356 build_project: BuildProject,
2357 kwargs: StaticLibraryKeywordArguments):
2358 self.prelink = kwargs.get('prelink', False)
2359 self.rust_crate_type = kwargs.get('rust_crate_type', 'rlib')
2360 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
2361 environment, compilers, build_project, kwargs)
2362 self.pic = self._extract_pic_pie(kwargs, 'pic', 'b_staticpic')
2363 if not self.pic:
2364 self.pie = self._extract_pic_pie(kwargs, 'pie', 'b_pie')
2365
2366 def post_init(self) -> None:
2367 super().post_init()
2368 if 'cs' in self.compilers:
2369 raise InvalidArguments('Static libraries not supported for C#.')
2370 if self.uses_rust():
2371 # See https://github.com/rust-lang/rust/issues/110460
2372 if self.rust_crate_type == 'rlib' and any(c in self.name for c in ['-', ' ', '.']):
2373 raise InvalidArguments(f'Rust crate {self.name} type {self.rust_crate_type} does not allow spaces, '
2374 'periods or dashes in the library name due to a limitation of rustc. '
2375 'Replace them with underscores, for example')
2376 if self.rust_crate_type == 'staticlib':
2377 # FIXME: In the case of no-std we should not add those libraries,
2378 # but we have no way to know currently.
2379
2380 # XXX:
2381 # In the case of no-std, we are likely in a bare metal case
2382 # and thus, machine_info kernel should be set to 'none'.
2383 # In that case, native_static_libs list is empty.
2384 rustc = T.cast('RustCompiler', self.compilers['rust'])
2385 if rustc.get_crt_static():
2386 # musl targets need self-contained for libc.a, libunwind.a etc.
2387 link_args = ['-L' + rustc.get_target_libdir() + '/self-contained']
2388 else:
2389 # Avoid embedding self-contained libc.a into shared libraries —
2390 # creates a second musl instance with uninitialized __libc state.
2391 link_args = []
2392 link_args += rustc.native_static_libs
2393 d = dependencies.InternalDependency(version='undefined', link_args=link_args,
2394 name='_rust_native_static_libs')
2395 self.external_deps.append(d)
2396
2397 default_prefix, default_suffix = self.determine_default_prefix_and_suffix()
2398 if not self.name_prefix_set:
2399 self.prefix = default_prefix
2400 if not self.name_suffix_set:
2401 self.suffix = default_suffix
2402 self.filename = self.prefix + self.name + '.' + self.suffix
2403 self.outputs[0] = self.filename
2404
2405 def _default_library_type(self) -> _LibraryType:
2406 bl = super()._default_library_type()
2407 return 'static' if bl == 'auto' else bl
2408
2409 def determine_default_prefix_and_suffix(self) -> T.Tuple[str, str]:
2410 scheme = self.environment.coredata.get_option_for_target(self, 'namingscheme')
2411 assert isinstance(scheme, str), 'for mypy'
2412 if scheme == 'platform':
2413 schemename = self.get_platform_scheme_name()
2414 prefix, suffix = DEFAULT_STATIC_LIBRARY_NAMES[schemename]
2415 else:
2416 prefix = ''
2417 suffix = ''
2418 # By default a static library is named libfoo.a even on Windows because
2419 # MSVC does not have a consistent convention for what static libraries
2420 # are called. The MSVC CRT uses libfoo.lib syntax but nothing else uses
2421 # it and GCC only looks for static libraries called foo.lib and
2422 # libfoo.a. However, we cannot use foo.lib because that's the same as
2423 # the import library. Using libfoo.a is ok because people using MSVC
2424 # always pass the library filename while linking anyway.
2425 #
2426 # See our FAQ for more detailed rationale:
2427 # https://mesonbuild.com/FAQ.html#why-does-building-my-project-with-msvc-output-static-libraries-called-libfooa
2428 if not hasattr(self, 'prefix'):
2429 prefix = 'lib'
2430 if not hasattr(self, 'suffix'):
2431 if self.uses_rust():
2432 if self.rust_crate_type == 'rlib':
2433 # default Rust static library suffix
2434 suffix = 'rlib'
2435 elif self.rust_crate_type == 'staticlib':
2436 suffix = 'a'
2437 elif self.environment.machines[self.for_machine].is_os2() and self.environment.coredata.optstore.get_value_for(OptionKey('os2_emxomf')):
2438 suffix = 'lib'
2439 else:
2440 suffix = 'a'
2441 if 'c' in self.compilers and self.compilers['c'].get_id() == 'tasking' and not self.prelink:
2442 key = OptionKey('b_lto', self.subproject, self.for_machine)
2443 v = self.environment.coredata.get_option_for_target(self, key)
2444 assert isinstance(v, bool), 'for mypy'
2445 if v:
2446 suffix = 'ma'
2447 return (prefix, suffix)
2448
2449 def get_default_install_dir(self) -> T.Tuple[str, str]:
2450 return self.environment.get_static_lib_dir(), '{libdir_static}'
2451
2452 def type_suffix(self) -> str:
2453 return "@rlib" if self.uses_rust_abi() else "@sta"
2454
2455 def is_linkable_target(self) -> bool:
2456 return True
2457
2458 def is_internal(self) -> bool:
2459 return not self.install
2460
2461 def set_shared(self, shared_library: SharedLibrary) -> None:
2462 self.both_lib = copy.copy(shared_library)
2463 self.both_lib.both_lib = None
2464
2465 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2466 result = self
2467 if lib_type == 'shared':
2468 result = self.both_lib or self
2469 if recursive:
2470 result.link_targets = [t.get(lib_type, True) for t in self.link_targets]
2471 return result
2472
2473 def link_whole(
2474 self,
2475 targets: T.Iterable[StaticTargetTypes],
2476 promoted: bool = False) -> None:
2477 for t in targets:
2478 self.check_can_link_together(t)
2479
2480 # When we're a static library and we link_whole: to another static
2481 # library, we need to add that target's objects to ourselves.
2482 self._bundle_static_library(t, promoted)
2483
2484 # If we install this static library we also need to include objects
2485 # from all uninstalled static libraries it depends on.
2486 if self.install:
2487 for lib in t.get_internal_static_libraries():
2488 self._bundle_static_library(lib, True)
2489 self.link_whole_targets.append(t)
2490
2491 def link(self, targets: T.Iterable[LinkableTargetTypes]) -> None:
2492 for t in targets:
2493 if self.install and t.is_internal():
2494 # When we're a static library and we link_with to an
2495 # internal/convenience library, promote to link_whole.
2496 assert isinstance(t, (StaticLibrary, CustomTarget, CustomTargetIndex)), 'for mypy'
2497 self.link_whole([t], promoted=True)
2498 continue
2499 self.check_can_link_together(t)
2500 self.link_targets.append(t)
2501
2502 def _bundle_static_library(self, t: StaticTargetTypes, promoted: bool = False) -> None:
2503 if self.uses_rust():
2504 # Rustc can bundle static libraries, no need to extract objects.
2505 self.link_whole_targets.append(t)
2506 elif isinstance(t, (CustomTarget, CustomTargetIndex)) or t.uses_rust():
2507 # To extract objects from a custom target we would have to extract
2508 # the archive, WIP implementation can be found in
2509 # https://github.com/mesonbuild/meson/pull/9218.
2510 # For Rust C ABI we could in theory have access to objects, but we
2511 # don't currently build them in such a way that this is possible:
2512 # https://github.com/mesonbuild/meson/issues/10724
2513 m = (f'Cannot link_whole a custom or Rust target {t.name!r} into a static library {self.name!r}. '
2514 'Instead, pass individual object files with the "objects:" keyword argument if possible.')
2515 if promoted:
2516 m += (f' Meson had to promote link to link_whole because {self.name!r} is installed but not {t.name!r},'
2517 f' and thus has to include objects from {t.name!r} to be usable.')
2518 raise InvalidArguments(m)
2519 else:
2520 self.objects.append(t.extract_all_objects())
2521
2522 class SharedLibrary(BuildTarget, LinkableTarget):
2523 typename = 'shared library'
2524
2525 # Used by AIX to decide whether to archive shared library or not.
2526 aix_so_archive = True
2527
2528 def __init__(
2529 self,
2530 name: str,
2531 subdir: str,
2532 orig_for_machine: MachineChoice,
2533 sources: T.List['SourceOutputs'],
2534 structured_sources: T.Optional[StructuredSources],
2535 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2536 environment: Environment,
2537 compilers: CompilerDict,
2538 build_project: BuildProject,
2539 kwargs: SharedLibraryKeywordArguments):
2540 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
2541 environment, compilers, build_project, kwargs)
2542 # Max length 2, first element is compatibility_version, second is current_version
2543 self.darwin_versions: T.Optional[T.Tuple[str, str]] = None
2544 self.soversion: T.Optional[str] = None
2545 self.ltversion: T.Optional[str] = None
2546 if not self.environment.machines[self.for_machine].is_android():
2547 # Shared library version
2548 self.ltversion = kwargs.get('version')
2549 self.soversion = kwargs.get('soversion')
2550 if self.soversion is None and self.ltversion is not None:
2551 # library version is defined, get the soversion from that
2552 # We replicate what Autotools does here and take the first
2553 # number of the version by default.
2554 self.soversion = self.ltversion.split('.')[0]
2555 # macOS, iOS and tvOS dylib compatibility_version and current_version
2556 self.darwin_versions = kwargs.get('darwin_versions')
2557 if self.darwin_versions is None and self.soversion is not None:
2558 # If unspecified, pick the soversion
2559 self.darwin_versions = (self.soversion, self.soversion)
2560
2561 self.win_subsystem = kwargs.get('win_subsystem') or 'console'
2562
2563 self.vs_module_defs: File | None = None
2564 # Visual Studio module-definitions file
2565 self.process_vs_module_defs_kw(kwargs)
2566
2567 # OS/2 uses a 8.3 name for a DLL
2568 self.shortname = kwargs.get('shortname')
2569
2570 # The import library this target will generate
2571 self.import_filename: str | None = None
2572
2573 # The debugging information file this target will generate
2574 self.debug_filename: str | None = None
2575
2576 # Use by the pkgconfig module
2577 self.shared_library_only = False
2578
2579 self.rust_crate_type = kwargs.get('rust_crate_type', 'dylib')
2580
2581 def post_init(self) -> None:
2582 super().post_init()
2583 if self.uses_rust():
2584 # See https://github.com/rust-lang/rust/issues/110460
2585 if self.rust_crate_type != 'cdylib' and any(c in self.name for c in ['-', ' ', '.']):
2586 raise InvalidArguments(f'Rust crate {self.name} type {self.rust_crate_type} does not allow spaces, '
2587 'periods or dashes in the library name due to a limitation of rustc. '
2588 'Replace them with underscores, for example')
2589
2590 if not hasattr(self, 'prefix'):
2591 self.prefix = None
2592 if not hasattr(self, 'suffix'):
2593 self.suffix = None
2594 self.basic_filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2595 self.determine_filenames()
2596
2597 def _default_library_type(self) -> _LibraryType:
2598 bl = super()._default_library_type()
2599 return 'shared' if bl == 'auto' else bl
2600
2601 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
2602 result: T.Dict[str, str] = {}
2603 mappings = dict(self.get_transitive_link_deps_mapping(prefix))
2604 old = get_target_macos_dylib_install_name(self)
2605 if old not in mappings:
2606 fname = self.get_filename()
2607 install_dir = self.install_dir[0]
2608 assert install_dir is not False, 'This is a bug'
2609 new = os.path.join(prefix, install_dir, fname)
2610 result.update({old: new})
2611 mappings.update(result)
2612 return mappings
2613
2614 def get_default_install_dir(self) -> T.Tuple[str, str]:
2615 return self.environment.get_shared_lib_dir(), '{libdir_shared}'
2616
2617 def determine_naming_info(self) -> T.Tuple[str, str, str, str, bool]:
2618 scheme = self.environment.coredata.get_option_for_target(self, 'namingscheme')
2619 assert isinstance(scheme, str), 'for mypy'
2620
2621 prefix: str | None
2622 suffix: str | None
2623 import_suffix: str | None
2624
2625 if scheme == 'platform':
2626 schemename = self.get_platform_scheme_name()
2627 prefix, suffix, import_suffix = DEFAULT_SHARED_LIBRARY_NAMES[schemename]
2628 else:
2629 prefix = None
2630 suffix = None
2631 import_suffix = None
2632 filename_tpl = self.basic_filename_tpl
2633 create_debug_file = False
2634 create_debug_file = False
2635 self.filename_tpl = self.basic_filename_tpl
2636 import_filename_tpl: str | None = None
2637 # NOTE: manual prefix/suffix override is currently only tested for C/C++
2638 # C# and Mono
2639 if 'cs' in self.compilers:
2640 prefix = ''
2641 suffix = 'dll'
2642 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2643 create_debug_file = True
2644 # C, C++, Swift, Vala
2645 # Only Windows and OS/2 uses a separate import library for linking
2646 # For all other targets/platforms import_filename stays None
2647 elif self.environment.machines[self.for_machine].is_windows():
2648 suffix = suffix if suffix is not None else 'dll'
2649 if self.uses_rust():
2650 # Shared library is of the form foo.dll
2651 prefix = prefix if prefix is not None else ''
2652 # Import library is called foo.dll.lib
2653 import_filename_tpl = '{0.prefix}{0.name}.dll.lib'
2654 # .pdb file is only created when debug symbols are enabled
2655 create_debug_file = self.environment.coredata.optstore.get_value_for(OptionKey("debug"))
2656 assert isinstance(create_debug_file, bool), 'for mypy'
2657 elif self.get_using_msvc():
2658 # Shared library is of the form foo.dll
2659 prefix = prefix if prefix is not None else ''
2660 # Import library is called foo.lib
2661 import_suffix = import_suffix if import_suffix is not None else 'lib'
2662 import_filename_tpl = '{0.prefix}{0.name}.' + import_suffix
2663 # .pdb file is only created when debug symbols are enabled
2664 create_debug_file = self.environment.coredata.optstore.get_value_for(OptionKey("debug"))
2665 assert isinstance(create_debug_file, bool), 'for mypy'
2666 # Assume GCC-compatible naming
2667 else:
2668 # Shared library is of the form libfoo.dll
2669 prefix = prefix if prefix is not None else 'lib'
2670 # Import library is called libfoo.dll.a
2671 import_suffix = import_suffix if import_suffix is not None else '.dll.a'
2672 import_filename_tpl = '{0.prefix}{0.name}' + import_suffix
2673 # Shared library has the soversion if it is defined
2674 if self.soversion:
2675 filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
2676 else:
2677 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2678 elif self.environment.machines[self.for_machine].is_cygwin():
2679 suffix = 'dll'
2680 # Shared library is of the form cygfoo.dll
2681 # (ld --dll-search-prefix=cyg is the default)
2682 prefix = 'cyg'
2683 # Import library is called libfoo.dll.a
2684 import_suffix = import_suffix if import_suffix is not None else '.dll.a'
2685 import_prefix = self.prefix if self.prefix is not None else 'lib'
2686 import_filename_tpl = import_prefix + '{0.name}' + import_suffix
2687 if self.soversion:
2688 filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
2689 else:
2690 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2691 elif self.environment.machines[self.for_machine].is_darwin():
2692 prefix = prefix if prefix is not None else 'lib'
2693 suffix = suffix if suffix is not None else 'dylib'
2694 # On macOS, the filename can only contain the major version
2695 if self.soversion:
2696 # libfoo.X.dylib
2697 filename_tpl = '{0.prefix}{0.name}.{0.soversion}.{0.suffix}'
2698 else:
2699 # libfoo.dylib
2700 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2701 elif self.environment.machines[self.for_machine].is_android():
2702 prefix = prefix if prefix is not None else 'lib'
2703 suffix = suffix if suffix is not None else 'so'
2704 # Android doesn't support shared_library versioning
2705 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2706 elif self.environment.machines[self.for_machine].is_os2():
2707 # Shared library is of the form foo.dll
2708 prefix = prefix if prefix is not None else ''
2709 suffix = suffix if suffix is not None else 'dll'
2710 # Import library is called foo_dll.a or foo_dll.lib
2711 if import_suffix is None:
2712 import_suffix = '_dll.lib' if self.environment.coredata.optstore.get_value_for(OptionKey('os2_emxomf')) else '_dll.a'
2713 import_filename_tpl = '{0.prefix}{0.name}' + import_suffix
2714 filename_tpl = '{0.shortname}' if self.shortname else '{0.prefix}{0.name}'
2715 if self.soversion:
2716 # fooX.dll
2717 filename_tpl += '{0.soversion}'
2718 filename_tpl += '.{0.suffix}'
2719 else:
2720 prefix = prefix if prefix is not None else 'lib'
2721 suffix = suffix if suffix is not None else 'so'
2722 if self.ltversion:
2723 # libfoo.so.X[.Y[.Z]] (.Y and .Z are optional)
2724 filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.ltversion}'
2725 elif self.soversion:
2726 # libfoo.so.X
2727 filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.soversion}'
2728 else:
2729 # No versioning, libfoo.so
2730 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2731 return (prefix, suffix, filename_tpl, import_filename_tpl, create_debug_file)
2732
2733 def determine_filenames(self) -> None:
2734 """
2735 See https://github.com/mesonbuild/meson/pull/417 for details.
2736
2737 First we determine the filename template (self.filename_tpl), then we
2738 set the output filename (self.filename).
2739
2740 The template is needed while creating aliases (self.get_aliases),
2741 which are needed while generating .so shared libraries for Linux.
2742
2743 Besides this, there's also the import library name (self.import_filename),
2744 which is only used on Windows and OS/2 since on that platform the linker uses a
2745 separate library called the "import library" during linking instead of
2746 the shared library (DLL).
2747 """
2748 prefix, suffix, filename_tpl, import_filename_tpl, create_debug_file = self.determine_naming_info()
2749 if self.prefix is None:
2750 self.prefix = prefix
2751 if self.suffix is None:
2752 self.suffix = suffix
2753 self.filename_tpl = filename_tpl
2754 self.filename = self.filename_tpl.format(self)
2755 if self.environment.machines[self.for_machine].is_os2():
2756 # OS/2 does not allow a longer DLL name than 8 chars
2757 name = os.path.splitext(self.filename)[0]
2758 if len(name) > 8:
2759 name = name[:8]
2760 if self.soversion:
2761 name = name[:-len(self.soversion)] + self.soversion
2762 self.filename = '{}.{}'.format(name, self.suffix)
2763 if import_filename_tpl:
2764 self.import_filename = import_filename_tpl.format(self)
2765 # There may have been more outputs added by the time we get here, so
2766 # only replace the first entry
2767 self.outputs[0] = self.filename
2768 if create_debug_file:
2769 self.debug_filename = os.path.splitext(self.filename)[0] + '.pdb'
2770
2771 def get_import_filename(self) -> T.Optional[str]:
2772 """
2773 The name of the import library that will be outputted by the compiler
2774
2775 Returns None if there is no import library required for this platform
2776 """
2777 return self.import_filename
2778
2779 def get_debug_filename(self) -> T.Optional[str]:
2780 """
2781 The name of debuginfo file that will be created by the compiler
2782
2783 Returns None if the build won't create any debuginfo file
2784 """
2785 return self.debug_filename
2786
2787 def get_aliases(self) -> T.List[T.Tuple[str, str, str]]:
2788 """
2789 If the versioned library name is libfoo.so.0.100.0, aliases are:
2790 * libfoo.so.0 (soversion) -> libfoo.so.0.100.0
2791 * libfoo.so (unversioned; for linking) -> libfoo.so.0
2792 Same for dylib:
2793 * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib
2794 """
2795 aliases: T.List[T.Tuple[str, str, str]] = []
2796 # Aliases are only useful with .so and .dylib libraries. Also if
2797 # there's no self.soversion (no versioning), we don't need aliases.
2798 if self.suffix not in ('so', 'dylib') or not self.soversion:
2799 return aliases
2800 # With .so libraries, the minor and micro versions are also in the
2801 # filename. If ltversion != soversion we create an soversion alias:
2802 # libfoo.so.0 -> libfoo.so.0.100.0
2803 # Where libfoo.so.0.100.0 is the actual library
2804 if self.suffix == 'so' and self.ltversion and self.ltversion != self.soversion:
2805 alias_tpl = self.filename_tpl.replace('ltversion', 'soversion')
2806 ltversion_filename = alias_tpl.format(self)
2807 tag = self.install_tag[0] or 'runtime'
2808 aliases.append((ltversion_filename, self.filename, tag))
2809 # libfoo.so.0/libfoo.0.dylib is the actual library
2810 else:
2811 ltversion_filename = self.filename
2812 # Unversioned alias:
2813 # libfoo.so -> libfoo.so.0
2814 # libfoo.dylib -> libfoo.0.dylib
2815 tag = self.install_tag[0] or 'devel'
2816 aliases.append((self.basic_filename_tpl.format(self), ltversion_filename, tag))
2817 return aliases
2818
2819 def type_suffix(self) -> str:
2820 return "@sha"
2821
2822 def is_linkable_target(self) -> bool:
2823 return True
2824
2825 def set_static(self, static_library: StaticLibrary) -> None:
2826 self.both_lib = copy.copy(static_library)
2827 self.both_lib.both_lib = None
2828
2829 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2830 result = self
2831 if lib_type == 'static':
2832 result = self.both_lib or self
2833 if recursive:
2834 result.link_targets = [t.get(lib_type, True) for t in self.link_targets]
2835 return result
2836
2837 def link_whole(
2838 self,
2839 targets: T.Iterable[StaticTargetTypes],
2840 promoted: bool = False) -> None:
2841 for t in targets:
2842 self.check_can_link_together(t)
2843 if not getattr(t, 'pic', True):
2844 msg = f"Can't link non-PIC static library {t.name!r} into shared library {self.name!r}. "
2845 msg += "Use the 'pic' option to static_library to build with PIC."
2846 raise InvalidArguments(msg)
2847 self.link_whole_targets.append(t)
2848
2849 def link(self, targets: T.Iterable[LinkableTargetTypes]) -> None:
2850 for t in targets:
2851 if isinstance(t, StaticLibrary) and not t.pic:
2852 msg = f"Can't link non-PIC static library {t.name!r} into shared library {self.name!r}. "
2853 msg += "Use the 'pic' option to static_library to build with PIC."
2854 raise InvalidArguments(msg)
2855 self.check_can_link_together(t)
2856 self.link_targets.append(t)
2857
2858 # A shared library that is meant to be used with dlopen rather than linking
2859 # into something else.
2860 class SharedModule(SharedLibrary):
2861 typename = 'shared module'
2862
2863 # Used by AIX to not archive shared library for dlopen mechanism
2864 aix_so_archive = False
2865
2866 def __init__(
2867 self,
2868 name: str,
2869 subdir: str,
2870 orig_for_machine: MachineChoice,
2871 sources: T.List['SourceOutputs'],
2872 structured_sources: T.Optional[StructuredSources],
2873 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2874 environment: Environment,
2875 compilers: CompilerDict,
2876 build_project: BuildProject,
2877 kwargs: SharedModuleKeywordArguments):
2878 super().__init__(name, subdir, orig_for_machine, sources,
2879 structured_sources, objects, environment, compilers, build_project,
2880 # SharedModuleKeywordArguments is a subclass, it's annoying mypy can't figure this out
2881 T.cast('SharedLibraryKeywordArguments', kwargs))
2882 # We need to set the soname in cases where build files link the module
2883 # to build targets, see: https://github.com/mesonbuild/meson/issues/9492
2884 self.force_soname = False
2885
2886 def get_default_install_dir(self) -> T.Tuple[str, str]:
2887 return self.environment.get_shared_module_dir(), '{moduledir_shared}'
2888
2889 class BothLibraries(SecondLevelHolder, LinkableTarget):
2890 typename: T.ClassVar[str] = 'both libraries'
2891
2892 def __init__(self, shared: SharedLibrary, static: StaticLibrary, preferred_library: Literal['shared', 'static']) -> None:
2893 self._preferred_library = preferred_library
2894 self.shared = shared
2895 self.static = static
2896 self.subproject = self.shared.subproject
2897
2898 def __repr__(self) -> str:
2899 return f'<BothLibraries: static={repr(self.static)}; shared={repr(self.shared)}>'
2900
2901 def get(self, lib_type: _LibraryType) -> T.Union[StaticLibrary, SharedLibrary]:
2902 if lib_type == 'static':
2903 return self.static
2904 if lib_type == 'shared':
2905 return self.shared
2906 return self.get_default_object()
2907
2908 def get_default_object(self) -> T.Union[StaticLibrary, SharedLibrary]:
2909 if self._preferred_library == 'shared':
2910 return self.shared
2911 elif self._preferred_library == 'static':
2912 return self.static
2913 raise MesonBugException(f'self._preferred_library == "{self._preferred_library}" is neither "shared" nor "static".')
2914
2915 def get_id(self) -> str:
2916 return self.get_default_object().get_id()
2917
2918 def is_linkable_target(self) -> bool:
2919 # For polymorphism with build targets
2920 return True
2921
2922
2923 def flatten_command(cmd: T.Iterable[CommandTypes],
2924 subproject: SubProject) -> tuple[list[str | File | BuildTarget | CustomTarget | programs.Program],
2925 list[File], list[BuildTarget | CustomTarget]]:
2926 final_cmd: list[str | File | programs.Program | BuildTarget | CustomTarget] = []
2927 depend_files: list[File] = []
2928 dependencies: list[BuildTarget | CustomTarget] = []
2929 for c in cmd:
2930 if isinstance(c, LocalProgram):
2931 c = c.program
2932 if isinstance(c, str):
2933 final_cmd.append(c)
2934 elif isinstance(c, File):
2935 depend_files.append(c)
2936 final_cmd.append(c)
2937 elif isinstance(c, programs.Program):
2938 if not c.found():
2939 raise InvalidArguments('Tried to use not-found external program in "command"')
2940 # We know path is not none if c.found()
2941 path = unwrap(c.get_path())
2942 if os.path.isabs(path):
2943 # Can only add a dependency on an external program which we
2944 # know the absolute path of
2945 depend_files.append(File.from_absolute_file(path))
2946 # Do NOT flatten -- it is needed for later parsing
2947 final_cmd.append(c)
2948 elif isinstance(c, (BuildTarget, CustomTarget)):
2949 dependencies.append(c)
2950 final_cmd.append(c)
2951 elif isinstance(c, CustomTargetIndex):
2952 FeatureNew.single_use('CustomTargetIndex for command argument', '0.60', subproject)
2953 dependencies.append(c.target)
2954 c, df, d = flatten_command([File.from_built_file(c.get_subdir(), c.get_filename())], subproject)
2955 final_cmd.extend(c)
2956 depend_files.extend(df)
2957 dependencies.extend(d)
2958 elif isinstance(c, list):
2959 # TODO: is this case even reachable?
2960 c, df, d = flatten_command(c, subproject)
2961 final_cmd.extend(c)
2962 depend_files.extend(df)
2963 dependencies.extend(d)
2964 else:
2965 raise InvalidArguments(f'Argument {c!r} in "command" is invalid')
2966 return final_cmd, depend_files, dependencies
2967
2968
2969 class CustomTargetBase(LinkableTarget, metaclass=SimpleABC):
2970 ''' Base class for CustomTarget and CustomTargetIndex
2971
2972 This base class can be used to provide a dummy implementation of some
2973 private methods to avoid repeating `isinstance(t, BuildTarget)` when dealing
2974 with custom targets.
2975 '''
2976
2977 rust_crate_type = ''
2978
2979 def get_dependencies_recurse(self, result: OrderedSet[BuildTargetTypes],
2980 visited: T.Set[tuple[BuildTargetTypes, bool, bool]],
2981 include_internals: bool = True,
2982 handled_by_rustc: bool = False) -> None:
2983 pass
2984
2985 def get_internal_static_libraries(self) -> OrderedSet[StaticTargetTypes]:
2986 return OrderedSet()
2987
2988 def get_internal_static_libraries_recurse(self, result: OrderedSet[StaticTargetTypes]) -> None:
2989 pass
2990
2991 def get_all_linked_targets(self) -> ImmutableListProtocol[BuildTargetTypes]:
2992 return []
2993
2994 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2995 """Base case used by BothLibraries"""
2996 assert isinstance(self, (CustomTarget, CustomTargetIndex))
2997 return self
2998
2999 def uses_rust_abi(self) -> bool:
3000 return False
3001
3002 def uses_fortran(self) -> bool:
3003 return False
3004
3005 def uses_swift_cpp_interop(self) -> bool:
3006 return False
3007
3008
3009 class CustomTarget(Target, CustomTargetBase):
3010
3011 typename = 'custom'
3012
3013 def __init__(self,
3014 name: T.Optional[str],
3015 subdir: str,
3016 environment: Environment,
3017 command: T.Sequence[CommandTypes],
3018 sources: T.Sequence[CustomTargetSources],
3019 outputs: T.List[str],
3020 build_project: BuildProject,
3021 *,
3022 build_always_stale: bool = False,
3023 build_by_default: T.Optional[bool] = None,
3024 capture: bool = False,
3025 console: bool = False,
3026 depend_files: list[File] | None = None,
3027 extra_depends: T.Optional[T.Sequence[TargetDepends]] = None,
3028 depfile: T.Optional[str] = None,
3029 depfile_type: T.Optional[Literal['gcc', 'msvc']] = None,
3030 env: T.Optional[EnvironmentVariables] = None,
3031 feed: bool = False,
3032 install: bool = False,
3033 install_dir: T.Optional[T.List[T.Union[str, Literal[False]]]] = None,
3034 install_mode: T.Optional[FileMode] = None,
3035 install_tag: T.Optional[T.List[T.Optional[str]]] = None,
3036 rspable: bool = False,
3037 absolute_paths: bool = False,
3038 backend: T.Optional['Backend'] = None,
3039 description: str = 'Generating {} with a custom command',
3040 build_subdir: str = '',
3041 ):
3042 # TODO expose keyword arg to make MachineChoice.HOST configurable
3043 super().__init__(name, subdir, False, MachineChoice.HOST, environment,
3044 build_project, install, build_always_stale, build_subdir = build_subdir)
3045 self.sources = list(sources)
3046 self.outputs = substitute_values(
3047 outputs, get_filenames_templates_dict(
3048 get_sources_string_names(sources, backend),
3049 []))
3050 self.build_by_default = build_by_default if build_by_default is not None else install
3051 self.capture = capture
3052 self.console = console
3053 self.depend_files = list(depend_files or [])
3054 self.dependencies: T.List[T.Union[CustomTarget, BuildTarget]] = []
3055 # must be after depend_files and dependencies
3056 c, df, d = flatten_command(command, build_project.subproject)
3057 self.command = c
3058 self.depend_files.extend(df)
3059 self.dependencies.extend(d)
3060 self.depfile = depfile
3061 self.depfile_type = 'gcc' if depfile else depfile_type
3062 self.env = env or EnvironmentVariables()
3063 self.feed = feed
3064 self.install_dir = list(install_dir or [])
3065 self.has_custom_install_dir = bool(self.install_dir)
3066 self.install_mode = install_mode
3067 self.install_tag = _process_install_tag(install_tag, len(self.outputs))
3068 self.name = name if name else self.outputs[0]
3069 self.description = description
3070
3071 # Whether to use absolute paths for all files on the commandline
3072 self.absolute_paths = absolute_paths
3073
3074 # Whether to enable using response files for the underlying tool
3075 self.rspable = rspable
3076
3077 self.extra_depends: T.List[T.Union[GeneratedTypes, BuildTarget]] = []
3078 if extra_depends:
3079 for d in extra_depends:
3080 if isinstance(d, LocalProgram):
3081 d = d.get_target()
3082 elif isinstance(d, programs.Program):
3083 path = d.get_path()
3084 # Can only add a dependency on an external program which we
3085 # know the absolute path of
3086 if not os.path.isabs(path):
3087 continue
3088 d = File.from_absolute_file(path)
3089 if isinstance(d, File):
3090 self.depend_files.append(d)
3091 else:
3092 self.extra_depends.append(d)
3093
3094 def install_dir_names(self) -> T.List[T.Optional[str]]:
3095 install_dir_names: T.List[T.Optional[str]] = []
3096 if self.has_custom_install_dir:
3097 install_dir_names = [getattr(i, 'optname', None) for i in self.install_dir]
3098
3099 return install_dir_names
3100
3101 def __repr__(self) -> str:
3102 repr_str = "<{0} {1}: {2}>"
3103 return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
3104
3105 def get_target_dependencies(self) -> T.List[TargetDepends | File | ExtractedObjects]:
3106 deps: T.List[TargetDepends | File | ExtractedObjects] = []
3107 deps.extend(self.dependencies)
3108 deps.extend(self.extra_depends)
3109 for c in self.sources:
3110 if isinstance(c, CustomTargetIndex):
3111 deps.append(c.target)
3112 elif not isinstance(c, programs.ExternalProgram):
3113 deps.append(c)
3114 return deps
3115
3116 def get_transitive_build_target_deps(self) -> T.Set[T.Union[BuildTarget, 'CustomTarget']]:
3117 '''
3118 Recursively fetch the build targets that this custom target depends on,
3119 whether through `command:`, `depends:`, or `sources:` The recursion is
3120 only performed on custom targets.
3121 This is useful for setting PATH on Windows for finding required DLLs.
3122 F.ex, if you have a python script that loads a C module that links to
3123 other DLLs in your project.
3124 '''
3125 bdeps: T.Set[T.Union[BuildTarget, 'CustomTarget']] = set()
3126 deps = self.get_target_dependencies()
3127 for d in deps:
3128 if isinstance(d, BuildTarget):
3129 bdeps.add(d)
3130 elif isinstance(d, CustomTarget):
3131 bdeps.update(d.get_transitive_build_target_deps())
3132 return bdeps
3133
3134 def get_dependencies(self) -> T.List[T.Union[CustomTarget, BuildTarget]]:
3135 return self.dependencies
3136
3137 def should_install(self) -> bool:
3138 return self.install
3139
3140 def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
3141 return self.install_dir
3142
3143 def get_custom_install_mode(self) -> T.Optional['FileMode']:
3144 return self.install_mode
3145
3146 def get_outputs(self) -> T.List[str]:
3147 return self.outputs
3148
3149 def get_filename(self) -> str:
3150 return self.outputs[0]
3151
3152 def get_sources(self) -> T.List[CustomTargetSources]:
3153 return self.sources
3154
3155 def get_generated_lists(self) -> T.List[GeneratedList]:
3156 genlists: T.List[GeneratedList] = []
3157 for c in self.sources:
3158 if isinstance(c, GeneratedList):
3159 genlists.append(c)
3160 return genlists
3161
3162 def get_generated_sources(self) -> T.List[GeneratedList]:
3163 return self.get_generated_lists()
3164
3165 def get_dep_outname(self, infilenames: list[str]) -> str:
3166 if self.depfile is None:
3167 raise InvalidArguments('Tried to get depfile name for custom_target that does not have depfile defined.')
3168 if infilenames:
3169 plainname = os.path.basename(infilenames[0])
3170 basename = os.path.splitext(plainname)[0]
3171 return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
3172 else:
3173 if '@BASENAME@' in self.depfile or '@PLAINNAME@' in self.depfile:
3174 raise InvalidArguments('Substitution in depfile for custom_target that does not have an input file.')
3175 return self.depfile
3176
3177 def is_linkable_output(self, output: str) -> bool:
3178 if output.endswith(('.a', '.dll', '.lib', '.so', '.dylib')):
3179 return True
3180 # libfoo.so.X soname
3181 if re.search(r'\.so(\.\d+)*$', output):
3182 return True
3183 return False
3184
3185 def is_linkable_target(self) -> bool:
3186 if len(self.outputs) != 1:
3187 return False
3188 return self.is_linkable_output(self.outputs[0])
3189
3190 def links_dynamically(self) -> bool:
3191 """Whether this target links dynamically or statically
3192
3193 Does not assert the target is linkable, just that it is not shared
3194
3195 :return: True if is dynamically linked, otherwise False
3196 """
3197 suf = os.path.splitext(self.outputs[0])[-1]
3198 return suf not in {'.a', '.lib'}
3199
3200 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
3201 return {}
3202
3203 def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
3204 return OrderedSet()
3205
3206 def get_all_link_deps(self) -> ImmutableListProtocol[BuildTargetTypes]:
3207 return []
3208
3209 def is_internal(self) -> bool:
3210 '''
3211 Returns True if this is a not installed static library.
3212 '''
3213 if len(self.outputs) != 1:
3214 return False
3215 return CustomTargetIndex(self, self.outputs[0]).is_internal()
3216
3217 def type_suffix(self) -> str:
3218 return "@cus"
3219
3220 def __getitem__(self, index: int) -> 'CustomTargetIndex':
3221 return CustomTargetIndex(self, self.outputs[index])
3222
3223 def __setitem__(self, index: T.Any, value: T.Any) -> T.Any:
3224 raise NotImplementedError
3225
3226 def __delitem__(self, index: T.Any) -> T.Any:
3227 raise NotImplementedError
3228
3229 def __iter__(self) -> T.Iterator[CustomTargetIndex]:
3230 for i in self.outputs:
3231 yield CustomTargetIndex(self, i)
3232
3233 def __len__(self) -> int:
3234 return len(self.outputs)
3235
3236 class CompileTarget(BuildTarget):
3237 '''
3238 Target that only compile sources without linking them together.
3239 It can be used as preprocessor, or transpiler.
3240 '''
3241
3242 typename = 'compile'
3243
3244 def __init__(self,
3245 name: str,
3246 subdir: str,
3247 environment: Environment,
3248 sources: T.List['SourceOutputs'],
3249 output_templ: str,
3250 compiler: Compiler,
3251 backend: Backend,
3252 compile_args: T.List[str],
3253 include_directories: T.List[IncludeDirs],
3254 dependencies: T.List[dependencies.Dependency],
3255 build_project: BuildProject,
3256 depends: T.List[BuildTargetTypes]):
3257 compilers = {compiler.get_language(): compiler}
3258 kwargs: BuildTargetKeywordArguments = {
3259 'build_by_default': False,
3260 'language_args': defaultdict(list, [(compiler.language, compile_args)]),
3261 'include_directories': include_directories,
3262 'dependencies': dependencies,
3263 'native': compiler.for_machine,
3264 }
3265 super().__init__(name, subdir, compiler.for_machine,
3266 sources, None, [], environment, compilers,
3267 build_project, kwargs)
3268 self.filename = name
3269 self.compiler = compiler
3270 self.output_templ = output_templ
3271 self.outputs = []
3272 self.sources_map: T.Dict[File, str] = {}
3273 self.depends = list(depends or [])
3274 for f in self.sources:
3275 self._add_output(f)
3276 for gensrc in self.generated:
3277 for s in gensrc.get_outputs():
3278 rel_src = backend.get_target_generated_dir(self, gensrc, s)
3279 self._add_output(File.from_built_relative(rel_src))
3280
3281 def type_suffix(self) -> str:
3282 return "@compile"
3283
3284 def _add_output(self, f: File) -> None:
3285 plainname = os.path.basename(f.fname)
3286 basename = os.path.splitext(plainname)[0]
3287 o = self.output_templ.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
3288 self.outputs.append(o)
3289 self.sources_map[f] = o
3290
3291 def get_generated_headers(self) -> T.List[File]:
3292 gen_headers: T.List[File] = []
3293 for dep in self.depends:
3294 gen_headers += [File(True, dep.subdir, o) for o in dep.get_outputs()]
3295 return gen_headers
3296
3297 def is_linkable_output(self, output: str) -> bool:
3298 return False
3299
3300 class RunTarget(Target):
3301
3302 typename = 'run'
3303
3304 def __init__(self, name: str,
3305 command: T.Sequence[CommandTypes],
3306 # the RunTarget case is used by gnome.yelp()
3307 dependencies: T.Sequence[Target | CustomTargetIndex | GeneratedList | programs.Program],
3308 subdir: str,
3309 environment: Environment,
3310 build_project: BuildProject,
3311 env: T.Optional[EnvironmentVariables] = None,
3312 default_env: bool = True):
3313 # These don't produce output artifacts
3314 super().__init__(name, subdir, False, MachineChoice.BUILD, environment, build_project)
3315 self.dependencies = list(dependencies)
3316 self.command, self.depend_files, d = flatten_command(command, build_project.subproject)
3317 self.dependencies.extend(d)
3318 self.absolute_paths = False
3319 self.env = env
3320 self.default_env = default_env
3321
3322 def __repr__(self) -> str:
3323 repr_str = "<{0} {1}: {2}>"
3324 return repr_str.format(self.__class__.__name__, self.get_id(), self.command[0])
3325
3326 def get_dependencies(self) -> T.List[Target | CustomTargetIndex | GeneratedList | programs.Program]:
3327 return self.dependencies
3328
3329 def get_generated_sources(self) -> T.List[GeneratedTypes]:
3330 return []
3331
3332 def get_sources(self) -> T.List[File]:
3333 return []
3334
3335 def should_install(self) -> bool:
3336 return False
3337
3338 def get_filename(self) -> str:
3339 return self.name
3340
3341 def get_outputs(self) -> T.List[str]:
3342 return [self.name]
3343
3344 def type_suffix(self) -> str:
3345 return "@run"
3346
3347 class AliasTarget(RunTarget):
3348
3349 typename = 'alias'
3350
3351 def __init__(self, name: str, dependencies: T.Sequence[Target],
3352 subdir: str, environment: Environment,
3353 build_project: BuildProject):
3354 super().__init__(name, [], dependencies, subdir, environment, build_project)
3355
3356 def __repr__(self) -> str:
3357 repr_str = "<{0} {1}>"
3358 return repr_str.format(self.__class__.__name__, self.get_id())
3359
3360 class Jar(BuildTarget):
3361 typename = 'jar'
3362 rust_crate_type = '' # type: ignore[assignment]
3363
3364 def __init__(self, name: str, subdir: str, orig_for_machine: MachineChoice,
3365 sources: T.List[SourceOutputs], structured_sources: T.Optional['StructuredSources'],
3366 objects: T.Sequence[ObjectTypes | GeneratedTypes], environment: Environment, compilers: CompilerDict,
3367 build_project: BuildProject, kwargs: JarKeywordArguments):
3368 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
3369 environment, compilers, build_project, kwargs)
3370 for s in self.sources:
3371 if not s.endswith('.java'):
3372 raise InvalidArguments(f'Jar source {s} is not a java file.')
3373 for t in self.link_targets:
3374 if not isinstance(t, Jar):
3375 raise InvalidArguments(f'Link target {t} is not a jar target.')
3376 if self.structured_sources:
3377 raise InvalidArguments('structured sources are not supported in Java targets.')
3378 self.filename = self.name + '.jar'
3379 self.outputs = [self.filename]
3380 self.java_args = self.extra_args['java']
3381 self.main_class = kwargs.get('main_class', '')
3382 self.java_resources: T.Optional[StructuredSources] = kwargs.get('java_resources', None)
3383
3384 def _extract_link_with(self, kwargs: BuildTargetKeywordArguments) -> list[LinkableTargetTypes]:
3385 return kwargs['link_with']
3386
3387 def get_main_class(self) -> str:
3388 return self.main_class
3389
3390 def type_suffix(self) -> str:
3391 return "@jar"
3392
3393 def get_java_args(self) -> T.List[str]:
3394 return self.java_args
3395
3396 def get_java_resources(self) -> T.Optional[StructuredSources]:
3397 return self.java_resources
3398
3399 def validate_install(self) -> None:
3400 # All jar targets are installable.
3401 pass
3402
3403 def is_linkable_target(self) -> bool:
3404 return True
3405
3406 def get_classpath_args(self) -> T.List[str]:
3407 cp_paths = [os.path.join(l.get_subdir(), l.get_filename()) for l in self.link_targets]
3408 cp_string = os.pathsep.join(cp_paths)
3409 if cp_string:
3410 return ['-cp', os.pathsep.join(cp_paths)]
3411 return []
3412
3413 def get_default_install_dir(self) -> T.Tuple[str, str]:
3414 return self.environment.get_jar_dir(), '{jardir}'
3415
3416 @dataclass(eq=False)
3417 class CustomTargetIndex(CustomTargetBase, HoldableObject):
3418
3419 """A special opaque object returned by indexing a CustomTarget. This object
3420 exists in Meson, but acts as a proxy in the backends, making targets depend
3421 on the CustomTarget it's derived from, but only adding one source file to
3422 the sources.
3423 """
3424
3425 typename: T.ClassVar[str] = 'custom'
3426
3427 target: T.Union[CustomTarget, CompileTarget]
3428 output: str
3429
3430 def __post_init__(self) -> None:
3431 self.for_machine = self.target.for_machine
3432
3433 @lazy_property
3434 def __index(self) -> int:
3435 # Must be detected lazily becuase preporcessed sources don't end up in the
3436 # outputs, but can still be in a CustomTargetIndex.
3437 return self.target.outputs.index(self.output)
3438
3439 @property
3440 def name(self) -> str:
3441 return f'{self.target.name}[{self.output}]'
3442
3443 @property
3444 def depend_files(self) -> T.List[File]:
3445 return self.target.depend_files
3446
3447 @property
3448 def subdir(self) -> str:
3449 return self.target.subdir
3450
3451 @property
3452 def has_custom_install_dir(self) -> bool:
3453 return self.target.has_custom_install_dir
3454
3455 @property
3456 def install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
3457 return [self.target.install_dir[self.__index]]
3458
3459 def __repr__(self) -> str:
3460 return '<CustomTargetIndex: {!r}[{}]>'.format(self.target, self.output)
3461
3462 def get_outputs(self) -> T.List[str]:
3463 return [self.output]
3464
3465 def get_subdir(self) -> str:
3466 return self.target.get_subdir()
3467
3468 def get_build_subdir(self) -> str:
3469 return self.target.get_build_subdir()
3470
3471 def get_builddir(self) -> str:
3472 return self.target.get_builddir()
3473
3474 def get_filename(self) -> str:
3475 return self.output
3476
3477 def get_id(self) -> str:
3478 return self.target.get_id()
3479
3480 def get_target(self) -> BuildTarget | CustomTarget:
3481 return self.target
3482
3483 def get_all_link_deps(self) -> ImmutableListProtocol[BuildTargetTypes]:
3484 return self.target.get_all_link_deps()
3485
3486 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
3487 return self.target.get_link_deps_mapping(prefix)
3488
3489 def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
3490 return self.target.get_link_dep_subdirs()
3491
3492 def is_linkable_target(self) -> bool:
3493 return self.target.is_linkable_output(self.output)
3494
3495 def links_dynamically(self) -> bool:
3496 """Whether this target links dynamically or statically
3497
3498 Does not assert the target is linkable, just that it is not shared
3499
3500 :return: True if is dynamically linked, otherwise False
3501 """
3502 suf = os.path.splitext(self.output)[-1]
3503 return suf not in {'.a', '.lib'}
3504
3505 def should_install(self) -> bool:
3506 return self.target.should_install()
3507
3508 def is_internal(self) -> bool:
3509 '''
3510 Returns True if this is a not installed static library
3511 '''
3512 suf = os.path.splitext(self.output)[-1]
3513 return suf in {'.a', '.lib'} and not self.should_install()
3514
3515 def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
3516 return self.target.get_custom_install_dir()
3517
3518 def get_basename(self) -> str:
3519 return self.target.get_basename()
3520
3521 def install_dir_names(self) -> T.List[T.Optional[str]]:
3522 install_dir_names = self.target.install_dir_names()
3523 return [install_dir_names[self.__index]]
3524
3525
3526 class ConfigurationData(HoldableObject):
3527 def __init__(self, initial_values: T.Optional[T.Union[
3528 T.Dict[str, T.Tuple[T.Union[str, int, bool], T.Optional[str]]],
3529 T.Dict[str, T.Union[str, int, bool]]]
3530 ] = None):
3531 super().__init__()
3532 self.values: T.Dict[str, T.Tuple[T.Union[str, int, bool], T.Optional[str]]] = \
3533 {k: v if isinstance(v, tuple) else (v, None) for k, v in initial_values.items()} if initial_values else {}
3534 self.used: bool = False
3535
3536 def __repr__(self) -> str:
3537 return repr(self.values)
3538
3539 def __contains__(self, value: str) -> bool:
3540 return value in self.values
3541
3542 def __bool__(self) -> bool:
3543 return bool(self.values)
3544
3545 def get(self, name: str) -> T.Tuple[T.Union[str, int, bool], T.Optional[str]]:
3546 return self.values[name] # (val, desc)
3547
3548 def keys(self) -> T.Iterable[str]:
3549 return self.values.keys()
3550
3551 class LocalProgram(programs.Program):
3552 def __init__(self, program: T.Union[programs.ExternalProgram, Executable, CustomTarget, CustomTargetIndex], version: str,
3553 file: T.Optional[File] = None) -> None:
3554 super().__init__()
3555 if isinstance(program, CustomTarget):
3556 if len(program.outputs) != 1:
3557 raise InvalidArguments('CustomTarget used as LocalProgram must have exactly one output.')
3558 if isinstance(program, programs.ExternalProgram):
3559 if not file:
3560 raise MesonBugException('ExternalProgram used as LocalProgram must be a file from the project')
3561 self.name = program.name
3562 self.file = file
3563 self.for_machine = program.for_machine
3564 self.program = program
3565 self.version = version
3566
3567 def found(self) -> bool:
3568 return True
3569
3570 def get_version(self, interpreter: T.Optional[Interpreter] = None) -> str:
3571 return self.version
3572
3573 def get_command(self) -> T.List[str]:
3574 if isinstance(self.program, programs.ExternalProgram):
3575 return self.program.get_command()
3576 # Only the backend knows the actual path to the build program.
3577 raise MesonBugException('Cannot call get_command() on program that is a build target.')
3578
3579 def get_path(self) -> str:
3580 if isinstance(self.program, programs.ExternalProgram):
3581 return self.program.get_path()
3582 # Only the backend knows the actual path to the build program.
3583 raise MesonBugException('Cannot call get_path() on program that is a build target.')
3584
3585 def get_target(self) -> T.Union[File, Executable, CustomTarget, CustomTargetIndex]:
3586 if self.file:
3587 return self.file
3588 assert not isinstance(self.program, programs.ExternalProgram)
3589 return self.program
3590
3591 def description(self) -> str:
3592 if isinstance(self.program, programs.ExternalProgram):
3593 return self.program.description()
3594 if isinstance(self.program, Executable):
3595 return self.program.name
3596 return self.program.get_filename()
3597
3598 def runnable(self) -> bool:
3599 return isinstance(self.program, programs.ExternalProgram)
3600
3601 def get_name(self) -> str:
3602 return self.name
3603
3604 # A bit poorly named, but this represents plain data files to copy
3605 # during install.
3606 @dataclass(eq=False)
3607 class Data(HoldableObject):
3608 sources: T.List[File]
3609 install_dir: str
3610 install_dir_name: str
3611 install_mode: 'FileMode'
3612 subproject: SubProject
3613 rename: T.List[str] = None
3614 install_tag: T.Optional[str] = None
3615 data_type: str = None
3616 follow_symlinks: T.Optional[bool] = None
3617
3618 def __post_init__(self) -> None:
3619 if self.rename is None:
3620 self.rename = [os.path.basename(f.fname) for f in self.sources]
3621
3622 @dataclass(eq=False)
3623 class SymlinkData(HoldableObject):
3624 target: str
3625 name: str
3626 install_dir: str
3627 subproject: SubProject
3628 install_tag: T.Optional[str] = None
3629
3630 def __post_init__(self) -> None:
3631 if self.name != os.path.basename(self.name):
3632 raise InvalidArguments(f'Link name is "{self.name}", but link names cannot contain path separators. '
3633 'The dir part should be in install_dir.')
3634
3635 @dataclass(eq=False)
3636 class TestSetup:
3637 exe_wrapper: T.List[str]
3638 gdb: bool
3639 timeout_multiplier: int
3640 env: EnvironmentVariables
3641 exclude_suites: T.List[str]
3642
3643
3644 def get_sources_string_names(sources: T.Sequence[CustomTargetSources], backend: Backend) -> list[str]:
3645 '''
3646 For the specified list of @sources which can be strings, Files,
3647 ExternalPrograms, or targets, get all the output basenames.
3648 '''
3649 names: list[str] = []
3650 for s in sources:
3651 if isinstance(s, (BuildTarget, CustomTarget, CustomTargetIndex, GeneratedList)):
3652 names += s.get_outputs()
3653 elif isinstance(s, ExtractedObjects):
3654 names += backend.determine_ext_objs(s)
3655 elif isinstance(s, File):
3656 names.append(s.fname)
3657 elif isinstance(s, programs.ExternalProgram):
3658 names.append(s.get_path())
3659 else:
3660 raise MesonBugException(f'Unknown source type: {s!r}')
3661 return names
3662
3663 def load(build_dir: str) -> Build:
3664 filename = os.path.join(build_dir, 'meson-private', 'build.dat')
3665 try:
3666 b = pickle_load(filename, 'Build data', Build)
3667 # We excluded coredata when saving Build object, load it separately
3668 b.environment.coredata = coredata.load(build_dir)
3669 return b
3670 except FileNotFoundError:
3671 raise MesonException(f'No such build data file as {filename!r}.')
3672
3673
3674 def save(obj: Build, filename: str) -> None:
3675 # Exclude coredata because we pickle it separately already
3676 cdata = obj.environment.coredata
3677 obj.environment.coredata = None
3678 try:
3679 with open(filename, 'wb') as f:
3680 pickle.dump(obj, f)
3681 finally:
3682 obj.environment.coredata = cdata