Debian Codegraph @

mesonbuild/backend/backends.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2016 The Meson development team
3
4 from __future__ import annotations
5
6 from collections import deque
7 from dataclasses import dataclass, InitVar
8 from functools import lru_cache
9 from itertools import chain
10 from pathlib import Path
11 import copy
12 import enum
13 import json
14 import os
15 import pickle
16 import re
17 import shlex
18 import shutil
19 import typing as T
20 import hashlib
21
22 from .. import build
23 from .. import dependencies
24 from .. import programs
25 from .. import mesonlib
26 from .. import mlog
27 from .. import compilers
28 from ..compilers import detect, lang_suffixes
29 from ..mesonlib import (
30 File, MachineChoice, MesonException, MesonBugException, OrderedSet,
31 ExecutableSerialisation, EnvironmentException, FileMode, InstallScriptFailure,
32 classify_unity_sources, get_compiler_for_source,
33 get_rsp_threshold, unique_list
34 )
35 from ..options import OptionKey
36
37
38 if T.TYPE_CHECKING:
39 from .._typing import ImmutableListProtocol
40 from ..arglist import CompilerArgs
41 from ..build import TargetSources
42 from ..compilers.compilers import Compiler, Language
43 from ..environment import Environment
44 from ..interpreter import Test
45 from ..linkers import StaticLinker
46 from ..mesonlib import InstallScript
47 from ..options import ElementaryOptionValues
48
49 from typing_extensions import Literal, TypedDict, NotRequired, TypeAlias
50
51 class CompilerIntrospectionData(TypedDict):
52
53 language: T.Union[Language, Literal['unknown']]
54 machine: NotRequired[str]
55 compiler: T.List[str]
56 parameters: T.List[str]
57 sources: T.List[str]
58 generated_sources: T.List[str]
59 unity_sources: NotRequired[T.List[str]]
60
61 class LinkerIntrospectionData(TypedDict):
62
63 linker: T.List[str]
64 parameters: T.List[str]
65
66 TargetIntrospectionData: TypeAlias = T.Union['CompilerIntrospectionData', 'LinkerIntrospectionData']
67
68 # Languages that can mix with C or C++ but don't support unity builds yet
69 # because the syntax we use for unity builds is specific to C/++/ObjC/++.
70 # Assembly files cannot be unitified and neither can LLVM IR files
71 LANGS_CANT_UNITY: T.FrozenSet[Language] = frozenset({'d', 'fortran', 'vala', 'rust'})
72
73 @dataclass(eq=False)
74 class RegenInfo:
75 source_dir: str
76 build_dir: str
77 depfiles: T.List[str]
78
79 class TestProtocol(enum.Enum):
80
81 EXITCODE = 0
82 TAP = 1
83 GTEST = 2
84 RUST = 3
85
86 @classmethod
87 def from_str(cls, string: str) -> 'TestProtocol':
88 if string == 'exitcode':
89 return cls.EXITCODE
90 elif string == 'tap':
91 return cls.TAP
92 elif string == 'gtest':
93 return cls.GTEST
94 elif string == 'rust':
95 return cls.RUST
96 raise MesonException(f'unknown test format {string}')
97
98 def __str__(self) -> str:
99 cls = type(self)
100 if self is cls.EXITCODE:
101 return 'exitcode'
102 elif self is cls.GTEST:
103 return 'gtest'
104 elif self is cls.RUST:
105 return 'rust'
106 return 'tap'
107
108
109 @dataclass(eq=False)
110 class CleanTrees:
111 '''
112 Directories outputted by custom targets that have to be manually cleaned
113 because on Linux `ninja clean` only deletes empty directories.
114 '''
115 build_dir: str
116 trees: T.List[str]
117
118 @dataclass(eq=False)
119 class InstallData:
120 source_dir: str
121 build_dir: str
122 prefix: str
123 libdir: str
124 strip_bin: T.List[str]
125 # TODO: in python 3.8 or with typing_Extensions this could be:
126 # `T.Union[T.Literal['preserve'], int]`, which would be more accurate.
127 install_umask: T.Union[str, int]
128 mesonintrospect: T.List[str]
129 version: str
130
131 def __post_init__(self) -> None:
132 self.targets: T.List[TargetInstallData] = []
133 self.headers: T.List[InstallDataBase] = []
134 self.man: T.List[InstallDataBase] = []
135 self.emptydir: T.List[InstallEmptyDir] = []
136 self.data: T.List[InstallDataBase] = []
137 self.symlinks: T.List[InstallSymlinkData] = []
138 self.install_scripts: T.List[InstallScript] = []
139 self.install_subdirs: T.List[SubdirInstallData] = []
140
141 @dataclass(eq=False)
142 class TargetInstallData:
143 fname: str
144 outdir: str
145 outdir_name: InitVar[T.Optional[str]]
146 strip: bool
147 install_name_mappings: T.Mapping[str, str]
148 rpath_dirs_to_remove: T.Set[bytes]
149 install_rpath: str
150 install_mode: FileMode
151 subproject: str
152 system: str
153 optional: bool = False
154 tag: T.Optional[str] = None
155 can_strip: bool = False
156
157 def __post_init__(self, outdir_name: T.Optional[str]) -> None:
158 if outdir_name is None:
159 outdir_name = os.path.join('{prefix}', self.outdir)
160 self.out_name = os.path.join(outdir_name, os.path.basename(self.fname))
161
162 @dataclass(eq=False)
163 class InstallEmptyDir:
164 path: str
165 install_mode: 'FileMode'
166 subproject: str
167 tag: T.Optional[str] = None
168
169 @dataclass(eq=False)
170 class InstallDataBase:
171 path: str
172 install_path: str
173 install_path_name: str
174 install_mode: 'FileMode'
175 subproject: str
176 tag: T.Optional[str] = None
177 data_type: T.Optional[str] = None
178 follow_symlinks: T.Optional[bool] = None
179
180 @dataclass(eq=False)
181 class InstallSymlinkData:
182 target: str
183 name: str
184 install_path: str
185 subproject: str
186 tag: T.Optional[str] = None
187
188 # cannot use dataclass here because "exclude" is out of order
189 class SubdirInstallData(InstallDataBase):
190 def __init__(self, path: str, install_path: str, install_path_name: str,
191 install_mode: 'FileMode', exclude: T.Tuple[T.Set[str], T.Set[str]],
192 subproject: str, tag: T.Optional[str] = None, data_type: T.Optional[str] = None,
193 follow_symlinks: T.Optional[bool] = None):
194 super().__init__(path, install_path, install_path_name, install_mode, subproject, tag, data_type, follow_symlinks)
195 self.exclude = exclude
196
197
198 @dataclass(eq=False)
199 class TestSerialisation:
200 name: str
201 project_name: str
202 suite: T.List[str]
203 fname: T.List[str]
204 is_cross_built: bool
205 exe_wrapper: T.Optional[programs.ExternalProgram]
206 needs_exe_wrapper: bool
207 is_parallel: bool
208 cmd_args: T.List[str]
209 env: mesonlib.EnvironmentVariables
210 expected_fail: bool
211 expected_exitcode: T.Optional[int]
212 timeout: T.Optional[int]
213 workdir: T.Optional[str]
214 extra_paths: T.List[str]
215 protocol: TestProtocol
216 priority: int
217 cmd_is_built: bool
218 cmd_is_exe: bool
219 depends: T.List[str]
220 version: str
221 verbose: bool
222
223 def __post_init__(self) -> None:
224 if self.exe_wrapper is not None:
225 assert isinstance(self.exe_wrapper, programs.ExternalProgram)
226
227
228 def get_backend_from_name(backend: str, build: T.Optional[build.Build] = None) -> Backend:
229 if backend == 'ninja':
230 from . import ninjabackend
231 return ninjabackend.NinjaBackend(build)
232 elif backend == 'vs':
233 from . import vs2010backend
234 return vs2010backend.autodetect_vs_version(build)
235 elif backend == 'vs2010':
236 from . import vs2010backend
237 return vs2010backend.Vs2010Backend(build)
238 elif backend == 'vs2012':
239 from . import vs2012backend
240 return vs2012backend.Vs2012Backend(build)
241 elif backend == 'vs2013':
242 from . import vs2013backend
243 return vs2013backend.Vs2013Backend(build)
244 elif backend == 'vs2015':
245 from . import vs2015backend
246 return vs2015backend.Vs2015Backend(build)
247 elif backend == 'vs2017':
248 from . import vs2017backend
249 return vs2017backend.Vs2017Backend(build)
250 elif backend == 'vs2019':
251 from . import vs2019backend
252 return vs2019backend.Vs2019Backend(build)
253 elif backend == 'vs2022':
254 from . import vs2022backend
255 return vs2022backend.Vs2022Backend(build)
256 elif backend == 'vs2026':
257 from . import vs2026backend
258 return vs2026backend.Vs2026Backend(build)
259 elif backend == 'xcode':
260 from . import xcodebackend
261 return xcodebackend.XCodeBackend(build)
262 elif backend == 'none':
263 from . import nonebackend
264 return nonebackend.NoneBackend(build)
265 raise MesonException(f'Unknown backend {backend}')
266
267
268 def get_genvslite_backend(genvsname: str, build: T.Optional[build.Build] = None) -> Backend:
269 if genvsname == 'vs2022':
270 from . import vs2022backend
271 return vs2022backend.Vs2022Backend(build, gen_lite = True)
272 if genvsname == 'vs2026':
273 from . import vs2026backend
274 return vs2026backend.Vs2026Backend(build, gen_lite = True)
275 raise MesonException(f'Unknown genvslite backend {genvsname}')
276
277 # This class contains the basic functionality that is needed by all backends.
278 # Feel free to move stuff in and out of it as you see fit.
279 class Backend:
280
281 environment: T.Optional['Environment']
282 name = '<UNKNOWN>'
283
284 def __init__(self, build: T.Optional[build.Build]):
285 # Make it possible to construct a dummy backend
286 # This is used for introspection without a build directory
287 if build is None:
288 self.environment = None
289 return
290 self.build = build
291 self.environment = build.environment
292 self.processed_targets: T.Set[str] = set()
293 self.build_dir = self.environment.get_build_dir()
294 self.source_dir = self.environment.get_source_dir()
295 self.build_to_src = mesonlib.relpath(self.environment.get_source_dir(),
296 self.environment.get_build_dir())
297 self.src_to_build = mesonlib.relpath(self.environment.get_build_dir(),
298 self.environment.get_source_dir())
299
300 # If requested via 'capture = True', returns captured compile args per
301 # target (e.g. captured_args[target]) that can be used later, for example,
302 # to populate things like intellisense fields in generated visual studio
303 # projects (as is the case when using '--genvslite').
304 #
305 # 'vslite_ctx' is only provided when
306 # we expect this backend setup/generation to make use of previously captured
307 # compile args (as is the case when using '--genvslite').
308 def generate(self, capture: bool = False, vslite_ctx: T.Optional[T.Dict] = None) -> T.Optional[T.Dict]:
309 raise RuntimeError(f'generate is not implemented in {type(self).__name__}')
310
311 def get_target_filename(self, t: build.AnyTargetType, *, warn_multi_output: bool = True) -> str:
312 if isinstance(t, build.CustomTarget):
313 if warn_multi_output and len(t.get_outputs()) != 1:
314 mlog.warning(f'custom_target {t.name!r} has more than one output! '
315 f'Using the first one. Consider using `{t.name}[0]`.')
316 filename = t.get_outputs()[0]
317 elif isinstance(t, build.CustomTargetIndex):
318 filename = t.get_outputs()[0]
319 else:
320 assert isinstance(t, build.BuildTarget), t
321 filename = t.get_filename()
322 return os.path.join(self.get_target_dir(t), filename)
323
324 def get_target_filename_abs(self, target: build.AnyTargetType) -> str:
325 return os.path.join(self.environment.get_build_dir(), self.get_target_filename(target))
326
327 def get_target_debug_filename(self, target: build.BuildTarget) -> T.Optional[str]:
328 if target.get_debug_filename():
329 debug_filename = target.get_debug_filename()
330 return os.path.join(self.get_target_dir(target), debug_filename)
331 else:
332 return None
333
334 def get_target_debug_filename_abs(self, target: build.BuildTarget) -> T.Optional[str]:
335 if not target.get_debug_filename():
336 return None
337 return os.path.join(self.environment.get_build_dir(), self.get_target_debug_filename(target))
338
339 def get_source_dir_include_args(self, target: build.BuildTarget, compiler: 'Compiler', *, absolute_path: bool = False) -> T.List[str]:
340 curdir = target.get_subdir()
341 if absolute_path:
342 lead = self.source_dir
343 else:
344 lead = self.build_to_src
345 tmppath = os.path.normpath(os.path.join(lead, curdir))
346 return compiler.get_include_args(tmppath, False)
347
348 def get_build_dir_include_args(self, target: build.BuildTarget, compiler: 'Compiler', *, absolute_path: bool = False) -> T.List[str]:
349 if absolute_path:
350 curdir = os.path.join(self.build_dir, target.get_builddir())
351 else:
352 curdir = target.get_builddir()
353 if curdir == '':
354 curdir = '.'
355 return compiler.get_include_args(curdir, False)
356
357 def get_target_filename_for_linking(self, target: build.AnyTargetType) -> T.Optional[str]:
358 # On some platforms (msvc for instance), the file that is used for
359 # dynamic linking is not the same as the dynamic library itself. This
360 # file is called an import library, and we want to link against that.
361 # On all other platforms, we link to the library directly.
362 if isinstance(target, build.SharedLibrary):
363 link_lib = target.get_import_filename() or target.get_filename()
364 # In AIX, if we archive .so, the blibpath must link to archived shared library otherwise to the .so file.
365 if mesonlib.is_aix() and target.aix_so_archive:
366 link_lib = re.sub('[.][a]([.]?([0-9]+))*([.]?([a-z]+))*', '.a', link_lib.replace('.so', '.a'))
367 return Path(self.get_target_dir(target), link_lib).as_posix()
368 elif isinstance(target, build.StaticLibrary):
369 return Path(self.get_target_dir(target), target.get_filename()).as_posix()
370 elif isinstance(target, (build.CustomTarget, build.CustomTargetIndex)):
371 if not target.is_linkable_target():
372 raise MesonException(f'Tried to link against custom target "{target.name}", which is not linkable.')
373 return Path(self.get_target_dir(target), target.get_filename()).as_posix()
374 elif isinstance(target, build.Executable):
375 if target.import_filename:
376 return Path(self.get_target_dir(target), target.get_import_filename()).as_posix()
377 else:
378 return None
379 raise AssertionError(f'BUG: Tried to link to {target!r} which is not linkable')
380
381 @lru_cache(maxsize=None)
382 def get_target_dir_cached(self, target: build.Target) -> str:
383 if isinstance(target, build.RunTarget):
384 # this produces no output, only a dummy top-level name
385 dirname = ''
386 elif self.environment.coredata.optstore.get_value_for(OptionKey('layout')) == 'mirror':
387 dirname = target.get_builddir()
388 else:
389 dirname = 'meson-out'
390 build_subdir = target.get_build_subdir()
391 if build_subdir:
392 dirname = os.path.join(dirname, build_subdir)
393 return dirname
394
395 def get_target_dir(self, target: build.AnyTargetType) -> str:
396 return self.get_target_dir_cached(target.get_target())
397
398 def get_target_dir_relative_to(self,
399 t: T.Union[build.Target, build.CustomTargetIndex],
400 o: T.Union[build.Target, build.CustomTargetIndex],
401 ) -> str:
402 '''Get a target dir relative to another target's directory'''
403 target_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(t))
404 othert_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(o))
405 return os.path.relpath(target_dir, othert_dir)
406
407 def get_target_source_dir(self, target: build.Target) -> str:
408 # if target dir is empty, avoid extraneous trailing / from os.path.join()
409 target_dir = self.get_target_dir(target)
410 if target_dir:
411 return os.path.join(self.build_to_src, target_dir)
412 return self.build_to_src
413
414 def get_target_private_dir(self, target: build.AnyTargetType) -> str:
415 return os.path.join(self.get_target_filename(target, warn_multi_output=False) + '.p')
416
417 def get_target_private_dir_abs(self, target: build.BuildTargetTypes) -> str:
418 return os.path.join(self.environment.get_build_dir(), self.get_target_private_dir(target))
419
420 @lru_cache(maxsize=None)
421 def get_target_generated_dir(
422 self, target: build.BuildTargetTypes,
423 gensrc: build.GeneratedTypes,
424 src: str) -> str:
425 """
426 Takes a BuildTarget, a generator source (CustomTarget or GeneratedList),
427 and a generated source filename.
428 Returns the full path of the generated source relative to the build root
429 """
430 # CustomTarget generators output to the build dir of the CustomTarget
431 if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex)):
432 return os.path.join(self.get_target_dir(gensrc), src)
433 # GeneratedList generators output to the private build directory of the
434 # target that the GeneratedList is used in
435 return os.path.join(self.get_target_private_dir(target), src)
436
437 def get_unity_source_file(self, target: build.BuildTargetTypes,
438 suffix: str, number: int) -> mesonlib.File:
439 # There is a potential conflict here, but it is unlikely that
440 # anyone both enables unity builds and has a file called foo-unity.cpp.
441 osrc = f'{target.name}-unity{number}.{suffix}'
442 return mesonlib.File.from_built_file(self.get_target_private_dir(target), osrc)
443
444 def generate_unity_files(self, target: build.BuildTarget, unity_src: list[File]) -> list[mesonlib.File]:
445 abs_files: T.List[str] = []
446 result: T.List[mesonlib.File] = []
447 compsrcs = classify_unity_sources(target.compilers.values(), unity_src)
448 unity_size = self.get_target_option(target, 'unity_size')
449 assert isinstance(unity_size, int), 'for mypy'
450
451 def init_language_file(suffix: str, unity_file_number: int) -> T.TextIO:
452 unity_src = self.get_unity_source_file(target, suffix, unity_file_number)
453 outfileabs = unity_src.absolute_path(self.environment.get_source_dir(),
454 self.environment.get_build_dir())
455 outfileabs_tmp = outfileabs + '.tmp'
456 abs_files.append(outfileabs)
457 outfileabs_tmp_dir = os.path.dirname(outfileabs_tmp)
458 if not os.path.exists(outfileabs_tmp_dir):
459 os.makedirs(outfileabs_tmp_dir)
460 result.append(unity_src)
461 return open(outfileabs_tmp, 'w', encoding='utf-8')
462
463 # For each language, generate unity source files and return the list
464 for comp, srcs in compsrcs.items():
465 files_in_current = unity_size + 1
466 unity_file_number = 0
467 # TODO: this could be simplified with an algorithm that pre-sorts
468 # the sources into the size of chunks we want
469 ofile = None
470 for src in srcs:
471 if files_in_current >= unity_size:
472 if ofile:
473 ofile.close()
474 ofile = init_language_file(comp.get_default_suffix(), unity_file_number)
475 unity_file_number += 1
476 files_in_current = 0
477 ofile.write(f'#include<{src.absolute_path(self.source_dir, self.build_dir)}>\n')
478 files_in_current += 1
479 if ofile:
480 ofile.close()
481
482 for x in abs_files:
483 mesonlib.replace_if_different(x, x + '.tmp')
484 return result
485
486 @staticmethod
487 def relpath(todir: str | os.PathLike[str], fromdir: str | os.PathLike[str]) -> str:
488 return os.path.relpath(os.path.join('dummyprefixdir', todir),
489 os.path.join('dummyprefixdir', fromdir))
490
491 def get_all_linked_targets(self, target: build.BuildTarget) -> T.Iterator[build.BuildTargetTypes]:
492 """Get all targets that have been linked with this one, including internal and
493 indirect static libraries unlike :method:`build.BuildTarget.get_all_link_deps`
494 and :method:`build.all_dependencies_recurse`, and targets whose objects
495 are borrowed by this one or any returned target.
496
497 This is useful for cases where we need to analyze these links, such as
498 for module information.
499 """
500 seen: T.Set[build.BuildTarget] = set()
501 stack: T.Deque[build.BuildTargetTypes] = deque()
502
503 def add_linked_targets(t: build.BuildTarget) -> None:
504 stack.extendleft(t.link_targets)
505 stack.extendleft(t.link_whole_targets)
506 _, od = self.flatten_object_list(t)
507 stack.extendleft(od)
508
509 add_linked_targets(target)
510 while stack:
511 t = stack.pop()
512 if t in seen or not isinstance(t, build.BuildTarget):
513 continue
514 seen.add(t)
515 add_linked_targets(t)
516 yield t
517 assert target not in seen, 'should not have self'
518
519 def flatten_object_list(self, target: build.BuildTarget, proj_dir_to_build_root: str = ''
520 ) -> T.Tuple[T.List[str], T.Iterable[build.BuildTarget]]:
521 obj_list, deps = self._flatten_object_list(target.get_objects(), proj_dir_to_build_root)
522 return unique_list(obj_list), deps
523
524 def determine_ext_objs(self, objects: build.ExtractedObjects) -> T.List[str]:
525 obj_list, _ = self._flatten_object_list([objects], '')
526 return unique_list(obj_list)
527
528 def _flatten_object_list(self, objects: T.Sequence[build.ObjectTypes],
529 proj_dir_to_build_root: str) -> T.Tuple[T.List[str], T.Iterable[build.BuildTarget]]:
530 # The same target can be reached through multiple ExtractObjects, so
531 # ensure each distinct target is visited exactly once.
532 seen: T.Set[build.BuildTarget] = set()
533 deps: OrderedSet[build.BuildTarget] = OrderedSet()
534 result: T.Dict[build.BuildTarget, T.List[str]] = {}
535
536 def visit_dfs(o: build.ExtractedObjects) -> T.Iterator[build.BuildTarget]:
537 t = o.target
538 deps.add(t)
539 if o.recursive:
540 if t in seen:
541 return
542 seen.add(t)
543 for obj in t.get_objects():
544 if isinstance(obj, build.ExtractedObjects):
545 yield from visit_dfs(obj)
546 yield t
547
548 def flatten_one(objs: T.Sequence[build.ObjectTypes]) -> T.List[str]:
549 obj_list: T.List[str] = []
550 for obj in objs:
551 if isinstance(obj, mesonlib.File):
552 if obj.is_built:
553 o = os.path.join(proj_dir_to_build_root,
554 obj.rel_to_builddir(self.build_to_src))
555 obj_list.append(o)
556 else:
557 o = os.path.join(proj_dir_to_build_root,
558 self.build_to_src)
559 obj_list.append(obj.rel_to_builddir(o))
560 elif isinstance(obj, build.ExtractedObjects):
561 # Whatever obj.target recursively depends on has already
562 # been yielded and flattened.
563 if obj.recursive:
564 obj_list.extend(result[obj.target])
565 new_objs = self._determine_ext_objs(obj)
566 if proj_dir_to_build_root:
567 for o in new_objs:
568 obj_list.append(os.path.join(proj_dir_to_build_root, o))
569 else:
570 obj_list.extend(new_objs)
571 else:
572 raise MesonBugException('Unknown data type in object list.')
573 return obj_list
574
575 for obj in objects:
576 if isinstance(obj, build.ExtractedObjects):
577 for t in visit_dfs(obj):
578 result[t] = flatten_one(t.get_objects())
579
580 return flatten_one(objects), deps
581
582 @staticmethod
583 def is_swift_target(target: build.BuildTargetTypes) -> bool:
584 if not isinstance(target, build.BuildTarget):
585 return False
586 for s in target.get_sources():
587 if s.endswith('swift'):
588 return True
589 return False
590
591 def determine_swift_dep_dirs(self, target: build.BuildTarget) -> T.List[str]:
592 result: T.List[str] = []
593 for l in target.link_targets:
594 result.append(self.get_target_private_dir_abs(l))
595 return result
596
597 def get_executable_serialisation(
598 self, cmd: T.Iterable[build.CommandTypes],
599 workdir: T.Optional[str] = None,
600 extra_bdeps: T.Optional[T.Iterable[build.BuildTargetTypes]] = None,
601 capture: T.Optional[str] = None,
602 feed: T.Optional[str] = None,
603 env: T.Optional[mesonlib.EnvironmentVariables] = None,
604 can_use_rsp_file: bool = False,
605 separator: str = ' ',
606 rsp_file_flag: str = '@',
607 tag: T.Optional[str] = None,
608 verbose: bool = False,
609 installdir_map: T.Optional[T.Dict[str, str]] = None) -> 'ExecutableSerialisation':
610 # XXX: cmd_args either need to be lowered to strings, or need to be checked for non-string arguments, right?
611 exe, *raw_cmd_args = cmd
612 if isinstance(exe, build.LocalProgram):
613 exe = exe.program
614 if isinstance(exe, programs.Program):
615 exe_cmd = exe.get_command()
616 exe_for_machine = exe.for_machine
617 elif isinstance(exe, build.BuildTarget):
618 exe_cmd = [self.get_target_filename_abs(exe)]
619 exe_for_machine = exe.for_machine
620 elif isinstance(exe, (build.CustomTarget, build.CustomTargetIndex)):
621 # The output of a custom target can either be directly runnable
622 # or not, that is, a script, a native binary or a cross compiled
623 # binary when exe wrapper is available and when it is not.
624 # This implementation is not exhaustive but it works in the
625 # common cases.
626 exe_cmd = [self.get_target_filename_abs(exe)]
627 exe_for_machine = MachineChoice.BUILD
628 elif isinstance(exe, mesonlib.File):
629 exe_cmd = [exe.rel_to_builddir(self.environment.source_dir)]
630 exe_for_machine = MachineChoice.BUILD
631 else:
632 exe_cmd = [exe]
633 exe_for_machine = MachineChoice.BUILD
634
635 cmd_args: T.List[str] = []
636 for c in raw_cmd_args:
637 if isinstance(c, build.LocalProgram):
638 c = c.program
639 if isinstance(c, programs.Program):
640 cmd_args += c.get_command()
641 elif isinstance(c, (build.BuildTarget, build.CustomTarget, build.CustomTargetIndex)):
642 cmd_args.append(self.get_target_filename_abs(c))
643 elif isinstance(c, mesonlib.File):
644 cmd_args.append(c.rel_to_builddir(self.environment.source_dir))
645 else:
646 cmd_args.append(c)
647
648 machine = self.environment.machines[exe_for_machine]
649 if machine.is_windows() or machine.is_cygwin():
650 extra_paths = self.determine_windows_extra_paths(exe, extra_bdeps or [])
651 else:
652 extra_paths = []
653
654 is_cross_built = not self.environment.machines.matches_build_machine(exe_for_machine)
655 if is_cross_built and self.environment.need_exe_wrapper():
656 if not self.environment.has_exe_wrapper():
657 msg = 'An exe_wrapper is needed for ' + exe_cmd[0] + ' but was not found. Please define one ' \
658 'in cross file and check the command and/or add it to PATH.'
659 raise MesonException(msg)
660 exe_wrapper = self.environment.get_exe_wrapper()
661 else:
662 if exe_cmd[0].endswith('.jar'):
663 exe_cmd = ['java', '-jar'] + exe_cmd
664 elif exe_cmd[0].endswith('.exe') and not (mesonlib.is_windows() or mesonlib.is_cygwin() or mesonlib.is_wsl() or machine.is_os2()):
665 exe_cmd = ['mono'] + exe_cmd
666 exe_wrapper = None
667
668 workdir = workdir or self.environment.get_build_dir()
669
670 # Must include separators as well
671 needs_rsp_file = can_use_rsp_file and sum(len(i) + 1 for i in cmd_args) >= get_rsp_threshold()
672
673 if needs_rsp_file:
674 hasher = hashlib.sha1()
675 args = separator.join(mesonlib.quote_arg(arg) for arg in cmd_args)
676 hasher.update(args.encode(encoding='utf-8', errors='ignore'))
677 digest = hasher.hexdigest()
678 scratch_file = f'meson_rsp_{digest}.rsp'
679 rsp_file = os.path.join(self.environment.get_scratch_dir(), scratch_file)
680 with open(rsp_file, 'w', encoding='utf-8', newline='\n') as f:
681 f.write(args)
682 cmd_args = [f'{rsp_file_flag}{rsp_file}']
683
684 return ExecutableSerialisation(exe_cmd + cmd_args, env,
685 exe_wrapper, workdir,
686 extra_paths, capture, feed, tag, verbose, installdir_map)
687
688 def as_meson_exe_cmdline(self, exe: build.CommandTypes,
689 cmd_args: T.Iterable[build.CommandTypes],
690 workdir: T.Optional[str] = None,
691 extra_bdeps: T.Optional[T.Iterable[build.BuildTargetTypes]] = None,
692 capture: T.Optional[str] = None,
693 feed: T.Optional[str] = None,
694 force_serialize: bool = False,
695 env: T.Optional[mesonlib.EnvironmentVariables] = None,
696 can_use_rsp_file: bool = False,
697 separator: str = ' ',
698 rsp_file_flag: str = '@',
699 verbose: bool = False) -> T.Tuple[T.List[str], str]:
700 '''
701 Serialize an executable for running with a generator or a custom target
702 '''
703 cmd: T.List[build.CommandTypes] = []
704 cmd.append(exe)
705 cmd.extend(cmd_args)
706 es = self.get_executable_serialisation(cmd, workdir, extra_bdeps, capture, feed, env, can_use_rsp_file, separator=separator, rsp_file_flag=rsp_file_flag, verbose=verbose)
707 reasons: T.List[str] = []
708 if es.extra_paths:
709 reasons.append('to set PATH')
710
711 if es.exe_wrapper:
712 reasons.append('to use exe_wrapper')
713
714 if workdir:
715 reasons.append('to set workdir')
716
717 if any('\n' in c for c in es.cmd_args):
718 reasons.append('because command contains newlines')
719
720 if env and env.varnames:
721 reasons.append('to set env')
722
723 if separator != ' ':
724 reasons.append('to use a custom argument separator')
725
726 # force_serialize passed to this function means that the VS backend has
727 # decided it absolutely cannot use real commands. This is "always",
728 # because it's not clear what will work (other than compilers) and so
729 # we don't bother to handle a variety of common cases that probably do
730 # work.
731 #
732 # It's also overridden for a few conditions that can't be handled
733 # inside a command line
734
735 can_use_env = env and env.can_use_env and not force_serialize
736 force_serialize = force_serialize or bool(reasons)
737
738 if capture:
739 reasons.append('to capture output')
740 if feed:
741 reasons.append('to feed input')
742
743 if can_use_env and reasons == ['to set env'] and shutil.which('env'):
744 envlist = []
745 for k, v in env.get_env({}).items():
746 envlist.append(f'{k}={v}')
747 return ['env'] + envlist + es.cmd_args, ', '.join(reasons)
748
749 if can_use_rsp_file and any(a.startswith(rsp_file_flag) for a in es.cmd_args):
750 reasons.append('because command is too long')
751
752 if not force_serialize:
753 if not capture and not feed:
754 return es.cmd_args, ''
755 args: T.List[str] = []
756 if capture:
757 args += ['--capture', capture]
758 if feed:
759 args += ['--feed', feed]
760
761 return (
762 self.environment.get_build_command() + ['--internal', 'exe'] + args + ['--'] + es.cmd_args,
763 ', '.join(reasons)
764 )
765
766 if isinstance(exe, (programs.Program,
767 build.BuildTarget, build.CustomTarget, build.CustomTargetIndex)):
768 basename = os.path.basename(exe.name)
769 elif isinstance(exe, mesonlib.File):
770 basename = os.path.basename(exe.fname)
771 else:
772 basename = os.path.basename(exe)
773
774 # Can't just use exe.name here; it will likely be run more than once
775 # Take a digest of the cmd args, env, workdir, capture, and feed. This
776 # avoids collisions and also makes the name deterministic over
777 # regenerations which avoids a rebuild by Ninja because the cmdline
778 # stays the same.
779 hasher = hashlib.sha1()
780 if es.env:
781 es.env.hash(hasher)
782 hasher.update(bytes(str(es.cmd_args), encoding='utf-8'))
783 hasher.update(bytes(str(es.workdir), encoding='utf-8'))
784 hasher.update(bytes(str(capture), encoding='utf-8'))
785 hasher.update(bytes(str(feed), encoding='utf-8'))
786 digest = hasher.hexdigest()
787 scratch_file = f'meson_exe_{basename}_{digest}.dat'
788 exe_data = os.path.join(self.environment.get_scratch_dir(), scratch_file)
789 with open(exe_data, 'wb') as f:
790 pickle.dump(es, f)
791 return (self.environment.get_build_command() + ['--internal', 'exe', '--unpickle', exe_data],
792 ', '.join(reasons))
793
794 def serialize_tests(self) -> T.Tuple[str, str]:
795 test_data = os.path.join(self.environment.get_scratch_dir(), 'meson_test_setup.dat')
796 with open(test_data, 'wb') as datafile:
797 self.write_test_file(datafile)
798 benchmark_data = os.path.join(self.environment.get_scratch_dir(), 'meson_benchmark_setup.dat')
799 with open(benchmark_data, 'wb') as datafile:
800 self.write_benchmark_file(datafile)
801 return test_data, benchmark_data
802
803 def determine_linker_and_stdlib_args(self, target: build.BuildTarget) -> T.Tuple[T.Union['Compiler', 'StaticLinker'], T.List[str]]:
804 '''
805 If we're building a static library, there is only one static linker.
806 Otherwise, we query the target for the dynamic linker.
807 '''
808 if isinstance(target, build.StaticLibrary):
809 return self.build.get_static_linker(target), []
810 l, stdlib_args = target.get_clink_dynamic_linker_and_stdlibs()
811 return l, stdlib_args
812
813 @staticmethod
814 @lru_cache(maxsize=None)
815 def canonicalize_filename(fname: str) -> str:
816 if os.path.altsep is not None:
817 fname = fname.replace(os.path.altsep, os.path.sep)
818 parts = fname.split(os.path.sep)
819 hashed = ''
820 if len(parts) > 5:
821 temp = '/'.join(parts[-5:])
822 # is it shorter to hash the beginning of the path?
823 if len(fname) > len(temp) + 41:
824 hashed = hashlib.sha1(fname.encode('utf-8')).hexdigest() + '_'
825 fname = temp
826 for ch in ('/', '\\', ':'):
827 fname = fname.replace(ch, '_')
828 return hashed + fname
829
830 def object_filename_from_source(self, target: build.BuildTarget, compiler: Compiler, source: File, targetdir: T.Optional[str] = None) -> str:
831 if isinstance(target, build.CompileTarget):
832 return target.sources_map[source]
833 build_dir = self.environment.get_build_dir()
834 rel_src = source.rel_to_builddir(self.build_to_src)
835
836 # foo.vala files compile down to foo.c and then foo.c.o, not foo.vala.o
837 if rel_src.endswith(('.vala', '.gs')):
838 # See description in generate_vala_compile for this logic.
839 if source.is_built:
840 if os.path.isabs(rel_src):
841 rel_src = rel_src[len(build_dir) + 1:]
842 rel_src = os.path.relpath(rel_src, self.get_target_private_dir(target))
843 else:
844 rel_src = os.path.relpath(rel_src, os.path.join(self.build_to_src, target.get_subdir()))
845 # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
846 gen_source = 'meson-generated_' + rel_src[:-5] + '.c'
847 elif source.is_built:
848 if os.path.isabs(rel_src):
849 rel_src = rel_src[len(build_dir) + 1:]
850 # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
851 gen_source = 'meson-generated_' + os.path.relpath(rel_src, self.get_target_private_dir(target))
852 else:
853 if os.path.isabs(rel_src):
854 # Use the absolute path directly to avoid file name conflicts
855 gen_source = rel_src
856 else:
857 gen_source = os.path.relpath(os.path.join(build_dir, rel_src),
858 os.path.join(self.environment.get_source_dir(), target.get_subdir()))
859 machine = self.environment.machines[target.for_machine]
860 object_suffix = machine.get_object_suffix()
861 # For the TASKING compiler, in case of LTO or prelinking the object suffix has to be .mil
862 if compiler.get_id() == 'tasking':
863 use_lto = self.get_target_option(target, 'b_lto')
864 if use_lto or (isinstance(target, build.StaticLibrary) and target.prelink):
865 if not source.rsplit('.', 1)[1] in lang_suffixes['c']:
866 if isinstance(target, build.StaticLibrary) and not target.prelink:
867 raise EnvironmentException('Tried using MIL linking for a static library with a assembly file. This can only be done if the static library is prelinked or disable \'b_lto\'.')
868 else:
869 object_suffix = 'mil'
870 ret = self.canonicalize_filename(gen_source) + '.' + object_suffix
871 if targetdir is not None:
872 return os.path.join(targetdir, ret)
873 return ret
874
875 @lru_cache(maxsize=None)
876 def _determine_ext_objs(self, extobj: 'build.ExtractedObjects') -> T.List[str]:
877 result: T.List[str] = []
878
879 targetdir = self.get_target_private_dir(extobj.target)
880
881 # Merge sources and generated sources
882 raw_sources: T.List[File] = list(extobj.srclist)
883 for gensrc in extobj.genlist:
884 for r in gensrc.get_outputs():
885 path = self.get_target_generated_dir(extobj.target, gensrc, r)
886 raw_sources.append(File.from_built_relative(path))
887
888 # Filter out headers and all non-source files
889 sources: T.List[File] = []
890 for s in raw_sources:
891 if compilers.is_source(s):
892 sources.append(s)
893 elif compilers.is_object(s):
894 result.append(s.relative_name())
895
896 # MSVC generate an object file for PCH
897 if extobj.pch and self.target_uses_pch(extobj.target):
898 for lang, pch in extobj.target.pch.items():
899 if pch:
900 compiler = extobj.target.compilers[lang]
901 if compiler.get_argument_syntax() == 'msvc':
902 objname = self.get_msvc_pch_objname(lang, pch)
903 result.append(os.path.join(targetdir, objname))
904
905 # extobj could contain only objects and no sources
906 if not sources:
907 return result
908
909 # With unity builds, sources don't map directly to objects,
910 # we only support extracting all the objects in this mode,
911 # so just return all object files.
912 if self.is_unity(extobj.target):
913 compsrcs = classify_unity_sources(extobj.target.compilers.values(), sources)
914 sources = []
915 unity_size = self.get_target_option(extobj.target, 'unity_size')
916 assert isinstance(unity_size, int), 'for mypy'
917
918 for comp, srcs in compsrcs.items():
919 if comp.language in LANGS_CANT_UNITY:
920 sources += srcs
921 continue
922 for i in range((len(srcs) + unity_size - 1) // unity_size):
923 _src = self.get_unity_source_file(extobj.target,
924 comp.get_default_suffix(), i)
925 sources.append(_src)
926
927 for osrc in sources:
928 compiler = get_compiler_for_source(extobj.target.compilers.values(), osrc)
929 objname = self.object_filename_from_source(extobj.target, compiler, osrc, targetdir)
930 result.append(objname)
931
932 return result
933
934 def get_pch_include_args(self, compiler: 'Compiler', target: build.BuildTarget) -> T.List[str]:
935 args: T.List[str] = []
936 pchpath = self.get_target_private_dir(target)
937 includeargs = compiler.get_include_args(pchpath, False)
938 p = target.pch.get(compiler.get_language())
939 if p:
940 args += compiler.get_pch_use_args(pchpath, p[0])
941 return includeargs + args
942
943 def get_msvc_pch_objname(self, lang: str, pch: T.Tuple[str, T.Optional[str]]) -> str:
944 if pch[1] is None:
945 # Same name as in create_msvc_pch_implementation() below.
946 return f'meson_pch-{lang}.obj'
947 return os.path.splitext(pch[1])[0] + '.obj'
948
949 def create_msvc_pch_implementation(self, target: build.BuildTarget, lang: str, pch_header: str) -> str:
950 # We have to include the language in the file name, otherwise
951 # pch.c and pch.cpp will both end up as pch.obj in VS backends.
952 impl_name = f'meson_pch-{lang}.{lang}'
953 pch_rel_to_build = os.path.join(self.get_target_private_dir(target), impl_name)
954 # Make sure to prepend the build dir, since the working directory is
955 # not defined. Otherwise, we might create the file in the wrong path.
956 pch_file = os.path.join(self.build_dir, pch_rel_to_build)
957 os.makedirs(os.path.dirname(pch_file), exist_ok=True)
958
959 content = f'#include "{os.path.basename(pch_header)}"'
960 pch_file_tmp = pch_file + '.tmp'
961 with open(pch_file_tmp, 'w', encoding='utf-8') as f:
962 f.write(content)
963 mesonlib.replace_if_different(pch_file, pch_file_tmp)
964 return pch_rel_to_build
965
966 def target_uses_pch(self, target: build.BuildTarget) -> bool:
967 try:
968 return T.cast('bool', self.get_target_option(target, 'b_pch'))
969 except (KeyError, AttributeError):
970 return False
971
972 @staticmethod
973 def escape_extra_args(args: T.List[str]) -> T.List[str]:
974 # all backslashes in defines are doubly-escaped
975 extra_args: T.List[str] = []
976 for arg in args:
977 if arg.startswith(('-D', '/D')):
978 arg = arg.replace('\\', '\\\\')
979 extra_args.append(arg)
980
981 return extra_args
982
983 def get_no_stdlib_args(self, target: 'build.BuildTarget', compiler: 'Compiler') -> T.List[str]:
984 if compiler.language in self.build.stdlibs[target.for_machine]:
985 return compiler.get_no_stdinc_args()
986 return []
987
988 def generate_basic_compiler_args(self, target: build.BuildTarget, compiler: 'Compiler') -> 'CompilerArgs':
989 # Create an empty commands list, and start adding arguments from
990 # various sources in the order in which they must override each other
991 # starting from hard-coded defaults followed by build options and so on.
992 commands = compiler.compiler_args()
993
994 # First, the trivial ones that are impossible to override.
995 #
996 # Add -nostdinc/-nostdinc++ if needed; can't be overridden
997 commands += self.get_no_stdlib_args(target, compiler)
998 # Add things like /NOLOGO or -pipe; usually can't be overridden
999 commands += compiler.get_always_args()
1000 # warning_level is a string, but mypy can't determine that
1001 commands += compiler.get_warn_args(T.cast('str', self.get_target_option(target, 'warning_level')))
1002 # Add -Werror if werror=true is set in the build options set on the
1003 # command-line or default_options inside project(). This only sets the
1004 # action to be done for warnings if/when they are emitted, so it's ok
1005 # to set it after or get_warn_args().
1006 if self.get_target_option(target, 'werror'):
1007 commands += compiler.get_werror_args()
1008 # Add compile args for c_* or cpp_* build options set on the
1009 # command-line or default_options inside project().
1010 commands += compiler.get_option_compile_args(target, target.subproject)
1011 commands += compiler.get_option_std_args(target, target.subproject)
1012
1013 optimization = self.get_target_option(target, 'optimization')
1014 assert isinstance(optimization, str), 'for mypy'
1015 commands += compiler.get_optimization_args(optimization)
1016
1017 debug = self.get_target_option(target, 'debug')
1018 assert isinstance(debug, bool), 'for mypy'
1019 commands += compiler.get_debug_args(debug)
1020
1021 # Add compile args added using add_project_arguments()
1022 commands += self.build.get_project_args(compiler, target)
1023 # Add compile args added using add_global_arguments()
1024 # These override per-project arguments
1025 commands += self.build.get_global_args(compiler, target)
1026 # Compile args added from the env: CFLAGS/CXXFLAGS, etc, or the cross
1027 # file. We want these to override all the defaults, but not the
1028 # per-target compile args.
1029 commands += self.environment.coredata.get_external_args(target.for_machine, compiler.get_language())
1030 # Using both /Z7 or /ZI and /Zi at the same times produces a compiler warning.
1031 # We do not add /Z7 or /ZI by default. If it is being used it is because the user has explicitly enabled it.
1032 # /Zi needs to be removed in that case to avoid cl's warning to that effect (D9025 : overriding '/Zi' with '/ZI')
1033 if ('/Zi' in commands) and (('/ZI' in commands) or ('/Z7' in commands)):
1034 commands.remove('/Zi')
1035 # Always set -fPIC for shared libraries
1036 if isinstance(target, build.SharedLibrary):
1037 commands += compiler.get_pic_args()
1038 # Set -fPIC for static libraries by default unless explicitly disabled
1039 if isinstance(target, build.StaticLibrary) and target.pic:
1040 commands += compiler.get_pic_args()
1041 elif isinstance(target, (build.StaticLibrary, build.Executable)) and target.pie:
1042 commands += compiler.get_pie_args()
1043 # Add compile args needed to find external dependencies. Link args are
1044 # added while generating the link command.
1045 # NOTE: We must preserve the order in which external deps are
1046 # specified, so we reverse the list before iterating over it.
1047 for dep in reversed(target.get_external_deps()):
1048 if not dep.found():
1049 continue
1050
1051 if compiler.language == 'vala':
1052 if dep.type_name == 'pkgconfig':
1053 assert isinstance(dep, dependencies.ExternalDependency)
1054 commands += ['--pkg', dep.name]
1055 elif isinstance(dep, dependencies.ExternalLibrary):
1056 commands += dep.get_link_args('vala')
1057 else:
1058 commands += compiler.get_dependency_compile_args(dep)
1059 # Qt needs -fPIC for executables
1060 # XXX: We should move to -fPIC for all executables
1061 if isinstance(target, build.Executable):
1062 commands += dep.get_exe_args(compiler)
1063 # For 'automagic' deps: Boost and GTest. Also dependency('threads').
1064 # pkg-config puts the thread flags itself via `Cflags:`
1065 if compiler.language == 'vala':
1066 # Vala wants to know the minimum glib version
1067 for dep in target.added_deps:
1068 if dep.name == 'glib-2.0':
1069 if dep.type_name == 'pkgconfig':
1070 assert isinstance(dep, dependencies.ExternalDependency)
1071 if dep.version_reqs is not None:
1072 for req in dep.version_reqs:
1073 if req.startswith(('>=', '==')):
1074 commands += ['--target-glib', req[2:].strip()]
1075 break
1076 elif isinstance(dep, dependencies.InternalDependency) and dep.version is not None:
1077 glib_version = dep.version.split('.')
1078 if len(glib_version) != 3:
1079 mlog.warning(f'GLib version has unexpected format: {dep.version}')
1080 break
1081 try:
1082 # If GLib version is a development version, downgrade
1083 # --target-glib to the previous version, as valac will
1084 # complain about non-even minor versions
1085 glib_version[1] = str((int(glib_version[1]) // 2) * 2)
1086 except ValueError:
1087 mlog.warning(f'GLib version has unexpected format: {dep.version}')
1088 break
1089 commands += ['--target-glib', f'{glib_version[0]}.{glib_version[1]}']
1090
1091 # Fortran requires extra include directives.
1092 if compiler.language == 'fortran':
1093 for lt in chain(target.link_targets, target.link_whole_targets):
1094 priv_dir = self.get_target_private_dir(lt)
1095 commands += compiler.get_include_args(priv_dir, False)
1096 return commands
1097
1098 def build_target_link_arguments(self, compiler: Compiler, deps: T.Iterable[build.BuildTargetTypes]) -> T.List[str]:
1099 args: T.List[str] = []
1100 for d in deps:
1101 if not d.is_linkable_target():
1102 raise RuntimeError(f'Tried to link with a non-library target "{d.get_basename()}".')
1103 arg = self.get_target_filename_for_linking(d)
1104 if not arg:
1105 continue
1106 if compiler.get_language() == 'd':
1107 arg = '-Wl,' + arg
1108 elif compiler.get_linker_id() == 'nvlink' and arg.endswith('.a'):
1109 # We need to pass static archives without -Xlinker= to nvcc,
1110 # since they may contain relocatable device code. When passing
1111 # the static archive to nvcc with -Xlinker=, we bypass the
1112 # frontend which means we lose the opportunity to perform device
1113 # linking. We only need to do this for static archives, since
1114 # nvcc doesn't support device linking with dynamic libraries:
1115 # https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#libraries
1116 pass
1117 else:
1118 arg = compiler.get_linker_lib_prefix() + arg
1119 args.append(arg)
1120 return args
1121
1122 def get_mingw_extra_paths(self, target: build.BuildTarget) -> T.List[str]:
1123 paths: OrderedSet[str] = OrderedSet()
1124 # The cross bindir
1125 root = self.environment.properties[target.for_machine].get_root()
1126 if root:
1127 paths.add(os.path.join(root, 'bin'))
1128 # The toolchain bindir
1129 sys_root = self.environment.properties[target.for_machine].get_sys_root()
1130 if sys_root:
1131 paths.add(os.path.join(sys_root, 'bin'))
1132 # Get program and library dirs from all target compilers
1133 if isinstance(target, build.BuildTarget):
1134 for cc in target.compilers.values():
1135 paths.update(cc.get_program_dirs())
1136 paths.update(cc.get_library_dirs())
1137 return list(paths)
1138
1139 @staticmethod
1140 @lru_cache(maxsize=None)
1141 def search_dll_path(link_arg: str) -> T.Optional[str]:
1142 if link_arg.startswith(('-l', '-L')):
1143 link_arg = link_arg[2:]
1144
1145 p = Path(link_arg)
1146 if not p.is_absolute():
1147 return None
1148
1149 try:
1150 p = p.resolve(strict=True)
1151 except FileNotFoundError:
1152 return None
1153
1154 for f in p.parent.glob('*.dll'):
1155 # path contains dlls
1156 return str(p.parent)
1157
1158 if p.is_file():
1159 p = p.parent
1160 # Heuristic: replace *last* occurrence of '/lib'
1161 binpath = Path('/bin'.join(p.as_posix().rsplit('/lib', maxsplit=1)))
1162 for _ in binpath.glob('*.dll'):
1163 return str(binpath)
1164
1165 return None
1166
1167 @classmethod
1168 @lru_cache(maxsize=None)
1169 def extract_dll_paths(cls, target: build.BuildTarget) -> T.Set[str]:
1170 """Find paths to all DLLs needed for a given target, since
1171 we link against import libs, and we don't know the actual
1172 path of the DLLs.
1173
1174 1. If there are DLLs in the same directory than the .lib dir, use it
1175 2. If there is a sibbling directory named 'bin' with DLLs in it, use it
1176 """
1177 results = set()
1178 for dep in target.external_deps:
1179
1180 if dep.type_name == 'pkgconfig':
1181 # If by chance pkg-config knows the bin dir...
1182 bindir = dep.get_variable(pkgconfig='bindir', default_value='')
1183 if bindir:
1184 results.add(bindir)
1185 continue
1186
1187 results.update(filter(None, map(cls.search_dll_path, dep.link_args))) # pylint: disable=bad-builtin
1188
1189 for i in chain(target.link_targets, target.link_whole_targets):
1190 if isinstance(i, build.BuildTarget):
1191 results.update(cls.extract_dll_paths(i))
1192
1193 return results
1194
1195 def determine_windows_extra_paths(
1196 self, target: T.Union[build.BuildTargetTypes, programs.Program, mesonlib.File, str],
1197 extra_bdeps: T.Iterable[build.BuildTargetTypes]) -> T.List[str]:
1198 """On Windows there is no such thing as an rpath.
1199
1200 We must determine all locations of DLLs that this exe
1201 links to and return them so they can be used in unit
1202 tests.
1203 """
1204 prospectives: T.Set[build.BuildTargetTypes] = set()
1205 internal_deps: T.Set[str] = set()
1206 external_deps: T.Set[str] = set()
1207
1208 if isinstance(target, build.BuildTarget):
1209 prospectives.update(target.get_all_link_deps())
1210
1211 for bdep in extra_bdeps:
1212 prospectives.add(bdep)
1213 if isinstance(bdep, build.BuildTarget):
1214 prospectives.update(bdep.get_all_link_deps())
1215
1216 # Internal deps
1217 for ld in prospectives:
1218 dirseg = os.path.join(self.environment.get_build_dir(), self.get_target_dir(ld))
1219 internal_deps.add(dirseg)
1220
1221 if isinstance(target, build.BuildTarget):
1222 # External deps
1223 external_deps.update(self.extract_dll_paths(target))
1224
1225 if not self.environment.machines.matches_build_machine(target.for_machine):
1226 external_deps.update(self.get_mingw_extra_paths(target))
1227
1228 return list(internal_deps) + list(external_deps)
1229
1230 def write_benchmark_file(self, datafile: T.BinaryIO) -> None:
1231 self.write_test_serialisation(self.build.get_benchmarks(), datafile)
1232
1233 def write_test_file(self, datafile: T.BinaryIO) -> None:
1234 self.write_test_serialisation(self.build.get_tests(), datafile)
1235
1236 def create_test_serialisation(self, tests: T.List['Test']) -> T.List[TestSerialisation]:
1237 arr: T.List[TestSerialisation] = []
1238 for t in sorted(tests, key=lambda tst: -1 * tst.priority):
1239 exe = t.get_exe()
1240 if isinstance(exe, build.LocalProgram):
1241 exe = exe.program
1242 if isinstance(exe, (build.BuildTarget, build.CustomTarget, build.CustomTargetIndex)):
1243 cmd = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(exe))]
1244 else:
1245 cmd = exe.get_command()
1246
1247 if isinstance(exe, (build.BuildTarget, programs.ExternalProgram)):
1248 test_for_machine = exe.for_machine
1249 else:
1250 # E.g. an external verifier or simulator program run on a generated executable.
1251 # Can always be run without a wrapper.
1252 test_for_machine = MachineChoice.BUILD
1253
1254 # we allow passing compiled executables to tests, which may be cross built.
1255 # We need to consider these as well when considering whether the target is cross or not.
1256 for a in t.cmd_args:
1257 if isinstance(a, build.LocalProgram):
1258 a = a.program
1259 if isinstance(a, (build.BuildTarget, programs.ExternalProgram)):
1260 if a.for_machine is MachineChoice.HOST:
1261 test_for_machine = MachineChoice.HOST
1262 break
1263
1264 is_cross = self.environment.is_cross_build(test_for_machine)
1265 exe_wrapper = self.environment.get_exe_wrapper()
1266 machine = self.environment.machines[exe.for_machine]
1267 if machine.is_windows() or machine.is_cygwin():
1268 extra_bdeps: T.List[build.BuildTargetTypes] = []
1269 if isinstance(exe, build.CustomTarget):
1270 extra_bdeps = list(exe.get_transitive_build_target_deps())
1271 extra_bdeps.extend(t.depends)
1272 extra_bdeps.extend(a for a in t.cmd_args if isinstance(a, build.BuildTarget))
1273 extra_paths = self.determine_windows_extra_paths(exe, extra_bdeps)
1274 else:
1275 extra_paths = []
1276
1277 cmd_args: T.List[str] = []
1278 depends: T.Set[build.BuildTargetTypes] = set(t.depends)
1279 if isinstance(exe, (build.BuildTarget, build.CustomTarget, build.CustomTargetIndex)):
1280 depends.add(exe)
1281 for a in t.cmd_args:
1282 if isinstance(a, build.LocalProgram):
1283 a = a.program
1284 if isinstance(a, (build.BuildTarget, build.CustomTarget, build.CustomTargetIndex)):
1285 depends.add(a)
1286
1287 if isinstance(a, mesonlib.File):
1288 a = os.path.join(self.environment.get_build_dir(), a.rel_to_builddir(self.build_to_src))
1289 cmd_args.append(a)
1290 elif isinstance(a, str):
1291 cmd_args.append(a)
1292 elif isinstance(a, (build.Target, build.CustomTargetIndex)):
1293 cmd_args.extend(self.construct_target_rel_paths(a, t.workdir))
1294 elif isinstance(a, programs.ExternalProgram):
1295 cmd_args.extend(a.get_command())
1296 else:
1297 raise MesonException('Bad object in test command.')
1298
1299 # set LD_LIBRARY_PATH for
1300 # a) dependencies, as relying on rpath is not very safe:
1301 # https://github.com/mesonbuild/meson/pull/11119
1302 # b) depends and targets passed via args.
1303 t_env = copy.deepcopy(t.env)
1304 if not machine.is_windows() and not machine.is_cygwin():
1305 ld_lib_path_libs: T.Set[build.SharedLibrary] = set()
1306 for d in depends:
1307 if isinstance(d, build.BuildTarget):
1308 for l in d.get_all_link_deps():
1309 if isinstance(l, build.SharedLibrary):
1310 ld_lib_path_libs.add(l)
1311
1312 env_build_dir = self.environment.get_build_dir()
1313 ld_lib_path: T.Set[str] = set(os.path.join(env_build_dir, l.get_builddir()) for l in ld_lib_path_libs)
1314
1315 if ld_lib_path:
1316 t_env.prepend('LD_LIBRARY_PATH', list(ld_lib_path), ':')
1317 if machine.is_darwin():
1318 t_env.prepend('DYLD_LIBRARY_PATH', list(ld_lib_path), ':')
1319
1320 ts = TestSerialisation(t.get_name(), t.project_name, t.suite, cmd, is_cross,
1321 exe_wrapper, self.environment.need_exe_wrapper(),
1322 t.is_parallel, cmd_args, t_env,
1323 t.expected_fail, t.expected_exitcode, t.timeout, t.workdir,
1324 extra_paths, t.protocol, t.priority,
1325 isinstance(exe, (build.Target, build.CustomTargetIndex)),
1326 isinstance(exe, build.Executable),
1327 [x.get_id() for x in depends],
1328 self.environment.coredata.version,
1329 t.verbose)
1330 arr.append(ts)
1331 return arr
1332
1333 def write_test_serialisation(self, tests: T.List['Test'], datafile: T.BinaryIO) -> None:
1334 pickle.dump(self.create_test_serialisation(tests), datafile)
1335
1336 def construct_target_rel_paths(self, t: build.AnyTargetType, workdir: T.Optional[str]) -> T.List[str]:
1337 target_dir = self.get_target_dir(t)
1338 # ensure that test executables can be run when passed as arguments
1339 if isinstance(t, build.Executable) and workdir is None:
1340 target_dir = target_dir or '.'
1341
1342 if isinstance(t, build.BuildTarget):
1343 outputs = [t.get_filename()]
1344 else:
1345 assert isinstance(t, (build.CustomTarget, build.CustomTargetIndex))
1346 outputs = t.get_outputs()
1347
1348 outputs = [os.path.join(target_dir, x) for x in outputs]
1349 if workdir is not None:
1350 assert os.path.isabs(workdir)
1351 outputs = [os.path.join(self.environment.get_build_dir(), x) for x in outputs]
1352 outputs = [os.path.relpath(x, workdir) for x in outputs]
1353 return outputs
1354
1355 def generate_depmf_install(self, d: InstallData) -> None:
1356 depmf_path = self.build.dep_manifest_name
1357 if depmf_path is None:
1358 option_dir = self.environment.coredata.optstore.get_value_for(OptionKey('licensedir'))
1359 assert isinstance(option_dir, str), 'for mypy'
1360 if option_dir:
1361 depmf_path = os.path.join(option_dir, 'depmf.json')
1362 else:
1363 return
1364 ifilename = os.path.join(self.environment.get_build_dir(), 'depmf.json')
1365 ofilename = os.path.join(self.environment.get_prefix(), depmf_path)
1366 odirname = os.path.join(self.environment.get_prefix(), os.path.dirname(depmf_path))
1367 out_name = os.path.join('{prefix}', depmf_path)
1368 out_dir = os.path.join('{prefix}', os.path.dirname(depmf_path))
1369 mfobj = {'type': 'dependency manifest', 'version': '1.0',
1370 'projects': {k: v.to_json() for k, v in self.build.dep_manifest.items()}}
1371 with open(ifilename, 'w', encoding='utf-8') as f:
1372 f.write(json.dumps(mfobj))
1373 # Copy file from, to, and with mode unchanged
1374 d.data.append(InstallDataBase(ifilename, ofilename, out_name, None, '',
1375 tag='devel', data_type='depmf'))
1376 for m in self.build.dep_manifest.values():
1377 for ifilename, name in m.license_mapping():
1378 ofilename = os.path.join(odirname, name)
1379 out_name = os.path.join(out_dir, name)
1380 d.data.append(InstallDataBase(ifilename, ofilename, out_name, None,
1381 m.subproject, tag='devel', data_type='depmf'))
1382
1383 def get_regen_filelist(self) -> T.List[str]:
1384 '''List of all files whose alteration means that the build
1385 definition needs to be regenerated.'''
1386 deps = OrderedSet([str(Path(self.build_to_src) / df)
1387 for df in self.build.def_files])
1388 if self.environment.is_cross_build():
1389 deps.update(self.environment.coredata.cross_files)
1390 deps.update(self.environment.coredata.config_files)
1391 deps.add('meson-private/coredata.dat')
1392 self.check_clock_skew(deps)
1393 return list(deps)
1394
1395 def generate_regen_info(self) -> None:
1396 deps = self.get_regen_filelist()
1397 regeninfo = RegenInfo(self.environment.get_source_dir(),
1398 self.environment.get_build_dir(),
1399 deps)
1400 filename = os.path.join(self.environment.get_scratch_dir(),
1401 'regeninfo.dump')
1402 with open(filename, 'wb') as f:
1403 pickle.dump(regeninfo, f)
1404
1405 def check_clock_skew(self, file_list: T.Iterable[str]) -> None:
1406 # If a file that leads to reconfiguration has a time
1407 # stamp in the future, it will trigger an eternal reconfigure
1408 # loop.
1409 import time
1410 now = time.time()
1411 for f in file_list:
1412 absf = os.path.join(self.environment.get_build_dir(), f)
1413 ftime = os.path.getmtime(absf)
1414 delta = ftime - now
1415 # On Windows disk time stamps sometimes point
1416 # to the future by a minuscule amount, less than
1417 # 0.001 seconds. I don't know why.
1418 if delta > 0.001:
1419 raise MesonException(f'Clock skew detected. File {absf} has a time stamp {delta:.4f}s in the future.')
1420
1421 def build_target_to_cmd_array(self, bt: T.Union[build.BuildTargetTypes, programs.Program]) -> T.List[str]:
1422 if isinstance(bt, build.LocalProgram):
1423 bt = bt.program
1424 if isinstance(bt, (build.Target, build.CustomTargetIndex)):
1425 arr = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(bt))]
1426 else:
1427 arr = bt.get_command()
1428 return arr
1429
1430 def replace_extra_args(self, args: T.List[str], genlist: 'build.GeneratedList') -> T.List[str]:
1431 final_args: T.List[str] = []
1432 for a in args:
1433 if a == '@EXTRA_ARGS@':
1434 final_args += genlist.get_extra_args()
1435 else:
1436 final_args.append(a)
1437 return final_args
1438
1439 def replace_outputs(self, args: T.List[str], private_dir: str, output_list: T.List[str]) -> T.List[str]:
1440 newargs: T.List[str] = []
1441 regex = re.compile(r'@OUTPUT(\d+)@')
1442 for arg in args:
1443 m = regex.search(arg)
1444 while m is not None:
1445 index = int(m.group(1))
1446 src = f'@OUTPUT{index}@'
1447 arg = arg.replace(src, os.path.join(private_dir, output_list[index]))
1448 m = regex.search(arg)
1449 newargs.append(arg)
1450 return newargs
1451
1452 def get_build_by_default_targets(self) -> dict[str, build.Target]:
1453 return {k: v for k, v in self.build.targets.items() if v.build_by_default}
1454
1455 def get_testlike_targets(self, benchmark: bool = False) -> T.Iterable[T.Union[build.BuildTarget, build.CustomTarget]]:
1456 targets = self.build.get_benchmarks() if benchmark else self.build.get_tests()
1457 for t in targets:
1458 exe = t.exe
1459 if isinstance(exe, build.CustomTargetIndex):
1460 yield exe.target
1461 elif isinstance(exe, (build.CustomTarget, build.BuildTarget)):
1462 yield exe
1463 for arg in t.cmd_args:
1464 if isinstance(arg, build.CustomTargetIndex):
1465 yield arg.target
1466 elif isinstance(arg, (build.CustomTarget, build.BuildTarget)):
1467 yield arg
1468 for dep in t.depends:
1469 assert isinstance(dep, (build.CustomTarget, build.BuildTarget, build.CustomTargetIndex))
1470 if isinstance(dep, build.CustomTargetIndex):
1471 yield dep.target
1472 else:
1473 yield dep
1474
1475 @lru_cache(maxsize=None)
1476 def get_custom_target_provided_by_generated_source(self, generated_source: build.CustomTarget) -> 'ImmutableListProtocol[str]':
1477 libs: T.List[str] = []
1478 for f in generated_source.get_outputs():
1479 if compilers.is_library(f):
1480 libs.append(os.path.join(self.get_target_dir(generated_source), f))
1481 return libs
1482
1483 @lru_cache(maxsize=None)
1484 def get_custom_target_provided_libraries(self, target: T.Union[build.BuildTarget, build.CustomTarget]) -> 'ImmutableListProtocol[str]':
1485 libs: T.List[str] = []
1486 for t in target.get_generated_sources():
1487 if not isinstance(t, build.CustomTarget):
1488 continue
1489 libs.extend(self.get_custom_target_provided_by_generated_source(t))
1490 return libs
1491
1492 def get_custom_target_sources(self, target: build.RunTarget | build.CustomTarget) -> T.List[str]:
1493 '''
1494 Custom target sources can be of various object types; strings, File,
1495 BuildTarget, even other CustomTargets.
1496 Returns the path to them relative to the build root directory.
1497 '''
1498 srcs: T.List[str] = []
1499 for i in target.get_sources():
1500 if isinstance(i, build.LocalProgram):
1501 i = i.program
1502 if isinstance(i, str):
1503 fname = [os.path.join(self.build_to_src, target.subdir, i)]
1504 elif isinstance(i, build.BuildTarget):
1505 fname = [self.get_target_filename(i)]
1506 elif isinstance(i, (build.CustomTarget, build.CustomTargetIndex)):
1507 fname = [os.path.join(self.get_custom_target_output_dir(i), p) for p in i.get_outputs()]
1508 elif isinstance(i, build.GeneratedList):
1509 assert not isinstance(target, build.RunTarget)
1510 fname = [os.path.join(self.get_target_private_dir(target), p) for p in i.get_outputs()]
1511 elif isinstance(i, build.ExtractedObjects):
1512 fname = self.determine_ext_objs(i)
1513 elif isinstance(i, programs.Program):
1514 assert i.found(), "This shouldn't be possible"
1515 fname = [mesonlib.unwrap(i.get_path())]
1516 else:
1517 fname = [i.rel_to_builddir(self.build_to_src)]
1518 if target.absolute_paths:
1519 fname = [os.path.join(self.environment.get_build_dir(), f) for f in fname]
1520 srcs += fname
1521 return srcs
1522
1523 def get_paths_for_dep_outputs(self, target: build.Target, dep_targets: T.Iterable[build.Target | build.GeneratedList | build.CustomTargetIndex | programs.Program]) -> T.List[str]:
1524 """Return a list of strings with the paths to all the outputs of all targets in
1525 dep_targets."""
1526 deps = []
1527 for i in dep_targets:
1528 if isinstance(i, build.LocalProgram):
1529 i = i.program
1530 if isinstance(i, programs.Program):
1531 continue
1532 for output in i.get_outputs():
1533 if isinstance(i, build.GeneratedList):
1534 assert isinstance(target, (build.BuildTarget, build.CustomTarget, build.CustomTargetIndex))
1535 deps.append(os.path.join(self.get_target_private_dir(target), output))
1536 else:
1537 deps.append(os.path.join(self.get_target_dir(i), output))
1538 return deps
1539
1540 def get_target_depend_files(self, target: T.Union[build.Target, build.GeneratedList], absolute_paths: bool = False) -> T.List[str]:
1541 deps: T.List[str] = []
1542 for i in target.depend_files:
1543 if absolute_paths:
1544 deps.append(i.absolute_path(self.environment.get_source_dir(),
1545 self.environment.get_build_dir()))
1546 else:
1547 deps.append(i.rel_to_builddir(self.build_to_src))
1548 return deps
1549
1550 def get_custom_target_output_dir(self, target: build.AnyTargetType) -> str:
1551 # The XCode backend is special. A target foo/bar does
1552 # not go to ${BUILDDIR}/foo/bar but instead to
1553 # ${BUILDDIR}/${BUILDTYPE}/foo/bar.
1554 # Currently we set the include dir to be the former,
1555 # and not the latter. Thus we need this extra customisation
1556 # point. If in the future we make include dirs et al match
1557 # ${BUILDDIR}/${BUILDTYPE} instead, this becomes unnecessary.
1558 return self.get_target_dir(target)
1559
1560 @lru_cache(maxsize=None)
1561 def get_normpath_target(self, source: str) -> str:
1562 return os.path.normpath(source)
1563
1564 def get_custom_target_dirs(self, target: build.BuildTarget | build.CustomTarget, compiler: 'Compiler', *,
1565 absolute_path: bool = False) -> T.List[str]:
1566 custom_target_include_dirs: T.List[str] = []
1567 for i in target.get_generated_sources():
1568 # Generator output goes into the target private dir which is
1569 # already in the include paths list. Only custom targets have their
1570 # own target build dir.
1571 if not isinstance(i, (build.CustomTarget, build.CustomTargetIndex)):
1572 continue
1573 idir = self.get_normpath_target(self.get_custom_target_output_dir(i))
1574 if not idir:
1575 idir = '.'
1576 if absolute_path:
1577 idir = os.path.join(self.environment.get_build_dir(), idir)
1578 if idir not in custom_target_include_dirs:
1579 custom_target_include_dirs.append(idir)
1580 return custom_target_include_dirs
1581
1582 def get_custom_target_dir_include_args(
1583 self, target: build.BuildTarget | build.CustomTarget, compiler: 'Compiler', *,
1584 absolute_path: bool = False) -> T.List[str]:
1585 incs: T.List[str] = []
1586 for i in self.get_custom_target_dirs(target, compiler, absolute_path=absolute_path):
1587 incs += compiler.get_include_args(i, False)
1588 return incs
1589
1590 def eval_custom_target_command(
1591 self, target: build.RunTarget | build.CustomTarget, absolute_outputs: bool = False) -> \
1592 T.Tuple[T.List[str], T.List[str], T.List[str | programs.Program]]:
1593 # We want the outputs to be absolute only when using the VS backend
1594 # XXX: Maybe allow the vs backend to use relative paths too?
1595 source_root = self.build_to_src
1596 build_root = '.'
1597 outdir = self.get_custom_target_output_dir(target)
1598 if absolute_outputs:
1599 source_root = self.environment.get_source_dir()
1600 build_root = self.environment.get_build_dir()
1601 outdir = os.path.join(self.environment.get_build_dir(), outdir)
1602 outputs = [os.path.join(outdir, i) for i in target.get_outputs()]
1603 inputs = self.get_custom_target_sources(target)
1604 # Evaluate the command list
1605 cmd: T.List[str | programs.Program] = []
1606 for i in target.command:
1607 if isinstance(i, build.BuildTarget):
1608 cmd += self.build_target_to_cmd_array(i)
1609 continue
1610 elif isinstance(i, build.CustomTarget):
1611 # GIR scanner will attempt to execute this binary but
1612 # it assumes that it is in path, so always give it a full path.
1613 tmp = i.get_outputs()[0]
1614 i = os.path.join(self.get_custom_target_output_dir(i), tmp)
1615 elif isinstance(i, mesonlib.File):
1616 i = i.rel_to_builddir(self.build_to_src)
1617 if target.absolute_paths or absolute_outputs:
1618 i = os.path.join(self.environment.get_build_dir(), i)
1619 # FIXME: str types are blindly added ignoring 'target.absolute_paths'
1620 # because we can't know if they refer to a file or just a string
1621 elif isinstance(i, str):
1622 if '@SOURCE_ROOT@' in i:
1623 i = i.replace('@SOURCE_ROOT@', source_root)
1624 if '@BUILD_ROOT@' in i:
1625 i = i.replace('@BUILD_ROOT@', build_root)
1626 if '@CURRENT_SOURCE_DIR@' in i:
1627 i = i.replace('@CURRENT_SOURCE_DIR@', os.path.join(source_root, target.get_subdir()))
1628 if '@DEPFILE@' in i:
1629 assert not isinstance(target, build.RunTarget)
1630 if target.depfile is None:
1631 msg = f'Custom target {target.name!r} has @DEPFILE@ but no depfile ' \
1632 'keyword argument.'
1633 raise MesonException(msg)
1634 dfilename = os.path.join(outdir, target.depfile)
1635 i = i.replace('@DEPFILE@', dfilename)
1636 if '@PRIVATE_DIR@' in i:
1637 assert not isinstance(target, build.RunTarget)
1638 pdir = self.get_target_private_dir_abs(target)
1639 os.makedirs(pdir, exist_ok=True)
1640 if not target.absolute_paths:
1641 pdir = self.get_target_private_dir(target)
1642 i = i.replace('@PRIVATE_DIR@', pdir)
1643 elif isinstance(i, programs.Program):
1644 # Let it pass and be extended elsewhere
1645 pass
1646 else:
1647 raise RuntimeError(f'Argument {i} is of unknown type {type(i)}')
1648 cmd.append(i)
1649 # Substitute the rest of the template strings
1650 values = mesonlib.get_filenames_templates_dict(inputs, outputs)
1651 cmd = mesonlib.substitute_values(cmd, values)
1652 # This should not be necessary but removing it breaks
1653 # building GStreamer on Windows. The underlying issue
1654 # is problems with quoting backslashes on Windows
1655 # which is the seventh circle of hell. The downside is
1656 # that this breaks custom targets whose command lines
1657 # have backslashes. If you try to fix this be sure to
1658 # check that it does not break GST.
1659 #
1660 # The bug causes file paths such as c:\foo to get escaped
1661 # into c:\\foo.
1662 #
1663 # Unfortunately we have not been able to come up with an
1664 # isolated test case for this so unless you manage to come up
1665 # with one, the only way is to test the building with Gst's
1666 # setup. Note this in your MR or ping us and we will get it
1667 # fixed.
1668 #
1669 # https://github.com/mesonbuild/meson/pull/737
1670 cmd = [i.replace('\\', '/') if isinstance(i, str) else i for i in cmd]
1671 return inputs, outputs, cmd
1672
1673 def transform_link_args(self, target: build.BuildTarget, args: list[str]) -> list[str]:
1674 resolved_args = []
1675 for i in args:
1676 if '@PRIVATE_DIR@' in i:
1677 pdir = self.get_target_private_dir(target)
1678 i = i.replace('@PRIVATE_DIR@', pdir)
1679 resolved_args.append(i)
1680 return resolved_args
1681
1682 def get_introspect_command(self) -> str:
1683 return ' '.join(shlex.quote(x) for x in self.environment.get_build_command() + ['introspect'])
1684
1685 def get_run_target_env(self, target: build.RunTarget) -> mesonlib.EnvironmentVariables:
1686 env = target.env if target.env else mesonlib.EnvironmentVariables()
1687 if target.default_env:
1688 env.set('MESON_SOURCE_ROOT', [self.environment.get_source_dir()])
1689 env.set('MESON_BUILD_ROOT', [self.environment.get_build_dir()])
1690 env.set('MESON_SUBDIR', [target.get_subdir()])
1691 env.set('MESONINTROSPECT', [self.get_introspect_command()])
1692 return env
1693
1694 def run_postconf_scripts(self) -> None:
1695 from ..scripts.meson_exe import run_exe
1696 env = {'MESON_SOURCE_ROOT': self.environment.get_source_dir(),
1697 'MESON_BUILD_ROOT': self.environment.get_build_dir(),
1698 'MESONINTROSPECT': self.get_introspect_command(),
1699 }
1700
1701 for s in self.build.postconf_scripts:
1702 name = ' '.join(s.cmd_args)
1703 mlog.log(f'Running postconf script {name!r}')
1704 rc = run_exe(s, env)
1705 if rc != 0:
1706 raise MesonException(f'Postconf script \'{name}\' failed with exit code {rc}.')
1707
1708 def create_install_data(self) -> InstallData:
1709 strip_bin = self.environment.lookup_binary_entry(MachineChoice.HOST, 'strip')
1710 if strip_bin is None:
1711 if self.environment.is_cross_build():
1712 mlog.warning('Cross file does not specify strip binary, result will not be stripped.')
1713 else:
1714 # TODO go through all candidates, like others
1715 strip_bin = [detect.defaults['strip'][0]]
1716
1717 umask = self.environment.coredata.optstore.get_value_for(OptionKey('install_umask'))
1718 assert isinstance(umask, (str, int)), 'for mypy'
1719
1720 d = InstallData(self.environment.get_source_dir(),
1721 self.environment.get_build_dir(),
1722 self.environment.get_prefix(),
1723 self.environment.get_libdir(),
1724 strip_bin,
1725 umask,
1726 self.environment.get_build_command() + ['introspect'],
1727 self.environment.coredata.version)
1728 self.generate_depmf_install(d)
1729 self.generate_target_install(d)
1730 self.generate_header_install(d)
1731 self.generate_man_install(d)
1732 self.generate_emptydir_install(d)
1733 self.generate_data_install(d)
1734 self.generate_symlink_install(d)
1735 self.generate_custom_install_script(d)
1736 self.generate_subdir_install(d)
1737 return d
1738
1739 def create_install_data_files(self) -> None:
1740 install_data_file = os.path.join(self.environment.get_scratch_dir(), 'install.dat')
1741 with open(install_data_file, 'wb') as ofile:
1742 pickle.dump(self.create_install_data(), ofile)
1743
1744 def guess_install_tag(self, fname: str, outdir: T.Optional[str] = None) -> T.Optional[str]:
1745 prefix = self.environment.get_prefix()
1746 sbindir = Path(prefix, self.environment.get_sbindir())
1747 bindir = Path(prefix, self.environment.get_bindir())
1748 libdir = Path(prefix, self.environment.get_libdir())
1749 incdir = Path(prefix, self.environment.get_includedir())
1750 _ldir = self.environment.coredata.optstore.get_value_for(OptionKey('localedir'))
1751 assert isinstance(_ldir, str), 'for mypy'
1752 localedir = Path(prefix, _ldir)
1753 dest_path = Path(prefix, outdir, Path(fname).name) if outdir else Path(prefix, fname)
1754 if bindir in dest_path.parents or sbindir in dest_path.parents:
1755 return 'runtime'
1756 elif libdir in dest_path.parents:
1757 if dest_path.suffix in {'.a', '.pc'}:
1758 return 'devel'
1759 elif dest_path.suffix in {'.so', '.dll'}:
1760 return 'runtime'
1761 elif incdir in dest_path.parents:
1762 return 'devel'
1763 elif localedir in dest_path.parents:
1764 return 'i18n'
1765 elif 'installed-tests' in dest_path.parts:
1766 return 'tests'
1767 elif 'systemtap' in dest_path.parts:
1768 return 'systemtap'
1769 mlog.debug('Failed to guess install tag for', dest_path)
1770 return None
1771
1772 def generate_target_install(self, d: InstallData) -> None:
1773 for t in self.build.get_targets().values():
1774 if not t.should_install():
1775 continue
1776 # Mypy doesn't understand that AliasTarget and RunTarget always return False above
1777 assert isinstance(t, (build.BuildTarget, build.CustomTarget)), 'for mypy'
1778 outdirs = t.install_dir
1779 install_dir_names = t.install_dir_names()
1780 # Sanity-check the outputs and install_dirs
1781 num_outdirs, num_out = len(outdirs), len(t.get_outputs())
1782 if num_outdirs not in {1, num_out}:
1783 m = 'Target {!r} has {} outputs: {!r}, but {} "install_dir"s were found: {!r}.\n' \
1784 "Pass 'false' for outputs that should not be installed and 'true' for\n" \
1785 'using the default installation directory for an output.'
1786 raise MesonException(m.format(t.name, num_out, t.get_outputs(), num_outdirs, outdirs))
1787 assert len(t.install_tag) == num_out
1788 install_mode = t.get_custom_install_mode() or FileMode()
1789 # because mypy gets confused type narrowing in lists
1790 first_outdir = outdirs[0]
1791 first_outdir_name = install_dir_names[0]
1792
1793 # Install the target output(s)
1794 if isinstance(t, build.BuildTarget):
1795 # In general, stripping static archives is tricky and full of pitfalls.
1796 # Wholesale stripping of static archives with a command such as
1797 #
1798 # strip libfoo.a
1799 #
1800 # is broken, as GNU's strip will remove *every* symbol in a static
1801 # archive. One solution to this nonintuitive behaviour would be
1802 # to only strip local/debug symbols. Unfortunately, strip arguments
1803 # are not specified by POSIX and therefore not portable. GNU's `-g`
1804 # option (i.e. remove debug symbols) is equivalent to Apple's `-S`.
1805 #
1806 # TODO: Create GNUStrip/AppleStrip/etc. hierarchy for more
1807 # fine-grained stripping of static archives.
1808 can_strip = not isinstance(t, build.StaticLibrary)
1809 should_strip = can_strip and self.get_target_option(t, 'strip')
1810 assert isinstance(should_strip, bool), 'for mypy'
1811 # Install primary build output (library/executable/jar, etc)
1812 # Done separately because of strip/aliases/rpath
1813 if first_outdir is not False:
1814 tag = t.install_tag[0] or ('devel' if isinstance(t, build.StaticLibrary) else 'runtime')
1815 mappings = t.get_link_deps_mapping(d.prefix)
1816 i = TargetInstallData(self.get_target_filename(t), first_outdir,
1817 first_outdir_name,
1818 should_strip, mappings, t.rpath_dirs_to_remove,
1819 t.install_rpath, install_mode, t.subproject,
1820 tag=tag, can_strip=can_strip,
1821 system=self.environment.machines[t.for_machine].system)
1822 d.targets.append(i)
1823
1824 for alias, to, tag in t.get_aliases():
1825 alias = os.path.join(first_outdir, alias)
1826 s = InstallSymlinkData(to, alias, first_outdir, t.subproject, tag)
1827 d.symlinks.append(s)
1828
1829 if isinstance(t, (build.SharedLibrary, build.SharedModule, build.Executable)):
1830 # On toolchains/platforms that use an import library for
1831 # linking (separate from the shared library with all the
1832 # code), we need to install that too (dll.a/.lib).
1833 if t.get_import_filename():
1834 if t.has_custom_install_dir:
1835 # If the DLL is installed into a custom directory,
1836 # install the import library into the same place so
1837 # it doesn't go into a surprising place
1838 implib_install_dir = first_outdir
1839 else:
1840 implib_install_dir = self.environment.get_import_lib_dir()
1841 # Install the import library; may not exist for shared modules
1842 i = TargetInstallData(self.get_target_filename_for_linking(t),
1843 implib_install_dir, first_outdir_name,
1844 False, {}, set(), '', install_mode,
1845 t.subproject, optional=isinstance(t, build.SharedModule),
1846 tag='devel',
1847 system=self.environment.machines[t.for_machine].system)
1848 d.targets.append(i)
1849
1850 if not should_strip and t.get_debug_filename():
1851 debug_file = os.path.join(self.get_target_dir(t), t.get_debug_filename())
1852 i = TargetInstallData(debug_file, first_outdir,
1853 first_outdir_name,
1854 False, {}, set(), '',
1855 install_mode, t.subproject,
1856 optional=True, tag='devel',
1857 system=self.environment.machines[t.for_machine].system)
1858 d.targets.append(i)
1859 # Install secondary outputs. Only used for Vala right now.
1860 if num_outdirs > 1:
1861 for output, outdir, outdir_name, tag in zip(t.get_outputs()[1:], outdirs[1:], install_dir_names[1:], t.install_tag[1:]):
1862 # User requested that we not install this output
1863 if outdir is False:
1864 continue
1865 f = os.path.join(self.get_target_dir(t), output)
1866 i = TargetInstallData(f, outdir, outdir_name, False, {}, set(), None,
1867 install_mode, t.subproject,
1868 tag=tag,
1869 system=self.environment.machines[t.for_machine].system)
1870 d.targets.append(i)
1871 elif isinstance(t, build.CustomTarget):
1872 # If only one install_dir is specified, assume that all
1873 # outputs will be installed into it. This is for
1874 # backwards-compatibility and because it makes sense to
1875 # avoid repetition since this is a common use-case.
1876 #
1877 # To selectively install only some outputs, pass `false` as
1878 # the install_dir for the corresponding output by index
1879 #
1880 # XXX: this wouldn't be needed if we just always matches outdirs
1881 # to the length of outputs…
1882 if num_outdirs == 1 and num_out > 1:
1883 if first_outdir is not False:
1884 for output, tag in zip(t.get_outputs(), t.install_tag):
1885 tag = tag or self.guess_install_tag(output, first_outdir)
1886 f = os.path.join(self.get_target_dir(t), output)
1887 i = TargetInstallData(f, first_outdir, first_outdir_name,
1888 False, {}, set(), None, install_mode,
1889 t.subproject, optional=not t.build_by_default,
1890 tag=tag,
1891 system=self.environment.machines[t.for_machine].system)
1892 d.targets.append(i)
1893 else:
1894 for output, outdir, outdir_name, tag in zip(t.get_outputs(), outdirs, install_dir_names, t.install_tag):
1895 # User requested that we not install this output
1896 if outdir is False:
1897 continue
1898 tag = tag or self.guess_install_tag(output, outdir)
1899 f = os.path.join(self.get_target_dir(t), output)
1900 i = TargetInstallData(f, outdir, outdir_name,
1901 False, {}, set(), None, install_mode,
1902 t.subproject, optional=not t.build_by_default,
1903 tag=tag,
1904 system=self.environment.machines[t.for_machine].system)
1905 d.targets.append(i)
1906
1907 def generate_custom_install_script(self, d: InstallData) -> None:
1908 d.install_scripts = self.build.install_scripts
1909 for i in d.install_scripts:
1910 if not i.tag:
1911 name = i.name if isinstance(i, InstallScriptFailure) else ' '.join(i.cmd_args)
1912 mlog.debug('Failed to guess install tag for install script:', name)
1913
1914 def generate_header_install(self, d: InstallData) -> None:
1915 incroot = self.environment.get_includedir()
1916 headers = self.build.get_headers()
1917
1918 srcdir = self.environment.get_source_dir()
1919 builddir = self.environment.get_build_dir()
1920 for h in headers:
1921 outdir = outdir_name = h.get_custom_install_dir()
1922 if outdir is None:
1923 subdir = h.get_install_subdir()
1924 if subdir is None:
1925 outdir = incroot
1926 outdir_name = '{includedir}'
1927 else:
1928 outdir = os.path.join(incroot, subdir)
1929 outdir_name = os.path.join('{includedir}', subdir)
1930
1931 for f in h.get_sources():
1932 abspath = f.absolute_path(srcdir, builddir)
1933 i = InstallDataBase(abspath, outdir, outdir_name, h.get_custom_install_mode(), h.subproject, tag=h.install_tag, follow_symlinks=h.follow_symlinks)
1934 d.headers.append(i)
1935
1936 def generate_man_install(self, d: InstallData) -> None:
1937 manroot = self.environment.get_mandir()
1938 man = self.build.get_man()
1939 for m in man:
1940 for f in m.get_sources():
1941 num = f.split('.')[-1]
1942 subdir = m.get_custom_install_dir()
1943 if subdir is None:
1944 if m.locale:
1945 subdir = os.path.join('{mandir}', m.locale, 'man' + num)
1946 else:
1947 subdir = os.path.join('{mandir}', 'man' + num)
1948 fname = f.fname
1949 if m.locale: # strip locale from file name
1950 fname = fname.replace(f'.{m.locale}', '')
1951 srcabs = f.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())
1952 dstname = os.path.join(subdir, os.path.basename(fname))
1953 dstabs = dstname.replace('{mandir}', manroot)
1954 tag = m.install_tag or 'man'
1955 i = InstallDataBase(srcabs, dstabs, dstname, m.get_custom_install_mode(), m.subproject, tag=tag)
1956 d.man.append(i)
1957
1958 def generate_emptydir_install(self, d: InstallData) -> None:
1959 emptydir: T.List[build.EmptyDir] = self.build.get_emptydir()
1960 for e in emptydir:
1961 tag = e.install_tag or self.guess_install_tag(e.path)
1962 i = InstallEmptyDir(e.path, e.install_mode, e.subproject, tag)
1963 d.emptydir.append(i)
1964
1965 def generate_data_install(self, d: InstallData) -> None:
1966 data = self.build.get_data()
1967 srcdir = self.environment.get_source_dir()
1968 builddir = self.environment.get_build_dir()
1969 for de in data:
1970 assert isinstance(de, build.Data)
1971 subdir = de.install_dir
1972 subdir_name = de.install_dir_name
1973 for src_file, dst_name in zip(de.sources, de.rename):
1974 assert isinstance(src_file, mesonlib.File)
1975 dst_abs = os.path.join(subdir, dst_name)
1976 dstdir_name = os.path.join(subdir_name, dst_name)
1977 tag = de.install_tag or self.guess_install_tag(dst_abs)
1978 i = InstallDataBase(src_file.absolute_path(srcdir, builddir), dst_abs, dstdir_name,
1979 de.install_mode, de.subproject, tag=tag, data_type=de.data_type,
1980 follow_symlinks=de.follow_symlinks)
1981 d.data.append(i)
1982
1983 def generate_symlink_install(self, d: InstallData) -> None:
1984 links: T.List[build.SymlinkData] = self.build.get_symlinks()
1985 for l in links:
1986 assert isinstance(l, build.SymlinkData)
1987 install_dir = l.install_dir
1988 name_abs = os.path.join(install_dir, l.name)
1989 tag = l.install_tag or self.guess_install_tag(name_abs)
1990 s = InstallSymlinkData(l.target, name_abs, install_dir, l.subproject, tag)
1991 d.symlinks.append(s)
1992
1993 def generate_subdir_install(self, d: InstallData) -> None:
1994 for sd in self.build.get_install_subdirs():
1995 if sd.from_source_dir:
1996 from_dir = self.environment.get_source_dir()
1997 else:
1998 from_dir = self.environment.get_build_dir()
1999 src_dir = os.path.join(from_dir,
2000 sd.source_subdir,
2001 sd.installable_subdir).rstrip('/')
2002 dst_dir = os.path.join(self.environment.get_prefix(),
2003 sd.install_dir)
2004 dst_name = os.path.join('{prefix}', sd.install_dir)
2005 if sd.install_dir != sd.install_dir_name:
2006 dst_name = sd.install_dir_name
2007 if not sd.strip_directory:
2008 dst_dir = os.path.join(dst_dir, os.path.basename(src_dir))
2009 dst_name = os.path.join(dst_name, os.path.basename(src_dir))
2010 tag = sd.install_tag or self.guess_install_tag(os.path.join(sd.install_dir, 'dummy'))
2011 i = SubdirInstallData(src_dir, dst_dir, dst_name, sd.install_mode, sd.exclude, sd.subproject, tag,
2012 follow_symlinks=sd.follow_symlinks)
2013 d.install_subdirs.append(i)
2014
2015 def get_introspection_data(self, target_id: str, target: build.Target) -> T.List[TargetIntrospectionData]:
2016 '''
2017 Returns a list of source dicts with the following format for a given target:
2018 [
2019 {
2020 "language": "<LANG>",
2021 "compiler": ["result", "of", "comp.get_exelist()"],
2022 "parameters": ["list", "of", "compiler", "parameters],
2023 "sources": ["list", "of", "all", "<LANG>", "source", "files"],
2024 "generated_sources": ["list", "of", "generated", "source", "files"]
2025 }
2026 ]
2027
2028 This is a limited fallback / reference implementation. The backend should override this method.
2029 '''
2030 if isinstance(target, (build.CustomTarget, build.BuildTarget)):
2031 source_list_raw = target.sources
2032 source_list = []
2033 for j in source_list_raw:
2034 if isinstance(j, mesonlib.File):
2035 source_list += [j.absolute_path(self.source_dir, self.build_dir)]
2036 elif isinstance(j, (build.CustomTarget, build.BuildTarget)):
2037 source_list += [os.path.join(self.build_dir, j.get_builddir(), o) for o in j.get_outputs()]
2038 source_list = [os.path.normpath(s) for s in source_list]
2039
2040 compiler: T.List[str] = []
2041 if isinstance(target, build.CustomTarget):
2042 tmp_compiler = target.command
2043 for k in tmp_compiler:
2044 if isinstance(k, mesonlib.File):
2045 compiler += [k.absolute_path(self.source_dir, self.build_dir)]
2046 elif isinstance(k, str):
2047 compiler += [k]
2048 elif isinstance(k, (build.BuildTarget, build.CustomTarget)):
2049 compiler += k.get_outputs()
2050 elif isinstance(k, programs.Program):
2051 compiler += k.get_command()
2052 else:
2053 raise RuntimeError(f'Type "{type(k).__name__}" is not supported in get_introspection_data. This is a bug')
2054
2055 return [{
2056 'language': 'unknown',
2057 'compiler': compiler,
2058 'parameters': [],
2059 'sources': source_list,
2060 'generated_sources': []
2061 }]
2062
2063 return []
2064
2065 def get_devenv(self) -> mesonlib.EnvironmentVariables:
2066 extra_paths = set()
2067 library_paths = set()
2068 host_machine = self.environment.machines[MachineChoice.HOST]
2069 for t in self.build.get_targets().values():
2070 if t.for_machine is not MachineChoice.HOST or not t.should_install():
2071 continue
2072
2073 # Mypy doesn't understand that AliasTarget and RunTarget always return False above
2074 assert isinstance(t, (build.BuildTarget, build.CustomTarget)), 'for mypy'
2075
2076 if (host_machine.is_windows() or host_machine.is_cygwin()) and isinstance(t, (build.Executable, build.SharedModule)):
2077 # On windows we cannot rely on rpath to run executables from build
2078 # directory. We have to add in PATH the location of every DLL needed.
2079 library_paths.update(self.determine_windows_extra_paths(t, []))
2080
2081 if t.has_custom_install_dir:
2082 # Do not update paths for target installed in non default location
2083 continue
2084
2085 tdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(t))
2086 if isinstance(t, build.Executable):
2087 # Add binaries that are going to be installed in bindir into PATH
2088 # so they get used by default instead of searching on system when
2089 # in developer environment.
2090 extra_paths.add(tdir)
2091
2092 elif isinstance(t, build.SharedLibrary):
2093 # Add libraries that are going to be installed in libdir into
2094 # LD_LIBRARY_PATH. This allows running system applications using
2095 # that library.
2096 library_paths.add(tdir)
2097
2098 return self.environment.get_env_for_paths(library_paths, extra_paths)
2099
2100 def compiler_to_generator_args(self, target: build.BuildTarget,
2101 compiler: 'Compiler', output: str = '@OUTPUT@',
2102 depfile: T.Union[str, None] = '@DEPFILE@',
2103 extras: T.Union[T.List[str], None] = None,
2104 input: str = '@INPUT@') -> CompilerArgs:
2105 '''
2106 The VS and Xcode backends need the full set of arguments for making a
2107 custom build rule. This is a convenience method to convert a Compiler
2108 to its arguments, for later concatenation.
2109 '''
2110 # FIXME: There are many other args missing
2111 commands = self.generate_basic_compiler_args(target, compiler)
2112 if depfile:
2113 commands += compiler.get_dependency_gen_args(output, depfile)
2114 commands += compiler.get_output_args(output)
2115 commands += self.get_source_dir_include_args(target, compiler)
2116 commands += self.get_build_dir_include_args(target, compiler)
2117 commands += compiler.get_compile_only_args()
2118 # Add per-target compile args, f.ex, `c_args : ['-DFOO']`. We set these
2119 # near the end since these are supposed to override everything else.
2120 commands += self.escape_extra_args(target.get_extra_args(compiler.get_language()))
2121 # Do not escape this one, it is interpreted by the build system
2122 # (Xcode considers these as variables to expand at build time)
2123 if extras is not None:
2124 commands += extras
2125 commands += [input]
2126 return commands
2127
2128 def have_language(self, langname: str) -> bool:
2129 for for_machine in MachineChoice:
2130 if langname in self.environment.coredata.compilers[for_machine]:
2131 return True
2132 return False
2133
2134 def compiler_to_generator(self, target: build.BuildTarget,
2135 compiler: 'Compiler',
2136 sources: T.List[TargetSources],
2137 output_templ: str,
2138 depends: T.Optional[T.List[build.BuildTargetTypes]] = None,
2139 ) -> build.GeneratedList:
2140 '''
2141 Some backends don't support custom compilers. This is a convenience
2142 method to convert a Compiler to a Generator.
2143 '''
2144 exe = programs.ExternalProgram(compiler.get_exe())
2145 args = compiler.get_exe_args()
2146 commands = self.compiler_to_generator_args(target, compiler)
2147 generator = build.Generator(self.environment,
2148 exe, args + commands.to_native(),
2149 [output_templ], depfile='@[email protected]',
2150 depends=depends)
2151 return generator.process_files(sources)
2152
2153 def compile_target_to_generator(self, target: build.CompileTarget) -> build.GeneratedList:
2154 all_sources: T.List[TargetSources] = [*target.sources, *target.generated]
2155 return self.compiler_to_generator(target, target.compiler, all_sources,
2156 target.output_templ, target.depends)
2157
2158 def is_unity(self, target: build.BuildTarget) -> bool:
2159 if isinstance(target, build.CompileTarget):
2160 return False
2161 val = self.get_target_option(target, 'unity')
2162 if val == 'on':
2163 return True
2164 if val == 'off':
2165 return False
2166 if val == 'subprojects':
2167 return target.subproject != ''
2168 raise MesonException(f'Internal error: invalid option type for "unity": {val}')
2169
2170 def get_target_option(self, target: build.BuildTarget, name: T.Union[str, OptionKey]) -> ElementaryOptionValues:
2171 if isinstance(name, str):
2172 key = OptionKey(name, subproject=target.subproject)
2173 elif isinstance(name, OptionKey):
2174 key = name
2175 else:
2176 raise MesonBugException('Internal error: invalid option type.')
2177 return self.environment.coredata.get_option_for_target(target, key)