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