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 = False
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 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
1327 return self.get_transitive_link_deps_mapping(prefix)
1328
1329 @lru_cache(maxsize=None)
1330 def get_transitive_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
1331 result: T.Dict[str, str] = {}
1332 for i in itertools.chain(self.link_targets, self.link_whole_targets):
1333 mapping = i.get_link_deps_mapping(prefix)
1334 # we are merging two dictionaries, while keeping the earlier one dominant
1335 # use dict() both to copy and change type
1336 result_tmp = dict(mapping)
1337 result_tmp.update(result)
1338 result = result_tmp
1339 return result
1340
1341 @lru_cache(maxsize=None)
1342 def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
1343 result: OrderedSet[str] = OrderedSet()
1344 for i in self.link_targets:
1345 if not isinstance(i, StaticLibrary):
1346 result.add(i.get_builddir())
1347 result.update(i.get_link_dep_subdirs())
1348 return result
1349
1350 def get_single_compile_base_args(self, compiler: Compiler) -> CompilerArgs:
1351 # Return a mutable CompilerArgs populated from the cached immutable
1352 # arguments so that callers can safely modify it.
1353 return compiler.compiler_args(self.single_compile_base_args[compiler])
1354
1355 def _generate_single_compile_base_args(self, compiler: Compiler) -> ImmutableListProtocol[str]:
1356 # Create an empty commands list, and start adding arguments from
1357 # various sources in the order in which they must override each other
1358 commands = compiler.compiler_args()
1359 # Start with symbol visibility.
1360 commands += compiler.gnu_symbol_visibility_args(self.gnu_symbol_visibility)
1361 # Add compiler args for compiling this target derived from 'base' build
1362 # options passed on the command-line, in default_options, etc.
1363 # These have the lowest priority.
1364 commands += get_base_compile_args(self, compiler, self.environment)
1365 return list(commands) # Avoid call to iterable.flush_pre_post in CompilerArgs.__init__
1366
1367 def get_default_install_dir(self) -> T.Tuple[str, str]:
1368 return self.environment.get_libdir(), '{libdir}'
1369
1370 def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
1371 return self.install_dir
1372
1373 def get_custom_install_mode(self) -> T.Optional['FileMode']:
1374 return self.install_mode
1375
1376 def get_override(self, name: str) -> T.Optional[ElementaryOptionValues]:
1377 return self.raw_overrides.get(name, None)
1378
1379 @T.overload
1380 def _extract_pic_pie(self, kwargs: StaticLibraryKeywordArguments, arg: Literal['pic'],
1381 option: Literal['b_staticpic']) -> bool: ...
1382
1383 @T.overload
1384 def _extract_pic_pie(self, kwargs: T.Union[StaticLibraryKeywordArguments, ExecutableKeywordArguments],
1385 arg: Literal['pie'], option: Literal['b_pie']) -> bool: ...
1386
1387 def _extract_pic_pie(self, kwargs: T.Union[StaticLibraryKeywordArguments, ExecutableKeywordArguments],
1388 arg: Literal['pic', 'pie'], option: Literal['b_staticpic', 'b_pie']) -> bool:
1389 # You can't disable PIC on OS X. The compiler ignores -fno-PIC.
1390 # PIC is always on for Windows (all code is position-independent
1391 # since library loading is done differently)
1392 m = self.environment.machines[self.for_machine]
1393 if arg == 'pic' and (m.is_darwin() or m.is_windows()):
1394 return True
1395
1396 # Executables must be PIE on Android
1397 if arg == 'pie' and m.is_android():
1398 return True
1399
1400 # Check if we have -fPIC, -fpic, -fPIE, or -fpie in cflags
1401 all_flags = self.extra_args['c'] + self.extra_args['cpp']
1402 if '-f' + arg.lower() in all_flags or '-f' + arg.upper() in all_flags:
1403 mlog.warning(f"Use the '{arg}' kwarg instead of passing '-f{arg}' manually to {self.name!r}")
1404 return True
1405
1406 if (a := kwargs.get(arg)) is not None:
1407 assert isinstance(a, bool), 'for mypy'
1408 return a
1409
1410 k = OptionKey(option)
1411 if k in self.environment.coredata.optstore:
1412 val = self.environment.coredata.get_option_for_target(self, k)
1413 assert isinstance(val, bool), 'for mypy'
1414 return val
1415
1416 return False
1417
1418 def install_dir_names(self) -> T.List[T.Optional[str]]:
1419 install_dir_names: T.List[T.Optional[str]]
1420 if self.has_custom_install_dir:
1421 install_dir_names = [getattr(i, 'optname', None) for i in self.install_dir]
1422 else:
1423 default = self.get_default_install_dir()[1]
1424 install_dir_names = T.cast('T.List[T.Optional[str]]', [default]) * len(self.install_dir)
1425
1426 return install_dir_names
1427
1428 def get_filename(self) -> str:
1429 return self.filename
1430
1431 def get_debug_filename(self) -> T.Optional[str]:
1432 """
1433 The name of debuginfo file that will be created by the compiler
1434
1435 Returns None if the build won't create any debuginfo file
1436 """
1437 return self.debug_filename
1438
1439 def get_outputs(self) -> T.List[str]:
1440 return self.outputs
1441
1442 def get_extra_args(self, language: Language) -> T.List[str]:
1443 return self.extra_args[language]
1444
1445 @lru_cache(maxsize=None)
1446 def get_dependencies(self) -> OrderedSet[BuildTargetTypes]:
1447 # Get all targets needed for linking. This includes all link_with and
1448 # link_whole targets, and also all dependencies of static libraries
1449 # recursively. The algorithm here is closely related to what we do in
1450 # get_internal_static_libraries(): Installed static libraries include
1451 # objects from all their dependencies already.
1452 result: OrderedSet[BuildTargetTypes] = OrderedSet()
1453 visited: T.Set[T.Tuple[BuildTargetTypes, bool, bool]] = set()
1454 for t in itertools.chain(self.link_targets, self.link_whole_targets):
1455 if t not in result:
1456 result.add(t)
1457 if isinstance(t, (StaticLibrary, CustomTarget, CustomTargetIndex)):
1458 t.get_dependencies_recurse(result, visited, handled_by_rustc=self.uses_rust())
1459 return result
1460
1461 def get_dependencies_recurse(self, result: OrderedSet[BuildTargetTypes],
1462 visited: T.Set[T.Tuple[BuildTargetTypes, bool, bool]],
1463 include_internals: bool = True, handled_by_rustc: bool = False) -> None:
1464 # self is always a static library because we don't need to pull dependencies
1465 # of shared libraries. If self is installed (not internal) it already
1466 # include objects extracted from all its internal dependencies so we can
1467 # skip them.
1468 include_internals = include_internals and self.is_internal()
1469 key = (self, include_internals, handled_by_rustc)
1470 if key in visited:
1471 return
1472 visited.add(key)
1473
1474 for t in self.link_targets:
1475 uses_rust_abi = isinstance(t, BuildTarget) and t.uses_rust_abi()
1476 if not handled_by_rustc and uses_rust_abi:
1477 # Rules for including libraries via Rust rlibs and staticlibs are complex:
1478 # - proc-macro crates should be skipped completely when the build product
1479 # is not a Rust program, because only rustc knows that they are
1480 # special build-machine shared libraries
1481 # - rlibs must always be returned for Rust programs, because even though
1482 # the -l flag is implicitly added, the -L flag is not. ninjabackend.py
1483 # handles leaving out the -l flag
1484 # - rlibs are bundled into staticlibs and need not be in the command line of
1485 # non-Rust programs; this is the case when t is not added to result.
1486 # - C-ABI libraries included in link_with use -lstatic:-bundle, so even for
1487 # staticlibs we do need to recurse into rlibs and collect these non-bundled
1488 # libraries. So don't return, unlike for procedural macros
1489 if t.rust_crate_type == 'proc-macro':
1490 continue
1491
1492 elif not include_internals and t.is_internal():
1493 pass
1494
1495 else:
1496 result.add(t)
1497 if isinstance(t, StaticLibrary):
1498 t.get_dependencies_recurse(result, visited, include_internals, handled_by_rustc and uses_rust_abi)
1499 for t in self.link_whole_targets:
1500 uses_rust_abi = isinstance(t, BuildTarget) and t.uses_rust_abi()
1501 t.get_dependencies_recurse(result, visited, include_internals, handled_by_rustc and uses_rust_abi)
1502
1503 def get_sources(self) -> T.List[File]:
1504 return self.sources
1505
1506 def get_objects(self) -> T.List[ObjectTypes]:
1507 return self.objects
1508
1509 def get_generated_sources(self) -> T.List['GeneratedTypes']:
1510 return self.generated
1511
1512 def should_install(self) -> bool:
1513 return self.install
1514
1515 def has_pch(self) -> bool:
1516 return any(x is not None for x in self.pch.values())
1517
1518 def get_include_dirs(self) -> T.List['IncludeDirs']:
1519 return self.include_dirs
1520
1521 def add_deps(self, deps: T.List[dependencies.Dependency]) -> None:
1522 for dep in deps:
1523 if dep in self.added_deps:
1524 # Prefer to add dependencies to added_deps which have a name
1525 if dep.is_named():
1526 self.added_deps.remove(dep)
1527 self.added_deps.add(dep)
1528 continue
1529
1530 if isinstance(dep, dependencies.InternalDependency):
1531 # Those parts that are internal.
1532 self.process_sourcelist(dep.sources)
1533 self.extra_files.extend(f for f in dep.extra_files if f not in self.extra_files)
1534 self.add_include_dirs(dep.include_directories, dep.get_include_type())
1535 self.objects.extend(dep.objects)
1536 self.link_targets.extend(dep.libraries)
1537 self.link_whole_targets.extend(dep.whole_libraries)
1538 if dep.get_compile_args() or dep.get_link_args():
1539 # Those parts that are external.
1540 extpart = type(dep)(dep.version,
1541 compile_args=dep.get_compile_args(),
1542 link_args=dep.get_link_args(),
1543 name=dep.name)
1544 self.external_deps.append(extpart)
1545 # Deps of deps.
1546 self.add_deps(dep.ext_deps)
1547 else:
1548 if dep not in self.external_deps:
1549 self.external_deps.append(dep)
1550 self.process_sourcelist(dep.get_sources())
1551 self.add_deps(dep.ext_deps)
1552
1553 dep_d_features = dep.d_features
1554
1555 for feature in ('versions', 'import_dirs'):
1556 if feature in dep_d_features:
1557 self.d_features[feature].extend(dep_d_features[feature])
1558
1559 self.added_deps.add(dep)
1560
1561 def get_external_deps(self) -> T.List[dependencies.Dependency]:
1562 return self.external_deps
1563
1564 def is_internal(self) -> bool:
1565 return False
1566
1567 def link(self, targets: T.Iterable[LinkableTargetTypes]) -> None:
1568 for t in targets:
1569 self.check_can_link_together(t)
1570 self.link_targets.append(t)
1571
1572 def link_whole(
1573 self,
1574 targets: T.Iterable[StaticTargetTypes],
1575 promoted: bool = False) -> None:
1576 for t in targets:
1577 self.check_can_link_together(t)
1578 self.link_whole_targets.append(t)
1579
1580 @lru_cache(maxsize=None)
1581 def get_internal_static_libraries(self) -> OrderedSet[StaticTargetTypes]:
1582 result: OrderedSet[StaticTargetTypes] = OrderedSet()
1583 self.get_internal_static_libraries_recurse(result)
1584 return result
1585
1586 def get_internal_static_libraries_recurse(self, result: OrderedSet[StaticTargetTypes]) -> None:
1587 for t in self.link_targets:
1588 if t.is_internal() and t not in result:
1589 assert isinstance(t, (StaticLibrary, CustomTarget, CustomTargetIndex)), 'for mypy'
1590 result.add(t)
1591 t.get_internal_static_libraries_recurse(result)
1592 for t in self.link_whole_targets:
1593 if t.is_internal():
1594 t.get_internal_static_libraries_recurse(result)
1595
1596 def check_can_link_together(self, t: BuildTargetTypes) -> None:
1597 links_with_rust_abi = isinstance(t, BuildTarget) and t.uses_rust_abi()
1598 if not self.uses_rust() and links_with_rust_abi:
1599 raise InvalidArguments(f'Try to link Rust ABI library {t.name!r} with a non-Rust target {self.name!r}')
1600 if self.for_machine is not t.for_machine and (not links_with_rust_abi or t.rust_crate_type != 'proc-macro'):
1601 msg = f'Tried to mix a {t.for_machine} library ("{t.name}") with a {self.for_machine} target "{self.name}"'
1602 if self.environment.is_cross_build():
1603 raise InvalidArguments(msg + ' This is not possible in a cross build.')
1604 else:
1605 mlog.warning(msg + ' This will fail in cross build.')
1606
1607 def add_include_dirs(self, args: T.Sequence['IncludeDirs'], set_is_system: str = 'preserve') -> None:
1608 if set_is_system != 'preserve':
1609 is_system = set_is_system == 'system'
1610 self.include_dirs.extend([IncludeDirs(x.curdir, x.incdirs, is_system, x.build_project,
1611 x.extra_build_dirs) for x in args])
1612 else:
1613 self.include_dirs.extend(args)
1614
1615 def get_aliases(self) -> T.List[T.Tuple[str, str, str]]:
1616 return []
1617
1618 def get_langs_used_by_deps(self) -> T.List[Language]:
1619 '''
1620 Sometimes you want to link to a C++ library that exports C API, which
1621 means the linker must link in the C++ stdlib, and we must use a C++
1622 compiler for linking. The same is also applicable for objc/objc++, etc,
1623 so we can keep using clink_langs for the priority order.
1624
1625 See: https://github.com/mesonbuild/meson/issues/1653
1626 '''
1627 langs: T.List[Language] = []
1628
1629 # Check if any of the external libraries were written in this language
1630 for dep in self.external_deps:
1631 if dep.language is None:
1632 continue
1633 if dep.language not in langs:
1634 langs.append(dep.language)
1635 # Check if any of the internal libraries this target links to were
1636 # written in this language
1637 for t in itertools.chain(self.link_targets, self.link_whole_targets):
1638 if isinstance(t, (CustomTarget, CustomTargetIndex)):
1639 continue
1640 target_langs = [t.link_language] if t.link_language else list(t.compilers)
1641 for language in target_langs:
1642 if language == 'rust' and not t.uses_rust_abi():
1643 # All Rust dependencies must go through a C-ABI dependency, so ignore it
1644 continue
1645 if language not in langs:
1646 langs.append(language)
1647
1648 return langs
1649
1650 def get_prelinker(self) -> Compiler:
1651 if self.link_language:
1652 comp = self.all_compilers[self.link_language]
1653 return comp
1654 for l in T.cast('T.Tuple[Language, ...]', clink_langs):
1655 if l in self.compilers:
1656 try:
1657 prelinker = self.all_compilers[l]
1658 except KeyError:
1659 raise MesonException(
1660 f'Could not get a prelinker linker for build target {self.name!r}. '
1661 f'Requires a compiler for language "{l}", but that is not '
1662 'a project language.')
1663 return prelinker
1664 raise MesonException(f'Could not determine prelinker for {self.name!r}.')
1665
1666 def get_clink_dynamic_linker_and_stdlibs(self) -> T.Tuple['Compiler', T.List[str]]:
1667 '''
1668 We use the order of languages in `clink_langs` to determine which
1669 linker to use in case the target has sources compiled with multiple
1670 compilers. All languages other than those in this list have their own
1671 linker.
1672 Note that Vala outputs C code, so Vala sources can use any linker
1673 that can link compiled C. We don't actually need to add an exception
1674 for Vala here because of that.
1675 '''
1676 # If the user set the link_language, just return that.
1677 if self.link_language:
1678 comp = self.all_compilers[self.link_language]
1679 return comp, comp.language_stdlib_only_link_flags()
1680
1681 # Since dependencies could come from subprojects, they could have
1682 # languages we don't have in self.all_compilers. Use the global list of
1683 # all compilers here.
1684 all_compilers = self.environment.coredata.compilers[self.for_machine]
1685
1686 # Languages used by dependencies
1687 dep_langs = self.get_langs_used_by_deps()
1688
1689 # Pick a compiler based on the language priority-order
1690 for l in T.cast('T.Tuple[Language, ...]', clink_langs):
1691 if l in self.compilers or l in dep_langs:
1692 try:
1693 linker = all_compilers[l]
1694 except KeyError:
1695 raise MesonException(
1696 f'Could not get a dynamic linker for build target {self.name!r}. '
1697 f'Requires a linker for language "{l}", but that is not '
1698 'a project language.')
1699 stdlib_args: T.List[str] = self.get_used_stdlib_args(linker.language)
1700 # Type of var 'linker' is Compiler.
1701 # Pretty hard to fix because the return value is passed everywhere
1702 return linker, stdlib_args
1703
1704 # None of our compilers can do clink, this happens for example if the
1705 # target only has ASM sources. Pick the first capable compiler.
1706 for l in T.cast('T.Tuple[Language, ...]', clink_langs):
1707 try:
1708 comp = self.all_compilers[l]
1709 return comp, comp.language_stdlib_only_link_flags()
1710 except KeyError:
1711 pass
1712
1713 raise AssertionError(f'Could not get a dynamic linker for build target {self.name!r}')
1714
1715 def get_used_stdlib_args(self, link_language: Language) -> T.List[str]:
1716 all_compilers = self.environment.coredata.compilers[self.for_machine]
1717 all_langs = set(self.compilers).union(self.get_langs_used_by_deps())
1718 stdlib_args: T.List[str] = []
1719 for dl in all_langs:
1720 if dl != link_language and (dl, link_language) not in self._MASK_LANGS:
1721 # We need to use all_compilers here because
1722 # get_langs_used_by_deps could return a language from a
1723 # subproject
1724 stdlib_args.extend(all_compilers[dl].language_stdlib_only_link_flags())
1725 return stdlib_args
1726
1727 def uses_rust(self) -> bool:
1728 return 'rust' in self.compilers
1729
1730 def uses_rust_abi(self) -> bool:
1731 return self.uses_rust() and self.rust_crate_type in {'dylib', 'rlib', 'proc-macro'}
1732
1733 def uses_fortran(self) -> bool:
1734 return 'fortran' in self.compilers
1735
1736 def uses_cython(self) -> bool:
1737 return 'cython' in self.compilers
1738
1739 def uses_cuda(self) -> bool:
1740 return 'cuda' in self.compilers
1741
1742 def uses_vala(self) -> bool:
1743 return 'vala' in self.compilers
1744
1745 def uses_swift_cpp_interop(self) -> bool:
1746 return self.swift_interoperability_mode == 'cpp' and 'swift' in self.compilers
1747
1748 def get_using_msvc(self) -> bool:
1749 '''
1750 Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,
1751 and SharedLibrary for deciding when to use MSVC-specific file naming
1752 and debug filenames.
1753
1754 If at least some code is built with MSVC and the final library is
1755 linked with MSVC, we can be sure that some debug info will be
1756 generated. We only check the dynamic linker here because the static
1757 linker is guaranteed to be of the same type.
1758
1759 Interesting cases:
1760 1. The Vala compiler outputs C code to be compiled by whatever
1761 C compiler we're using, so all objects will still be created by the
1762 MSVC compiler.
1763 2. If the target contains only objects, process_compilers guesses and
1764 picks the first compiler that smells right.
1765 '''
1766 # Rustc can use msvc style linkers
1767 if self.uses_rust():
1768 compiler = self.all_compilers['rust']
1769 else:
1770 compiler, _ = self.get_clink_dynamic_linker_and_stdlibs()
1771 # Mixing many languages with MSVC is not supported yet so ignore stdlibs.
1772 return bool(compiler) and compiler.get_linker_id() in {'link', 'lld-link', 'xilink', 'optlink'}
1773
1774 def check_module_linking(self) -> None:
1775 '''
1776 Warn if shared modules are linked with target: (link_with) #2865
1777 '''
1778 for link_target in self.link_targets:
1779 if isinstance(link_target, SharedModule) and not link_target.force_soname:
1780 if self.environment.machines[self.for_machine].is_darwin():
1781 raise MesonException(
1782 f'target {self.name} links against shared module {link_target.name}. This is not permitted on OSX')
1783 elif self.environment.machines[self.for_machine].is_android() and isinstance(self, SharedModule):
1784 # Android requires shared modules that use symbols from other shared modules to
1785 # be linked before they can be dlopen()ed in the correct order. Not doing so
1786 # leads to a missing symbol error: https://github.com/android/ndk/issues/201
1787 link_target.force_soname = True
1788 else:
1789 mlog.deprecation(f'target {self.name} links against shared module {link_target.name}, which is incorrect.'
1790 '\n '
1791 f'This will be an error in meson 2.0, so please use shared_library() for {link_target.name} instead.'
1792 '\n '
1793 f'If shared_module() was used for {link_target.name} because it has references to undefined symbols,'
1794 '\n '
1795 'use shared_library() with `override_options: [\'b_lundef=false\']` instead.')
1796 link_target.force_soname = True
1797
1798 def process_vs_module_defs_kw(self, kwargs: ExecutableKeywordArguments | SharedModuleKeywordArguments) -> None:
1799 path = kwargs.get('vs_module_defs')
1800 if path is None:
1801 return
1802
1803 self.link_depends.append(path)
1804 if isinstance(path, File):
1805 # When passing a generated file.
1806 self.vs_module_defs = path
1807 else:
1808 # When passing output of a Custom Target
1809 self.vs_module_defs = File.from_built_file(path.get_builddir(), path.get_filename())
1810
1811 def _default_library_type(self) -> _LibraryType:
1812 bl_type = self.environment.coredata.optstore.get_value_for(OptionKey('default_both_libraries'))
1813 assert isinstance(bl_type, str), 'for mypy'
1814 return T.cast('_LibraryType', bl_type)
1815
1816 def _extract_link_with(self, kwargs: BuildTargetKeywordArguments) -> list[LinkableTargetTypes]:
1817 bl_type = self._default_library_type()
1818
1819 lib_list: list[LinkableTargetTypes] = []
1820 for lib in itertools.chain(kwargs.get('link_with', []), self.link_targets):
1821 if isinstance(lib, (CustomTarget, CustomTargetIndex)):
1822 lib_list.append(lib)
1823 else:
1824 lib_list.append(lib.get(bl_type))
1825 return lib_list
1826
1827 def _extract_link_whole(self, kwargs: BuildTargetKeywordArguments) -> list[StaticTargetTypes]:
1828 lib_list: list[StaticTargetTypes] = []
1829 for lib in itertools.chain(kwargs.get('link_whole', []), self.link_whole_targets):
1830 if isinstance(lib, BothLibraries):
1831 lib = lib.get('static')
1832 if not isinstance(lib, StaticLibrary):
1833 raise MesonBugException('Tried to statically link a non-static library. How did we get here?')
1834 lib_list.append(lib)
1835 else:
1836 lib_list.append(lib)
1837 return lib_list
1838
1839 def determine_rpath_dirs(self) -> T.Tuple[str, ...]:
1840 result: OrderedSet[str]
1841 if self.environment.coredata.optstore.get_value_for(OptionKey('layout')) == 'mirror':
1842 # Need a copy here
1843 result = OrderedSet(self.get_link_dep_subdirs())
1844 else:
1845 result = OrderedSet()
1846 result.add('meson-out')
1847 result.update(self.rpaths_for_non_system_absolute_shared_libraries())
1848 self.rpath_dirs_to_remove.update([d.encode('utf-8') for d in result])
1849 return tuple(result)
1850
1851 @lru_cache(maxsize=None)
1852 def rpaths_for_non_system_absolute_shared_libraries(self, exclude_system: bool = True) -> ImmutableListProtocol[str]:
1853 paths: OrderedSet[str] = OrderedSet()
1854 srcdir = self.environment.get_source_dir()
1855
1856 system_dirs = set()
1857 if exclude_system:
1858 for cc in self.compilers.values():
1859 system_dirs.update(cc.get_library_dirs())
1860
1861 external_rpaths = self.get_external_rpath_dirs()
1862 build_to_src = relpath(self.environment.get_source_dir(),
1863 self.environment.get_build_dir())
1864
1865 for dep in self.external_deps:
1866 if dep.type_name not in {'library', 'pkgconfig', 'cmake'}:
1867 continue
1868 for libpath in dep.link_args:
1869 if libpath.startswith('-'):
1870 continue
1871 # For all link args that are absolute paths to a library file, add RPATH args
1872 if not os.path.isabs(libpath):
1873 continue
1874 libdir, libname = os.path.split(libpath)
1875 # Windows doesn't support rpaths, but we use this function to
1876 # emulate rpaths by setting PATH
1877 # .dll is there for mingw gcc
1878 # .so's may be extended with version information, e.g. libxyz.so.1.2.3
1879 if not (
1880 libname.endswith(('.dll', '.lib', '.so', '.dylib'))
1881 or '.so.' in libname
1882 ):
1883 continue
1884
1885 # Don't remove rpaths specified in LDFLAGS.
1886 if libdir in external_rpaths:
1887 continue
1888 if system_dirs and os.path.normpath(libdir) in system_dirs:
1889 # No point in adding system paths.
1890 continue
1891
1892 if is_parent_path(srcdir, libdir):
1893 rel_to_src = libdir[len(srcdir) + 1:]
1894 assert not os.path.isabs(rel_to_src), f'rel_to_src: {rel_to_src} is absolute'
1895 paths.add(os.path.join(build_to_src, rel_to_src))
1896 else:
1897 paths.add(libdir)
1898 # Don't remove rpaths specified by the dependency
1899 paths.difference_update(self.get_rpath_dirs_from_link_args(dep.link_args))
1900 for i in itertools.chain(self.link_targets, self.link_whole_targets):
1901 if isinstance(i, BuildTarget):
1902 paths.update(i.rpaths_for_non_system_absolute_shared_libraries(exclude_system))
1903 return list(paths)
1904
1905 def get_external_rpath_dirs(self) -> T.Set[str]:
1906 args: T.List[str] = []
1907 for lang in LANGUAGES_USING_LDFLAGS:
1908 try:
1909 args += self.environment.coredata.get_external_link_args(self.for_machine, lang)
1910 except KeyError:
1911 pass
1912 return self.get_rpath_dirs_from_link_args(args)
1913
1914 # Match rpath formats:
1915 # -Wl,-rpath=
1916 # -Wl,-rpath,
1917 _rpath_regex = re.compile(r'-Wl,-rpath[=,]([^,]+)')
1918 # Match solaris style compat runpath formats:
1919 # -Wl,-R
1920 # -Wl,-R,
1921 _runpath_regex = re.compile(r'-Wl,-R[,]?([^,]+)')
1922 # Match symbols formats:
1923 # -Wl,--just-symbols=
1924 # -Wl,--just-symbols,
1925 _symbols_regex = re.compile(r'-Wl,--just-symbols[=,]([^,]+)')
1926
1927 @classmethod
1928 def get_rpath_dirs_from_link_args(cls, args: T.List[str]) -> T.Set[str]:
1929 dirs: T.Set[str] = set()
1930
1931 for arg in args:
1932 if not arg.startswith('-Wl,'):
1933 continue
1934
1935 rpath_match = cls._rpath_regex.match(arg)
1936 if rpath_match:
1937 for dir in rpath_match.group(1).split(':'):
1938 dirs.add(dir)
1939 runpath_match = cls._runpath_regex.match(arg)
1940 if runpath_match:
1941 for dir in runpath_match.group(1).split(':'):
1942 # The symbols arg is an rpath if the path is a directory
1943 if os.path.isdir(dir):
1944 dirs.add(dir)
1945 symbols_match = cls._symbols_regex.match(arg)
1946 if symbols_match:
1947 for dir in symbols_match.group(1).split(':'):
1948 # Prevent usage of --just-symbols to specify rpath
1949 if os.path.isdir(dir):
1950 raise MesonException(f'Invalid arg for --just-symbols, {dir} is a directory.')
1951 return dirs
1952
1953 def get_platform_scheme_name(self) -> str:
1954 m = self.environment.machines[self.for_machine]
1955 if m.is_cygwin():
1956 return 'cygwin'
1957 elif m.is_windows():
1958 return 'windows'
1959 elif m.is_darwin():
1960 return 'darwin'
1961 else:
1962 return 'unix'
1963
1964
1965 class LinkableTarget(metaclass=SimpleABC):
1966 @abc.abstractmethod
1967 def get(self, lib_type: _LibraryType) -> LinkableTargetTypes:
1968 """If applicable, return the shared or static "part" of this target.
1969 Otherwise, just return self."""
1970
1971
1972 class FileInTargetPrivateDir:
1973 """Represents a file with the path '/path/to/build/target_private_dir/fname'.
1974 target_private_dir is the return value of get_target_private_dir which is e.g. 'subdir/target.p'.
1975 """
1976
1977 def __init__(self, fname: str):
1978 self.fname = fname
1979
1980 def __str__(self) -> str:
1981 return self.fname
1982
1983 class FileMaybeInTargetPrivateDir:
1984 """Union between 'File' and 'FileInTargetPrivateDir'"""
1985
1986 def __init__(self, inner: T.Union[File, FileInTargetPrivateDir]):
1987 self.inner = inner
1988
1989 @property
1990 def fname(self) -> str:
1991 return self.inner.fname
1992
1993 def rel_to_builddir(self, build_to_src: str, target_private_dir: str) -> str:
1994 if isinstance(self.inner, FileInTargetPrivateDir):
1995 return os.path.join(target_private_dir, self.inner.fname)
1996 return self.inner.rel_to_builddir(build_to_src)
1997
1998 def absolute_path(self, srcdir: str, builddir: str) -> str:
1999 if isinstance(self.inner, FileInTargetPrivateDir):
2000 raise RuntimeError('Unreachable code')
2001 return self.inner.absolute_path(srcdir, builddir)
2002
2003 def __str__(self) -> str:
2004 return self.fname
2005
2006 class Generator(HoldableObject):
2007 def __init__(self, env: Environment,
2008 exe: programs.Program,
2009 arguments: T.List[str],
2010 output: T.List[str],
2011 # how2dataclass
2012 *,
2013 depfile: T.Optional[str] = None,
2014 capture: bool = False,
2015 depends: T.Optional[T.Sequence[TargetDepends]] = None,
2016 name: str = 'Generator'):
2017 self.environment = env
2018 self.exe = exe
2019 self.depfile = depfile
2020 self.capture = capture
2021 self.depends: T.List[TargetDepends] = list(depends or [])
2022 self.arglist = arguments
2023 self.outputs = output
2024 self.name = name
2025
2026 def __repr__(self) -> str:
2027 repr_str = "<{0}: {1}>"
2028 return repr_str.format(self.__class__.__name__, self.exe)
2029
2030 def get_exe(self) -> programs.Program:
2031 return self.exe
2032
2033 def get_base_outnames(self, inname: str) -> T.List[str]:
2034 plainname = os.path.basename(inname)
2035 basename = os.path.splitext(plainname)[0]
2036 bases = [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.outputs]
2037 return bases
2038
2039 def get_dep_outname(self, inname: str) -> str:
2040 if self.depfile is None:
2041 raise InvalidArguments('Tried to get dep name for rule that does not have dependency file defined.')
2042 plainname = os.path.basename(inname)
2043 basename = os.path.splitext(plainname)[0]
2044 return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
2045
2046 def get_arglist(self, inname: str) -> T.List[str]:
2047 plainname = os.path.basename(inname)
2048 basename = os.path.splitext(plainname)[0]
2049 return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.arglist]
2050
2051 def process_files(self, files: T.Iterable[TargetSources],
2052 subdir: str = '',
2053 preserve_path_from: T.Optional[str] = None,
2054 extra_args: T.Optional[T.List[str]] = None,
2055 env: T.Optional[EnvironmentVariables] = None,
2056 extra_depends: T.Optional[T.Sequence[TargetDepends]] = None) -> 'GeneratedList':
2057 output = GeneratedList(
2058 self,
2059 subdir,
2060 preserve_path_from,
2061 extra_args=extra_args if extra_args is not None else [],
2062 env=env if env is not None else EnvironmentVariables(),
2063 extra_depends=list(extra_depends) if extra_depends is not None else [])
2064
2065 for e in files:
2066 if isinstance(e, (CustomTarget, CustomTargetIndex)):
2067 output.depends.add(e)
2068 fs = [File.from_built_file(e.get_builddir(), f) for f in e.get_outputs()]
2069 elif isinstance(e, GeneratedList):
2070 if preserve_path_from:
2071 raise InvalidArguments("generator.process: 'preserve_path_from' is not allowed if one input is a 'generated_list'.")
2072 output.depends.add(e)
2073 output.add_files(FileMaybeInTargetPrivateDir(FileInTargetPrivateDir(f))
2074 for f in e.get_outputs())
2075 continue
2076 elif isinstance(e, str):
2077 fs = [File.from_source_file(self.environment.source_dir, subdir, e)]
2078 else:
2079 fs = [e]
2080
2081 for f in fs:
2082 if preserve_path_from:
2083 abs_f = f.absolute_path(self.environment.source_dir, self.environment.build_dir)
2084 if not is_parent_path(preserve_path_from, abs_f):
2085 raise InvalidArguments('generator.process: When using preserve_path_from, all input files must be in a subdirectory of the given dir.')
2086 f = FileMaybeInTargetPrivateDir(f)
2087 output.add_file(f)
2088 return output
2089
2090
2091 @dataclass(eq=False)
2092 class GeneratedList(HoldableObject):
2093
2094 """The output of generator.process."""
2095
2096 generator: Generator
2097 subdir: str
2098 preserve_path_from: T.Optional[str]
2099 extra_args: T.List[str]
2100 env: T.Optional[EnvironmentVariables]
2101 extra_depends: T.List[TargetDepends]
2102
2103 def __post_init__(self) -> None:
2104 self.name = self.generator.exe
2105 self.depends: T.Set[GeneratedTypes] = set()
2106 self.infilelist: T.List[FileMaybeInTargetPrivateDir] = []
2107 self.outfilelist: T.List[str] = []
2108 self.outmap: T.Dict[FileMaybeInTargetPrivateDir, T.List[str]] = {}
2109 self.depend_files: T.List[File] = []
2110
2111 if self.extra_args is None:
2112 self.extra_args: T.List[str] = []
2113
2114 if self.env is None:
2115 self.env: EnvironmentVariables = EnvironmentVariables()
2116
2117 if self.extra_depends is None:
2118 self.extra_depends: T.List[TargetDepends] = []
2119
2120 if isinstance(self.generator.exe, programs.Program):
2121 if not self.generator.exe.found():
2122 raise InvalidArguments('Tried to use not-found external program as generator')
2123 if isinstance(self.generator.exe, LocalProgram):
2124 t = self.generator.exe.get_target()
2125 if isinstance(t, File):
2126 self.depend_files.append(t)
2127 else:
2128 self.extra_depends.append(t)
2129 else:
2130 path = self.generator.exe.get_path()
2131 if os.path.isabs(path):
2132 # Can only add a dependency on an external program which we
2133 # know the absolute path of
2134 self.depend_files.append(File.from_absolute_file(path))
2135
2136 def get_preserved_path_segment(self, infile: FileMaybeInTargetPrivateDir) -> str:
2137 in_abs = infile.absolute_path(self.generator.environment.source_dir, self.generator.environment.build_dir)
2138 assert os.path.isabs(self.preserve_path_from)
2139 rel = os.path.relpath(in_abs, self.preserve_path_from)
2140 return os.path.dirname(rel)
2141
2142 def add_files(self, newfiles: T.Iterable[FileMaybeInTargetPrivateDir]) -> None:
2143 for f in newfiles:
2144 self.add_file(f)
2145
2146 def add_file(self, newfile: FileMaybeInTargetPrivateDir) -> None:
2147 self.infilelist.append(newfile)
2148 outfiles = self.generator.get_base_outnames(newfile.fname)
2149 if self.preserve_path_from:
2150 path_segment = self.get_preserved_path_segment(newfile)
2151 outfiles = [os.path.join(path_segment, of) for of in outfiles]
2152 self.outfilelist += outfiles
2153 self.outmap[newfile] = outfiles
2154
2155 def get_inputs(self) -> T.List[FileMaybeInTargetPrivateDir]:
2156 return self.infilelist
2157
2158 def get_outputs(self) -> T.List[str]:
2159 return self.outfilelist
2160
2161 def get_outputs_for(self, filename: FileMaybeInTargetPrivateDir) -> T.List[str]:
2162 return self.outmap[filename]
2163
2164 def get_generator(self) -> 'Generator':
2165 return self.generator
2166
2167 def get_extra_args(self) -> T.List[str]:
2168 return self.extra_args
2169
2170 def get_subdir(self) -> str:
2171 return self.subdir
2172
2173 def get_basename(self) -> str:
2174 return self.generator.name
2175
2176
2177 class Executable(BuildTarget, LinkableTarget):
2178 typename = 'executable'
2179
2180 def __init__(
2181 self,
2182 name: str,
2183 subdir: str,
2184 orig_for_machine: MachineChoice,
2185 sources: T.List['SourceOutputs'],
2186 structured_sources: T.Optional[StructuredSources],
2187 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2188 environment: Environment,
2189 compilers: CompilerDict,
2190 build_project: BuildProject,
2191 kwargs: ExecutableKeywordArguments):
2192 self.export_dynamic = kwargs.get('export_dynamic', False)
2193 self.rust_crate_type = kwargs.get('rust_crate_type', 'bin')
2194 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
2195 environment, compilers, build_project, kwargs)
2196 self.win_subsystem = kwargs.get('win_subsystem') or 'console'
2197 self.pie = self._extract_pic_pie(kwargs, 'pie', 'b_pie')
2198 # Check for export_dynamic
2199 self.implib_name = kwargs.get('implib')
2200 # Only linkwithable if using export_dynamic
2201 self.is_linkwithable = self.export_dynamic
2202
2203 self.vs_module_defs: T.Optional[File] = None
2204 self.process_vs_module_defs_kw(kwargs)
2205
2206 def _set_vala_args(self, kwargs: BuildTargetKeywordArguments) -> None:
2207 # These don't get generated if the executable doesn't have
2208 # export_dynamic set to true.
2209 if self.export_dynamic:
2210 super()._set_vala_args(kwargs)
2211
2212 def post_init(self) -> None:
2213 super().post_init()
2214 machine = self.environment.machines[self.for_machine]
2215 # Unless overridden, executables have no suffix or prefix. Except on
2216 # Windows and with C#/Mono executables where the suffix is 'exe'
2217 if not hasattr(self, 'prefix'):
2218 self.prefix = ''
2219 if not hasattr(self, 'suffix'):
2220 # Executable for Windows or C#/Mono
2221 if machine.is_windows() or machine.is_cygwin() or 'cs' in self.compilers:
2222 self.suffix = 'exe'
2223 elif machine.system.startswith('wasm') or machine.system == 'emscripten':
2224 self.suffix = 'js'
2225 elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('armclang') or
2226 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('armclang')):
2227 self.suffix = 'axf'
2228 elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('ccrx') or
2229 'cpp' in self.compilers and self.compilers['cpp'].get_id().startswith('ccrx')):
2230 self.suffix = 'abs'
2231 elif ('c' in self.compilers and self.compilers['c'].get_id().startswith('xc16')):
2232 self.suffix = 'elf'
2233 elif ('c' in self.compilers and self.compilers['c'].get_id() in {'ti', 'c2000', 'c6000'} or
2234 'cpp' in self.compilers and self.compilers['cpp'].get_id() in {'ti', 'c2000', 'c6000'}):
2235 self.suffix = 'out'
2236 elif ('c' in self.compilers and self.compilers['c'].get_id() in {'mwccarm', 'mwcceppc'} or
2237 'cpp' in self.compilers and self.compilers['cpp'].get_id() in {'mwccarm', 'mwcceppc'}):
2238 self.suffix = 'nef'
2239 elif ('c' in self.compilers and self.compilers['c'].get_id() == 'tasking'):
2240 self.suffix = 'elf'
2241 else:
2242 self.suffix = machine.get_exe_suffix()
2243 self.filename = self.name
2244 if self.prefix:
2245 self.filename = self.prefix + self.filename
2246 if self.suffix:
2247 self.filename += '.' + self.suffix
2248 self.outputs[0] = self.filename
2249
2250 # The import library this target will generate
2251 self.import_filename: str | None = None
2252 # The debugging information file this target will generate
2253 self.debug_filename: str | None = None
2254
2255 # If using export_dynamic, set the import library name
2256 if self.export_dynamic:
2257 implib_basename = self.implib_name or self.name + '.exe'
2258 if machine.is_windows() or machine.is_cygwin():
2259 if self.get_using_msvc():
2260 self.import_filename = f'{implib_basename}.lib'
2261 else:
2262 self.import_filename = f'lib{implib_basename}.a'
2263
2264 create_debug_file = (
2265 machine.is_windows()
2266 and ('cs' in self.compilers or self.uses_rust() or self.get_using_msvc())
2267 # .pdb file is created only when debug symbols are enabled
2268 and self.environment.coredata.optstore.get_value_for(OptionKey("debug"))
2269 )
2270 if create_debug_file:
2271 # If the target is has a standard exe extension (i.e. 'foo.exe'),
2272 # then the pdb name simply becomes 'foo.pdb'. If the extension is
2273 # something exotic, then include that in the name for uniqueness
2274 # reasons (e.g. 'foo_com.pdb').
2275 name = self.name
2276 if getattr(self, 'suffix', 'exe') != 'exe':
2277 name += '_' + self.suffix
2278 self.debug_filename = name + '.pdb'
2279
2280 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2281 """Base case used by BothLibraries"""
2282 return self
2283
2284 def get_default_install_dir(self) -> T.Tuple[str, str]:
2285 return self.environment.get_bindir(), '{bindir}'
2286
2287 def type_suffix(self) -> str:
2288 return "@exe"
2289
2290 def get_import_filename(self) -> T.Optional[str]:
2291 """
2292 The name of the import library that will be outputted by the compiler
2293
2294 Returns None if there is no import library required for this platform
2295 """
2296 return self.import_filename
2297
2298 def get_debug_filename(self) -> T.Optional[str]:
2299 """
2300 The name of debuginfo file that will be created by the compiler
2301
2302 Returns None if the build won't create any debuginfo file
2303 """
2304 return self.debug_filename
2305
2306 def is_linkable_target(self) -> bool:
2307 return self.is_linkwithable
2308
2309
2310 class StaticLibrary(BuildTarget, LinkableTarget):
2311 typename = 'static library'
2312
2313 def __init__(
2314 self,
2315 name: str,
2316 subdir: str,
2317 orig_for_machine: MachineChoice,
2318 sources: T.List['SourceOutputs'],
2319 structured_sources: T.Optional[StructuredSources],
2320 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2321 environment: Environment,
2322 compilers: CompilerDict,
2323 build_project: BuildProject,
2324 kwargs: StaticLibraryKeywordArguments):
2325 self.prelink = kwargs.get('prelink', False)
2326 self.rust_crate_type = kwargs.get('rust_crate_type', 'rlib')
2327 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
2328 environment, compilers, build_project, kwargs)
2329 self.pic = self._extract_pic_pie(kwargs, 'pic', 'b_staticpic')
2330 if not self.pic:
2331 self.pie = self._extract_pic_pie(kwargs, 'pie', 'b_pie')
2332
2333 def post_init(self) -> None:
2334 super().post_init()
2335 if 'cs' in self.compilers:
2336 raise InvalidArguments('Static libraries not supported for C#.')
2337 if self.uses_rust():
2338 # See https://github.com/rust-lang/rust/issues/110460
2339 if self.rust_crate_type == 'rlib' and any(c in self.name for c in ['-', ' ', '.']):
2340 raise InvalidArguments(f'Rust crate {self.name} type {self.rust_crate_type} does not allow spaces, '
2341 'periods or dashes in the library name due to a limitation of rustc. '
2342 'Replace them with underscores, for example')
2343 if self.rust_crate_type == 'staticlib':
2344 # FIXME: In the case of no-std we should not add those libraries,
2345 # but we have no way to know currently.
2346
2347 # XXX:
2348 # In the case of no-std, we are likely in a bare metal case
2349 # and thus, machine_info kernel should be set to 'none'.
2350 # In that case, native_static_libs list is empty.
2351 rustc = T.cast('RustCompiler', self.compilers['rust'])
2352 if rustc.get_crt_static():
2353 # musl targets need self-contained for libc.a, libunwind.a etc.
2354 link_args = ['-L' + rustc.get_target_libdir() + '/self-contained']
2355 else:
2356 # Avoid embedding self-contained libc.a into shared libraries —
2357 # creates a second musl instance with uninitialized __libc state.
2358 link_args = []
2359 link_args += rustc.native_static_libs
2360 d = dependencies.InternalDependency(version='undefined', link_args=link_args,
2361 name='_rust_native_static_libs')
2362 self.external_deps.append(d)
2363
2364 default_prefix, default_suffix = self.determine_default_prefix_and_suffix()
2365 if not self.name_prefix_set:
2366 self.prefix = default_prefix
2367 if not self.name_suffix_set:
2368 self.suffix = default_suffix
2369 self.filename = self.prefix + self.name + '.' + self.suffix
2370 self.outputs[0] = self.filename
2371
2372 def _default_library_type(self) -> _LibraryType:
2373 bl = super()._default_library_type()
2374 return 'static' if bl == 'auto' else bl
2375
2376 def determine_default_prefix_and_suffix(self) -> T.Tuple[str, str]:
2377 scheme = self.environment.coredata.get_option_for_target(self, 'namingscheme')
2378 assert isinstance(scheme, str), 'for mypy'
2379 if scheme == 'platform':
2380 schemename = self.get_platform_scheme_name()
2381 prefix, suffix = DEFAULT_STATIC_LIBRARY_NAMES[schemename]
2382 else:
2383 prefix = ''
2384 suffix = ''
2385 # By default a static library is named libfoo.a even on Windows because
2386 # MSVC does not have a consistent convention for what static libraries
2387 # are called. The MSVC CRT uses libfoo.lib syntax but nothing else uses
2388 # it and GCC only looks for static libraries called foo.lib and
2389 # libfoo.a. However, we cannot use foo.lib because that's the same as
2390 # the import library. Using libfoo.a is ok because people using MSVC
2391 # always pass the library filename while linking anyway.
2392 #
2393 # See our FAQ for more detailed rationale:
2394 # https://mesonbuild.com/FAQ.html#why-does-building-my-project-with-msvc-output-static-libraries-called-libfooa
2395 if not hasattr(self, 'prefix'):
2396 prefix = 'lib'
2397 if not hasattr(self, 'suffix'):
2398 if self.uses_rust():
2399 if self.rust_crate_type == 'rlib':
2400 # default Rust static library suffix
2401 suffix = 'rlib'
2402 elif self.rust_crate_type == 'staticlib':
2403 suffix = 'a'
2404 elif self.environment.machines[self.for_machine].is_os2() and self.environment.coredata.optstore.get_value_for(OptionKey('os2_emxomf')):
2405 suffix = 'lib'
2406 else:
2407 suffix = 'a'
2408 if 'c' in self.compilers and self.compilers['c'].get_id() == 'tasking' and not self.prelink:
2409 key = OptionKey('b_lto', self.subproject, self.for_machine)
2410 v = self.environment.coredata.get_option_for_target(self, key)
2411 assert isinstance(v, bool), 'for mypy'
2412 if v:
2413 suffix = 'ma'
2414 return (prefix, suffix)
2415
2416 def get_default_install_dir(self) -> T.Tuple[str, str]:
2417 return self.environment.get_static_lib_dir(), '{libdir_static}'
2418
2419 def type_suffix(self) -> str:
2420 return "@rlib" if self.uses_rust_abi() else "@sta"
2421
2422 def is_linkable_target(self) -> bool:
2423 return True
2424
2425 def is_internal(self) -> bool:
2426 return not self.install
2427
2428 def set_shared(self, shared_library: SharedLibrary) -> None:
2429 self.both_lib = copy.copy(shared_library)
2430 self.both_lib.both_lib = None
2431
2432 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2433 result = self
2434 if lib_type == 'shared':
2435 result = self.both_lib or self
2436 if recursive:
2437 result.link_targets = [t.get(lib_type, True) for t in self.link_targets]
2438 return result
2439
2440 def link_whole(
2441 self,
2442 targets: T.Iterable[StaticTargetTypes],
2443 promoted: bool = False) -> None:
2444 for t in targets:
2445 self.check_can_link_together(t)
2446
2447 # When we're a static library and we link_whole: to another static
2448 # library, we need to add that target's objects to ourselves.
2449 self._bundle_static_library(t, promoted)
2450
2451 # If we install this static library we also need to include objects
2452 # from all uninstalled static libraries it depends on.
2453 if self.install:
2454 for lib in t.get_internal_static_libraries():
2455 self._bundle_static_library(lib, True)
2456 self.link_whole_targets.append(t)
2457
2458 def link(self, targets: T.Iterable[LinkableTargetTypes]) -> None:
2459 for t in targets:
2460 if self.install and t.is_internal():
2461 # When we're a static library and we link_with to an
2462 # internal/convenience library, promote to link_whole.
2463 assert isinstance(t, (StaticLibrary, CustomTarget, CustomTargetIndex)), 'for mypy'
2464 self.link_whole([t], promoted=True)
2465 continue
2466 self.check_can_link_together(t)
2467 self.link_targets.append(t)
2468
2469 def _bundle_static_library(self, t: StaticTargetTypes, promoted: bool = False) -> None:
2470 if self.uses_rust():
2471 # Rustc can bundle static libraries, no need to extract objects.
2472 self.link_whole_targets.append(t)
2473 elif isinstance(t, (CustomTarget, CustomTargetIndex)) or t.uses_rust():
2474 # To extract objects from a custom target we would have to extract
2475 # the archive, WIP implementation can be found in
2476 # https://github.com/mesonbuild/meson/pull/9218.
2477 # For Rust C ABI we could in theory have access to objects, but we
2478 # don't currently build them in such a way that this is possible:
2479 # https://github.com/mesonbuild/meson/issues/10724
2480 m = (f'Cannot link_whole a custom or Rust target {t.name!r} into a static library {self.name!r}. '
2481 'Instead, pass individual object files with the "objects:" keyword argument if possible.')
2482 if promoted:
2483 m += (f' Meson had to promote link to link_whole because {self.name!r} is installed but not {t.name!r},'
2484 f' and thus has to include objects from {t.name!r} to be usable.')
2485 raise InvalidArguments(m)
2486 else:
2487 self.objects.append(t.extract_all_objects())
2488
2489 class SharedLibrary(BuildTarget, LinkableTarget):
2490 typename = 'shared library'
2491
2492 # Used by AIX to decide whether to archive shared library or not.
2493 aix_so_archive = True
2494
2495 def __init__(
2496 self,
2497 name: str,
2498 subdir: str,
2499 orig_for_machine: MachineChoice,
2500 sources: T.List['SourceOutputs'],
2501 structured_sources: T.Optional[StructuredSources],
2502 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2503 environment: Environment,
2504 compilers: CompilerDict,
2505 build_project: BuildProject,
2506 kwargs: SharedLibraryKeywordArguments):
2507 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
2508 environment, compilers, build_project, kwargs)
2509 # Max length 2, first element is compatibility_version, second is current_version
2510 self.darwin_versions: T.Optional[T.Tuple[str, str]] = None
2511 self.soversion: T.Optional[str] = None
2512 self.ltversion: T.Optional[str] = None
2513 if not self.environment.machines[self.for_machine].is_android():
2514 # Shared library version
2515 self.ltversion = kwargs.get('version')
2516 self.soversion = kwargs.get('soversion')
2517 if self.soversion is None and self.ltversion is not None:
2518 # library version is defined, get the soversion from that
2519 # We replicate what Autotools does here and take the first
2520 # number of the version by default.
2521 self.soversion = self.ltversion.split('.')[0]
2522 # macOS, iOS and tvOS dylib compatibility_version and current_version
2523 self.darwin_versions = kwargs.get('darwin_versions')
2524 if self.darwin_versions is None and self.soversion is not None:
2525 # If unspecified, pick the soversion
2526 self.darwin_versions = (self.soversion, self.soversion)
2527
2528 self.win_subsystem = kwargs.get('win_subsystem') or 'console'
2529
2530 self.vs_module_defs: File | None = None
2531 # Visual Studio module-definitions file
2532 self.process_vs_module_defs_kw(kwargs)
2533
2534 # OS/2 uses a 8.3 name for a DLL
2535 self.shortname = kwargs.get('shortname')
2536
2537 # The import library this target will generate
2538 self.import_filename: str | None = None
2539
2540 # The debugging information file this target will generate
2541 self.debug_filename: str | None = None
2542
2543 # Use by the pkgconfig module
2544 self.shared_library_only = False
2545
2546 self.rust_crate_type = kwargs.get('rust_crate_type', 'dylib')
2547
2548 def post_init(self) -> None:
2549 super().post_init()
2550 if self.uses_rust():
2551 # See https://github.com/rust-lang/rust/issues/110460
2552 if self.rust_crate_type != 'cdylib' and any(c in self.name for c in ['-', ' ', '.']):
2553 raise InvalidArguments(f'Rust crate {self.name} type {self.rust_crate_type} does not allow spaces, '
2554 'periods or dashes in the library name due to a limitation of rustc. '
2555 'Replace them with underscores, for example')
2556
2557 if not hasattr(self, 'prefix'):
2558 self.prefix = None
2559 if not hasattr(self, 'suffix'):
2560 self.suffix = None
2561 self.basic_filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2562 self.determine_filenames()
2563
2564 def _default_library_type(self) -> _LibraryType:
2565 bl = super()._default_library_type()
2566 return 'shared' if bl == 'auto' else bl
2567
2568 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
2569 result: T.Dict[str, str] = {}
2570 mappings = dict(self.get_transitive_link_deps_mapping(prefix))
2571 old = get_target_macos_dylib_install_name(self)
2572 if old not in mappings:
2573 fname = self.get_filename()
2574 install_dir = self.install_dir[0]
2575 assert install_dir is not False, 'This is a bug'
2576 new = os.path.join(prefix, install_dir, fname)
2577 result.update({old: new})
2578 mappings.update(result)
2579 return mappings
2580
2581 def get_default_install_dir(self) -> T.Tuple[str, str]:
2582 return self.environment.get_shared_lib_dir(), '{libdir_shared}'
2583
2584 def determine_naming_info(self) -> T.Tuple[str, str, str, str, bool]:
2585 scheme = self.environment.coredata.get_option_for_target(self, 'namingscheme')
2586 assert isinstance(scheme, str), 'for mypy'
2587
2588 prefix: str | None
2589 suffix: str | None
2590 import_suffix: str | None
2591
2592 if scheme == 'platform':
2593 schemename = self.get_platform_scheme_name()
2594 prefix, suffix, import_suffix = DEFAULT_SHARED_LIBRARY_NAMES[schemename]
2595 else:
2596 prefix = None
2597 suffix = None
2598 import_suffix = None
2599 filename_tpl = self.basic_filename_tpl
2600 create_debug_file = False
2601 create_debug_file = False
2602 self.filename_tpl = self.basic_filename_tpl
2603 import_filename_tpl: str | None = None
2604 # NOTE: manual prefix/suffix override is currently only tested for C/C++
2605 # C# and Mono
2606 if 'cs' in self.compilers:
2607 prefix = ''
2608 suffix = 'dll'
2609 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2610 create_debug_file = True
2611 # C, C++, Swift, Vala
2612 # Only Windows and OS/2 uses a separate import library for linking
2613 # For all other targets/platforms import_filename stays None
2614 elif self.environment.machines[self.for_machine].is_windows():
2615 suffix = suffix if suffix is not None else 'dll'
2616 if self.uses_rust():
2617 # Shared library is of the form foo.dll
2618 prefix = prefix if prefix is not None else ''
2619 # Import library is called foo.dll.lib
2620 import_filename_tpl = '{0.prefix}{0.name}.dll.lib'
2621 # .pdb file is only created when debug symbols are enabled
2622 create_debug_file = self.environment.coredata.optstore.get_value_for(OptionKey("debug"))
2623 assert isinstance(create_debug_file, bool), 'for mypy'
2624 elif self.get_using_msvc():
2625 # Shared library is of the form foo.dll
2626 prefix = prefix if prefix is not None else ''
2627 # Import library is called foo.lib
2628 import_suffix = import_suffix if import_suffix is not None else 'lib'
2629 import_filename_tpl = '{0.prefix}{0.name}.' + import_suffix
2630 # .pdb file is only created when debug symbols are enabled
2631 create_debug_file = self.environment.coredata.optstore.get_value_for(OptionKey("debug"))
2632 assert isinstance(create_debug_file, bool), 'for mypy'
2633 # Assume GCC-compatible naming
2634 else:
2635 # Shared library is of the form libfoo.dll
2636 prefix = prefix if prefix is not None else 'lib'
2637 # Import library is called libfoo.dll.a
2638 import_suffix = import_suffix if import_suffix is not None else '.dll.a'
2639 import_filename_tpl = '{0.prefix}{0.name}' + import_suffix
2640 # Shared library has the soversion if it is defined
2641 if self.soversion:
2642 filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
2643 else:
2644 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2645 elif self.environment.machines[self.for_machine].is_cygwin():
2646 suffix = 'dll'
2647 # Shared library is of the form cygfoo.dll
2648 # (ld --dll-search-prefix=cyg is the default)
2649 prefix = 'cyg'
2650 # Import library is called libfoo.dll.a
2651 import_suffix = import_suffix if import_suffix is not None else '.dll.a'
2652 import_prefix = self.prefix if self.prefix is not None else 'lib'
2653 import_filename_tpl = import_prefix + '{0.name}' + import_suffix
2654 if self.soversion:
2655 filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
2656 else:
2657 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2658 elif self.environment.machines[self.for_machine].is_darwin():
2659 prefix = prefix if prefix is not None else 'lib'
2660 suffix = suffix if suffix is not None else 'dylib'
2661 # On macOS, the filename can only contain the major version
2662 if self.soversion:
2663 # libfoo.X.dylib
2664 filename_tpl = '{0.prefix}{0.name}.{0.soversion}.{0.suffix}'
2665 else:
2666 # libfoo.dylib
2667 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2668 elif self.environment.machines[self.for_machine].is_android():
2669 prefix = prefix if prefix is not None else 'lib'
2670 suffix = suffix if suffix is not None else 'so'
2671 # Android doesn't support shared_library versioning
2672 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2673 elif self.environment.machines[self.for_machine].is_os2():
2674 # Shared library is of the form foo.dll
2675 prefix = prefix if prefix is not None else ''
2676 suffix = suffix if suffix is not None else 'dll'
2677 # Import library is called foo_dll.a or foo_dll.lib
2678 if import_suffix is None:
2679 import_suffix = '_dll.lib' if self.environment.coredata.optstore.get_value_for(OptionKey('os2_emxomf')) else '_dll.a'
2680 import_filename_tpl = '{0.prefix}{0.name}' + import_suffix
2681 filename_tpl = '{0.shortname}' if self.shortname else '{0.prefix}{0.name}'
2682 if self.soversion:
2683 # fooX.dll
2684 filename_tpl += '{0.soversion}'
2685 filename_tpl += '.{0.suffix}'
2686 else:
2687 prefix = prefix if prefix is not None else 'lib'
2688 suffix = suffix if suffix is not None else 'so'
2689 if self.ltversion:
2690 # libfoo.so.X[.Y[.Z]] (.Y and .Z are optional)
2691 filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.ltversion}'
2692 elif self.soversion:
2693 # libfoo.so.X
2694 filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.soversion}'
2695 else:
2696 # No versioning, libfoo.so
2697 filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
2698 return (prefix, suffix, filename_tpl, import_filename_tpl, create_debug_file)
2699
2700 def determine_filenames(self) -> None:
2701 """
2702 See https://github.com/mesonbuild/meson/pull/417 for details.
2703
2704 First we determine the filename template (self.filename_tpl), then we
2705 set the output filename (self.filename).
2706
2707 The template is needed while creating aliases (self.get_aliases),
2708 which are needed while generating .so shared libraries for Linux.
2709
2710 Besides this, there's also the import library name (self.import_filename),
2711 which is only used on Windows and OS/2 since on that platform the linker uses a
2712 separate library called the "import library" during linking instead of
2713 the shared library (DLL).
2714 """
2715 prefix, suffix, filename_tpl, import_filename_tpl, create_debug_file = self.determine_naming_info()
2716 if self.prefix is None:
2717 self.prefix = prefix
2718 if self.suffix is None:
2719 self.suffix = suffix
2720 self.filename_tpl = filename_tpl
2721 self.filename = self.filename_tpl.format(self)
2722 if self.environment.machines[self.for_machine].is_os2():
2723 # OS/2 does not allow a longer DLL name than 8 chars
2724 name = os.path.splitext(self.filename)[0]
2725 if len(name) > 8:
2726 name = name[:8]
2727 if self.soversion:
2728 name = name[:-len(self.soversion)] + self.soversion
2729 self.filename = '{}.{}'.format(name, self.suffix)
2730 if import_filename_tpl:
2731 self.import_filename = import_filename_tpl.format(self)
2732 # There may have been more outputs added by the time we get here, so
2733 # only replace the first entry
2734 self.outputs[0] = self.filename
2735 if create_debug_file:
2736 self.debug_filename = os.path.splitext(self.filename)[0] + '.pdb'
2737
2738 def get_import_filename(self) -> T.Optional[str]:
2739 """
2740 The name of the import library that will be outputted by the compiler
2741
2742 Returns None if there is no import library required for this platform
2743 """
2744 return self.import_filename
2745
2746 def get_debug_filename(self) -> T.Optional[str]:
2747 """
2748 The name of debuginfo file that will be created by the compiler
2749
2750 Returns None if the build won't create any debuginfo file
2751 """
2752 return self.debug_filename
2753
2754 def get_aliases(self) -> T.List[T.Tuple[str, str, str]]:
2755 """
2756 If the versioned library name is libfoo.so.0.100.0, aliases are:
2757 * libfoo.so.0 (soversion) -> libfoo.so.0.100.0
2758 * libfoo.so (unversioned; for linking) -> libfoo.so.0
2759 Same for dylib:
2760 * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib
2761 """
2762 aliases: T.List[T.Tuple[str, str, str]] = []
2763 # Aliases are only useful with .so and .dylib libraries. Also if
2764 # there's no self.soversion (no versioning), we don't need aliases.
2765 if self.suffix not in ('so', 'dylib') or not self.soversion:
2766 return aliases
2767 # With .so libraries, the minor and micro versions are also in the
2768 # filename. If ltversion != soversion we create an soversion alias:
2769 # libfoo.so.0 -> libfoo.so.0.100.0
2770 # Where libfoo.so.0.100.0 is the actual library
2771 if self.suffix == 'so' and self.ltversion and self.ltversion != self.soversion:
2772 alias_tpl = self.filename_tpl.replace('ltversion', 'soversion')
2773 ltversion_filename = alias_tpl.format(self)
2774 tag = self.install_tag[0] or 'runtime'
2775 aliases.append((ltversion_filename, self.filename, tag))
2776 # libfoo.so.0/libfoo.0.dylib is the actual library
2777 else:
2778 ltversion_filename = self.filename
2779 # Unversioned alias:
2780 # libfoo.so -> libfoo.so.0
2781 # libfoo.dylib -> libfoo.0.dylib
2782 tag = self.install_tag[0] or 'devel'
2783 aliases.append((self.basic_filename_tpl.format(self), ltversion_filename, tag))
2784 return aliases
2785
2786 def type_suffix(self) -> str:
2787 return "@sha"
2788
2789 def is_linkable_target(self) -> bool:
2790 return True
2791
2792 def set_static(self, static_library: StaticLibrary) -> None:
2793 self.both_lib = copy.copy(static_library)
2794 self.both_lib.both_lib = None
2795
2796 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2797 result = self
2798 if lib_type == 'static':
2799 result = self.both_lib or self
2800 if recursive:
2801 result.link_targets = [t.get(lib_type, True) for t in self.link_targets]
2802 return result
2803
2804 def link_whole(
2805 self,
2806 targets: T.Iterable[StaticTargetTypes],
2807 promoted: bool = False) -> None:
2808 for t in targets:
2809 self.check_can_link_together(t)
2810 if not getattr(t, 'pic', True):
2811 msg = f"Can't link non-PIC static library {t.name!r} into shared library {self.name!r}. "
2812 msg += "Use the 'pic' option to static_library to build with PIC."
2813 raise InvalidArguments(msg)
2814 self.link_whole_targets.append(t)
2815
2816 def link(self, targets: T.Iterable[LinkableTargetTypes]) -> None:
2817 for t in targets:
2818 if isinstance(t, StaticLibrary) and not t.pic:
2819 msg = f"Can't link non-PIC static library {t.name!r} into shared library {self.name!r}. "
2820 msg += "Use the 'pic' option to static_library to build with PIC."
2821 raise InvalidArguments(msg)
2822 self.check_can_link_together(t)
2823 self.link_targets.append(t)
2824
2825 # A shared library that is meant to be used with dlopen rather than linking
2826 # into something else.
2827 class SharedModule(SharedLibrary):
2828 typename = 'shared module'
2829
2830 # Used by AIX to not archive shared library for dlopen mechanism
2831 aix_so_archive = False
2832
2833 def __init__(
2834 self,
2835 name: str,
2836 subdir: str,
2837 orig_for_machine: MachineChoice,
2838 sources: T.List['SourceOutputs'],
2839 structured_sources: T.Optional[StructuredSources],
2840 objects: T.Sequence[ObjectTypes | GeneratedTypes],
2841 environment: Environment,
2842 compilers: CompilerDict,
2843 build_project: BuildProject,
2844 kwargs: SharedModuleKeywordArguments):
2845 super().__init__(name, subdir, orig_for_machine, sources,
2846 structured_sources, objects, environment, compilers, build_project,
2847 # SharedModuleKeywordArguments is a subclass, it's annoying mypy can't figure this out
2848 T.cast('SharedLibraryKeywordArguments', kwargs))
2849 # We need to set the soname in cases where build files link the module
2850 # to build targets, see: https://github.com/mesonbuild/meson/issues/9492
2851 self.force_soname = False
2852
2853 def get_default_install_dir(self) -> T.Tuple[str, str]:
2854 return self.environment.get_shared_module_dir(), '{moduledir_shared}'
2855
2856 class BothLibraries(SecondLevelHolder, LinkableTarget):
2857 typename: T.ClassVar[str] = 'both libraries'
2858
2859 def __init__(self, shared: SharedLibrary, static: StaticLibrary, preferred_library: Literal['shared', 'static']) -> None:
2860 self._preferred_library = preferred_library
2861 self.shared = shared
2862 self.static = static
2863 self.subproject = self.shared.subproject
2864
2865 def __repr__(self) -> str:
2866 return f'<BothLibraries: static={repr(self.static)}; shared={repr(self.shared)}>'
2867
2868 def get(self, lib_type: _LibraryType) -> T.Union[StaticLibrary, SharedLibrary]:
2869 if lib_type == 'static':
2870 return self.static
2871 if lib_type == 'shared':
2872 return self.shared
2873 return self.get_default_object()
2874
2875 def get_default_object(self) -> T.Union[StaticLibrary, SharedLibrary]:
2876 if self._preferred_library == 'shared':
2877 return self.shared
2878 elif self._preferred_library == 'static':
2879 return self.static
2880 raise MesonBugException(f'self._preferred_library == "{self._preferred_library}" is neither "shared" nor "static".')
2881
2882 def get_id(self) -> str:
2883 return self.get_default_object().get_id()
2884
2885 def is_linkable_target(self) -> bool:
2886 # For polymorphism with build targets
2887 return True
2888
2889
2890 def flatten_command(cmd: T.Iterable[CommandTypes],
2891 subproject: SubProject) -> tuple[list[str | File | BuildTarget | CustomTarget | programs.Program],
2892 list[File], list[BuildTarget | CustomTarget]]:
2893 final_cmd: list[str | File | programs.Program | BuildTarget | CustomTarget] = []
2894 depend_files: list[File] = []
2895 dependencies: list[BuildTarget | CustomTarget] = []
2896 for c in cmd:
2897 if isinstance(c, LocalProgram):
2898 c = c.program
2899 if isinstance(c, str):
2900 final_cmd.append(c)
2901 elif isinstance(c, File):
2902 depend_files.append(c)
2903 final_cmd.append(c)
2904 elif isinstance(c, programs.Program):
2905 if not c.found():
2906 raise InvalidArguments('Tried to use not-found external program in "command"')
2907 # We know path is not none if c.found()
2908 path = unwrap(c.get_path())
2909 if os.path.isabs(path):
2910 # Can only add a dependency on an external program which we
2911 # know the absolute path of
2912 depend_files.append(File.from_absolute_file(path))
2913 # Do NOT flatten -- it is needed for later parsing
2914 final_cmd.append(c)
2915 elif isinstance(c, (BuildTarget, CustomTarget)):
2916 dependencies.append(c)
2917 final_cmd.append(c)
2918 elif isinstance(c, CustomTargetIndex):
2919 FeatureNew.single_use('CustomTargetIndex for command argument', '0.60', subproject)
2920 dependencies.append(c.target)
2921 c, df, d = flatten_command([File.from_built_file(c.get_subdir(), c.get_filename())], subproject)
2922 final_cmd.extend(c)
2923 depend_files.extend(df)
2924 dependencies.extend(d)
2925 elif isinstance(c, list):
2926 # TODO: is this case even reachable?
2927 c, df, d = flatten_command(c, subproject)
2928 final_cmd.extend(c)
2929 depend_files.extend(df)
2930 dependencies.extend(d)
2931 else:
2932 raise InvalidArguments(f'Argument {c!r} in "command" is invalid')
2933 return final_cmd, depend_files, dependencies
2934
2935
2936 class CustomTargetBase(LinkableTarget, metaclass=SimpleABC):
2937 ''' Base class for CustomTarget and CustomTargetIndex
2938
2939 This base class can be used to provide a dummy implementation of some
2940 private methods to avoid repeating `isinstance(t, BuildTarget)` when dealing
2941 with custom targets.
2942 '''
2943
2944 rust_crate_type = ''
2945
2946 def get_dependencies_recurse(self, result: OrderedSet[BuildTargetTypes],
2947 visited: T.Set[tuple[BuildTargetTypes, bool, bool]],
2948 include_internals: bool = True,
2949 handled_by_rustc: bool = False) -> None:
2950 pass
2951
2952 def get_internal_static_libraries(self) -> OrderedSet[StaticTargetTypes]:
2953 return OrderedSet()
2954
2955 def get_internal_static_libraries_recurse(self, result: OrderedSet[StaticTargetTypes]) -> None:
2956 pass
2957
2958 def get(self, lib_type: _LibraryType, recursive: bool = False) -> LinkableTargetTypes:
2959 """Base case used by BothLibraries"""
2960 assert isinstance(self, (CustomTarget, CustomTargetIndex))
2961 return self
2962
2963 def uses_rust_abi(self) -> bool:
2964 return False
2965
2966 def uses_fortran(self) -> bool:
2967 return False
2968
2969 def uses_swift_cpp_interop(self) -> bool:
2970 return False
2971
2972
2973 class CustomTarget(Target, CustomTargetBase):
2974
2975 typename = 'custom'
2976
2977 def __init__(self,
2978 name: T.Optional[str],
2979 subdir: str,
2980 environment: Environment,
2981 command: T.Sequence[CommandTypes],
2982 sources: T.Sequence[CustomTargetSources],
2983 outputs: T.List[str],
2984 build_project: BuildProject,
2985 *,
2986 build_always_stale: bool = False,
2987 build_by_default: T.Optional[bool] = None,
2988 capture: bool = False,
2989 console: bool = False,
2990 depend_files: list[File] | None = None,
2991 extra_depends: T.Optional[T.Sequence[TargetDepends]] = None,
2992 depfile: T.Optional[str] = None,
2993 depfile_type: T.Optional[Literal['gcc', 'msvc']] = None,
2994 env: T.Optional[EnvironmentVariables] = None,
2995 feed: bool = False,
2996 install: bool = False,
2997 install_dir: T.Optional[T.List[T.Union[str, Literal[False]]]] = None,
2998 install_mode: T.Optional[FileMode] = None,
2999 install_tag: T.Optional[T.List[T.Optional[str]]] = None,
3000 rspable: bool = False,
3001 absolute_paths: bool = False,
3002 backend: T.Optional['Backend'] = None,
3003 description: str = 'Generating {} with a custom command',
3004 build_subdir: str = '',
3005 ):
3006 # TODO expose keyword arg to make MachineChoice.HOST configurable
3007 super().__init__(name, subdir, False, MachineChoice.HOST, environment,
3008 build_project, install, build_always_stale, build_subdir = build_subdir)
3009 self.sources = list(sources)
3010 self.outputs = substitute_values(
3011 outputs, get_filenames_templates_dict(
3012 get_sources_string_names(sources, backend),
3013 []))
3014 self.build_by_default = build_by_default if build_by_default is not None else install
3015 self.capture = capture
3016 self.console = console
3017 self.depend_files = list(depend_files or [])
3018 self.dependencies: T.List[T.Union[CustomTarget, BuildTarget]] = []
3019 # must be after depend_files and dependencies
3020 c, df, d = flatten_command(command, build_project.subproject)
3021 self.command = c
3022 self.depend_files.extend(df)
3023 self.dependencies.extend(d)
3024 self.depfile = depfile
3025 self.depfile_type = 'gcc' if depfile else depfile_type
3026 self.env = env or EnvironmentVariables()
3027 self.feed = feed
3028 self.install_dir = list(install_dir or [])
3029 self.has_custom_install_dir = bool(self.install_dir)
3030 self.install_mode = install_mode
3031 self.install_tag = _process_install_tag(install_tag, len(self.outputs))
3032 self.name = name if name else self.outputs[0]
3033 self.description = description
3034
3035 # Whether to use absolute paths for all files on the commandline
3036 self.absolute_paths = absolute_paths
3037
3038 # Whether to enable using response files for the underlying tool
3039 self.rspable = rspable
3040
3041 self.extra_depends: T.List[T.Union[GeneratedTypes, BuildTarget]] = []
3042 if extra_depends:
3043 for d in extra_depends:
3044 if isinstance(d, LocalProgram):
3045 d = d.get_target()
3046 elif isinstance(d, programs.Program):
3047 path = d.get_path()
3048 # Can only add a dependency on an external program which we
3049 # know the absolute path of
3050 if not os.path.isabs(path):
3051 continue
3052 d = File.from_absolute_file(path)
3053 if isinstance(d, File):
3054 self.depend_files.append(d)
3055 else:
3056 self.extra_depends.append(d)
3057
3058 def install_dir_names(self) -> T.List[T.Optional[str]]:
3059 install_dir_names: T.List[T.Optional[str]] = []
3060 if self.has_custom_install_dir:
3061 install_dir_names = [getattr(i, 'optname', None) for i in self.install_dir]
3062
3063 return install_dir_names
3064
3065 def __repr__(self) -> str:
3066 repr_str = "<{0} {1}: {2}>"
3067 return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
3068
3069 def get_target_dependencies(self) -> T.List[TargetDepends | File | ExtractedObjects]:
3070 deps: T.List[TargetDepends | File | ExtractedObjects] = []
3071 deps.extend(self.dependencies)
3072 deps.extend(self.extra_depends)
3073 for c in self.sources:
3074 if isinstance(c, CustomTargetIndex):
3075 deps.append(c.target)
3076 elif not isinstance(c, programs.ExternalProgram):
3077 deps.append(c)
3078 return deps
3079
3080 def get_transitive_build_target_deps(self) -> T.Set[T.Union[BuildTarget, 'CustomTarget']]:
3081 '''
3082 Recursively fetch the build targets that this custom target depends on,
3083 whether through `command:`, `depends:`, or `sources:` The recursion is
3084 only performed on custom targets.
3085 This is useful for setting PATH on Windows for finding required DLLs.
3086 F.ex, if you have a python script that loads a C module that links to
3087 other DLLs in your project.
3088 '''
3089 bdeps: T.Set[T.Union[BuildTarget, 'CustomTarget']] = set()
3090 deps = self.get_target_dependencies()
3091 for d in deps:
3092 if isinstance(d, BuildTarget):
3093 bdeps.add(d)
3094 elif isinstance(d, CustomTarget):
3095 bdeps.update(d.get_transitive_build_target_deps())
3096 return bdeps
3097
3098 def get_dependencies(self) -> T.List[T.Union[CustomTarget, BuildTarget]]:
3099 return self.dependencies
3100
3101 def should_install(self) -> bool:
3102 return self.install
3103
3104 def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
3105 return self.install_dir
3106
3107 def get_custom_install_mode(self) -> T.Optional['FileMode']:
3108 return self.install_mode
3109
3110 def get_outputs(self) -> T.List[str]:
3111 return self.outputs
3112
3113 def get_filename(self) -> str:
3114 return self.outputs[0]
3115
3116 def get_sources(self) -> T.List[CustomTargetSources]:
3117 return self.sources
3118
3119 def get_generated_lists(self) -> T.List[GeneratedList]:
3120 genlists: T.List[GeneratedList] = []
3121 for c in self.sources:
3122 if isinstance(c, GeneratedList):
3123 genlists.append(c)
3124 return genlists
3125
3126 def get_generated_sources(self) -> T.List[GeneratedList]:
3127 return self.get_generated_lists()
3128
3129 def get_dep_outname(self, infilenames: list[str]) -> str:
3130 if self.depfile is None:
3131 raise InvalidArguments('Tried to get depfile name for custom_target that does not have depfile defined.')
3132 if infilenames:
3133 plainname = os.path.basename(infilenames[0])
3134 basename = os.path.splitext(plainname)[0]
3135 return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
3136 else:
3137 if '@BASENAME@' in self.depfile or '@PLAINNAME@' in self.depfile:
3138 raise InvalidArguments('Substitution in depfile for custom_target that does not have an input file.')
3139 return self.depfile
3140
3141 def is_linkable_output(self, output: str) -> bool:
3142 if output.endswith(('.a', '.dll', '.lib', '.so', '.dylib')):
3143 return True
3144 # libfoo.so.X soname
3145 if re.search(r'\.so(\.\d+)*$', output):
3146 return True
3147 return False
3148
3149 def is_linkable_target(self) -> bool:
3150 if len(self.outputs) != 1:
3151 return False
3152 return self.is_linkable_output(self.outputs[0])
3153
3154 def links_dynamically(self) -> bool:
3155 """Whether this target links dynamically or statically
3156
3157 Does not assert the target is linkable, just that it is not shared
3158
3159 :return: True if is dynamically linked, otherwise False
3160 """
3161 suf = os.path.splitext(self.outputs[0])[-1]
3162 return suf not in {'.a', '.lib'}
3163
3164 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
3165 return {}
3166
3167 def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
3168 return OrderedSet()
3169
3170 def get_all_link_deps(self) -> ImmutableListProtocol[BuildTargetTypes]:
3171 return []
3172
3173 def is_internal(self) -> bool:
3174 '''
3175 Returns True if this is a not installed static library.
3176 '''
3177 if len(self.outputs) != 1:
3178 return False
3179 return CustomTargetIndex(self, self.outputs[0]).is_internal()
3180
3181 def type_suffix(self) -> str:
3182 return "@cus"
3183
3184 def __getitem__(self, index: int) -> 'CustomTargetIndex':
3185 return CustomTargetIndex(self, self.outputs[index])
3186
3187 def __setitem__(self, index: T.Any, value: T.Any) -> T.Any:
3188 raise NotImplementedError
3189
3190 def __delitem__(self, index: T.Any) -> T.Any:
3191 raise NotImplementedError
3192
3193 def __iter__(self) -> T.Iterator[CustomTargetIndex]:
3194 for i in self.outputs:
3195 yield CustomTargetIndex(self, i)
3196
3197 def __len__(self) -> int:
3198 return len(self.outputs)
3199
3200 class CompileTarget(BuildTarget):
3201 '''
3202 Target that only compile sources without linking them together.
3203 It can be used as preprocessor, or transpiler.
3204 '''
3205
3206 typename = 'compile'
3207
3208 def __init__(self,
3209 name: str,
3210 subdir: str,
3211 environment: Environment,
3212 sources: T.List['SourceOutputs'],
3213 output_templ: str,
3214 compiler: Compiler,
3215 backend: Backend,
3216 compile_args: T.List[str],
3217 include_directories: T.List[IncludeDirs],
3218 dependencies: T.List[dependencies.Dependency],
3219 build_project: BuildProject,
3220 depends: T.List[BuildTargetTypes]):
3221 compilers = {compiler.get_language(): compiler}
3222 kwargs: BuildTargetKeywordArguments = {
3223 'build_by_default': False,
3224 'language_args': defaultdict(list, [(compiler.language, compile_args)]),
3225 'include_directories': include_directories,
3226 'dependencies': dependencies,
3227 'native': compiler.for_machine,
3228 }
3229 super().__init__(name, subdir, compiler.for_machine,
3230 sources, None, [], environment, compilers,
3231 build_project, kwargs)
3232 self.filename = name
3233 self.compiler = compiler
3234 self.output_templ = output_templ
3235 self.outputs = []
3236 self.sources_map: T.Dict[File, str] = {}
3237 self.depends = list(depends or [])
3238 for f in self.sources:
3239 self._add_output(f)
3240 for gensrc in self.generated:
3241 for s in gensrc.get_outputs():
3242 rel_src = backend.get_target_generated_dir(self, gensrc, s)
3243 self._add_output(File.from_built_relative(rel_src))
3244
3245 def type_suffix(self) -> str:
3246 return "@compile"
3247
3248 def _add_output(self, f: File) -> None:
3249 plainname = os.path.basename(f.fname)
3250 basename = os.path.splitext(plainname)[0]
3251 o = self.output_templ.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
3252 self.outputs.append(o)
3253 self.sources_map[f] = o
3254
3255 def get_generated_headers(self) -> T.List[File]:
3256 gen_headers: T.List[File] = []
3257 for dep in self.depends:
3258 gen_headers += [File(True, dep.subdir, o) for o in dep.get_outputs()]
3259 return gen_headers
3260
3261 def is_linkable_output(self, output: str) -> bool:
3262 return False
3263
3264 class RunTarget(Target):
3265
3266 typename = 'run'
3267
3268 def __init__(self, name: str,
3269 command: T.Sequence[CommandTypes],
3270 # the RunTarget case is used by gnome.yelp()
3271 dependencies: T.Sequence[Target | CustomTargetIndex | GeneratedList | programs.Program],
3272 subdir: str,
3273 environment: Environment,
3274 build_project: BuildProject,
3275 env: T.Optional[EnvironmentVariables] = None,
3276 default_env: bool = True):
3277 # These don't produce output artifacts
3278 super().__init__(name, subdir, False, MachineChoice.BUILD, environment, build_project)
3279 self.dependencies = list(dependencies)
3280 self.command, self.depend_files, d = flatten_command(command, build_project.subproject)
3281 self.dependencies.extend(d)
3282 self.absolute_paths = False
3283 self.env = env
3284 self.default_env = default_env
3285
3286 def __repr__(self) -> str:
3287 repr_str = "<{0} {1}: {2}>"
3288 return repr_str.format(self.__class__.__name__, self.get_id(), self.command[0])
3289
3290 def get_dependencies(self) -> T.List[Target | CustomTargetIndex | GeneratedList | programs.Program]:
3291 return self.dependencies
3292
3293 def get_generated_sources(self) -> T.List[GeneratedTypes]:
3294 return []
3295
3296 def get_sources(self) -> T.List[File]:
3297 return []
3298
3299 def should_install(self) -> bool:
3300 return False
3301
3302 def get_filename(self) -> str:
3303 return self.name
3304
3305 def get_outputs(self) -> T.List[str]:
3306 return [self.name]
3307
3308 def type_suffix(self) -> str:
3309 return "@run"
3310
3311 class AliasTarget(RunTarget):
3312
3313 typename = 'alias'
3314
3315 def __init__(self, name: str, dependencies: T.Sequence[Target],
3316 subdir: str, environment: Environment,
3317 build_project: BuildProject):
3318 super().__init__(name, [], dependencies, subdir, environment, build_project)
3319
3320 def __repr__(self) -> str:
3321 repr_str = "<{0} {1}>"
3322 return repr_str.format(self.__class__.__name__, self.get_id())
3323
3324 class Jar(BuildTarget):
3325 typename = 'jar'
3326 rust_crate_type = '' # type: ignore[assignment]
3327
3328 def __init__(self, name: str, subdir: str, orig_for_machine: MachineChoice,
3329 sources: T.List[SourceOutputs], structured_sources: T.Optional['StructuredSources'],
3330 objects: T.Sequence[ObjectTypes | GeneratedTypes], environment: Environment, compilers: CompilerDict,
3331 build_project: BuildProject, kwargs: JarKeywordArguments):
3332 super().__init__(name, subdir, orig_for_machine, sources, structured_sources, objects,
3333 environment, compilers, build_project, kwargs)
3334 for s in self.sources:
3335 if not s.endswith('.java'):
3336 raise InvalidArguments(f'Jar source {s} is not a java file.')
3337 for t in self.link_targets:
3338 if not isinstance(t, Jar):
3339 raise InvalidArguments(f'Link target {t} is not a jar target.')
3340 if self.structured_sources:
3341 raise InvalidArguments('structured sources are not supported in Java targets.')
3342 self.filename = self.name + '.jar'
3343 self.outputs = [self.filename]
3344 self.java_args = self.extra_args['java']
3345 self.main_class = kwargs.get('main_class', '')
3346 self.java_resources: T.Optional[StructuredSources] = kwargs.get('java_resources', None)
3347
3348 def _extract_link_with(self, kwargs: BuildTargetKeywordArguments) -> list[LinkableTargetTypes]:
3349 return kwargs['link_with']
3350
3351 def get_main_class(self) -> str:
3352 return self.main_class
3353
3354 def type_suffix(self) -> str:
3355 return "@jar"
3356
3357 def get_java_args(self) -> T.List[str]:
3358 return self.java_args
3359
3360 def get_java_resources(self) -> T.Optional[StructuredSources]:
3361 return self.java_resources
3362
3363 def validate_install(self) -> None:
3364 # All jar targets are installable.
3365 pass
3366
3367 def is_linkable_target(self) -> bool:
3368 return True
3369
3370 def get_classpath_args(self) -> T.List[str]:
3371 cp_paths = [os.path.join(l.get_subdir(), l.get_filename()) for l in self.link_targets]
3372 cp_string = os.pathsep.join(cp_paths)
3373 if cp_string:
3374 return ['-cp', os.pathsep.join(cp_paths)]
3375 return []
3376
3377 def get_default_install_dir(self) -> T.Tuple[str, str]:
3378 return self.environment.get_jar_dir(), '{jardir}'
3379
3380 @dataclass(eq=False)
3381 class CustomTargetIndex(CustomTargetBase, HoldableObject):
3382
3383 """A special opaque object returned by indexing a CustomTarget. This object
3384 exists in Meson, but acts as a proxy in the backends, making targets depend
3385 on the CustomTarget it's derived from, but only adding one source file to
3386 the sources.
3387 """
3388
3389 typename: T.ClassVar[str] = 'custom'
3390
3391 target: T.Union[CustomTarget, CompileTarget]
3392 output: str
3393
3394 def __post_init__(self) -> None:
3395 self.for_machine = self.target.for_machine
3396
3397 @lazy_property
3398 def __index(self) -> int:
3399 # Must be detected lazily becuase preporcessed sources don't end up in the
3400 # outputs, but can still be in a CustomTargetIndex.
3401 return self.target.outputs.index(self.output)
3402
3403 @property
3404 def name(self) -> str:
3405 return f'{self.target.name}[{self.output}]'
3406
3407 @property
3408 def depend_files(self) -> T.List[File]:
3409 return self.target.depend_files
3410
3411 @property
3412 def subdir(self) -> str:
3413 return self.target.subdir
3414
3415 @property
3416 def has_custom_install_dir(self) -> bool:
3417 return self.target.has_custom_install_dir
3418
3419 @property
3420 def install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
3421 return [self.target.install_dir[self.__index]]
3422
3423 def __repr__(self) -> str:
3424 return '<CustomTargetIndex: {!r}[{}]>'.format(self.target, self.output)
3425
3426 def get_outputs(self) -> T.List[str]:
3427 return [self.output]
3428
3429 def get_subdir(self) -> str:
3430 return self.target.get_subdir()
3431
3432 def get_build_subdir(self) -> str:
3433 return self.target.get_build_subdir()
3434
3435 def get_builddir(self) -> str:
3436 return self.target.get_builddir()
3437
3438 def get_filename(self) -> str:
3439 return self.output
3440
3441 def get_id(self) -> str:
3442 return self.target.get_id()
3443
3444 def get_target(self) -> BuildTarget | CustomTarget:
3445 return self.target
3446
3447 def get_all_link_deps(self) -> ImmutableListProtocol[BuildTargetTypes]:
3448 return self.target.get_all_link_deps()
3449
3450 def get_link_deps_mapping(self, prefix: str) -> T.Mapping[str, str]:
3451 return self.target.get_link_deps_mapping(prefix)
3452
3453 def get_link_dep_subdirs(self) -> T.AbstractSet[str]:
3454 return self.target.get_link_dep_subdirs()
3455
3456 def is_linkable_target(self) -> bool:
3457 return self.target.is_linkable_output(self.output)
3458
3459 def links_dynamically(self) -> bool:
3460 """Whether this target links dynamically or statically
3461
3462 Does not assert the target is linkable, just that it is not shared
3463
3464 :return: True if is dynamically linked, otherwise False
3465 """
3466 suf = os.path.splitext(self.output)[-1]
3467 return suf not in {'.a', '.lib'}
3468
3469 def should_install(self) -> bool:
3470 return self.target.should_install()
3471
3472 def is_internal(self) -> bool:
3473 '''
3474 Returns True if this is a not installed static library
3475 '''
3476 suf = os.path.splitext(self.output)[-1]
3477 return suf in {'.a', '.lib'} and not self.should_install()
3478
3479 def get_custom_install_dir(self) -> T.List[T.Union[str, Literal[False]]]:
3480 return self.target.get_custom_install_dir()
3481
3482 def get_basename(self) -> str:
3483 return self.target.get_basename()
3484
3485 def install_dir_names(self) -> T.List[T.Optional[str]]:
3486 install_dir_names = self.target.install_dir_names()
3487 return [install_dir_names[self.__index]]
3488
3489
3490 class ConfigurationData(HoldableObject):
3491 def __init__(self, initial_values: T.Optional[T.Union[
3492 T.Dict[str, T.Tuple[T.Union[str, int, bool], T.Optional[str]]],
3493 T.Dict[str, T.Union[str, int, bool]]]
3494 ] = None):
3495 super().__init__()
3496 self.values: T.Dict[str, T.Tuple[T.Union[str, int, bool], T.Optional[str]]] = \
3497 {k: v if isinstance(v, tuple) else (v, None) for k, v in initial_values.items()} if initial_values else {}
3498 self.used: bool = False
3499
3500 def __repr__(self) -> str:
3501 return repr(self.values)
3502
3503 def __contains__(self, value: str) -> bool:
3504 return value in self.values
3505
3506 def __bool__(self) -> bool:
3507 return bool(self.values)
3508
3509 def get(self, name: str) -> T.Tuple[T.Union[str, int, bool], T.Optional[str]]:
3510 return self.values[name] # (val, desc)
3511
3512 def keys(self) -> T.Iterable[str]:
3513 return self.values.keys()
3514
3515 class LocalProgram(programs.Program):
3516 def __init__(self, program: T.Union[programs.ExternalProgram, Executable, CustomTarget, CustomTargetIndex], version: str,
3517 file: T.Optional[File] = None) -> None:
3518 super().__init__()
3519 if isinstance(program, CustomTarget):
3520 if len(program.outputs) != 1:
3521 raise InvalidArguments('CustomTarget used as LocalProgram must have exactly one output.')
3522 if isinstance(program, programs.ExternalProgram):
3523 if not file:
3524 raise MesonBugException('ExternalProgram used as LocalProgram must be a file from the project')
3525 self.name = program.name
3526 self.file = file
3527 self.for_machine = program.for_machine
3528 self.program = program
3529 self.version = version
3530
3531 def found(self) -> bool:
3532 return True
3533
3534 def get_version(self, interpreter: T.Optional[Interpreter] = None) -> str:
3535 return self.version
3536
3537 def get_command(self) -> T.List[str]:
3538 if isinstance(self.program, programs.ExternalProgram):
3539 return self.program.get_command()
3540 # Only the backend knows the actual path to the build program.
3541 raise MesonBugException('Cannot call get_command() on program that is a build target.')
3542
3543 def get_path(self) -> str:
3544 if isinstance(self.program, programs.ExternalProgram):
3545 return self.program.get_path()
3546 # Only the backend knows the actual path to the build program.
3547 raise MesonBugException('Cannot call get_path() on program that is a build target.')
3548
3549 def get_target(self) -> T.Union[File, Executable, CustomTarget, CustomTargetIndex]:
3550 if self.file:
3551 return self.file
3552 assert not isinstance(self.program, programs.ExternalProgram)
3553 return self.program
3554
3555 def description(self) -> str:
3556 if isinstance(self.program, programs.ExternalProgram):
3557 return self.program.description()
3558 if isinstance(self.program, Executable):
3559 return self.program.name
3560 return self.program.get_filename()
3561
3562 def runnable(self) -> bool:
3563 return isinstance(self.program, programs.ExternalProgram)
3564
3565 def get_name(self) -> str:
3566 return self.name
3567
3568 # A bit poorly named, but this represents plain data files to copy
3569 # during install.
3570 @dataclass(eq=False)
3571 class Data(HoldableObject):
3572 sources: T.List[File]
3573 install_dir: str
3574 install_dir_name: str
3575 install_mode: 'FileMode'
3576 subproject: SubProject
3577 rename: T.List[str] = None
3578 install_tag: T.Optional[str] = None
3579 data_type: str = None
3580 follow_symlinks: T.Optional[bool] = None
3581
3582 def __post_init__(self) -> None:
3583 if self.rename is None:
3584 self.rename = [os.path.basename(f.fname) for f in self.sources]
3585
3586 @dataclass(eq=False)
3587 class SymlinkData(HoldableObject):
3588 target: str
3589 name: str
3590 install_dir: str
3591 subproject: SubProject
3592 install_tag: T.Optional[str] = None
3593
3594 def __post_init__(self) -> None:
3595 if self.name != os.path.basename(self.name):
3596 raise InvalidArguments(f'Link name is "{self.name}", but link names cannot contain path separators. '
3597 'The dir part should be in install_dir.')
3598
3599 @dataclass(eq=False)
3600 class TestSetup:
3601 exe_wrapper: T.List[str]
3602 gdb: bool
3603 timeout_multiplier: int
3604 env: EnvironmentVariables
3605 exclude_suites: T.List[str]
3606
3607
3608 def get_sources_string_names(sources: T.Sequence[CustomTargetSources], backend: Backend) -> list[str]:
3609 '''
3610 For the specified list of @sources which can be strings, Files,
3611 ExternalPrograms, or targets, get all the output basenames.
3612 '''
3613 names: list[str] = []
3614 for s in sources:
3615 if isinstance(s, (BuildTarget, CustomTarget, CustomTargetIndex, GeneratedList)):
3616 names += s.get_outputs()
3617 elif isinstance(s, ExtractedObjects):
3618 names += backend.determine_ext_objs(s)
3619 elif isinstance(s, File):
3620 names.append(s.fname)
3621 elif isinstance(s, programs.ExternalProgram):
3622 names.append(s.get_path())
3623 else:
3624 raise MesonBugException(f'Unknown source type: {s!r}')
3625 return names
3626
3627 def load(build_dir: str) -> Build:
3628 filename = os.path.join(build_dir, 'meson-private', 'build.dat')
3629 try:
3630 b = pickle_load(filename, 'Build data', Build)
3631 # We excluded coredata when saving Build object, load it separately
3632 b.environment.coredata = coredata.load(build_dir)
3633 return b
3634 except FileNotFoundError:
3635 raise MesonException(f'No such build data file as {filename!r}.')
3636
3637
3638 def save(obj: Build, filename: str) -> None:
3639 # Exclude coredata because we pickle it separately already
3640 cdata = obj.environment.coredata
3641 obj.environment.coredata = None
3642 try:
3643 with open(filename, 'wb') as f:
3644 pickle.dump(obj, f)
3645 finally:
3646 obj.environment.coredata = cdata