Debian Codegraph @

mesonbuild/coredata.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2013-2026 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 import copy
8
9 from . import mlog, options
10 import pickle, os, uuid
11 import sys
12 from functools import lru_cache
13 from collections import OrderedDict
14 import textwrap
15
16 from .mesonlib import (
17 MesonException, MachineChoice, PerMachine,
18 PerMachineDefaultable,
19 pickle_load
20 )
21
22 from .options import OptionKey
23
24 import enum
25 import typing as T
26
27 if T.TYPE_CHECKING:
28 from . import dependencies
29 from .compilers.compilers import Compiler, CompilerDict, CompileResult, RunResult, CompileCheckMode, Language
30 from .dependencies.detect import TV_DepID
31 from .mesonlib import FileOrString, SubProject
32 from .cmake.traceparser import CMakeCacheEntry
33 from .options import ElementaryOptionValues, MutableKeyedOptionDictType
34 from .build import BuildTarget
35 from .cmdline import SharedCMDOptions
36
37 OptionDictType = T.Dict[str, options.AnyOptionType]
38 CompilerCheckCacheKey = T.Tuple[T.Tuple[str, ...], str, FileOrString, T.Tuple[str, ...], CompileCheckMode]
39 # code, args
40 RunCheckCacheKey = T.Tuple[str, T.Tuple[str, ...]]
41
42 # Check major_versions_differ() if changing versioning scheme.
43 #
44 # Pip requires that RCs are named like this: '0.1.0.rc1'
45 # But the corresponding Git tag needs to be '0.1.0rc1'
46 version = '1.12.0'
47
48 # The next stable version when we are in dev. This is used to allow projects to
49 # require meson version >=1.2.0 when using 1.1.99. FeatureNew won't warn when
50 # using a feature introduced in 1.2.0 when using Meson 1.1.99.
51 stable_version = version
52 if stable_version.endswith('.99'):
53 stable_version_array = stable_version.split('.')
54 stable_version_array[-1] = '0'
55 stable_version_array[-2] = str(int(stable_version_array[-2]) + 1)
56 stable_version = '.'.join(stable_version_array)
57
58
59 def get_genvs_default_buildtype_list() -> list[str]:
60 # just debug, debugoptimized, and release for now
61 # but this should probably be configurable through some extra option, alongside --genvslite.
62 return options.buildtypelist[1:-2]
63
64
65 class MesonVersionMismatchException(MesonException):
66 '''Build directory generated with Meson version is incompatible with current version'''
67 def __init__(self, old_version: str, current_version: str, extra_msg: str = '') -> None:
68 super().__init__(f'Build directory has been generated with Meson version {old_version}, '
69 f'which is incompatible with the current version {current_version}.'
70 + extra_msg)
71 self.old_version = old_version
72 self.current_version = current_version
73
74
75 class DependencyCacheType(enum.Enum):
76
77 OTHER = 0
78 PKG_CONFIG = 1
79 CMAKE = 2
80
81 @classmethod
82 def from_type(cls, dep: 'dependencies.Dependency') -> 'DependencyCacheType':
83 # As more types gain search overrides they'll need to be added here
84 if dep.type_name == 'pkgconfig':
85 return cls.PKG_CONFIG
86 if dep.type_name == 'cmake':
87 return cls.CMAKE
88 return cls.OTHER
89
90
91 class DependencySubCache:
92
93 def __init__(self, type_: DependencyCacheType):
94 self.types = [type_]
95 self.__cache: T.Dict[T.Tuple[str, ...], 'dependencies.Dependency'] = {}
96
97 def __getitem__(self, key: T.Tuple[str, ...]) -> 'dependencies.Dependency':
98 return self.__cache[key]
99
100 def __setitem__(self, key: T.Tuple[str, ...], value: 'dependencies.Dependency') -> None:
101 self.__cache[key] = value
102
103 def __contains__(self, key: T.Tuple[str, ...]) -> bool:
104 return key in self.__cache
105
106 def values(self) -> T.Iterable['dependencies.Dependency']:
107 return self.__cache.values()
108
109
110 class DependencyCache:
111
112 """Class that stores a cache of dependencies.
113
114 This class is meant to encapsulate the fact that we need multiple keys to
115 successfully lookup by providing a simple get/put interface.
116 """
117
118 def __init__(self, builtins: options.OptionStore, for_machine: MachineChoice):
119 self.__cache: T.MutableMapping[TV_DepID, DependencySubCache] = OrderedDict()
120 self.__builtins = builtins
121 self.__pkg_conf_key = options.OptionKey('pkg_config_path', machine=for_machine)
122 self.__cmake_key = options.OptionKey('cmake_prefix_path', machine=for_machine)
123
124 def __calculate_subkey(self, type_: DependencyCacheType) -> T.Tuple[str, ...]:
125 data: T.Dict[DependencyCacheType, T.List[str]] = {
126 DependencyCacheType.PKG_CONFIG: T.cast('T.List[str]', self.__builtins.get_value_for(self.__pkg_conf_key)),
127 DependencyCacheType.CMAKE: T.cast('T.List[str]', self.__builtins.get_value_for(self.__cmake_key)),
128 DependencyCacheType.OTHER: [],
129 }
130 assert type_ in data, 'Someone forgot to update subkey calculations for a new type'
131 return tuple(data[type_])
132
133 def __iter__(self) -> T.Iterator['TV_DepID']:
134 return self.keys()
135
136 def put(self, key: 'TV_DepID', dep: 'dependencies.Dependency') -> None:
137 t = DependencyCacheType.from_type(dep)
138 if key not in self.__cache:
139 self.__cache[key] = DependencySubCache(t)
140 subkey = self.__calculate_subkey(t)
141 self.__cache[key][subkey] = dep
142
143 def get(self, key: 'TV_DepID') -> T.Optional['dependencies.Dependency']:
144 """Get a value from the cache.
145
146 If there is no cache entry then None will be returned.
147 """
148 try:
149 val = self.__cache[key]
150 except KeyError:
151 return None
152
153 for t in val.types:
154 subkey = self.__calculate_subkey(t)
155 try:
156 return val[subkey]
157 except KeyError:
158 pass
159 return None
160
161 def values(self) -> T.Iterator['dependencies.Dependency']:
162 for c in self.__cache.values():
163 yield from c.values()
164
165 def keys(self) -> T.Iterator['TV_DepID']:
166 return iter(self.__cache.keys())
167
168 def items(self) -> T.Iterator[T.Tuple['TV_DepID', T.List['dependencies.Dependency']]]:
169 for k, v in self.__cache.items():
170 vs: T.List[dependencies.Dependency] = []
171 for t in v.types:
172 subkey = self.__calculate_subkey(t)
173 if subkey in v:
174 vs.append(v[subkey])
175 yield k, vs
176
177 def clear(self) -> None:
178 self.__cache.clear()
179
180
181 class CMakeStateCache:
182 """Class that stores internal CMake compiler states.
183
184 This cache is used to reduce the startup overhead of CMake by caching
185 all internal CMake compiler variables.
186 """
187
188 def __init__(self) -> None:
189 self.__cache: T.Dict[str, T.Dict[str, T.List[str]]] = {}
190 self.cmake_cache: T.Dict[str, 'CMakeCacheEntry'] = {}
191
192 def __iter__(self) -> T.Iterator[T.Tuple[str, T.Dict[str, T.List[str]]]]:
193 return iter(self.__cache.items())
194
195 def items(self) -> T.Iterator[T.Tuple[str, T.Dict[str, T.List[str]]]]:
196 return iter(self.__cache.items())
197
198 def update(self, language: str, variables: T.Dict[str, T.List[str]]) -> None:
199 if language not in self.__cache:
200 self.__cache[language] = {}
201 self.__cache[language].update(variables)
202
203 @property
204 def languages(self) -> T.Set[str]:
205 return set(self.__cache.keys())
206
207
208 # Can't bind this near the class method it seems, sadly.
209 _V = T.TypeVar('_V')
210
211 # This class contains all data that must persist over multiple
212 # invocations of Meson. It is roughly the same thing as
213 # cmakecache.
214
215 class CoreData:
216
217 def __init__(self, cmd_options: SharedCMDOptions, scratch_dir: str, meson_command: T.List[str]):
218 self.lang_guids = {
219 'default': '8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942',
220 'c': '8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942',
221 'cpp': '8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942',
222 'masm': '8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942',
223 'test': '3AC096D0-A1C2-E12C-1390-A8335801FDAB',
224 'directory': '2150E333-8FDC-42A3-9474-1A3956D46DE8',
225 }
226 self.test_guid = str(uuid.uuid4()).upper()
227 self.regen_guid = str(uuid.uuid4()).upper()
228 self.install_guid = str(uuid.uuid4()).upper()
229 self.meson_command = meson_command
230 self.target_guids: T.Dict[str, str] = {}
231 self.version = version
232 self.cross_files = self.__load_config_files(cmd_options, scratch_dir, 'cross')
233 self.compilers: PerMachine[CompilerDict] = PerMachine(OrderedDict(), OrderedDict())
234 self.optstore = options.OptionStore(self.is_cross_build())
235
236 # Stores the (name, hash) of the options file, The name will be either
237 # "meson_options.txt" or "meson.options".
238 # This is used by mconf to reload the option file if it's changed.
239 self.options_files: T.Dict[SubProject, T.Optional[T.Tuple[str, str]]] = {}
240
241 # Set of subprojects that have already been initialized once, this is
242 # required to be stored and reloaded with the coredata, as we don't
243 # want to overwrite options for such subprojects.
244 self.initialized_subprojects: T.Set[str] = set()
245
246 # For host == build configurations these caches should be the same.
247 self.deps: PerMachine[DependencyCache] = PerMachineDefaultable.default(
248 self.is_cross_build(),
249 DependencyCache(self.optstore, MachineChoice.BUILD),
250 DependencyCache(self.optstore, MachineChoice.HOST))
251
252 self.compiler_check_cache: T.Dict['CompilerCheckCacheKey', 'CompileResult'] = OrderedDict()
253 self.run_check_cache: T.Dict['RunCheckCacheKey', 'RunResult'] = OrderedDict()
254
255 # CMake cache
256 self.cmake_cache: PerMachine[CMakeStateCache] = PerMachine(CMakeStateCache(), CMakeStateCache())
257
258 # Only to print a warning if it changes between Meson invocations.
259 self.config_files = self.__load_config_files(cmd_options, scratch_dir, 'native')
260 self.builtin_options_libdir_cross_fixup()
261 self.optstore.init_builtins()
262
263 @staticmethod
264 def __load_config_files(cmd_options: SharedCMDOptions, scratch_dir: str, ftype: str) -> T.List[str]:
265 # Need to try and make the passed filenames absolute because when the
266 # files are parsed later we'll have chdir()d.
267 if ftype == 'cross':
268 filenames = cmd_options.cross_file
269 else:
270 filenames = cmd_options.native_file
271
272 if not filenames:
273 return []
274
275 found_invalid: T.List[str] = []
276 missing: T.List[str] = []
277 real: T.List[str] = []
278 for i, f in enumerate(filenames):
279 f = os.path.expanduser(os.path.expandvars(f))
280 if os.path.exists(f):
281 if os.path.isfile(f):
282 real.append(os.path.abspath(f))
283 continue
284 elif os.path.isdir(f):
285 found_invalid.append(os.path.abspath(f))
286 else:
287 # in this case we've been passed some kind of pipe, copy
288 # the contents of that file into the meson private (scratch)
289 # directory so that it can be re-read when wiping/reconfiguring
290 fcopy = os.path.join(scratch_dir, f'{uuid.uuid4()}.{ftype}.ini')
291 with open(f, encoding='utf-8') as rf:
292 with open(fcopy, 'w', encoding='utf-8') as wf:
293 wf.write(rf.read())
294 real.append(fcopy)
295
296 # Also replace the command line argument, as the pipe
297 # probably won't exist on reconfigure
298 filenames[i] = fcopy
299 continue
300 if sys.platform != 'win32':
301 paths = [
302 os.environ.get('XDG_DATA_HOME', os.path.expanduser('~/.local/share')),
303 ] + os.environ.get('XDG_DATA_DIRS', '/usr/local/share:/usr/share').split(':')
304 for path in paths:
305 path_to_try = os.path.join(path, 'meson', ftype, f)
306 if os.path.isfile(path_to_try):
307 real.append(path_to_try)
308 break
309 else:
310 missing.append(f)
311 else:
312 missing.append(f)
313
314 if missing:
315 if found_invalid:
316 mlog.log('Found invalid candidates for', ftype, 'file:', *found_invalid)
317 mlog.log('Could not find any valid candidate for', ftype, 'files:', *missing)
318 raise MesonException(f'Cannot find specified {ftype} file: {f}')
319 return real
320
321 def builtin_options_libdir_cross_fixup(self) -> None:
322 # By default set libdir to "lib" when cross compiling since
323 # getting the "system default" is always wrong on multiarch
324 # platforms as it gets a value like lib/x86_64-linux-gnu.
325 if self.cross_files:
326 options.BUILTIN_OPTIONS[OptionKey('libdir')].default = 'lib'
327
328 def init_backend_options(self, backend_name: str) -> None:
329 if backend_name == 'ninja':
330 self.optstore.add_system_option('backend_max_links', options.UserIntegerOption(
331 'backend_max_links',
332 'Maximum number of linker processes to run or 0 for no '
333 'limit',
334 0,
335 min_value=0))
336 elif backend_name.startswith('vs'):
337 self.optstore.add_system_option('backend_startup_project', options.UserStringOption(
338 'backend_startup_project',
339 'Default project to execute in Visual Studio',
340 ''))
341
342 def get_option_for_target(self, target: 'BuildTarget', key: T.Union[str, OptionKey]) -> ElementaryOptionValues:
343 if isinstance(key, str):
344 assert ':' not in key
345 newkey = OptionKey(key, target.subproject)
346 else:
347 newkey = key
348 if newkey.subproject != target.subproject:
349 # FIXME: this should be an error. The caller needs to ensure that
350 # key and target have the same subproject for consistency.
351 # Now just do this to get things going.
352 newkey = newkey.evolve(subproject=target.subproject)
353 if self.is_cross_build():
354 newkey = newkey.evolve(machine=target.for_machine)
355 option_object, value = self.optstore.get_option_and_value_for(newkey)
356 override = target.get_override(newkey.name)
357 if override is not None:
358 try:
359 return option_object.validate_value(override)
360 except MesonException as e:
361 raise MesonException(f'In override_options for {target}: {e!s}')
362 return value
363
364 def set_from_configure_command(self, options: SharedCMDOptions) -> bool:
365 return self.optstore.set_from_configure_command(options.cmd_line_options)
366
367 def clear_cache(self) -> None:
368 self.deps.host.clear()
369 self.deps.build.clear()
370 self.compiler_check_cache.clear()
371 self.run_check_cache.clear()
372
373 def get_nondefault_buildtype_args(self) -> T.List[T.Union[T.Tuple[str, str, str], T.Tuple[str, bool, bool]]]:
374 result: T.List[T.Union[T.Tuple[str, str, str], T.Tuple[str, bool, bool]]] = []
375 value = self.optstore.get_value_for('buildtype')
376 if value == 'plain':
377 opt = 'plain'
378 debug = False
379 elif value == 'debug':
380 opt = '0'
381 debug = True
382 elif value == 'debugoptimized':
383 opt = '2'
384 debug = True
385 elif value == 'release':
386 opt = '3'
387 debug = False
388 elif value == 'minsize':
389 opt = 's'
390 debug = True
391 else:
392 assert value == 'custom'
393 return []
394 actual_opt = self.optstore.get_value_for('optimization')
395 actual_debug = self.optstore.get_value_for('debug')
396 assert isinstance(actual_opt, str) # for mypy
397 assert isinstance(actual_debug, bool) # for mypy
398 if actual_opt != opt:
399 result.append(('optimization', actual_opt, opt))
400 if actual_debug != debug:
401 result.append(('debug', actual_debug, debug))
402 return result
403
404 def get_external_args(self, for_machine: MachineChoice, lang: str) -> T.List[str]:
405 # mypy cannot analyze type of OptionKey
406 key = OptionKey(f'{lang}_args', machine=for_machine)
407 return T.cast('T.List[str]', self.optstore.get_value_for(key))
408
409 @lru_cache(maxsize=None)
410 def get_external_link_args(self, for_machine: MachineChoice, lang: str) -> T.List[str]:
411 # mypy cannot analyze type of OptionKey
412 linkkey = OptionKey(f'{lang}_link_args', machine=for_machine)
413 return T.cast('T.List[str]', self.optstore.get_value_for(linkkey))
414
415 def is_cross_build(self, when_building_for: MachineChoice = MachineChoice.HOST) -> bool:
416 if when_building_for == MachineChoice.BUILD:
417 return False
418 return len(self.cross_files) > 0
419
420 def add_compiler_options(self, c_options: MutableKeyedOptionDictType, lang: Language, for_machine: MachineChoice,
421 subproject: str) -> None:
422 for k, o in c_options.items():
423 assert k.subproject is None and k.machine is for_machine
424 if subproject:
425 k = k.evolve(subproject=subproject)
426 if lang == 'objc' and k.name == 'c_std':
427 # For objective C, always fall back to c_std.
428 self.optstore.add_compiler_option('c', k, o)
429 elif lang == 'objcpp' and k.name == 'cpp_std':
430 self.optstore.add_compiler_option('cpp', k, o)
431 else:
432 self.optstore.add_compiler_option(lang, k, o)
433
434 def process_compiler_options(self, lang: Language, comp: Compiler, subproject: str) -> None:
435 self.add_compiler_options(comp.get_options(), lang, comp.for_machine, subproject)
436
437 for key in [OptionKey(f'{lang}_args'), OptionKey(f'{lang}_link_args')]:
438 if self.is_cross_build():
439 key = key.evolve(machine=comp.for_machine)
440 # the global option is already there, but any augment is still
441 # sitting in pending_options has to be taken into account
442 assert key in self.optstore
443 if subproject:
444 skey = key.evolve(subproject=subproject)
445 self.optstore.add_compiler_option(lang, skey, self.optstore.get_value_object(key))
446
447 for key in comp.base_options:
448 if subproject:
449 skey = key.evolve(subproject=subproject)
450 else:
451 skey = key
452 if skey not in self.optstore:
453 self.optstore.add_system_option(skey, copy.deepcopy(options.COMPILER_BASE_OPTIONS[key]))
454
455 comp.init_from_options()
456
457 self.emit_base_options_warnings()
458
459 def emit_base_options_warnings(self) -> None:
460 bcodekey = OptionKey('b_bitcode')
461 if bcodekey in self.optstore and self.optstore.get_value_for(bcodekey):
462 msg = textwrap.dedent('''Base option 'b_bitcode' is enabled, which is incompatible with many linker options.
463 Incompatible options such as \'b_asneeded\' have been disabled.'
464 Please see https://mesonbuild.com/Builtin-options.html#Notes_about_Apple_Bitcode_support for more details.''')
465 mlog.warning(msg, once=True, fatal=False)
466
467
468 def major_versions_differ(v1: str, v2: str) -> bool:
469 v1_major, v1_minor = v1.rsplit('.', 1)
470 v2_major, v2_minor = v2.rsplit('.', 1)
471 # Major version differ, or one is development version but not the other.
472 return v1_major != v2_major or ('99' in {v1_minor, v2_minor} and v1_minor != v2_minor)
473
474 def load(build_dir: str, suggest_reconfigure: bool = True) -> CoreData:
475 filename = os.path.join(build_dir, 'meson-private', 'coredata.dat')
476 return pickle_load(filename, 'Coredata', CoreData, suggest_reconfigure)
477
478
479 def save(obj: CoreData, build_dir: str) -> str:
480 filename = os.path.join(build_dir, 'meson-private', 'coredata.dat')
481 prev_filename = filename + '.prev'
482 tempfilename = filename + '~'
483 if major_versions_differ(obj.version, version):
484 raise MesonException('Fatal version mismatch corruption.')
485 if os.path.exists(filename):
486 import shutil
487 shutil.copyfile(filename, prev_filename)
488 with open(tempfilename, 'wb') as f:
489 pickle.dump(obj, f)
490 f.flush()
491 os.fsync(f.fileno())
492 os.replace(tempfilename, filename)
493 return filename
494
495
496 FORBIDDEN_TARGET_NAMES = frozenset({
497 'clean',
498 'clean-ctlist',
499 'clean-gcno',
500 'clean-gcda',
501 'coverage',
502 'coverage-text',
503 'coverage-xml',
504 'coverage-html',
505 'phony',
506 'PHONY',
507 'all',
508 'test',
509 'benchmark',
510 'install',
511 'uninstall',
512 'build.ninja',
513 'scan-build',
514 'reconfigure',
515 'dist',
516 'distcheck',
517 })