Debian Codegraph @

mesonbuild/environment.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2012-2020 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 import dataclasses
8 import itertools
9 import os, re
10 import typing as T
11 import collections
12
13 from . import cmdline
14 from . import coredata
15 from . import mesonlib
16 from . import machinefile
17 from . import options
18
19 from .mesonlib import (
20 MesonException, MachineChoice, Popen_safe, PerMachine,
21 PerMachineDefaultable, PerThreeMachineDefaultable, split_args,
22 MesonBugException, ThreeMachineChoice
23 )
24 from .options import OptionKey
25 from . import mlog
26 from .programs import ExternalProgram
27
28 from .envconfig import (
29 BinaryTable, MachineInfo, Properties, CMakeVariables,
30 detect_machine_info, machine_info_can_run
31 )
32 from . import compilers
33
34 from mesonbuild import envconfig
35
36 if T.TYPE_CHECKING:
37 from .compilers.compilers import Compiler, CompilerDict, Language
38 from .options import OptionDict, ElementaryOptionValues
39 from .wrap.wrap import Resolver
40
41 import enum
42
43
44 NON_LANG_ENV_OPTIONS = [
45 ('PKG_CONFIG_PATH', 'pkg_config_path'),
46 ('CMAKE_PREFIX_PATH', 'cmake_prefix_path'),
47 ('LDFLAGS', 'ldflags'),
48 ('CPPFLAGS', 'cppflags'),
49 ]
50
51 build_filename = 'meson.build'
52
53
54 def _as_str(val: object) -> str:
55 assert isinstance(val, str), 'for mypy'
56 return val
57
58
59 def _get_env_var(for_machine: MachineChoice, is_cross: bool, var_name: str) -> T.Optional[str]:
60 """
61 Returns the exact env var and the value.
62 """
63 candidates = PerMachine(
64 # The prefixed build version takes priority, but if we are native
65 # compiling we fall back on the unprefixed host version. This
66 # allows native builds to never need to worry about the 'BUILD_*'
67 # ones.
68 ([var_name + '_FOR_BUILD'] if is_cross else [var_name]),
69 # Always just the unprefixed host versions
70 [var_name]
71 )[for_machine]
72 for var in candidates:
73 value = os.environ.get(var)
74 if value is not None:
75 break
76 else:
77 formatted = ', '.join([f'{var!r}' for var in candidates])
78 mlog.debug(f'None of {formatted} are defined in the environment, not changing global flags.')
79 return None
80 mlog.debug(f'Using {var!r} from environment with value: {value!r}')
81 return value
82
83
84 @dataclasses.dataclass
85 class MachineMap:
86 # BUILD if cross compiling, HOST if not cross compiling
87 build: MachineChoice
88 # This is not entirely correct: it is possible in principle for
89 # the host machine to be originally configured as a target, and
90 # switched to be the host for a single subproject. Ultimately,
91 # Environment should include N arbitrarily-named configurations,
92 # and kwargs['native'] would be supplanted by kwargs['for_machine']
93 # of type T.NewType('MachineChoice', str) after parameter parsing.
94 host: MachineChoice
95 target: ThreeMachineChoice
96
97 @T.overload
98 def __getitem__(self, machine: MachineChoice) -> MachineChoice:
99 ...
100
101 @T.overload
102 def __getitem__(self, machine: ThreeMachineChoice) -> ThreeMachineChoice:
103 ...
104
105 def __getitem__(self, machine: MachineChoice | ThreeMachineChoice) -> enum.IntEnum:
106 return [self.build, self.host, self.target][machine.value]
107
108
109 class Environment:
110 private_dir = 'meson-private'
111 log_dir = 'meson-logs'
112 info_dir = 'meson-info'
113
114 exe_wrapper: ExternalProgram | None
115
116 def __init__(self, source_dir: str, build_dir: T.Optional[str], cmd_options: cmdline.SharedCMDOptions) -> None:
117 self.source_dir = source_dir
118 # Do not try to create build directories when build_dir is none.
119 # This reduced mode is used by the --buildoptions introspector
120 if build_dir is not None:
121 self.build_dir = build_dir
122 self.scratch_dir = os.path.join(build_dir, Environment.private_dir)
123 self.log_dir = os.path.join(build_dir, Environment.log_dir)
124 self.info_dir = os.path.join(build_dir, Environment.info_dir)
125 os.makedirs(self.scratch_dir, exist_ok=True)
126 os.makedirs(self.log_dir, exist_ok=True)
127 os.makedirs(self.info_dir, exist_ok=True)
128 try:
129 self.coredata: coredata.CoreData = coredata.load(self.get_build_dir(), suggest_reconfigure=False)
130 self.first_invocation = False
131 except FileNotFoundError:
132 self.create_new_coredata(cmd_options)
133 except coredata.MesonVersionMismatchException as e:
134 # This is routine, but tell the user the update happened
135 mlog.log('Regenerating configuration from scratch:', str(e))
136 cmdline.read_cmd_line_file(self.build_dir, cmd_options)
137 self.create_new_coredata(cmd_options)
138 except MesonException as e:
139 # If we stored previous command line options, we can recover from
140 # a broken/outdated coredata.
141 if os.path.isfile(cmdline.get_cmd_line_file(self.build_dir)):
142 mlog.warning('Regenerating configuration from scratch.', fatal=False)
143 mlog.log('Reason:', mlog.red(str(e)))
144 cmdline.read_cmd_line_file(self.build_dir, cmd_options)
145 self.create_new_coredata(cmd_options)
146 else:
147 raise MesonException(f'{str(e)} Try regenerating using "meson setup --wipe".')
148 else:
149 # Just create a fresh coredata in this case
150 self.build_dir = ''
151 self.scratch_dir = ''
152 self.create_new_coredata(cmd_options)
153
154 # Store which machine is actually returned by self.machines after
155 # taking into account defaults
156 if self.coredata.cross_files:
157 self.machine_map = MachineMap(MachineChoice.BUILD, MachineChoice.HOST, ThreeMachineChoice.HOST)
158 else:
159 self.machine_map = MachineMap(MachineChoice.HOST, MachineChoice.HOST, ThreeMachineChoice.HOST)
160
161 ## locally bind some unfrozen configuration
162
163 # Stores machine infos, the only *three* machine one because we have a
164 # target machine info on for the user (Meson never cares about the
165 # target machine.)
166 machines: PerThreeMachineDefaultable[MachineInfo] = PerThreeMachineDefaultable()
167
168 # Similar to coredata.compilers, but lower level in that there is no
169 # meta data, only names/paths.
170 binaries: PerMachineDefaultable[BinaryTable] = PerMachineDefaultable()
171
172 # Misc other properties about each machine.
173 properties: PerMachineDefaultable[Properties] = PerMachineDefaultable()
174
175 # CMake toolchain variables
176 cmakevars: PerMachineDefaultable[CMakeVariables] = PerMachineDefaultable()
177
178 ## Setup build machine defaults
179
180 # Will be fully initialized later using compilers later.
181 machines.build = detect_machine_info()
182
183 # Just uses hard-coded defaults and environment variables. Might be
184 # overwritten by a native file.
185 binaries.build = BinaryTable()
186 properties.build = Properties()
187
188 # Options with the key parsed into an OptionKey type.
189 #
190 # Note that order matters because of 'buildtype', if it is after
191 # 'optimization' and 'debug' keys, it override them.
192 self.options: OptionDict = collections.OrderedDict()
193
194 # Environment variables with the name converted into an OptionKey type.
195 # These have subtly different behavior compared to machine files, so do
196 # not store them in self.options. See _set_default_options_from_env.
197 self.env_opts: OptionDict = {}
198
199 self.machinestore = machinefile.MachineFileStore(self.coredata.config_files, self.coredata.cross_files, self.source_dir)
200
201 ## Read in native file(s) to override build machine configuration
202
203 if self.coredata.config_files is not None:
204 config = machinefile.parse_machine_files(self.coredata.config_files, self.source_dir)
205 binaries.build = BinaryTable(config.get('binaries', {}))
206 properties.build = Properties(config.get('properties', {}))
207 cmakevars.build = CMakeVariables(config.get('cmake', {}))
208 self._load_machine_file_options(config, properties.build, self.machine_map.build)
209
210 ## Read in cross file(s) to override host machine configuration
211
212 if self.coredata.cross_files:
213 config = machinefile.parse_machine_files(self.coredata.cross_files, self.source_dir)
214 properties.host = Properties(config.get('properties', {}))
215 binaries.host = BinaryTable(config.get('binaries', {}))
216 cmakevars.host = CMakeVariables(config.get('cmake', {}))
217 if 'host_machine' in config:
218 machines.host = MachineInfo.from_literal(config['host_machine'])
219 if 'target_machine' in config:
220 machines.target = MachineInfo.from_literal(config['target_machine'])
221 self.machine_map.target = ThreeMachineChoice.TARGET
222 # Keep only per machine options from the native file. The cross
223 # file takes precedence over all other options.
224 for key, value in list(self.options.items()):
225 if self.coredata.optstore.is_per_machine_option(key):
226 self.options[key.as_build()] = value
227 self._load_machine_file_options(config, properties.host, MachineChoice.HOST)
228
229 ## "freeze" now initialized configuration, and "save" to the class.
230
231 self.machines = machines.default_missing()
232 self.binaries = binaries.default_missing()
233 self.properties = properties.default_missing()
234 self.cmakevars = cmakevars.default_missing()
235
236 # Set host machine info for machine-aware handling of directory options
237 self.coredata.optstore.set_host_machine(self.machines.host)
238
239 # Take default value from env if not set in cross/native files or command line.
240 self._set_default_options_from_env()
241 self._set_default_binaries_from_env()
242 self._set_default_properties_from_env()
243
244 # Warn if the user is using two different ways of setting build-type
245 # options that override each other
246 bt = OptionKey('buildtype')
247 db = OptionKey('debug')
248 op = OptionKey('optimization')
249 if bt in self.options and (db in self.options or op in self.options):
250 mlog.warning('Recommend using either -Dbuildtype or -Doptimization + -Ddebug. '
251 'Using both is redundant since they override each other. '
252 'See: https://mesonbuild.com/Builtin-options.html#build-type-options',
253 fatal=False)
254
255 # Filter out build machine options that are not valid per-project.
256 # We allow this in the file because it makes the machine files more
257 # useful (ie, the same file can be used for host == build configuration
258 # a host != build configuration)
259 self.options = {k: v for k, v in self.options.items()
260 if k.machine is MachineChoice.HOST or self.coredata.optstore.is_per_machine_option(k)}
261
262 exe_wrapper = self.lookup_binary_entry(MachineChoice.HOST, 'exe_wrapper')
263 self.exe_wrapper: ExternalProgram | None
264 if exe_wrapper is not None:
265 self.exe_wrapper = ExternalProgram.from_bin_list(self, MachineChoice.HOST, 'exe_wrapper')
266 else:
267 self.exe_wrapper = None
268
269 self.default_cmake = ['cmake']
270 self.default_pkgconfig = ['pkg-config']
271 self.wrap_resolver: T.Optional['Resolver'] = None
272
273 def mfilestr2key(self, machine_file_string: str, section: T.Optional[str], section_subproject: T.Optional[str], machine: MachineChoice) -> OptionKey:
274 key = OptionKey.from_string(machine_file_string)
275 if key.subproject:
276 suggestion = section if section == 'project options' else 'built-in options'
277 raise MesonException(f'Do not set subproject options in [{section}] section, use [subproject:{suggestion}] instead.')
278 if section_subproject:
279 key = key.evolve(subproject=section_subproject)
280 if machine == MachineChoice.BUILD:
281 if key.machine == MachineChoice.BUILD:
282 mlog.deprecation('Setting build machine options in the native file does not need the "build." prefix', once=True)
283 return key.evolve(machine=machine)
284 return key
285
286 def _load_machine_file_options(self, config: T.Mapping[str, T.Mapping[str, ElementaryOptionValues]],
287 properties: Properties, machine: MachineChoice) -> None:
288 """Read the contents of a Machine file and put it in the options store."""
289
290 # Look for any options in the deprecated paths section, warn about
291 # those, then assign them. They will be overwritten by the ones in the
292 # "built-in options" section if they're in both sections.
293 paths = config.get('paths')
294 if paths:
295 mlog.deprecation('The [paths] section is deprecated, use the [built-in options] section instead.')
296 for strk, v in paths.items():
297 k = self.mfilestr2key(strk, 'paths', None, machine)
298 self.options[k] = v
299
300 # Next look for compiler options in the "properties" section, this is
301 # also deprecated, and these will also be overwritten by the "built-in
302 # options" section. We need to remove these from this section, as well.
303 deprecated_properties: T.Set[str] = set()
304 for lang in compilers.all_languages:
305 deprecated_properties.add(lang + '_args')
306 deprecated_properties.add(lang + '_link_args')
307 for strk, v in properties.properties.copy().items():
308 if strk in deprecated_properties:
309 mlog.deprecation(f'{strk} in the [properties] section of the machine file is deprecated, use the [built-in options] section.')
310 k = self.mfilestr2key(strk, 'properties', None, machine)
311 self.options[k] = v
312 del properties.properties[strk]
313
314 for section, values in config.items():
315 if ':' in section:
316 section_subproject, section = section.split(':', 1)
317 else:
318 section_subproject = ''
319 if section == 'built-in options':
320 for strk, v in values.items():
321 key = self.mfilestr2key(strk, section, section_subproject, machine)
322 # If we're in the cross file, and there is a `build.foo` warn about that. Later we'll remove it.
323 if machine is MachineChoice.HOST and key.machine is not machine:
324 mlog.deprecation('Setting build machine options in cross files, please use a native file instead, this will be removed in meson 2.0', once=True)
325 self.options[key] = v
326 elif section == 'project options' and machine is MachineChoice.HOST:
327 # Project options are only for the host machine, we don't want
328 # to read these from the native file
329 for strk, v in values.items():
330 # Project options are always for the host machine
331 key = self.mfilestr2key(strk, section, section_subproject, machine)
332 self.options[key] = v
333 elif ':' in section:
334 correct_subproject, correct_section = section.split(':')[-2:]
335 raise MesonException(
336 'Subproject options should always be set as '
337 '`[subproject:section]`, even if the options are from a '
338 'nested subproject. '
339 f'Replace `[{section_subproject}:{section}]` with `[{correct_subproject}:{correct_section}]`')
340
341 def _set_default_options_from_env(self) -> None:
342 opts: T.List[T.Tuple[str, str]] = (
343 [(v, f'{k}_args') for k, v in compilers.compilers.CFLAGS_MAPPING.items()] +
344 NON_LANG_ENV_OPTIONS
345 )
346
347 env_opts: T.DefaultDict[OptionKey, T.List[str]] = collections.defaultdict(list)
348
349 for (evar, keyname), for_machine in itertools.product(opts, MachineChoice):
350 p_env = _get_env_var(for_machine, self.is_cross_build(), evar)
351 if p_env is not None:
352 # these may contain duplicates, which must be removed, else
353 # a duplicates-in-array-option warning arises.
354 if keyname == 'cmake_prefix_path':
355 if self.machines[for_machine].is_windows():
356 # Cannot split on ':' on Windows because its in the drive letter
357 _p_env = p_env.split(os.pathsep)
358 else:
359 # https://github.com/mesonbuild/meson/issues/7294
360 _p_env = re.split(r':|;', p_env)
361 p_list = list(mesonlib.OrderedSet(_p_env))
362 elif keyname == 'pkg_config_path':
363 p_list = list(mesonlib.OrderedSet(p_env.split(os.pathsep)))
364 else:
365 p_list = split_args(p_env)
366 p_list = [e for e in p_list if e] # filter out any empty elements
367
368 # Take env vars only on first invocation, if the env changes when
369 # reconfiguring it gets ignored.
370 # FIXME: We should remember if we took the value from env to warn
371 # if it changes on future invocations.
372 if self.first_invocation:
373 if keyname == 'ldflags':
374 for lang in compilers.compilers.LANGUAGES_USING_LDFLAGS:
375 key = OptionKey(name=f'{lang}_link_args', machine=for_machine)
376 env_opts[key].extend(p_list)
377 elif keyname == 'cppflags':
378 for lang in compilers.compilers.LANGUAGES_USING_CPPFLAGS:
379 key = OptionKey(f'{lang}_args', machine=for_machine)
380 env_opts[key].extend(p_list)
381 else:
382 key = OptionKey.from_string(keyname).evolve(machine=for_machine)
383 env_opts[key].extend(p_list)
384
385 # If this is an environment variable, we have to
386 # store it separately until the compiler is
387 # instantiated, as we don't know whether the
388 # compiler will want to use these arguments at link
389 # time and compile time (instead of just at compile
390 # time) until we're instantiating that `Compiler`
391 # object. This is required so that passing
392 # `-Dc_args=` on the command line and `$CFLAGS`
393 # have subtly different behavior. `$CFLAGS` will be
394 # added to the linker command line if the compiler
395 # acts as a linker driver, `-Dc_args` will not.
396 for (_, keyname), for_machine in itertools.product(NON_LANG_ENV_OPTIONS, MachineChoice):
397 key = OptionKey.from_string(keyname).evolve(machine=for_machine)
398 # Only store options that are not already in self.options,
399 # otherwise we'd override the machine files
400 if key in env_opts and key not in self.options:
401 self.options[key] = env_opts[key]
402 del env_opts[key]
403
404 self.env_opts.update(env_opts)
405
406 def _set_default_binaries_from_env(self) -> None:
407 """Set default binaries from the environment.
408
409 For example, pkg-config can be set via PKG_CONFIG, or in the machine
410 file. We want to set the default to the env variable.
411 """
412 opts = itertools.chain(envconfig.DEPRECATED_ENV_PROG_MAP.items(),
413 envconfig.ENV_VAR_PROG_MAP.items())
414
415 for (name, evars), for_machine in itertools.product(opts, MachineChoice):
416 for evar in evars:
417 p_env = _get_env_var(for_machine, self.is_cross_build(), evar)
418 if p_env is not None:
419 if os.path.exists(p_env):
420 self.binaries[for_machine].binaries.setdefault(name, [p_env])
421 else:
422 self.binaries[for_machine].binaries.setdefault(name, mesonlib.split_args(p_env))
423 break
424
425 def _set_default_properties_from_env(self) -> None:
426 """Properties which can also be set from the environment."""
427 # name, evar, split
428 opts: T.List[T.Tuple[str, T.List[str], bool]] = [
429 ('boost_includedir', ['BOOST_INCLUDEDIR'], False),
430 ('boost_librarydir', ['BOOST_LIBRARYDIR'], False),
431 ('boost_root', ['BOOST_ROOT', 'BOOSTROOT'], True),
432 ('java_home', ['JAVA_HOME'], False),
433 ]
434
435 for (name, evars, split), for_machine in itertools.product(opts, MachineChoice):
436 for evar in evars:
437 p_env = _get_env_var(for_machine, self.is_cross_build(), evar)
438 if p_env is not None:
439 if split:
440 self.properties[for_machine].properties.setdefault(name, p_env.split(os.pathsep))
441 else:
442 self.properties[for_machine].properties.setdefault(name, p_env)
443 break
444
445 def create_new_coredata(self, options: cmdline.SharedCMDOptions) -> None:
446 # WARNING: Don't use any values from coredata in __init__. It gets
447 # re-initialized with project options by the interpreter during
448 # build file parsing.
449 # meson_command is used by the regenchecker script, which runs meson
450 try:
451 meson_command = mesonlib.get_meson_command().copy()
452 except MesonBugException:
453 meson_command = []
454 self.coredata = coredata.CoreData(options, self.scratch_dir, meson_command)
455 self.first_invocation = True
456
457 def init_backend_options(self, backend_name: str) -> None:
458 # Only init backend options on first invocation otherwise it would
459 # override values previously set from command line.
460 if not self.first_invocation:
461 return
462
463 self.coredata.init_backend_options(backend_name)
464 for k, v in self.options.items():
465 if self.coredata.optstore.is_backend_option(k):
466 self.coredata.optstore.set_option(k, v)
467
468 def is_cross_build(self, when_building_for: MachineChoice = MachineChoice.HOST) -> bool:
469 return self.machine_map[when_building_for] is not self.machine_map.build
470
471 def dump_coredata(self) -> str:
472 return coredata.save(self.coredata, self.get_build_dir())
473
474 def get_log_dir(self) -> str:
475 return self.log_dir
476
477 def get_coredata(self) -> coredata.CoreData:
478 return self.coredata
479
480 @staticmethod
481 def get_build_command(unbuffered: bool = False) -> T.List[str]:
482 cmd = mesonlib.get_meson_command().copy()
483 if unbuffered and 'python' in os.path.basename(cmd[0]):
484 cmd.insert(1, '-u')
485 return cmd
486
487 def lookup_binary_entry(self, for_machine: MachineChoice, name: str) -> T.Optional[T.List[str]]:
488 return self.binaries[for_machine].lookup_entry(name)
489
490 def get_scratch_dir(self) -> str:
491 return self.scratch_dir
492
493 def get_source_dir(self) -> str:
494 return self.source_dir
495
496 def get_build_dir(self) -> str:
497 return self.build_dir
498
499 def get_import_lib_dir(self) -> str:
500 "Install dir for the import library (library used for linking)"
501 return self.get_libdir()
502
503 def get_shared_module_dir(self) -> str:
504 "Install dir for shared modules that are loaded at runtime"
505 return self.get_libdir()
506
507 def get_shared_lib_dir(self) -> str:
508 "Install dir for the shared library"
509 m = self.machines.host
510 # Windows has no RPATH or similar, so DLLs must be next to EXEs.
511 if m.is_windows() or m.is_cygwin():
512 return self.get_bindir()
513 return self.get_libdir()
514
515 def get_jar_dir(self) -> str:
516 """Install dir for JAR files"""
517 return f"{self.get_datadir()}/java"
518
519 def get_static_lib_dir(self) -> str:
520 "Install dir for the static library"
521 return self.get_libdir()
522
523 def get_prefix(self) -> str:
524 return _as_str(self.coredata.optstore.get_value_for(OptionKey('prefix')))
525
526 def get_libdir(self) -> str:
527 return _as_str(self.coredata.optstore.get_value_for(OptionKey('libdir')))
528
529 def get_libexecdir(self) -> str:
530 return _as_str(self.coredata.optstore.get_value_for(OptionKey('libexecdir')))
531
532 def get_bindir(self) -> str:
533 return _as_str(self.coredata.optstore.get_value_for(OptionKey('bindir')))
534
535 def get_sbindir(self) -> str:
536 return _as_str(self.coredata.optstore.get_value_for(OptionKey('sbindir')))
537
538 def get_includedir(self) -> str:
539 return _as_str(self.coredata.optstore.get_value_for(OptionKey('includedir')))
540
541 def get_mandir(self) -> str:
542 return _as_str(self.coredata.optstore.get_value_for(OptionKey('mandir')))
543
544 def get_datadir(self) -> str:
545 return _as_str(self.coredata.optstore.get_value_for(OptionKey('datadir')))
546
547 def get_compiler_system_lib_dirs(self, for_machine: MachineChoice) -> T.List[str]:
548 for comp in self.coredata.compilers[for_machine].values():
549 if comp.id == 'clang':
550 index = 1
551 break
552 elif comp.id == 'gcc':
553 index = 2
554 break
555 else:
556 # This option is only supported by gcc and clang. If we don't get a
557 # GCC or Clang compiler return and empty list.
558 return []
559
560 p, out, _ = Popen_safe(comp.get_exelist() + ['-print-search-dirs'])
561 if p.returncode != 0:
562 raise mesonlib.MesonException('Could not calculate system search dirs')
563 split = out.split('\n')[index].lstrip('libraries: =').split(':')
564 return [os.path.normpath(p) for p in split]
565
566 def get_compiler_system_include_dirs(self, for_machine: MachineChoice) -> T.List[str]:
567 for comp in self.coredata.compilers[for_machine].values():
568 if comp.id == 'clang':
569 break
570 elif comp.id == 'gcc':
571 break
572 else:
573 # This option is only supported by gcc and clang. If we don't get a
574 # GCC or Clang compiler return and empty list.
575 return []
576 return comp.get_default_include_dirs()
577
578 def need_exe_wrapper(self, for_machine: MachineChoice = MachineChoice.HOST) -> bool:
579 value = self.properties[for_machine].get('needs_exe_wrapper', None)
580 if value is not None:
581 assert isinstance(value, bool), 'for mypy'
582 return value
583 if not self.is_cross_build():
584 return False
585 return not machine_info_can_run(self.machines[for_machine])
586
587 def get_exe_wrapper(self) -> T.Optional[ExternalProgram]:
588 if not self.need_exe_wrapper():
589 return None
590 return self.exe_wrapper
591
592 def has_exe_wrapper(self) -> bool:
593 return self.exe_wrapper is not None and self.exe_wrapper.found()
594
595 def get_env_for_paths(self, library_paths: T.Set[str], extra_paths: T.Set[str]) -> mesonlib.EnvironmentVariables:
596 env = mesonlib.EnvironmentVariables()
597 need_wine = not self.machines.build.is_windows() and self.machines.host.is_windows()
598 if need_wine:
599 # Executable paths should be in both PATH and WINEPATH.
600 # - Having them in PATH makes bash completion find it,
601 # and make running "foo.exe" find it when wine-binfmt is installed.
602 # - Having them in WINEPATH makes "wine foo.exe" find it.
603 library_paths.update(extra_paths)
604 if library_paths:
605 if need_wine:
606 env.prepend('WINEPATH', list(library_paths), separator=';')
607 elif self.machines.host.is_windows() or self.machines.host.is_cygwin():
608 extra_paths.update(library_paths)
609 elif self.machines.host.is_darwin():
610 env.prepend('DYLD_LIBRARY_PATH', list(library_paths))
611 else:
612 env.prepend('LD_LIBRARY_PATH', list(library_paths))
613 if extra_paths:
614 env.prepend('PATH', list(extra_paths))
615 return env
616
617 def add_lang_args(self, lang: Language, comp: T.Type['Compiler'],
618 for_machine: MachineChoice) -> None:
619 """Add global language arguments that are needed before compiler/linker detection."""
620 description = f'Extra arguments passed to the {lang}'
621 argkey = OptionKey(f'{lang}_args', machine=for_machine)
622 largkey = OptionKey(f'{lang}_link_args', machine=for_machine)
623
624 comp_args_from_envvar = False
625 comp_options = self.coredata.optstore.get_pending_value(argkey)
626 if comp_options is None:
627 comp_args_from_envvar = True
628 comp_options = self.env_opts.get(argkey, [])
629
630 link_options = self.coredata.optstore.get_pending_value(largkey)
631 if link_options is None:
632 link_options = self.env_opts.get(largkey, [])
633
634 assert isinstance(comp_options, (str, list)), 'for mypy'
635 assert isinstance(link_options, (str, list)), 'for mypy'
636
637 cargs = options.UserStringArrayOption(
638 argkey.name,
639 description + ' compiler',
640 comp_options, split_args=True, allow_dups=True)
641
642 largs = options.UserStringArrayOption(
643 largkey.name,
644 description + ' linker',
645 link_options, split_args=True, allow_dups=True)
646
647 self.coredata.optstore.add_compiler_option(lang, argkey, cargs)
648 self.coredata.optstore.add_compiler_option(lang, largkey, largs)
649
650 if comp.USED_FOR_SEPARATE_LINKING_STEP and comp_args_from_envvar:
651 # If the compiler acts as a linker driver, and we're using the
652 # environment variable flags for both the compiler and linker
653 # arguments, then put the compiler flags in the linker flags as well.
654 # This is how autotools works, and the env vars feature is for
655 # autotools compatibility.
656 largs.extend_value(comp_options)
657
658 def update_build_machine(self, compilers: T.Optional[CompilerDict] = None) -> None:
659 """Redetect the build machine and update the machine definitions
660
661 :compilers: An optional dictionary of compilers to use instead of the coredata dict.
662 """
663 compilers = compilers or self.coredata.compilers.build
664
665 machines = self.machines.miss_defaulting()
666 machines.build = detect_machine_info(compilers)
667 self.machines = machines.default_missing()