Debian Codegraph @

mesonbuild/msetup.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2016-2018 The Meson development team
3 # Copyright © 2023-2025 Intel Corporation
4
5 from __future__ import annotations
6
7 import argparse, datetime, glob, json, os, platform, shutil, sys, tempfile, time
8 import cProfile as profile
9 from pathlib import Path
10 import typing as T
11
12 from . import build, cmdline, coredata, environment, interpreter, mesonlib, mintro, mlog
13 from .dependencies import Dependency
14 from .mesonlib import MesonException, MachineChoice
15 from .interpreterbase import ObjectHolder
16 from .options import OptionKey
17
18 if T.TYPE_CHECKING:
19 from typing_extensions import Protocol
20 from .cmdline import SharedCMDOptions
21 from .interpreter import SubprojectHolder
22 from .mesonlib import PerMachine
23
24 class CMDOptions(SharedCMDOptions, Protocol):
25
26 profile: bool
27 fatal_warnings: bool
28 reconfigure: bool
29 wipe: bool
30 clearcache: bool
31 builddir: str
32 sourcedir: str
33 pager: bool
34
35 git_ignore_file = '''# This file is autogenerated by Meson. If you change or delete it, it won't be recreated.
36 *
37 '''
38
39 hg_ignore_file = '''# This file is autogenerated by Meson. If you change or delete it, it won't be recreated.
40 syntax: glob
41 **/*
42 '''
43
44 cachedir_tag_file = '''Signature: 8a477f597d28d172789f06886806bc55
45 # This file is a cache directory tag created by meson.
46 # For information about cache directory tags, see http://bford.info/cachedir/
47 '''
48
49
50 # Note: when adding arguments, please also add them to the completion
51 # scripts in $MESONSRC/data/shell-completions/
52 def add_arguments(parser: argparse.ArgumentParser) -> None:
53 cmdline.register_builtin_arguments(parser)
54 parser.add_argument('--native-file',
55 default=[],
56 action='append',
57 help='File containing overrides for native compilation environment.')
58 parser.add_argument('--cross-file',
59 default=[],
60 action='append',
61 help='File describing cross compilation environment.')
62 parser.add_argument('-v', '--version', action='version',
63 version=coredata.version)
64 parser.add_argument('--profile-self', action='store_true', dest='profile',
65 help=argparse.SUPPRESS)
66 parser.add_argument('--fatal-meson-warnings', action='store_true', dest='fatal_warnings',
67 help='Make all Meson warnings fatal')
68 parser.add_argument('--reconfigure', action='store_true',
69 help='Set options and reconfigure the project. Useful when new ' +
70 'options have been added to the project and the default value ' +
71 'is not working.')
72 parser.add_argument('--wipe', action='store_true',
73 help='Wipe build directory and reconfigure using previous command line options. ' +
74 'Useful when build directory got corrupted, or when rebuilding with a ' +
75 'newer version of meson.')
76 parser.add_argument('--clearcache', action='store_true', default=False,
77 help='Clear cached state (e.g. found dependencies). Since 1.3.0.')
78 parser.add_argument('builddir', nargs='?', default=None)
79 parser.add_argument('sourcedir', nargs='?', default=None)
80
81 class MesonApp:
82 def __init__(self, options: CMDOptions) -> None:
83 self.options = options
84 (self.source_dir, self.build_dir) = self.validate_dirs()
85 if options.wipe:
86 # Make a copy of the cmd line file to make sure we can always
87 # restore that file if anything bad happens. For example if
88 # configuration fails we need to be able to wipe again.
89 restore = []
90 with tempfile.TemporaryDirectory() as d:
91 for filename in [cmdline.get_cmd_line_file(self.build_dir)] + glob.glob(os.path.join(self.build_dir, environment.Environment.private_dir, '*.ini')):
92 try:
93 restore.append((shutil.copy(filename, d), filename))
94 except FileNotFoundError:
95 # validate_dirs() already verified that build_dir has
96 # a partial build or is empty.
97 pass
98
99 cmdline.read_cmd_line_file(self.build_dir, options)
100
101 try:
102 # Don't delete the whole tree, just all of the files and
103 # folders in the tree. Otherwise calling wipe form the builddir
104 # will cause a crash
105 for l in os.listdir(self.build_dir):
106 l = os.path.join(self.build_dir, l)
107 if os.path.isdir(l) and not os.path.islink(l):
108 mesonlib.windows_proof_rmtree(l)
109 else:
110 mesonlib.windows_proof_rm(l)
111 finally:
112 self.add_ignore_files(self.build_dir)
113 for b, f in restore:
114 os.makedirs(os.path.dirname(f), exist_ok=True)
115 shutil.move(b, f)
116
117 def has_build_file(self, dirname: str) -> bool:
118 fname = os.path.join(dirname, environment.build_filename)
119 return os.path.exists(fname)
120
121 def validate_core_dirs(self, dir1: T.Optional[str], dir2: T.Optional[str]) -> T.Tuple[str, str]:
122 invalid_msg_prefix = f'Neither directory {dir1!r} nor directory {dir2!r}'
123 if dir1 is None:
124 if dir2 is None:
125 if not self.has_build_file('.') and self.has_build_file('..'):
126 dir2 = '..'
127 else:
128 raise MesonException('Must specify at least one directory name.')
129 dir1 = os.getcwd()
130 if dir2 is None:
131 dir2 = os.getcwd()
132 ndir1 = os.path.abspath(os.path.realpath(dir1))
133 ndir2 = os.path.abspath(os.path.realpath(dir2))
134 if not os.path.exists(ndir1) and not os.path.exists(ndir2):
135 raise MesonException(f'{invalid_msg_prefix} exist.')
136 try:
137 os.makedirs(ndir1, exist_ok=True)
138 except FileExistsError as e:
139 raise MesonException(f'{dir1} is not a directory') from e
140 try:
141 os.makedirs(ndir2, exist_ok=True)
142 except FileExistsError as e:
143 raise MesonException(f'{dir2} is not a directory') from e
144 if os.path.samefile(ndir1, ndir2):
145 # Fallback to textual compare if undefined entries found
146 has_undefined = any((s.st_ino == 0 and s.st_dev == 0) for s in (os.stat(ndir1), os.stat(ndir2)))
147 if not has_undefined or ndir1 == ndir2:
148 raise MesonException('Source and build directories must not be the same. Create a pristine build directory.')
149 if self.has_build_file(ndir1):
150 if self.has_build_file(ndir2):
151 raise MesonException(f'Both directories contain a build file {environment.build_filename}.')
152 return ndir1, ndir2
153 if self.has_build_file(ndir2):
154 return ndir2, ndir1
155 raise MesonException(f'{invalid_msg_prefix} contain a build file {environment.build_filename}.')
156
157 def add_ignore_files(self, build_dir: str) -> None:
158 with open(os.path.join(build_dir, '.gitignore'), 'w', encoding='utf-8') as ofile:
159 ofile.write(git_ignore_file)
160 with open(os.path.join(build_dir, '.hgignore'), 'w', encoding='utf-8') as ofile:
161 ofile.write(hg_ignore_file)
162 with open(os.path.join(build_dir, 'CACHEDIR.TAG'), 'w', encoding='utf-8') as ofile:
163 ofile.write(cachedir_tag_file)
164
165 def validate_dirs(self) -> T.Tuple[str, str]:
166 (src_dir, build_dir) = self.validate_core_dirs(self.options.builddir, self.options.sourcedir)
167 if Path(build_dir) in Path(src_dir).parents:
168 raise MesonException(f'Build directory {build_dir} cannot be a parent of source directory {src_dir}')
169 if not os.listdir(build_dir):
170 self.add_ignore_files(build_dir)
171 return src_dir, build_dir
172 priv_dir = os.path.join(build_dir, 'meson-private')
173 has_valid_build = os.path.exists(os.path.join(priv_dir, 'coredata.dat'))
174 has_partial_build = os.path.isdir(priv_dir)
175 if has_valid_build:
176 if not self.options.reconfigure and not self.options.wipe:
177 print('Directory already configured.\n\n'
178 'Just run your build command (e.g. ninja) and Meson will regenerate as necessary.\n'
179 'Run "meson setup --reconfigure" to force Meson to regenerate.\n\n'
180 'If build failures persist, run "meson setup --wipe" to rebuild from scratch\n'
181 'using the same options as passed when configuring the build.')
182 if self.options.cmd_line_options:
183 from . import mconf
184 raise SystemExit(mconf.run_impl(self.options, build_dir))
185 raise SystemExit(0)
186 elif not has_partial_build and self.options.wipe:
187 raise MesonException(f'Directory is not empty and does not contain a previous build:\n{build_dir}')
188 return src_dir, build_dir
189
190 # See class Backend's 'generate' for comments on capture args and returned dictionary.
191 def generate(self, capture: bool = False, vslite_ctx: T.Optional[dict] = None) -> T.Optional[dict]:
192 env = environment.Environment(self.source_dir, self.build_dir, self.options)
193 if not env.first_invocation:
194 assert self.options.reconfigure
195 env.coredata.set_from_configure_command(self.options)
196 mlog.initialize(env.get_log_dir(), self.options.fatal_warnings)
197 if self.options.profile:
198 mlog.set_timestamp_start(time.monotonic())
199 if self.options.clearcache:
200 env.coredata.clear_cache()
201 with mesonlib.DirectoryLock(self.build_dir, 'meson-private/meson.lock',
202 mesonlib.DirectoryLockAction.FAIL,
203 'Some other Meson process is already using this build directory. Exiting.'):
204 return self._generate(env, capture, vslite_ctx)
205
206 def check_unused_options(self, coredata: 'coredata.CoreData', cmd_line_options: T.Dict[OptionKey, str],
207 all_subprojects: PerMachine[T.Dict[str, SubprojectHolder]]) -> None:
208 errlist: T.List[str] = []
209 known_subprojects: T.Set[str] = set()
210 for m in MachineChoice:
211 known_subprojects.update((name for name, obj in all_subprojects[m].items() if obj.found()))
212 for opt in cmd_line_options:
213 # Accept options that exist or could appear in subsequent reconfigurations,
214 # including options for subprojects that were not used
215 if opt in coredata.optstore or \
216 opt.evolve(subproject=None) in coredata.optstore or \
217 coredata.optstore.accept_as_pending_option(opt):
218 continue
219 if opt.subproject and opt.subproject not in known_subprojects:
220 continue
221 # "foo=true" may also refer to toplevel project option ":foo"
222 if opt.subproject is None and coredata.optstore.is_project_option(opt.as_root()):
223 continue
224 errlist.append(f'"{opt}"')
225 if errlist:
226 errstr = ', '.join(errlist)
227 raise MesonException(f'Unknown options: {errstr}')
228
229 def _generate(self, env: environment.Environment, capture: bool, vslite_ctx: T.Optional[dict]) -> T.Optional[dict]:
230 # Get all user defined options, including options that have been defined
231 # during a previous invocation or using meson configure.
232 user_defined_options = T.cast('CMDOptions', argparse.Namespace(**vars(self.options)))
233 cmdline.read_cmd_line_file(self.build_dir, user_defined_options)
234
235 mlog.debug('Build started at', datetime.datetime.now().isoformat())
236 mlog.debug('Main binary:', sys.executable)
237 mlog.debug('Build Options:', cmdline.format_cmd_line_options(user_defined_options))
238 mlog.debug('Python system:', platform.system())
239 mlog.log(mlog.bold('The Meson build system'))
240 mlog.log('Version:', coredata.version)
241 mlog.log('Source dir:', mlog.bold(self.source_dir))
242 mlog.log('Build dir:', mlog.bold(self.build_dir))
243 if env.is_cross_build():
244 mlog.log('Build type:', mlog.bold('cross build'))
245 else:
246 mlog.log('Build type:', mlog.bold('native build'))
247 b = build.Build(env)
248
249 intr = interpreter.Interpreter(b, user_defined_options=user_defined_options)
250 # Super hack because mlog.log and mlog.debug have different signatures,
251 # and there is currently no way to annotate them correctly, unionize them, or
252 # even to write `T.Callable[[*mlog.TV_Loggable], None]`
253 logger_fun = T.cast('T.Callable[[mlog.TV_Loggable, mlog.TV_Loggable], None]',
254 (mlog.log if env.is_cross_build() else mlog.debug))
255 logger_fun('Build machine cpu family:', mlog.bold(env.machines.build.cpu_family))
256 logger_fun('Build machine cpu:', mlog.bold(env.machines.build.cpu))
257 mlog.log('Host machine cpu family:', mlog.bold(env.machines.host.cpu_family))
258 mlog.log('Host machine cpu:', mlog.bold(env.machines.host.cpu))
259 logger_fun('Target machine cpu family:', mlog.bold(env.machines.target.cpu_family))
260 logger_fun('Target machine cpu:', mlog.bold(env.machines.target.cpu))
261 try:
262 if self.options.profile:
263 fname = os.path.join(self.build_dir, 'meson-logs', 'profile-interpreter.log')
264 profile.runctx('intr.run()', globals(), locals(), filename=fname)
265 else:
266 intr.run()
267 except Exception as e:
268 mintro.write_meson_info_file(b, [e])
269 raise
270
271 cdf: T.Optional[str] = None
272 captured_compile_args: T.Optional[dict] = None
273 try:
274 dumpfile = os.path.join(env.get_scratch_dir(), 'build.dat')
275 # We would like to write coredata as late as possible since we use the existence of
276 # this file to check if we generated the build file successfully. Since coredata
277 # includes settings, the build files must depend on it and appear newer. However, due
278 # to various kernel caches, we cannot guarantee that any time in Python is exactly in
279 # sync with the time that gets applied to any files. Thus, we dump this file as late as
280 # possible, but before build files, and if any error occurs, delete it.
281 cdf = env.dump_coredata()
282
283 self.finalize_postconf_hooks(b, intr)
284 self.check_unused_options(env.coredata,
285 intr.user_defined_options.cmd_line_options,
286 intr.subprojects)
287 if self.options.profile:
288 localvars = locals()
289 fname = f'profile-{intr.backend.name}-backend.log'
290 fname = os.path.join(self.build_dir, 'meson-logs', fname)
291 profile.runctx('gen_result = intr.backend.generate(capture, vslite_ctx)', globals(), localvars, filename=fname)
292 captured_compile_args = localvars['gen_result']
293 assert captured_compile_args is None or isinstance(captured_compile_args, dict)
294 else:
295 captured_compile_args = intr.backend.generate(capture, vslite_ctx)
296
297 build.save(b, dumpfile)
298 if env.first_invocation:
299 # Use path resolved by coredata because they could have been
300 # read from a pipe and wrote into a private file.
301 self.options.cross_file = env.coredata.cross_files
302 self.options.native_file = env.coredata.config_files
303 cmdline.write_cmd_line_file(self.build_dir, self.options)
304 else:
305 cmdline.update_cmd_line_file(self.build_dir, self.options)
306
307 # Generate an IDE introspection file with the same syntax as the already existing API
308 if self.options.profile:
309 fname = os.path.join(self.build_dir, 'meson-logs', 'profile-introspector.log')
310 profile.runctx('mintro.generate_introspection_file(b, intr.backend)', globals(), locals(), filename=fname)
311 else:
312 mintro.generate_introspection_file(b, intr.backend)
313 mintro.write_meson_info_file(b, [], True)
314
315 # Post-conf scripts must be run after writing coredata or else introspection fails.
316 intr.backend.run_postconf_scripts()
317
318 # collect warnings about unsupported build configurations; must be done after full arg processing
319 # by Interpreter() init, but this is most visible at the end
320 if env.coredata.optstore.get_value_for('backend') == 'xcode':
321 mlog.warning('xcode backend is currently unmaintained, patches welcome')
322 if env.coredata.optstore.get_value_for('layout') == 'flat':
323 mlog.warning('-Dlayout=flat is unsupported and probably broken. It was a failed experiment at '
324 'making Windows build artifacts runnable while uninstalled, due to PATH considerations, '
325 'but was untested by CI and anyways breaks reasonable use of conflicting targets in different subdirs. '
326 'Please consider using `meson devenv` instead. See https://github.com/mesonbuild/meson/pull/9243 '
327 'for details.')
328
329 if self.options.profile:
330 fname = os.path.join(self.build_dir, 'meson-logs', 'profile-startup-modules.json')
331 mods = set(sys.modules.keys())
332 mesonmods = {mod for mod in mods if (mod+'.').startswith('mesonbuild.')}
333 stdmods = sorted(mods - mesonmods)
334 data = {'stdlib': {'modules': stdmods, 'count': len(stdmods)}, 'meson': {'modules': sorted(mesonmods), 'count': len(mesonmods)}}
335 with open(fname, 'w', encoding='utf-8') as f:
336 json.dump(data, f)
337
338 mlog.log("meson setup completed") # Display timestamp
339
340 except Exception as e:
341 mintro.write_meson_info_file(b, [e])
342 if cdf is not None:
343 old_cdf = cdf + '.prev'
344 if os.path.exists(old_cdf):
345 os.replace(old_cdf, cdf)
346 else:
347 os.unlink(cdf)
348 raise
349
350 return captured_compile_args
351
352 def finalize_postconf_hooks(self, b: build.Build, intr: interpreter.Interpreter) -> None:
353 for varname, holder in intr.variables.items():
354 if isinstance(holder, ObjectHolder):
355 d = holder.held_object
356 if isinstance(d, Dependency) and d.found():
357 d.meson_variables.append(varname)
358
359 b.devenv.append(intr.backend.get_devenv())
360 for mod in intr.modules.values():
361 mod.postconf_hook(b)
362 b.def_files = intr.get_build_def_files()
363
364 def run_genvslite_setup(options: CMDOptions) -> None:
365 # With --genvslite, we essentially want to invoke multiple 'setup' iterations. I.e. -
366 # meson setup ... builddirprefix_debug
367 # meson setup ... builddirprefix_debugoptimized
368 # meson setup ... builddirprefix_release
369 # along with also setting up a new, thin/lite visual studio solution and projects with the multiple debug/opt/release configurations that
370 # invoke the appropriate 'meson compile ...' build commands upon the normal visual studio build/rebuild/clean actions, instead of using
371 # the native VS/msbuild system.
372 builddir_prefix = options.builddir
373 k_genvslite = OptionKey('genvslite')
374 genvsliteval = options.cmd_line_options.pop(k_genvslite)
375 # The command line may specify a '--backend' option, which doesn't make sense in conjunction with
376 # '--genvslite', where we always want to use a ninja back end -
377 k_backend = OptionKey('backend')
378 if k_backend in options.cmd_line_options:
379 if options.cmd_line_options[k_backend] != 'ninja':
380 raise MesonException('Explicitly specifying a backend option with \'genvslite\' is not necessary '
381 '(the ninja backend is always used) but specifying a non-ninja backend '
382 'conflicts with a \'genvslite\' setup')
383 else:
384 options.cmd_line_options[k_backend] = 'ninja'
385 buildtypes_list = coredata.get_genvs_default_buildtype_list()
386 vslite_ctx = {}
387
388 for buildtypestr in buildtypes_list:
389 options.builddir = f'{builddir_prefix}_{buildtypestr}' # E.g. builddir_release
390 options.cmd_line_options[OptionKey('buildtype')] = buildtypestr
391 app = MesonApp(options)
392 vslite_ctx[buildtypestr] = app.generate(capture=True)
393 #Now for generating the 'lite' solution and project files, which will use these builds we've just set up, above.
394 options.builddir = f'{builddir_prefix}_vs'
395 options.cmd_line_options[k_genvslite] = genvsliteval
396 app = MesonApp(options)
397 app.generate(capture=False, vslite_ctx=vslite_ctx)
398
399 def run(options: T.Union[CMDOptions, T.List[str]]) -> int:
400 if isinstance(options, list):
401 parser = argparse.ArgumentParser()
402 add_arguments(parser)
403 options = T.cast('CMDOptions', parser.parse_args(options))
404 cmdline.parse_cmd_line_options(options)
405
406 # Msetup doesn't actually use this option, but we pass msetup options to
407 # mconf, and it does. We won't actually hit the path that uses it, but don't
408 # lie
409 options.pager = False
410
411 if OptionKey('genvslite') in options.cmd_line_options:
412 run_genvslite_setup(options)
413 else:
414 app = MesonApp(options)
415 app.generate()
416
417 return 0