Debian Codegraph @

mesonbuild/backend/vs2010backend.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright 2014-2016 The Meson development team
3 # Copyright © 2023-2024 Intel Corporation
4
5 from __future__ import annotations
6 import copy
7 import itertools
8 import os
9 import xml.dom.minidom
10 import xml.etree.ElementTree as ET
11 import uuid
12 import typing as T
13 from pathlib import Path, PurePath, PureWindowsPath
14 import re
15 from collections import Counter
16
17 from . import backends
18 from .. import build
19 from .. import mlog
20 from .. import compilers
21 from .. import mesonlib
22 from .. import programs
23 from ..mesonlib import (
24 File, MesonBugException, MesonException, replace_if_different, version_compare, MachineChoice
25 )
26 from ..options import OptionKey
27 from ..environment import Environment, build_filename
28 from .. import coredata
29
30 if T.TYPE_CHECKING:
31 from typing_extensions import TypeAlias
32
33 from ..arglist import CompilerArgs
34 from ..compilers.compilers import Language
35
36 Project = T.Tuple[str, PurePath, str, MachineChoice]
37 FileLike = T.TypeVar('FileLike', bound=File | str)
38 _VSLITE_CTX: TypeAlias = dict[str, dict[str, dict[Language, list[str]]]]
39
40 def autodetect_vs_version(build: T.Optional[build.Build]) -> backends.Backend:
41 vs_version = os.getenv('VisualStudioVersion', None)
42 vs_install_dir = os.getenv('VSINSTALLDIR', None)
43 if not vs_install_dir:
44 raise MesonException('Could not detect Visual Studio: Environment variable VSINSTALLDIR is not set!\n'
45 'Are you running meson from the Visual Studio Developer Command Prompt?')
46 # VisualStudioVersion is set since Visual Studio 11.0, but sometimes
47 # vcvarsall.bat doesn't set it, so also use VSINSTALLDIR
48 if vs_version == '11.0' or 'Visual Studio 11' in vs_install_dir:
49 from mesonbuild.backend.vs2012backend import Vs2012Backend
50 return Vs2012Backend(build)
51 if vs_version == '12.0' or 'Visual Studio 12' in vs_install_dir:
52 from mesonbuild.backend.vs2013backend import Vs2013Backend
53 return Vs2013Backend(build)
54 if vs_version == '14.0' or 'Visual Studio 14' in vs_install_dir:
55 from mesonbuild.backend.vs2015backend import Vs2015Backend
56 return Vs2015Backend(build)
57 if vs_version == '15.0' or 'Visual Studio 17' in vs_install_dir or \
58 'Visual Studio\\2017' in vs_install_dir:
59 from mesonbuild.backend.vs2017backend import Vs2017Backend
60 return Vs2017Backend(build)
61 if vs_version == '16.0' or 'Visual Studio 19' in vs_install_dir or \
62 'Visual Studio\\2019' in vs_install_dir:
63 from mesonbuild.backend.vs2019backend import Vs2019Backend
64 return Vs2019Backend(build)
65 if vs_version == '17.0' or 'Visual Studio 22' in vs_install_dir or \
66 'Visual Studio\\2022' in vs_install_dir:
67 from mesonbuild.backend.vs2022backend import Vs2022Backend
68 return Vs2022Backend(build)
69 if vs_version == '18.0' or 'Visual Studio 26' in vs_install_dir or \
70 'Visual Studio\\2026' in vs_install_dir:
71 from mesonbuild.backend.vs2026backend import Vs2026Backend
72 return Vs2026Backend(build)
73 if 'Visual Studio 10.0' in vs_install_dir:
74 return Vs2010Backend(build)
75 raise MesonException('Could not detect Visual Studio using VisualStudioVersion: {!r} or VSINSTALLDIR: {!r}!\n'
76 'Please specify the exact backend to use.'.format(vs_version, vs_install_dir))
77
78
79 def split_o_flags_args(args: T.List[str]) -> T.List[str]:
80 """
81 Splits any /O args and returns them. Does not take care of flags overriding
82 previous ones. Skips non-O flag arguments.
83
84 ['/Ox', '/Ob1'] returns ['/Ox', '/Ob1']
85 ['/Oxj', '/MP'] returns ['/Ox', '/Oj']
86 """
87 o_flags = []
88 for arg in args:
89 if not arg.startswith('/O'):
90 continue
91 flags = list(arg[2:])
92 # Assume that this one can't be clumped with the others since it takes
93 # an argument itself
94 if 'b' in flags:
95 o_flags.append(arg)
96 else:
97 o_flags += ['/O' + f for f in flags]
98 return o_flags
99
100 def generate_guid_from_path(path: str | os.PathLike[str], path_type: str) -> str:
101 return str(uuid.uuid5(uuid.NAMESPACE_URL, 'meson-vs-' + path_type + ':' + str(path))).upper()
102
103 def detect_microsoft_gdk(platform: str) -> bool:
104 return re.match(r'Gaming\.(Desktop|Xbox.XboxOne|Xbox.Scarlett)\.x64', platform, re.IGNORECASE) is not None
105
106 def filtered_src_langs_generator(sources: T.List[str]) -> T.Iterable[Language]:
107 for src in sources:
108 ext = src.split('.')[-1]
109 if compilers.compilers.is_source_suffix(ext):
110 yield compilers.compilers.SUFFIX_TO_LANG[ext]
111
112 # Returns the source language (i.e. a key from 'lang_suffixes') of the most frequent source language in the given
113 # list of sources.
114 # We choose the most frequent language as 'primary' because it means the most sources in a target/project can
115 # simply refer to the project's shared intellisense define and include fields, rather than have to fill out their
116 # own duplicate full set of defines/includes/opts intellisense fields. All of which helps keep the vcxproj file
117 # size down.
118 def get_primary_source_lang(target_sources: T.List[File], custom_sources: T.List[str]) -> T.Optional[Language]:
119 lang_counts: Counter[Language] = Counter([compilers.compilers.SUFFIX_TO_LANG[src.suffix] for src in target_sources if compilers.compilers.is_source_suffix(src.suffix)])
120 lang_counts += Counter(filtered_src_langs_generator(custom_sources))
121 most_common_lang_list = lang_counts.most_common(1)
122 # It may be possible that we have a target with no actual src files of interest (e.g. a generator target),
123 # leaving us with an empty list, which we should handle -
124 return most_common_lang_list[0][0] if most_common_lang_list else None
125
126 # Returns a dictionary (by [src type][build type]) that contains a tuple of -
127 # (pre-processor defines, include paths, additional compiler options)
128 # fields to use to fill in the respective intellisense fields of sources that can't simply
129 # reference and re-use the shared 'primary' language intellisense fields of the vcxproj.
130 def get_non_primary_lang_intellisense_fields(vslite_ctx: _VSLITE_CTX,
131 target_id: str,
132 primary_src_lang: Language
133 ) -> T.Dict[str, T.Dict[str, T.Tuple[str, str, str]]]:
134 defs_paths_opts_per_lang_and_buildtype: dict[str, dict[str, tuple[str, str, str]]] = {}
135 for buildtype in coredata.get_genvs_default_buildtype_list():
136 captured_build_args = vslite_ctx[buildtype][target_id] # Results in a 'Src types to compile args' dict
137 non_primary_build_args_per_src_lang = [(lang, build_args) for lang, build_args in captured_build_args.items() if lang != primary_src_lang] # Only need to individually populate intellisense fields for sources of non-primary types.
138 for src_lang, args_list in non_primary_build_args_per_src_lang:
139 if src_lang not in defs_paths_opts_per_lang_and_buildtype:
140 defs_paths_opts_per_lang_and_buildtype[src_lang] = {}
141 defs_paths_opts_per_lang_and_buildtype[src_lang][buildtype] = Vs2010Backend._extract_nmake_fields(args_list)
142 return defs_paths_opts_per_lang_and_buildtype
143
144 class Vs2010Backend(backends.Backend):
145
146 name = 'vs2010'
147
148 def __init__(self, build: T.Optional[build.Build], gen_lite: bool = False):
149 super().__init__(build)
150 self.project_file_version = '10.0.30319.1'
151 self.sln_file_version = '11.00'
152 self.sln_version_comment = '2010'
153 self.platform_toolset: str | None = None
154 self.vs_version = '2010'
155 self.windows_target_platform_version: str | None = None
156 self.subdirs: dict[PurePath, tuple[str, str | None]] = {}
157 self.handled_target_deps: dict[str, list[str]] = {}
158 self.gen_lite = gen_lite # Synonymous with generating the simpler makefile-style multi-config projects that invoke 'meson compile' builds, avoiding native MSBuild complications
159
160 def detect_toolset(self) -> None:
161 pass
162
163 def get_target_private_dir(self, target: build.AnyTargetType) -> str:
164 return os.path.join(self.get_target_dir(target), target.get_id())
165
166 def generate_genlist_for_target(
167 self, genlist: build.GeneratedTypes,
168 target: build.BuildTarget | build.CustomTarget,
169 parent_node: ET.Element,
170 generator_output_files: T.List[str],
171 custom_target_include_dirs: T.List[str],
172 custom_target_output_files: T.List[str]) -> None:
173 if isinstance(genlist, build.GeneratedList):
174 for x in genlist.depends:
175 self.generate_genlist_for_target(x, target, parent_node, [], [], [])
176 target_private_dir = self.relpath(self.get_target_private_dir(target), self.get_target_dir(target))
177 down = self.target_to_build_root(target)
178 if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)):
179 for i in genlist.get_outputs():
180 # Path to the generated source from the current vcxproj dir via the build root
181 ipath = os.path.join(down, self.get_target_dir(genlist), i)
182 custom_target_output_files.append(ipath)
183 idir = self.relpath(self.get_target_dir(genlist), self.get_target_dir(target))
184 if idir not in custom_target_include_dirs:
185 custom_target_include_dirs.append(idir)
186 else:
187 generator = genlist.get_generator()
188 exe = generator.get_exe()
189 infilelist = genlist.get_inputs()
190 outfilelist = genlist.get_outputs()
191 source_dir = os.path.join(down, self.build_to_src, genlist.subdir)
192 idgroup = ET.SubElement(parent_node, 'ItemGroup')
193 samelen = len(infilelist) == len(outfilelist)
194 for i, curfile in enumerate(infilelist):
195 if samelen:
196 sole_output = os.path.join(target_private_dir, outfilelist[i])
197 else:
198 sole_output = ''
199 infilename = os.path.join(down, curfile.rel_to_builddir(self.build_to_src, self.get_target_private_dir(target)))
200 deps = self.get_target_depend_files(genlist, True)
201 deps += self.get_paths_for_dep_outputs(target, genlist.extra_depends)
202 base_args = generator.get_arglist(infilename)
203 outfiles_rel = genlist.get_outputs_for(curfile)
204 outfiles = [os.path.join(target_private_dir, of) for of in outfiles_rel]
205 generator_output_files += outfiles
206 args = [x.replace("@INPUT@", infilename).replace('@OUTPUT@', sole_output)
207 for x in base_args]
208 args = self.replace_outputs(args, target_private_dir, outfiles_rel)
209 args = [x.replace("@SOURCE_DIR@", self.environment.get_source_dir())
210 .replace("@BUILD_DIR@", target_private_dir)
211 for x in args]
212 args = [x.replace("@CURRENT_SOURCE_DIR@", source_dir) for x in args]
213 args = [x.replace("@SOURCE_ROOT@", self.environment.get_source_dir())
214 .replace("@BUILD_ROOT@", self.environment.get_build_dir())
215 for x in args]
216 args = [x.replace('\\', '/') for x in args]
217 # Always use a wrapper because MSBuild eats random characters when
218 # there are many arguments.
219 tdir_abs = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
220 cmd, _ = self.as_meson_exe_cmdline(
221 exe,
222 self.replace_extra_args(args, genlist),
223 workdir=tdir_abs,
224 capture=outfiles[0] if generator.capture else None,
225 force_serialize=True,
226 env=genlist.env
227 )
228 deps = cmd[-1:] + deps
229 abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
230 os.makedirs(abs_pdir, exist_ok=True)
231 cbs = ET.SubElement(idgroup, 'CustomBuild', Include=infilename)
232 ET.SubElement(cbs, 'Command').text = ' '.join(self.quote_arguments(cmd))
233 ET.SubElement(cbs, 'Outputs').text = ';'.join(outfiles)
234 ET.SubElement(cbs, 'AdditionalInputs').text = ';'.join(deps)
235
236 def generate_custom_generator_commands(
237 self, target: build.BuildTarget | build.CustomTarget, parent_node: ET.Element
238 ) -> tuple[list[str], list[str], list[str]]:
239 generator_output_files: list[str] = []
240 custom_target_include_dirs: list[str] = []
241 custom_target_output_files: list[str] = []
242 for genlist in target.get_generated_sources():
243 self.generate_genlist_for_target(genlist, target, parent_node, generator_output_files, custom_target_include_dirs, custom_target_output_files)
244 return generator_output_files, custom_target_output_files, custom_target_include_dirs
245
246 def generate(self,
247 capture: bool = False,
248 vslite_ctx: _VSLITE_CTX | None = None) -> None:
249 # Check for (currently) unexpected capture arg use cases -
250 if capture:
251 raise MesonBugException('We do not expect any vs backend to generate with \'capture = True\'')
252 self.detect_toolset()
253 host_machine = self.environment.machines.host.cpu_family
254 if host_machine in {'64', 'x86_64'}:
255 # amd64 or x86_64
256 target_system = self.environment.machines.host.system
257 if detect_microsoft_gdk(target_system):
258 self.platform = target_system
259 else:
260 self.platform = 'x64'
261 elif host_machine == 'x86':
262 # x86
263 self.platform = 'Win32'
264 elif host_machine in {'aarch64', 'arm64'}:
265 target_cpu = self.environment.machines.host.cpu
266 if target_cpu == 'arm64ec':
267 self.platform = 'arm64ec'
268 else:
269 self.platform = 'arm64'
270 elif 'arm' in host_machine.lower():
271 self.platform = 'ARM'
272 else:
273 raise MesonException('Unsupported Visual Studio platform: ' + host_machine)
274
275 build_machine = self.environment.machines.build.cpu_family
276 if build_machine in {'64', 'x86_64'}:
277 # amd64 or x86_64
278 self.build_platform = 'x64'
279 elif build_machine == 'x86':
280 # x86
281 self.build_platform = 'Win32'
282 elif build_machine in {'aarch64', 'arm64'}:
283 target_cpu = self.environment.machines.build.cpu
284 if target_cpu == 'arm64ec':
285 self.build_platform = 'arm64ec'
286 else:
287 self.build_platform = 'arm64'
288 elif 'arm' in build_machine.lower():
289 self.build_platform = 'ARM'
290 else:
291 raise MesonException('Unsupported Visual Studio platform: ' + build_machine)
292
293 buildtype = self.environment.coredata.optstore.get_value_for(OptionKey('buildtype'))
294 assert isinstance(buildtype, str), 'for mypy'
295 self.buildtype = buildtype
296
297 optimization = self.environment.coredata.optstore.get_value_for(OptionKey('optimization'))
298 assert isinstance(optimization, str), 'for mypy'
299 self.optimization = optimization
300
301 debug = self.environment.coredata.optstore.get_value_for(OptionKey('debug'))
302 assert isinstance(debug, bool), 'for mypy'
303 self.debug = debug
304
305 try:
306 sanitize = self.environment.coredata.optstore.get_value_for(OptionKey('b_sanitize'))
307 assert isinstance(sanitize, list), 'for mypy'
308 except KeyError:
309 sanitize = []
310 self.sanitize = sanitize
311
312 sln_filename = os.path.join(self.environment.get_build_dir(), self.build.project_name + '.sln')
313 projlist = self.generate_projects(vslite_ctx)
314 self.gen_testproj()
315 self.gen_installproj()
316 self.gen_regenproj()
317 self.generate_solution(sln_filename, projlist)
318 self.generate_regen_info()
319 Vs2010Backend.touch_regen_timestamp(self.environment.get_build_dir())
320
321 @staticmethod
322 def get_regen_stampfile(build_dir: str) -> str:
323 return os.path.join(os.path.join(build_dir, Environment.private_dir), 'regen.stamp')
324
325 @staticmethod
326 def touch_regen_timestamp(build_dir: str) -> None:
327 with open(Vs2010Backend.get_regen_stampfile(build_dir), 'w', encoding='utf-8'):
328 pass
329
330 def get_vcvars_command(self) -> str:
331 has_arch_values = 'VSCMD_ARG_TGT_ARCH' in os.environ and 'VSCMD_ARG_HOST_ARCH' in os.environ
332
333 # Use vcvarsall.bat if we found it.
334 if 'VCINSTALLDIR' in os.environ:
335 vs_version = os.environ['VisualStudioVersion'] \
336 if 'VisualStudioVersion' in os.environ else None
337 relative_path = 'Auxiliary\\Build\\' if vs_version is not None and vs_version >= '15.0' else ''
338 script_path = os.environ['VCINSTALLDIR'] + relative_path + 'vcvarsall.bat'
339 if os.path.exists(script_path):
340 if has_arch_values:
341 target_arch = os.environ['VSCMD_ARG_TGT_ARCH']
342 host_arch = os.environ['VSCMD_ARG_HOST_ARCH']
343 else:
344 target_arch = os.environ.get('Platform', 'x86')
345 host_arch = target_arch
346 arch = host_arch + '_' + target_arch if host_arch != target_arch else target_arch
347 return f'"{script_path}" {arch}'
348
349 # Otherwise try the VS2017 Developer Command Prompt.
350 if 'VS150COMNTOOLS' in os.environ and has_arch_values:
351 script_path = os.environ['VS150COMNTOOLS'] + 'VsDevCmd.bat'
352 if os.path.exists(script_path):
353 return '"%s" -arch=%s -host_arch=%s' % \
354 (script_path, os.environ['VSCMD_ARG_TGT_ARCH'], os.environ['VSCMD_ARG_HOST_ARCH'])
355 return ''
356
357 def get_obj_target_deps(self, obj_list: list[build.ObjectTypes]) -> T.Iterable[tuple[str, build.BuildTarget]]:
358 result = {}
359 for o in obj_list:
360 if isinstance(o, build.ExtractedObjects):
361 result[o.target.get_id()] = o.target
362 return result.items()
363
364 def get_target_deps(self, t: T.Mapping[str, build.Target], recursive: bool = False) -> T.Dict[str, build.Target]:
365 all_deps: T.Dict[str, build.Target] = {}
366 for target in t.values():
367 if isinstance(target, build.CustomTargetIndex):
368 # just transfer it to the CustomTarget code
369 target = target.target
370 if isinstance(target, build.CustomTarget):
371 for d in target.get_target_dependencies():
372 # FIXME: this isn't strictly correct, as the target doesn't
373 # Get dependencies on non-targets, such as Files
374 if isinstance(d, build.Target):
375 all_deps[d.get_id()] = d
376 elif isinstance(target, build.RunTarget):
377 for d in target.get_dependencies():
378 if isinstance(d, build.LocalProgram):
379 d = d.program
380 if isinstance(d, (programs.Program, build.GeneratedList)):
381 continue
382 all_deps[d.get_id()] = d.get_target()
383 elif isinstance(target, build.BuildTarget):
384 for ldep in target.link_targets:
385 all_deps[ldep.get_id()] = ldep.get_target()
386 for ldep in target.link_whole_targets:
387 all_deps[ldep.get_id()] = ldep.get_target()
388
389 for ldep in target.link_depends:
390 if isinstance(ldep, File):
391 # Already built, no target references needed
392 pass
393 else:
394 all_deps[ldep.get_id()] = ldep.get_target()
395
396 for obj_id, objdep in self.get_obj_target_deps(target.objects):
397 all_deps[obj_id] = objdep
398 else:
399 raise MesonException(f'Unknown target type for target {target}')
400
401 for gendep in target.get_generated_sources():
402 if isinstance(gendep, (build.CustomTarget, build.CustomTargetIndex)):
403 all_deps[gendep.get_id()] = gendep.get_target()
404 else:
405 generator = gendep.get_generator()
406 for d in itertools.chain(generator.depends, gendep.depends, gendep.extra_depends):
407 if isinstance(d, build.CustomTargetIndex):
408 all_deps[d.get_id()] = d.target
409 elif isinstance(d, build.Target):
410 all_deps[d.get_id()] = d
411 # FIXME: we don't handle other kinds of deps correctly here, such
412 # as GeneratedLists, StructuredSources, and generated File.
413
414 if not t or not recursive:
415 return all_deps
416 ret = self.get_target_deps(all_deps, recursive)
417 ret.update(all_deps)
418 return ret
419
420 def generate_solution_dirs(self, ofile: T.TextIO, parents: T.Sequence[PurePath]) -> None:
421 prj_templ = 'Project("{%s}") = "%s", "%s", "{%s}"\n'
422 iterpaths = reversed(parents)
423 # Skip first path
424 next(iterpaths)
425 for path in iterpaths:
426 if path not in self.subdirs:
427 basename = path.name
428 identifier = generate_guid_from_path(path, 'subdir')
429 # top-level directories have None as their parent_dir
430 parent_dir = path.parent
431 parent_identifier = self.subdirs[parent_dir][0] \
432 if parent_dir != PurePath('.') else None
433 self.subdirs[path] = (identifier, parent_identifier)
434 prj_line = prj_templ % (
435 self.environment.coredata.lang_guids['directory'],
436 basename, basename, self.subdirs[path][0])
437 ofile.write(prj_line)
438 ofile.write('EndProject\n')
439
440 def generate_solution(self, sln_filename: str, projlist: T.List[Project]) -> None:
441 default_projlist = self.get_build_by_default_targets()
442 for t in self.get_testlike_targets():
443 default_projlist[t.get_id()] = t
444 sln_filename_tmp = sln_filename + '~'
445 # Note using the utf-8 BOM requires the blank line, otherwise Visual Studio Version Selector fails.
446 # Without the BOM, VSVS fails if there is a blank line.
447 with open(sln_filename_tmp, 'w', encoding='utf-8-sig') as ofile:
448 ofile.write('\nMicrosoft Visual Studio Solution File, Format Version %s\n' % self.sln_file_version)
449 ofile.write('# Visual Studio %s\n' % self.sln_version_comment)
450 prj_templ = 'Project("{%s}") = "%s", "%s", "{%s}"\n'
451 for prj in projlist:
452 if self.environment.coredata.optstore.get_value_for(OptionKey('layout')) == 'mirror':
453 self.generate_solution_dirs(ofile, prj[1].parents)
454 target = self.build.targets[prj[0]]
455 lang = 'default'
456 if hasattr(target, 'compilers') and target.compilers:
457 for lang_out in target.compilers.keys():
458 lang = lang_out
459 break
460 prj_line = prj_templ % (
461 self.environment.coredata.lang_guids[lang],
462 prj[0], prj[1], prj[2])
463 ofile.write(prj_line)
464 target_dict: dict[str, build.Target] = {target.get_id(): target}
465 # Get recursive deps
466 recursive_deps = self.get_target_deps(
467 target_dict, recursive=True)
468 ofile.write('EndProject\n')
469 for dep, target in recursive_deps.items():
470 if prj[0] in default_projlist:
471 default_projlist[dep] = target.get_target()
472
473 test_line = prj_templ % (self.environment.coredata.lang_guids['default'],
474 'RUN_TESTS', 'RUN_TESTS.vcxproj',
475 self.environment.coredata.test_guid)
476 ofile.write(test_line)
477 ofile.write('EndProject\n')
478 if self.gen_lite: # REGEN is replaced by the lighter-weight RECONFIGURE utility, for now. See comment in 'gen_regenproj'
479 regen_proj_name = 'RECONFIGURE'
480 regen_proj_fname = 'RECONFIGURE.vcxproj'
481 else:
482 regen_proj_name = 'REGEN'
483 regen_proj_fname = 'REGEN.vcxproj'
484 regen_line = prj_templ % (self.environment.coredata.lang_guids['default'],
485 regen_proj_name, regen_proj_fname,
486 self.environment.coredata.regen_guid)
487 ofile.write(regen_line)
488 ofile.write('EndProject\n')
489 install_line = prj_templ % (self.environment.coredata.lang_guids['default'],
490 'RUN_INSTALL', 'RUN_INSTALL.vcxproj',
491 self.environment.coredata.install_guid)
492 ofile.write(install_line)
493 ofile.write('EndProject\n')
494 ofile.write('Global\n')
495 ofile.write('\tGlobalSection(SolutionConfigurationPlatforms) = '
496 'preSolution\n')
497 multi_config_buildtype_list = coredata.get_genvs_default_buildtype_list() if self.gen_lite else [self.buildtype]
498 for buildtype in multi_config_buildtype_list:
499 ofile.write('\t\t%s|%s = %s|%s\n' %
500 (buildtype, self.platform, buildtype,
501 self.platform))
502 ofile.write('\tEndGlobalSection\n')
503 ofile.write('\tGlobalSection(ProjectConfigurationPlatforms) = '
504 'postSolution\n')
505 # REGEN project (multi-)configurations
506 for buildtype in multi_config_buildtype_list:
507 ofile.write('\t\t{%s}.%s|%s.ActiveCfg = %s|%s\n' %
508 (self.environment.coredata.regen_guid, buildtype,
509 self.platform, buildtype, self.platform))
510 if not self.gen_lite: # With a 'genvslite'-generated solution, the regen (i.e. reconfigure) utility is only intended to run when the user explicitly builds this proj.
511 ofile.write('\t\t{%s}.%s|%s.Build.0 = %s|%s\n' %
512 (self.environment.coredata.regen_guid, buildtype,
513 self.platform, buildtype, self.platform))
514 # Create the solution configuration
515 for project_index, p in enumerate(projlist):
516 if p[3] is MachineChoice.BUILD:
517 config_platform = self.build_platform
518 else:
519 config_platform = self.platform
520 # Add to the list of projects in this solution
521 for buildtype in multi_config_buildtype_list:
522 ofile.write('\t\t{%s}.%s|%s.ActiveCfg = %s|%s\n' %
523 (p[2], buildtype, self.platform,
524 buildtype, config_platform))
525 # If we're building the solution with Visual Studio's build system, enable building of buildable
526 # projects. However, if we're building with meson (via --genvslite), then, since each project's
527 # 'build' action just ends up doing the same 'meson compile ...' we don't want the 'solution build'
528 # repeatedly going off and doing the same 'meson compile ...' multiple times over, so we default
529 # to building the startup project, which is the first listed project in the solution file by
530 # default for Visual Studio. The user is free to change this afterwards, but this provides a
531 # sensible default.
532 if (not self.gen_lite or project_index == 0) and \
533 p[0] in default_projlist and \
534 not isinstance(self.build.targets[p[0]], build.RunTarget):
535 ofile.write('\t\t{%s}.%s|%s.Build.0 = %s|%s\n' %
536 (p[2], buildtype, self.platform,
537 buildtype, config_platform))
538 # RUN_TESTS and RUN_INSTALL project (multi-)configurations
539 for buildtype in multi_config_buildtype_list:
540 ofile.write('\t\t{%s}.%s|%s.ActiveCfg = %s|%s\n' %
541 (self.environment.coredata.test_guid, buildtype,
542 self.platform, buildtype, self.platform))
543 ofile.write('\t\t{%s}.%s|%s.ActiveCfg = %s|%s\n' %
544 (self.environment.coredata.install_guid, buildtype,
545 self.platform, buildtype, self.platform))
546 ofile.write('\tEndGlobalSection\n')
547 ofile.write('\tGlobalSection(SolutionProperties) = preSolution\n')
548 ofile.write('\t\tHideSolutionNode = FALSE\n')
549 ofile.write('\tEndGlobalSection\n')
550 if self.subdirs:
551 ofile.write('\tGlobalSection(NestedProjects) = '
552 'preSolution\n')
553 for p in projlist:
554 if p[1].parent != PurePath('.'):
555 ofile.write("\t\t{{{}}} = {{{}}}\n".format(p[2], self.subdirs[p[1].parent][0]))
556 for subdir in self.subdirs.values():
557 if subdir[1]:
558 ofile.write("\t\t{{{}}} = {{{}}}\n".format(subdir[0], subdir[1]))
559 ofile.write('\tEndGlobalSection\n')
560 ofile.write('EndGlobal\n')
561 replace_if_different(sln_filename, sln_filename_tmp)
562
563 def generate_projects(self, vslite_ctx: _VSLITE_CTX | None = None) -> T.List[Project]:
564 startup_project = self.environment.coredata.optstore.get_value_for('backend_startup_project')
565 projlist: T.List[Project] = []
566 startup_idx = 0
567 for (i, (name, target)) in enumerate(self.build.targets.items()):
568 if startup_project and startup_project == target.get_basename():
569 startup_idx = i
570 outdir = Path(
571 self.environment.get_build_dir(),
572 self.get_target_dir(target)
573 )
574 outdir.mkdir(exist_ok=True, parents=True)
575 fname = name + '.vcxproj'
576 target_dir = PurePath(self.get_target_dir(target))
577 relname = target_dir / fname
578 projfile_path = outdir / fname
579 proj_uuid = self.environment.coredata.target_guids[name]
580 generated = self.gen_vcxproj(target, str(projfile_path), proj_uuid, vslite_ctx)
581 if generated:
582 projlist.append((name, relname, proj_uuid, target.for_machine))
583
584 # Put the startup project first in the project list
585 if startup_idx:
586 projlist.insert(0, projlist.pop(startup_idx))
587
588 return projlist
589
590 def split_sources(self, srclist: list[FileLike]) -> tuple[list[FileLike], list[FileLike], list[FileLike], list[str]]:
591 sources: list[FileLike] = []
592 headers: list[FileLike] = []
593 objects: list[FileLike] = []
594 languages: list[str] = []
595 for i in srclist:
596 if compilers.is_header(i):
597 headers.append(i)
598 elif compilers.is_object(i):
599 objects.append(i)
600 elif compilers.is_source(i):
601 sources.append(i)
602 lang = self.lang_from_source_file(i)
603 if lang not in languages:
604 languages.append(lang)
605 elif compilers.is_library(i):
606 pass
607 else:
608 # Everything that is not an object or source file is considered a header.
609 headers.append(i)
610 return sources, headers, objects, languages
611
612 def target_to_build_root(self, target: build.AnyTargetType) -> str:
613 if self.get_target_dir(target) == '':
614 return ''
615
616 directories = os.path.normpath(self.get_target_dir(target)).split(os.sep)
617 return os.sep.join(['..'] * len(directories))
618
619 def quote_arguments(self, arr: list[str]) -> list[str]:
620 return ['"%s"' % i for i in arr]
621
622 def add_project_reference(self, root: ET.Element, include: str, projid: str, link_outputs: bool = False) -> None:
623 ig = ET.SubElement(root, 'ItemGroup')
624 pref = ET.SubElement(ig, 'ProjectReference', Include=include)
625 ET.SubElement(pref, 'Project').text = '{%s}' % projid
626 if not link_outputs:
627 # Do not link in generated .lib files from dependencies automatically.
628 # We only use the dependencies for ordering and link in the generated
629 # objects and .lib files manually.
630 ET.SubElement(pref, 'LinkLibraryDependencies').text = 'false'
631
632 def add_target_deps(self, root: ET.Element, target: build.Target) -> None:
633 target_dict: T.Dict[str, build.Target] = {target.get_id(): target}
634 for dep in self.get_target_deps(target_dict).values():
635 if dep.get_id() in self.handled_target_deps[target.get_id()]:
636 # This dependency was already handled manually.
637 continue
638 relpath = self.get_target_dir_relative_to(dep, target)
639 vcxproj = os.path.join(relpath, dep.get_id() + '.vcxproj')
640 tid = self.environment.coredata.target_guids[dep.get_id()]
641 self.add_project_reference(root, vcxproj, tid)
642
643 def create_basic_project(self, target_name: str, *,
644 temp_dir: str,
645 guid: str,
646 conftype: str = 'Utility',
647 target_ext: T.Optional[str] = None,
648 target_platform: T.Optional[str] = None,
649 gen_manifest: bool | T.Literal['embed'] = True,
650 masm_type: T.Optional[T.Literal['masm', 'marmasm']] = None) -> T.Tuple[ET.Element, ET.Element]:
651 root = ET.Element('Project', {'DefaultTargets': "Build",
652 'ToolsVersion': '4.0',
653 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'})
654
655 confitems = ET.SubElement(root, 'ItemGroup', {'Label': 'ProjectConfigurations'})
656 if not target_platform:
657 target_platform = self.platform
658
659 multi_config_buildtype_list = coredata.get_genvs_default_buildtype_list() if self.gen_lite else [self.buildtype]
660 if "debug" not in multi_config_buildtype_list:
661 multi_config_buildtype_list.append('debug')
662 for buildtype in multi_config_buildtype_list:
663 prjconf = ET.SubElement(confitems, 'ProjectConfiguration',
664 {'Include': buildtype + '|' + target_platform})
665 ET.SubElement(prjconf, 'Configuration').text = buildtype
666 ET.SubElement(prjconf, 'Platform').text = target_platform
667
668 # Globals
669 globalgroup = ET.SubElement(root, 'PropertyGroup', Label='Globals')
670 guidelem = ET.SubElement(globalgroup, 'ProjectGuid')
671 guidelem.text = '{%s}' % guid
672 kw = ET.SubElement(globalgroup, 'Keyword')
673 kw.text = self.platform + 'Proj'
674
675 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.Default.props')
676
677 # Configuration
678 type_config = ET.SubElement(root, 'PropertyGroup', Label='Configuration')
679 ET.SubElement(type_config, 'ConfigurationType').text = conftype
680 if self.platform_toolset:
681 ET.SubElement(type_config, 'PlatformToolset').text = self.platform_toolset
682
683 # This must come AFTER the '<PropertyGroup Label="Configuration">' element; importing before the 'PlatformToolset' elt
684 # gets set leads to msbuild failures reporting -
685 # "The build tools for v142 (Platform Toolset = 'v142') cannot be found. ... please install v142 build tools."
686 # This is extremely unhelpful and misleading since the v14x build tools ARE installed.
687 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.props')
688 ext_settings_grp = ET.SubElement(root, 'ImportGroup', Label='ExtensionSettings')
689 if masm_type:
690 ET.SubElement(
691 ext_settings_grp,
692 'Import',
693 Project=rf'$(VCTargetsPath)\BuildCustomizations\{masm_type}.props',
694 )
695
696 # This attribute makes sure project names are displayed as expected in solution files even when their project file names differ
697 pname = ET.SubElement(globalgroup, 'ProjectName')
698 pname.text = target_name
699
700 if not self.gen_lite: # Plenty of elements aren't necessary for 'makefile'-style project that just redirects to meson builds
701 # XXX Wasn't here before for anything but gen_vcxproj , but seems fine?
702 ns = ET.SubElement(globalgroup, 'RootNamespace')
703 ns.text = target_name
704
705 p = ET.SubElement(globalgroup, 'Platform')
706 p.text = target_platform
707 if self.windows_target_platform_version:
708 ET.SubElement(globalgroup, 'WindowsTargetPlatformVersion').text = self.windows_target_platform_version
709 ET.SubElement(globalgroup, 'UseMultiToolTask').text = 'true'
710
711 ET.SubElement(type_config, 'CharacterSet').text = 'MultiByte'
712 # Fixme: wasn't here before for gen_vcxproj()
713 ET.SubElement(type_config, 'UseOfMfc').text = 'false'
714
715 # Project information
716 direlem = ET.SubElement(root, 'PropertyGroup')
717 fver = ET.SubElement(direlem, '_ProjectFileVersion')
718 fver.text = self.project_file_version
719 outdir = ET.SubElement(direlem, 'OutDir')
720 outdir.text = '.\\'
721 intdir = ET.SubElement(direlem, 'IntDir')
722 intdir.text = temp_dir + '\\'
723
724 tname = ET.SubElement(direlem, 'TargetName')
725 tname.text = target_name
726
727 if target_ext:
728 ET.SubElement(direlem, 'TargetExt').text = target_ext
729
730 # Fix weird mt.exe error:
731 # mt.exe is trying to compile a non-existent .generated.manifest file and link it
732 # with the target. This does not happen without masm props.
733 ET.SubElement(direlem, 'EmbedManifest').text = 'true' if masm_type or gen_manifest == 'embed' else 'false'
734 ET.SubElement(direlem, 'GenerateManifest').text = 'true' if gen_manifest else 'false'
735
736 return (root, type_config)
737
738 def gen_run_target_vcxproj(self, target: build.RunTarget, ofname: str, guid: str) -> None:
739 (root, type_config) = self.create_basic_project(target.name,
740 temp_dir=target.get_id(),
741 guid=guid,
742 gen_manifest=self.get_gen_manifest(target))
743 depend_files = self.get_target_depend_files(target)
744
745 if not target.command:
746 # This is an alias target and thus doesn't run any command. It's
747 # enough to emit the references to the other projects for them to
748 # be built/run/..., if necessary.
749 assert isinstance(target, build.AliasTarget)
750 assert len(depend_files) == 0
751 else:
752 assert not isinstance(target, build.AliasTarget)
753
754 target_env = self.get_run_target_env(target)
755 _, _, cmd_raw = self.eval_custom_target_command(target)
756 wrapper_cmd, _ = self.as_meson_exe_cmdline(target.command[0], cmd_raw[1:],
757 force_serialize=True, env=target_env,
758 verbose=True)
759 self.add_custom_build(root, 'run_target', ' '.join(self.quote_arguments(wrapper_cmd)),
760 deps=depend_files)
761
762 # The import is needed even for alias targets, otherwise the build
763 # target isn't defined
764 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.targets')
765 self.add_regen_dependency(root)
766 self.add_target_deps(root, target)
767 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
768
769 def gen_custom_target_vcxproj(self, target: build.CustomTarget, ofname: str, guid: str) -> None:
770 if target.for_machine is MachineChoice.BUILD:
771 platform = self.build_platform
772 else:
773 platform = self.platform
774 (root, type_config) = self.create_basic_project(target.name,
775 temp_dir=target.get_id(),
776 guid=guid,
777 target_platform=platform,
778 gen_manifest=self.get_gen_manifest(target))
779 # We need to always use absolute paths because our invocation is always
780 # from the target dir, not the build root.
781 target.absolute_paths = True
782 (srcs, ofilenames, cmd) = self.eval_custom_target_command(target, True)
783 depend_files = self.get_target_depend_files(target, True)
784 # Always use a wrapper because MSBuild eats random characters when
785 # there are many arguments.
786 tdir_abs = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
787 extra_bdeps = target.get_transitive_build_target_deps()
788 wrapper_cmd, _ = self.as_meson_exe_cmdline(target.command[0], cmd[1:],
789 # All targets run from the target dir
790 workdir=tdir_abs,
791 extra_bdeps=extra_bdeps,
792 capture=ofilenames[0] if target.capture else None,
793 feed=srcs[0] if target.feed else None,
794 force_serialize=True,
795 env=target.env,
796 verbose=target.console)
797 if target.build_always_stale:
798 # Use a nonexistent file to always consider the target out-of-date.
799 ofilenames += [self.nonexistent_file(os.path.join(self.environment.get_scratch_dir(),
800 'outofdate.file'))]
801 self.add_custom_build(root, 'custom_target', ' '.join(self.quote_arguments(wrapper_cmd)),
802 deps=wrapper_cmd[-1:] + srcs + depend_files, outputs=ofilenames,
803 verify_files=not target.build_always_stale)
804 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.targets')
805 self.generate_custom_generator_commands(target, root)
806 self.add_regen_dependency(root)
807 self.add_target_deps(root, target)
808 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
809
810 def gen_compile_target_vcxproj(self, target: build.CompileTarget, ofname: str, guid: str) -> None:
811 if target.for_machine is MachineChoice.BUILD:
812 platform = self.build_platform
813 else:
814 platform = self.platform
815
816 masm = self.get_masm_type(target)
817
818 (root, type_config) = self.create_basic_project(target.name,
819 temp_dir=target.get_id(),
820 guid=guid,
821 target_platform=platform,
822 gen_manifest=self.get_gen_manifest(target),
823 masm_type=masm)
824 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.targets')
825 ext_tgt_grp = ET.SubElement(root, 'ImportGroup', Label='ExtensionTargets')
826 if masm:
827 ET.SubElement(ext_tgt_grp, 'Import', Project=rf'$(VCTargetsPath)\BuildCustomizations\{masm}.targets')
828 target.generated = [self.compile_target_to_generator(target)]
829 target.sources = []
830 self.generate_custom_generator_commands(target, root)
831 self.add_regen_dependency(root)
832 self.add_target_deps(root, target)
833 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
834
835 @classmethod
836 def lang_from_source_file(cls, src: mesonlib.FileOrString) -> Language:
837 ext = src.split('.')[-1]
838 if ext in compilers.c_suffixes:
839 return 'c'
840 if ext in compilers.cpp_suffixes:
841 return 'cpp'
842 if ext in compilers.lang_suffixes['masm']:
843 return 'masm'
844 raise MesonException(f'Could not guess language from source file {src}.')
845
846 def add_pch(self, pch_sources: T.Dict[Language, T.Tuple[str, T.Optional[str], str, T.Optional[str]]],
847 lang: Language, inc_cl: ET.Element) -> None:
848 if lang in pch_sources:
849 self.use_pch(pch_sources, lang, inc_cl)
850
851 def create_pch(self, pch_sources: T.Dict[Language, T.Tuple[str, T.Optional[str], str, T.Optional[str]]],
852 lang: Language, inc_cl: ET.Element) -> None:
853 pch = ET.SubElement(inc_cl, 'PrecompiledHeader')
854 pch.text = 'Create'
855 self.add_pch_files(pch_sources, lang, inc_cl)
856
857 def use_pch(self, pch_sources: T.Dict[Language, T.Tuple[str, T.Optional[str], str, T.Optional[str]]],
858 lang: Language, inc_cl: ET.Element) -> None:
859 pch = ET.SubElement(inc_cl, 'PrecompiledHeader')
860 pch.text = 'Use'
861 header = self.add_pch_files(pch_sources, lang, inc_cl)
862 pch_include = ET.SubElement(inc_cl, 'ForcedIncludeFiles')
863 pch_include.text = header + ';%(ForcedIncludeFiles)'
864
865 def add_pch_files(self, pch_sources: T.Dict[Language, T.Tuple[str, T.Optional[str], str, T.Optional[str]]],
866 lang: Language, inc_cl: ET.Element) -> str:
867 header = os.path.basename(pch_sources[lang][0])
868 pch_file = ET.SubElement(inc_cl, 'PrecompiledHeaderFile')
869 # When USING PCHs, MSVC will not do the regular include
870 # directory lookup, but simply use a string match to find the
871 # PCH to use. That means the #include directive must match the
872 # pch_file.text used during PCH CREATION verbatim.
873 # When CREATING a PCH, MSVC will do the include directory
874 # lookup to find the actual PCH header to use. Thus, the PCH
875 # header must either be in the include_directories of the target
876 # or be in the same directory as the PCH implementation.
877 pch_file.text = header
878 pch_out = ET.SubElement(inc_cl, 'PrecompiledHeaderOutputFile')
879 pch_out.text = f'$(IntDir)$(TargetName)-{lang}.pch'
880
881 # Need to set the name for the pdb, as cl otherwise gives it a static
882 # name. Which leads to problems when there is more than one pch
883 # (e.g. for different languages).
884 pch_pdb = ET.SubElement(inc_cl, 'ProgramDataBaseFileName')
885 pch_pdb.text = f'$(IntDir)$(TargetName)-{lang}.pdb'
886
887 return header
888
889 def is_argument_with_msbuild_xml_entry(self, entry: str) -> bool:
890 # Remove arguments that have a top level XML entry so
891 # they are not used twice.
892 # FIXME add args as needed.
893 if entry[1:].startswith('fsanitize'):
894 return True
895 if entry[1:] in frozenset(['Zi', 'Z7', 'ZI']):
896 return True
897 return entry[1:].startswith('M')
898
899 def add_additional_options(self, lang: Language, parent_node: ET.Element, file_args: dict[Language, CompilerArgs]) -> None:
900 args = []
901 for arg in file_args[lang].to_native():
902 if self.is_argument_with_msbuild_xml_entry(arg):
903 continue
904 if arg == '%(AdditionalOptions)':
905 args.append(arg)
906 else:
907 args.append(self.escape_additional_option(arg))
908 ET.SubElement(parent_node, "AdditionalOptions").text = ' '.join(args)
909
910 # Set up each project's source file ('CLCompile') element with appropriate preprocessor, include dir, and compile option values for correct intellisense.
911 def add_project_nmake_defs_incs_and_opts(self, parent_node: ET.Element, src: str, defs_paths_opts_per_lang_and_buildtype: dict, platform: str) -> None:
912 # For compactness, sources whose type matches the primary src type (i.e. most frequent in the set of source types used in the target/project,
913 # according to the 'captured_build_args' map), can simply reference the preprocessor definitions, include dirs, and compile option NMake fields of
914 # the project itself.
915 # However, if a src is of a non-primary type, it could have totally different defs/dirs/options so we're going to have to fill in the full, verbose
916 # set of values for these fields, which needs to be fully expanded per build type / configuration.
917 #
918 # FIXME: Suppose a project contains .cpp and .c src files with different compile defs/dirs/options, while also having .h files, some of which
919 # are included by .cpp sources and others included by .c sources: How do we know whether the .h source should be using the .cpp or .c src
920 # defs/dirs/options? Might it also be possible for a .h header to be shared between .cpp and .c sources? If so, I don't see how we can
921 # correctly configure these intellisense fields.
922 # For now, all sources/headers that fail to find their extension's language in the '...nmake_defs_paths_opts...' map will just adopt the project
923 # defs/dirs/opts that are set for the nominal 'primary' src type.
924 ext = src.split('.')[-1]
925 lang = compilers.compilers.SUFFIX_TO_LANG.get(ext, None)
926 if lang in defs_paths_opts_per_lang_and_buildtype.keys():
927 # This is a non-primary src type for which can't simply reference the project's nmake fields;
928 # we must laboriously fill in the fields for all buildtypes.
929 for buildtype in coredata.get_genvs_default_buildtype_list():
930 (defs, paths, opts) = defs_paths_opts_per_lang_and_buildtype[lang][buildtype]
931 condition = f'\'$(Configuration)|$(Platform)\'==\'{buildtype}|{platform}\''
932 ET.SubElement(parent_node, 'PreprocessorDefinitions', Condition=condition).text = defs
933 ET.SubElement(parent_node, 'AdditionalIncludeDirectories', Condition=condition).text = paths
934 ET.SubElement(parent_node, 'AdditionalOptions', Condition=condition).text = opts
935 else: # Can't find bespoke nmake defs/dirs/opts fields for this extension, so just reference the project's fields
936 ET.SubElement(parent_node, 'PreprocessorDefinitions').text = '$(NMakePreprocessorDefinitions)'
937 ET.SubElement(parent_node, 'AdditionalIncludeDirectories').text = '$(NMakeIncludeSearchPath)'
938 ET.SubElement(parent_node, 'AdditionalOptions').text = '$(AdditionalOptions)'
939
940 def add_preprocessor_defines(self, lang: Language, parent_node: ET.Element, file_defines: dict[Language, list[str]]) -> None:
941 defines = []
942 for define in file_defines[lang]:
943 if define == '%(PreprocessorDefinitions)':
944 defines.append(define)
945 else:
946 defines.append(self.escape_preprocessor_define(define))
947 ET.SubElement(parent_node, "PreprocessorDefinitions").text = ';'.join(defines)
948
949 def add_include_dirs(self, lang: Language, parent_node: ET.Element, file_inc_dirs: dict[Language, list[str]]) -> None:
950 dirs = file_inc_dirs[lang]
951 ET.SubElement(parent_node, "AdditionalIncludeDirectories").text = ';'.join(dirs)
952
953 @staticmethod
954 def escape_preprocessor_define(define: str) -> str:
955 # See: https://msdn.microsoft.com/en-us/library/bb383819.aspx
956 table = str.maketrans({'%': '%25', '$': '%24', '@': '%40',
957 "'": '%27', ';': '%3B', '?': '%3F', '*': '%2A',
958 # We need to escape backslash because it'll be un-escaped by
959 # Windows during process creation when it parses the arguments
960 # Basically, this converts `\` to `\\`.
961 '\\': '\\\\'})
962 return define.translate(table)
963
964 @staticmethod
965 def escape_additional_option(option: str) -> str:
966 # See: https://msdn.microsoft.com/en-us/library/bb383819.aspx
967 table = str.maketrans({'%': '%25', '$': '%24', '@': '%40',
968 "'": '%27', ';': '%3B', '?': '%3F', '*': '%2A', ' ': '%20'})
969 option = option.translate(table)
970 # Since we're surrounding the option with ", if it ends in \ that will
971 # escape the " when the process arguments are parsed and the starting
972 # " will not terminate. So we escape it if that's the case. I'm not
973 # kidding, this is how escaping works for process args on Windows.
974 if option.endswith('\\'):
975 option += '\\'
976 return f'"{option}"'
977
978 @staticmethod
979 def split_link_args(args: list[str]) -> tuple[list[str], list[str], list[str]]:
980 """
981 Split a list of link arguments into three lists:
982 * library search paths
983 * library filenames (or paths)
984 * other link arguments
985 """
986 lpaths: list[str] = []
987 libs: list[str] = []
988 other: list[str] = []
989 for arg in args:
990 if arg.startswith('/LIBPATH:'):
991 lpath = arg[9:]
992 # De-dup library search paths by removing older entries when
993 # a new one is found. This is necessary because unlike other
994 # search paths such as the include path, the library is
995 # searched for in the newest (right-most) search path first.
996 if lpath in lpaths:
997 lpaths.remove(lpath)
998 lpaths.append(lpath)
999 elif arg.startswith(('/', '-')):
1000 other.append(arg)
1001 # It's ok if we miss libraries with non-standard extensions here.
1002 # They will go into the general link arguments.
1003 elif arg.endswith('.lib') or arg.endswith('.a'):
1004 # De-dup
1005 if arg not in libs:
1006 libs.append(arg)
1007 else:
1008 other.append(arg)
1009 return lpaths, libs, other
1010
1011 def _get_cl_compiler(self, target: build.BuildTarget) -> compilers.Compiler:
1012 for lang, c in target.compilers.items():
1013 if lang in {'c', 'cpp'}:
1014 return c
1015 # No C/C++ source files, only objects/assembly source, but we still need a compiler, so
1016 # return a found compiler
1017 if len(target.objects) > 0 or len(target.sources) > 0:
1018 for lang, c in self.environment.coredata.compilers[target.for_machine].items():
1019 if lang in {'c', 'cpp'}:
1020 return c
1021 raise MesonException('Could not find a C or C++ compiler. MSVC can only build C/C++ projects.')
1022
1023 def _prettyprint_vcxproj_xml(self, tree: ET.ElementTree, ofname: str) -> None:
1024 ofname_tmp = ofname + '~'
1025 tree.write(ofname_tmp, encoding='utf-8', xml_declaration=True)
1026
1027 # ElementTree cannot do pretty-printing, so do it manually
1028 doc = xml.dom.minidom.parse(ofname_tmp)
1029 with open(ofname_tmp, 'w', encoding='utf-8') as of:
1030 of.write(doc.toprettyxml())
1031 replace_if_different(ofname, ofname_tmp)
1032
1033 # Returns: (target_args,file_args), (target_defines,file_defines), (target_inc_dirs,file_inc_dirs)
1034 def get_args_defines_and_inc_dirs(
1035 self, target: build.BuildTarget,
1036 compiler: compilers.Compiler,
1037 generated_files_include_dirs: list[str],
1038 proj_to_src_root: str,
1039 proj_to_src_dir: str,
1040 build_args: list[str]
1041 ) -> tuple[tuple[list[str], dict[Language, CompilerArgs]], tuple[list[str], dict[Language, list[str]]], tuple[list[str], dict[Language, list[str]]]]:
1042 # Arguments, include dirs, defines for all files in the current target
1043 target_args: list[str] = []
1044 target_defines: list[str] = []
1045 target_inc_dirs: list[str] = []
1046 # Arguments, include dirs, defines passed to individual files in
1047 # a target; perhaps because the args are language-specific
1048 #
1049 # file_args is also later split out into defines and include_dirs in
1050 # case someone passed those in there
1051 file_args: T.Dict[Language, CompilerArgs] = {l: c.compiler_args() for l, c in target.compilers.items()}
1052 file_defines: dict[Language, list[str]] = {l: [] for l in target.compilers}
1053 file_inc_dirs: dict[Language, list[str]] = {l: [] for l in target.compilers}
1054 # The order in which these compile args are added must match
1055 # generate_single_compile() and generate_basic_compiler_args()
1056 for l, comp in target.compilers.items():
1057 if l in file_args:
1058 file_args[l] += comp.get_always_args()
1059 file_args[l] += compilers.get_base_compile_args(
1060 target, comp, self.environment)
1061 file_args[l] += comp.get_option_compile_args(
1062 target, target.subproject)
1063 file_args[l] += comp.get_option_std_args(
1064 target, target.subproject)
1065
1066 # Add compile args added using add_project_arguments() and add_global_arguments()
1067 for l, comp in target.compilers.items():
1068 file_args[l] += self.build.get_project_args(comp, target)
1069 file_args[l] += self.build.get_global_args(comp, target)
1070
1071 # Compile args added from the env or cross file: CFLAGS/CXXFLAGS, etc. We want these
1072 # to override all the defaults, but not the per-target compile args.
1073 for lang in file_args.keys():
1074 l_args = self.get_target_option(target, OptionKey(f'{lang}_args', machine=target.for_machine))
1075 assert isinstance(l_args, list), 'for mypy'
1076 file_args[lang] += l_args
1077 for args in file_args.values():
1078 # This is where Visual Studio will insert target_args, target_defines,
1079 # etc, which are added later from external deps (see below).
1080 args += ['%(AdditionalOptions)', '%(PreprocessorDefinitions)', '%(AdditionalIncludeDirectories)']
1081 # Add custom target dirs as includes automatically, but before
1082 # target-specific include dirs. See _generate_single_compile() in
1083 # the ninja backend for caveats.
1084 args += ['-I' + arg for arg in generated_files_include_dirs]
1085 # Add include dirs from the `include_directories:` kwarg on the target
1086 # and from `include_directories:` of internal deps of the target.
1087 #
1088 # Target include dirs should override internal deps include dirs.
1089 # This is handled in BuildTarget.process_kwargs()
1090 #
1091 # Include dirs from internal deps should override include dirs from
1092 # external deps and must maintain the order in which they are
1093 # specified. Hence, we must reverse so that the order is preserved.
1094 #
1095 # These are per-target, but we still add them as per-file because we
1096 # need them to be looked in first.
1097 for d in reversed(target.get_include_dirs()):
1098 # reversed is used to keep order of includes
1099 for i in reversed(d.incdirs):
1100 curdir = os.path.join(d.curdir, i)
1101 try:
1102 # Add source subdir first so that the build subdir overrides it
1103 args.append('-I' + os.path.join(proj_to_src_root, curdir)) # src dir
1104 args.append('-I' + self.relpath(curdir, target.subdir)) # build dir
1105 except ValueError:
1106 # Include is on different drive
1107 args.append('-I' + os.path.normpath(curdir))
1108 for i in d.extra_build_dirs:
1109 curdir = os.path.join(d.curdir, i)
1110 args.append('-I' + self.relpath(curdir, target.subdir)) # build dir
1111 # Add per-target compile args, f.ex, `c_args : ['/DFOO']`. We set these
1112 # near the end since these are supposed to override everything else.
1113 for l, args in target.extra_args.items():
1114 if l in file_args:
1115 file_args[l] += args
1116 # The highest priority includes. In order of directory search:
1117 # target private dir, target build dir, target source dir
1118 for args in file_args.values():
1119 t_inc_dirs = [self.relpath(self.get_target_private_dir(target),
1120 self.get_target_dir(target))]
1121 if target.implicit_include_directories:
1122 t_inc_dirs += ['.', proj_to_src_dir]
1123 args += ['-I' + arg for arg in t_inc_dirs]
1124
1125 # Split preprocessor defines and include directories out of the list of
1126 # all extra arguments. The rest go into %(AdditionalOptions).
1127 for l, args in file_args.items():
1128 for arg in args[:]:
1129 if arg.startswith(('-D', '/D')) or arg == '%(PreprocessorDefinitions)':
1130 file_args[l].remove(arg)
1131 # Don't escape the marker
1132 if arg == '%(PreprocessorDefinitions)':
1133 define = arg
1134 else:
1135 define = arg[2:]
1136 # De-dup
1137 if define not in file_defines[l]:
1138 file_defines[l].append(define)
1139 elif arg.startswith(('-I', '/I')) or arg == '%(AdditionalIncludeDirectories)':
1140 file_args[l].remove(arg)
1141 # Don't escape the marker
1142 if arg == '%(AdditionalIncludeDirectories)':
1143 inc_dir = arg
1144 else:
1145 inc_dir = arg[2:]
1146 # De-dup
1147 if inc_dir not in file_inc_dirs[l]:
1148 file_inc_dirs[l].append(inc_dir)
1149 # Add include dirs to target as well so that "Go to Document" works in headers
1150 if inc_dir not in target_inc_dirs:
1151 target_inc_dirs.append(inc_dir)
1152
1153 # Split compile args needed to find external dependencies
1154 # Link args are added while generating the link command
1155 for d in reversed(target.get_external_deps()):
1156 # Cflags required by external deps might have UNIX-specific flags,
1157 # so filter them out if needed
1158 if d.name != 'openmp':
1159 d_compile_args = compiler.unix_args_to_native(d.get_compile_args())
1160 for arg in d_compile_args:
1161 if arg.startswith(('-D', '/D')):
1162 define = arg[2:]
1163 # De-dup
1164 if define in target_defines:
1165 target_defines.remove(define)
1166 target_defines.append(define)
1167 elif arg.startswith(('-I', '/I')):
1168 inc_dir = arg[2:]
1169 # De-dup
1170 if inc_dir not in target_inc_dirs:
1171 target_inc_dirs.append(inc_dir)
1172 else:
1173 target_args.append(arg)
1174
1175 if '/Gw' in build_args:
1176 target_args.append('/Gw')
1177
1178 return (target_args, file_args), (target_defines, file_defines), (target_inc_dirs, file_inc_dirs)
1179
1180 def get_build_args(self, target: build.BuildTarget, compiler: compilers.Compiler, optimization_level: str, debug: bool, sanitize: list[str]) -> T.List[str]:
1181 build_args = compiler.get_optimization_args(optimization_level)
1182 build_args += compiler.get_debug_args(debug)
1183 build_args += compiler.sanitizer_compile_args(target, sanitize)
1184
1185 return build_args
1186
1187 # Used in populating a simple nmake-style project's intellisense fields.
1188 # Given a list of compile args, for example -
1189 # [ '-I..\\some\\dir\\include', '-I../../some/other/dir', '/MDd', '/W2', '/std:c++17', '/Od', '/Zi', '-DSOME_DEF=1', '-DANOTHER_DEF=someval', ...]
1190 # returns a tuple of pre-processor defs (for this example) -
1191 # 'SOME_DEF=1;ANOTHER_DEF=someval;'
1192 # and include paths, e.g. -
1193 # '..\\some\\dir\\include;../../some/other/dir;'
1194 # and finally any remaining compiler options, e.g. -
1195 # '/MDd /W2 /std:c++17 /Od/Zi'
1196 @staticmethod
1197 def _extract_nmake_fields(captured_build_args: list[str]) -> T.Tuple[str, str, str]:
1198 include_dir_options = [
1199 '-I',
1200 '/I',
1201 '-isystem', # regular gcc / clang option to denote system header include search paths
1202 '/clang:-isystem', # clang-cl (msvc 'cl'-style clang wrapper) option to pass '-isystem' option to clang driver
1203 '/imsvc', # clang-cl option to 'Add directory to system include search path'
1204 '/external:I', # msvc cl option to add 'external' include search paths
1205 ]
1206
1207 defs = ''
1208 paths = '$(VC_IncludePath);$(WindowsSDK_IncludePath);'
1209 additional_opts = ''
1210 for arg in captured_build_args:
1211 if arg.startswith(('-D', '/D')):
1212 defs += arg[2:] + ';'
1213 else:
1214 opt_match = next((opt for opt in include_dir_options if arg.startswith(opt)), None)
1215 if opt_match:
1216 paths += arg[len(opt_match):] + ';'
1217 elif arg.startswith(('-', '/')):
1218 additional_opts += arg + ' '
1219 return (defs, paths, additional_opts)
1220
1221 @staticmethod
1222 def get_nmake_base_meson_command_and_exe_search_paths() -> T.Tuple[str, str]:
1223 meson_cmd_list = mesonlib.get_meson_command()
1224 assert len(meson_cmd_list) in {1, 2}
1225 # We expect get_meson_command() to either be of the form -
1226 # 1: ['path/to/meson.exe']
1227 # or -
1228 # 2: ['path/to/python.exe', 'and/path/to/meson.py']
1229 # so we'd like to ensure our makefile-style project invokes the same meson executable or python src as this instance.
1230 exe_search_paths = os.path.dirname(meson_cmd_list[0])
1231 nmake_base_meson_command = os.path.basename(meson_cmd_list[0])
1232 if len(meson_cmd_list) != 1:
1233 # We expect to be dealing with case '2', shown above.
1234 # With Windows, it's also possible that we get a path to the second element of meson_cmd_list that contains spaces
1235 # (e.g. 'and/path to/meson.py'). So, because this will end up directly in the makefile/NMake command lines, we'd
1236 # better always enclose it in quotes. Only strictly necessary for paths with spaces but no harm for paths without -
1237 nmake_base_meson_command += ' \"' + meson_cmd_list[1] + '\"'
1238 exe_search_paths += ';' + os.path.dirname(meson_cmd_list[1])
1239
1240 # Additionally, in some cases, we appear to have to add 'C:\Windows\system32;C:\Windows' to the 'Path' environment (via the
1241 # ExecutablePath element), without which, the 'meson compile ...' (NMakeBuildCommandLine) command can fail (failure to find
1242 # stdio.h and similar), so something is quietly switching some critical build behaviour based on the presence of these in
1243 # the 'Path'.
1244 # Not sure if this ultimately comes down to some 'find and guess' hidden behaviours within meson or within MSVC tools, but
1245 # I guess some projects may implicitly rely on this behaviour.
1246 # Things would be cleaner, more robust, repeatable, and portable if meson (and msvc tools) replaced all this kind of
1247 # find/guess behaviour with the requirement that things just be explicitly specified by the user.
1248 # An example of this can be seen with -
1249 # 1: Download https://github.com/facebook/zstd source
1250 # 2: cd to the 'zstd-dev\build\meson' dir
1251 # 3: meson setup -Dbin_programs=true -Dbin_contrib=true --genvslite vs2022 builddir_vslite
1252 # 4: Open the generated 'builddir_vslite_vs\zstd.sln' and build through a project, which should explicitly add the above to
1253 # the project's 'Executable Directories' paths and build successfully.
1254 # 5: Remove 'C:\Windows\system32;C:\Windows;' from the same project's 'Executable Directories' paths and rebuild.
1255 # This should now fail.
1256 # It feels uncomfortable to do this but what better alternative is there (and might this introduce new problems)? -
1257 exe_search_paths += ';C:\\Windows\\system32;C:\\Windows'
1258 # A meson project that explicitly specifies compiler/linker tools and sdk/include paths is not going to have any problems
1259 # with this addition.
1260
1261 return (nmake_base_meson_command, exe_search_paths)
1262
1263 def get_target_whole_program_opt(self, target: build.BuildTarget) -> str:
1264 lto = False
1265 pgo = 'off'
1266 try:
1267 lto = self.get_target_option(target, 'b_lto')
1268 pgo = self.get_target_option(target, 'b_pgo')
1269 except KeyError:
1270 pass
1271
1272 if pgo == 'off':
1273 return 'true' if lto else 'false'
1274
1275 if not lto:
1276 raise MesonException("b_pgo requires b_lto on MSVC.")
1277 return 'PGInstrument' if pgo == 'generate' else 'PGOptimize'
1278
1279 def add_gen_lite_makefile_vcxproj_elements(self,
1280 root: ET.Element,
1281 platform: str,
1282 target_ext: str,
1283 vslite_ctx: _VSLITE_CTX,
1284 target: build.AnyTargetType,
1285 proj_to_build_root: str,
1286 primary_src_lang: T.Optional[Language]) -> None:
1287 ET.SubElement(root, 'ImportGroup', Label='ExtensionSettings')
1288 ET.SubElement(root, 'ImportGroup', Label='Shared')
1289 prop_sheets_grp = ET.SubElement(root, 'ImportGroup', Label='PropertySheets')
1290 ET.SubElement(prop_sheets_grp, 'Import', {'Project': r'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props',
1291 'Condition': r"exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')",
1292 'Label': 'LocalAppDataPlatform'
1293 })
1294 ET.SubElement(root, 'PropertyGroup', Label='UserMacros')
1295
1296 (nmake_base_meson_command, exe_search_paths) = Vs2010Backend.get_nmake_base_meson_command_and_exe_search_paths()
1297
1298 # Relative path from this .vcxproj to the directory containing the set of '..._[debug/debugoptimized/release]' setup meson build dirs.
1299 proj_to_multiconfigured_builds_parent_dir = os.path.join(proj_to_build_root, '..')
1300
1301 # Conditional property groups per configuration (buildtype). E.g. -
1302 # <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='release|x64'">
1303 multi_config_buildtype_list = coredata.get_genvs_default_buildtype_list()
1304 for buildtype in multi_config_buildtype_list:
1305 per_config_prop_group = ET.SubElement(root, 'PropertyGroup', Condition=f'\'$(Configuration)|$(Platform)\'==\'{buildtype}|{platform}\'')
1306 (_, build_dir_tail) = os.path.split(self.src_to_build)
1307 meson_build_dir_for_buildtype = build_dir_tail[:-2] + buildtype # Get the buildtype suffixed 'builddir_[debug/release/etc]' from 'builddir_vs', for example.
1308 proj_to_build_dir_for_buildtype = str(os.path.join(proj_to_multiconfigured_builds_parent_dir, meson_build_dir_for_buildtype))
1309 ET.SubElement(per_config_prop_group, 'OutDir').text = f'{proj_to_build_dir_for_buildtype}\\'
1310 ET.SubElement(per_config_prop_group, 'IntDir').text = f'{proj_to_build_dir_for_buildtype}\\'
1311 ET.SubElement(per_config_prop_group, 'NMakeBuildCommandLine').text = f'{nmake_base_meson_command} compile -C "{proj_to_build_dir_for_buildtype}"'
1312 ET.SubElement(per_config_prop_group, 'NMakeOutput').text = f'$(OutDir){target.name}{target_ext}'
1313 captured_build_args = vslite_ctx[buildtype][target.get_id()]
1314 # 'captured_build_args' is a dictionary, mapping from each src file type to a list of compile args to use for that type.
1315 # Usually, there's just one but we could have multiple src types. However, since there's only one field for the makefile
1316 # project's NMake... preprocessor/include intellisense fields, we'll just use the first src type we have to fill in
1317 # these fields. Then, any src files in this VS project that aren't of this first src type will then need to override
1318 # its intellisense fields instead of simply referencing the values in the project.
1319 ET.SubElement(per_config_prop_group, 'NMakeReBuildCommandLine').text = f'{nmake_base_meson_command} compile -C "{proj_to_build_dir_for_buildtype}" --clean && {nmake_base_meson_command} compile -C "{proj_to_build_dir_for_buildtype}"'
1320 ET.SubElement(per_config_prop_group, 'NMakeCleanCommandLine').text = f'{nmake_base_meson_command} compile -C "{proj_to_build_dir_for_buildtype}" --clean'
1321 # Need to set the 'ExecutablePath' element for the above NMake... commands to be able to invoke the meson command.
1322 ET.SubElement(per_config_prop_group, 'ExecutablePath').text = exe_search_paths
1323 # We may not have any src files and so won't have a primary src language. In which case, we've nothing to fill in for this target's intellisense fields -
1324 if primary_src_lang:
1325 primary_src_type_build_args = captured_build_args[primary_src_lang]
1326 preproc_defs, inc_paths, other_compile_opts = Vs2010Backend._extract_nmake_fields(primary_src_type_build_args)
1327 ET.SubElement(per_config_prop_group, 'NMakePreprocessorDefinitions').text = preproc_defs
1328 ET.SubElement(per_config_prop_group, 'NMakeIncludeSearchPath').text = inc_paths
1329 ET.SubElement(per_config_prop_group, 'AdditionalOptions').text = other_compile_opts
1330
1331 # Unless we explicitly specify the following empty path elements, the project is assigned a load of nasty defaults that fill these
1332 # with values like -
1333 # $(VC_IncludePath);$(WindowsSDK_IncludePath);
1334 # which are all based on the current install environment (a recipe for non-reproducibility problems), not the paths that will be used by
1335 # the actual meson compile jobs. Although these elements look like they're only for MSBuild operations, they're not needed with our simple,
1336 # lite/makefile-style projects so let's just remove them in case they do get used/confused by intellisense.
1337 ET.SubElement(per_config_prop_group, 'IncludePath')
1338 ET.SubElement(per_config_prop_group, 'ExternalIncludePath')
1339 ET.SubElement(per_config_prop_group, 'ReferencePath')
1340 ET.SubElement(per_config_prop_group, 'LibraryPath')
1341 ET.SubElement(per_config_prop_group, 'LibraryWPath')
1342 ET.SubElement(per_config_prop_group, 'SourcePath')
1343 ET.SubElement(per_config_prop_group, 'ExcludePath')
1344
1345 def add_non_makefile_vcxproj_elements(
1346 self,
1347 root: ET.Element,
1348 type_config: ET.Element,
1349 target: build.BuildTarget,
1350 platform: str,
1351 subsystem: str | None,
1352 version: str | None,
1353 build_args: list[str],
1354 target_args: list[str],
1355 target_defines: list[str],
1356 target_inc_dirs: list[str],
1357 file_args: dict[Language, CompilerArgs]
1358 ) -> None:
1359 compiler = self._get_cl_compiler(target)
1360 buildtype_link_args = compiler.get_optimization_link_args(self.optimization)
1361
1362 # Prefix to use to access the build root from the vcxproj dir
1363 down = self.target_to_build_root(target)
1364
1365 # FIXME: Should the following just be set in create_basic_project(), even if
1366 # irrelevant for current target?
1367
1368 ET.SubElement(type_config, 'WholeProgramOptimization').text = self.get_target_whole_program_opt(target)
1369
1370 # Let VS auto-set the RTC level
1371 ET.SubElement(type_config, 'BasicRuntimeChecks').text = 'Default'
1372 # Incremental linking increases code size
1373 if '/INCREMENTAL:NO' in buildtype_link_args:
1374 ET.SubElement(type_config, 'LinkIncremental').text = 'false'
1375
1376 # Build information
1377 compiles = ET.SubElement(root, 'ItemDefinitionGroup')
1378 clconf = ET.SubElement(compiles, 'ClCompile')
1379 if True in ((dep.name == 'openmp') for dep in target.get_external_deps()):
1380 ET.SubElement(clconf, 'OpenMPSupport').text = 'true'
1381 # CRT type; debug or release
1382 vscrt_type = self.get_target_option(target, 'b_vscrt')
1383 assert isinstance(vscrt_type, str), 'for mypy'
1384 vscrt_val = compiler.get_crt_val(vscrt_type)
1385 if vscrt_val == 'mdd':
1386 ET.SubElement(type_config, 'UseDebugLibraries').text = 'true'
1387 ET.SubElement(clconf, 'RuntimeLibrary').text = 'MultiThreadedDebugDLL'
1388 elif vscrt_val == 'mt':
1389 # FIXME, wrong
1390 ET.SubElement(type_config, 'UseDebugLibraries').text = 'false'
1391 ET.SubElement(clconf, 'RuntimeLibrary').text = 'MultiThreaded'
1392 elif vscrt_val == 'mtd':
1393 # FIXME, wrong
1394 ET.SubElement(type_config, 'UseDebugLibraries').text = 'true'
1395 ET.SubElement(clconf, 'RuntimeLibrary').text = 'MultiThreadedDebug'
1396 else:
1397 ET.SubElement(type_config, 'UseDebugLibraries').text = 'false'
1398 ET.SubElement(clconf, 'RuntimeLibrary').text = 'MultiThreadedDLL'
1399 # Sanitizers
1400 if '/fsanitize=address' in build_args:
1401 ET.SubElement(type_config, 'EnableASAN').text = 'true'
1402 # Debug format
1403 if '/ZI' in build_args or '-ZI' in build_args:
1404 ET.SubElement(clconf, 'DebugInformationFormat').text = 'EditAndContinue'
1405 elif '/Zi' in build_args or '-Zi' in build_args:
1406 ET.SubElement(clconf, 'DebugInformationFormat').text = 'ProgramDatabase'
1407 elif '/Z7' in build_args or '-Z7' in build_args:
1408 ET.SubElement(clconf, 'DebugInformationFormat').text = 'OldStyle'
1409 else:
1410 ET.SubElement(clconf, 'DebugInformationFormat').text = 'None'
1411 # Runtime checks
1412 if '/RTC1' in build_args:
1413 ET.SubElement(clconf, 'BasicRuntimeChecks').text = 'EnableFastChecks'
1414 elif '/RTCu' in build_args:
1415 ET.SubElement(clconf, 'BasicRuntimeChecks').text = 'UninitializedLocalUsageCheck'
1416 elif '/RTCs' in build_args:
1417 ET.SubElement(clconf, 'BasicRuntimeChecks').text = 'StackFrameRuntimeCheck'
1418 # Exception handling has to be set in the xml in addition to the "AdditionalOptions" because otherwise
1419 # cl will give warning D9025: overriding '/Ehs' with cpp_eh value
1420 if 'cpp' in target.compilers:
1421 eh = self.environment.coredata.get_option_for_target(target, OptionKey('cpp_eh', machine=target.for_machine))
1422 if eh == 'a':
1423 ET.SubElement(clconf, 'ExceptionHandling').text = 'Async'
1424 elif eh == 's':
1425 ET.SubElement(clconf, 'ExceptionHandling').text = 'SyncCThrow'
1426 elif eh == 'none':
1427 ET.SubElement(clconf, 'ExceptionHandling').text = 'false'
1428 else: # 'sc' or 'default'
1429 ET.SubElement(clconf, 'ExceptionHandling').text = 'Sync'
1430
1431 if len(target_args) > 0:
1432 target_args.append('%(AdditionalOptions)')
1433 ET.SubElement(clconf, "AdditionalOptions").text = ' '.join(target_args)
1434 ET.SubElement(clconf, 'AdditionalIncludeDirectories').text = ';'.join(target_inc_dirs)
1435 target_defines.append('%(PreprocessorDefinitions)')
1436 ET.SubElement(clconf, 'PreprocessorDefinitions').text = ';'.join(target_defines)
1437 ET.SubElement(clconf, 'FunctionLevelLinking').text = 'true'
1438 # Warning level
1439 warning_level = T.cast('str', self.get_target_option(target, 'warning_level'))
1440 warning_level = 'EnableAllWarnings' if warning_level == 'everything' else 'Level' + str(1 + int(warning_level))
1441 ET.SubElement(clconf, 'WarningLevel').text = warning_level
1442 if self.get_target_option(target, 'werror'):
1443 ET.SubElement(clconf, 'TreatWarningAsError').text = 'true'
1444 # Optimization flags
1445 o_flags = split_o_flags_args(build_args)
1446 if '/Ox' in o_flags:
1447 ET.SubElement(clconf, 'Optimization').text = 'Full'
1448 elif '/O2' in o_flags:
1449 ET.SubElement(clconf, 'Optimization').text = 'MaxSpeed'
1450 elif '/O1' in o_flags:
1451 ET.SubElement(clconf, 'Optimization').text = 'MinSpace'
1452 elif '/Od' in o_flags:
1453 ET.SubElement(clconf, 'Optimization').text = 'Disabled'
1454 if '/Oi' in o_flags:
1455 ET.SubElement(clconf, 'IntrinsicFunctions').text = 'true'
1456 if '/Ob1' in o_flags:
1457 ET.SubElement(clconf, 'InlineFunctionExpansion').text = 'OnlyExplicitInline'
1458 elif '/Ob2' in o_flags:
1459 ET.SubElement(clconf, 'InlineFunctionExpansion').text = 'AnySuitable'
1460 # Size-preserving flags
1461 if '/Os' in o_flags or '/O1' in o_flags:
1462 ET.SubElement(clconf, 'FavorSizeOrSpeed').text = 'Size'
1463 # Note: setting FavorSizeOrSpeed with clang-cl conflicts with /Od and can make debugging difficult, so don't.
1464 elif '/Od' not in o_flags:
1465 ET.SubElement(clconf, 'FavorSizeOrSpeed').text = 'Speed'
1466 # Note: SuppressStartupBanner is /NOLOGO and is 'true' by default
1467 self.generate_lang_standard_info(file_args, clconf)
1468
1469 resourcecompile = ET.SubElement(compiles, 'ResourceCompile')
1470 ET.SubElement(resourcecompile, 'PreprocessorDefinitions')
1471
1472 # Linker options
1473 link = ET.SubElement(compiles, 'Link')
1474 extra_link_args = compiler.compiler_args()
1475 extra_link_args += compiler.get_optimization_link_args(self.optimization)
1476 if self.get_target_option(target, 'werror'):
1477 extra_link_args += compiler.get_linker_fatal_warnings()
1478 # Generate Debug info
1479 if self.debug:
1480 self.generate_debug_information(link)
1481 else:
1482 ET.SubElement(link, 'GenerateDebugInformation').text = 'false'
1483 if not isinstance(target, build.StaticLibrary):
1484 if isinstance(target, build.SharedModule):
1485 extra_link_args += compiler.get_std_shared_module_link_args(target)
1486 extra_link_args += compiler.get_build_link_args(target, self.build)
1487 # Only non-static built targets need link args and link dependencies
1488 extra_link_args += target.link_args
1489 # External deps must be last because target link libraries may depend on them.
1490 for dep in target.get_external_deps():
1491 # Extend without reordering or de-dup to preserve `-L -l` sets
1492 # https://github.com/mesonbuild/meson/issues/1718
1493 if dep.name == 'openmp':
1494 ET.SubElement(clconf, 'OpenMPSupport').text = 'true'
1495 else:
1496 extra_link_args.extend_direct(dep.get_link_args())
1497 for d in target.get_dependencies():
1498 if isinstance(d, build.StaticLibrary):
1499 for dep in d.get_external_deps():
1500 if dep.name == 'openmp':
1501 ET.SubElement(clconf, 'OpenMPSupport').text = 'true'
1502 else:
1503 extra_link_args.extend_direct(dep.get_link_args())
1504 # Add link args for c_* or cpp_* build options. Currently this only
1505 # adds c_winlibs and cpp_winlibs when building for Windows. This needs
1506 # to be after all internal and external libraries so that unresolved
1507 # symbols from those can be found here. This is needed when the
1508 # *_winlibs that we want to link to are static mingw64 libraries.
1509 extra_link_args += compiler.get_option_link_args(target, target.subproject)
1510 (additional_libpaths, additional_links, extra_link_args) = self.split_link_args(extra_link_args.to_native())
1511
1512 # Add more libraries to be linked if needed
1513 for t in target.get_dependencies():
1514 if isinstance(t, build.CustomTargetIndex):
1515 # We don't need the actual project here, just the library name
1516 lobj = t
1517 else:
1518 lobj = self.build.targets[t.get_id()]
1519 targetname = self.get_target_filename_for_linking(lobj)
1520 if targetname is None:
1521 continue
1522 linkname = os.path.join(down, targetname)
1523 if t in target.link_whole_targets:
1524 if compiler.id == 'msvc' and version_compare(compiler.version, '<19.00.23918'):
1525 # Expand our object lists manually if we are on pre-Visual Studio 2015 Update 2
1526 if not isinstance(t, build.BuildTarget):
1527 raise MesonException(
1528 f'Cannot extract objects from custom target {t.name!r} to '
1529 f'link_whole it into {target.name!r}: this is not supported '
1530 'with versions of MSVC older than Visual Studio 2015 Update 2.')
1531 l = t.extract_all_objects(False)
1532
1533 # Unfortunately, we can't use self.object_filename_from_source()
1534 for gen in l.genlist:
1535 for src in gen.get_outputs():
1536 if compilers.is_source(src):
1537 path = self.get_target_generated_dir(t, gen, src)
1538 gen_src_ext = '.' + os.path.splitext(path)[1][1:]
1539 extra_link_args.append(path[:-len(gen_src_ext)] + '.obj')
1540
1541 for src in l.srclist:
1542 if compilers.is_source(src):
1543 target_private_dir = self.relpath(self.get_target_private_dir(t),
1544 self.get_target_dir(t))
1545 rel_obj = self.object_filename_from_source(t, compiler, src, target_private_dir)
1546 extra_link_args.append(rel_obj)
1547
1548 extra_link_args.extend(self.flatten_object_list(t)[0])
1549 else:
1550 # /WHOLEARCHIVE:foo must go into AdditionalOptions
1551 extra_link_args += compiler.get_link_whole_for([linkname])
1552 # To force Visual Studio to build this project even though it
1553 # has no sources, we include a reference to the vcxproj file
1554 # that builds this target. Technically we should add this only
1555 # if the current target has no sources, but it doesn't hurt to
1556 # have 'extra' references.
1557 trelpath = self.get_target_dir_relative_to(t, target)
1558 tvcxproj = os.path.join(trelpath, t.get_id() + '.vcxproj')
1559 tid = self.environment.coredata.target_guids[t.get_id()]
1560 self.add_project_reference(root, tvcxproj, tid, link_outputs=True)
1561 # Mark the dependency as already handled to not have
1562 # multiple references to the same target.
1563 self.handled_target_deps[target.get_id()].append(t.get_id())
1564 else:
1565 # Other libraries go into AdditionalDependencies
1566 if linkname not in additional_links:
1567 additional_links.append(linkname)
1568 for lib in self.get_custom_target_provided_libraries(target):
1569 additional_links.append(self.relpath(lib, self.get_target_dir(target)))
1570
1571 if len(extra_link_args) > 0:
1572 args = [self.escape_additional_option(arg) for arg in extra_link_args]
1573 args.append('%(AdditionalOptions)')
1574 ET.SubElement(link, "AdditionalOptions").text = ' '.join(args)
1575 if len(additional_libpaths) > 0:
1576 additional_libpaths.insert(0, '%(AdditionalLibraryDirectories)')
1577 ET.SubElement(link, 'AdditionalLibraryDirectories').text = ';'.join(additional_libpaths)
1578 if len(additional_links) > 0:
1579 additional_links.append('%(AdditionalDependencies)')
1580 ET.SubElement(link, 'AdditionalDependencies').text = ';'.join(additional_links)
1581 ofile = ET.SubElement(link, 'OutputFile')
1582 ofile.text = f'$(OutDir){target.get_filename()}'
1583 if subsystem is not None:
1584 subsys = ET.SubElement(link, 'SubSystem')
1585 subsys.text = subsystem
1586 if version is not None:
1587 # Undocumented, but you can find a reference in WDK props
1588 minver = ET.SubElement(link, 'MinimumRequiredVersion')
1589 minver.text = version
1590 if isinstance(target, (build.SharedLibrary, build.Executable)) and target.get_import_filename():
1591 # DLLs built with MSVC always have an import library except when
1592 # they're data-only DLLs, but we don't support those yet.
1593 ET.SubElement(link, 'ImportLibrary').text = target.get_import_filename()
1594 if isinstance(target, (build.SharedLibrary, build.Executable)):
1595 # Add module definitions file, if provided
1596 if target.vs_module_defs:
1597 relpath = os.path.join(down, target.vs_module_defs.rel_to_builddir(self.build_to_src))
1598 ET.SubElement(link, 'ModuleDefinitionFile').text = relpath
1599 if self.debug:
1600 pdb = ET.SubElement(link, 'ProgramDataBaseFileName')
1601 pdb.text = f'$(OutDir){target.name}.pdb'
1602 targetmachine = ET.SubElement(link, 'TargetMachine')
1603 if target.for_machine is MachineChoice.BUILD:
1604 targetplatform = platform.lower()
1605 else:
1606 targetplatform = self.platform.lower()
1607 if targetplatform == 'win32':
1608 targetmachine.text = 'MachineX86'
1609 elif targetplatform == 'x64' or detect_microsoft_gdk(targetplatform):
1610 targetmachine.text = 'MachineX64'
1611 elif targetplatform == 'arm':
1612 targetmachine.text = 'MachineARM'
1613 elif targetplatform == 'arm64':
1614 targetmachine.text = 'MachineARM64'
1615 elif targetplatform == 'arm64ec':
1616 targetmachine.text = 'MachineARM64EC'
1617 else:
1618 raise MesonException('Unsupported Visual Studio target machine: ' + targetplatform)
1619 # /nologo
1620 ET.SubElement(link, 'SuppressStartupBanner').text = 'true'
1621 # /release
1622 addchecksum = self.get_target_option(target, 'buildtype') != 'debug'
1623 if addchecksum:
1624 ET.SubElement(link, 'SetChecksum').text = 'true'
1625
1626 # Visual studio doesn't simply allow the src files of a project to be added with the 'Condition=...' attribute,
1627 # to allow us to point to the different debug/debugoptimized/release sets of generated src files for each of
1628 # the solution's configurations. Similarly, 'ItemGroup' also doesn't support 'Condition'. So, without knowing
1629 # a better (simple) alternative, for now, we'll repoint these generated sources (which will be incorrectly
1630 # pointing to non-existent files under our '[builddir]_vs' directory) to the appropriate location under one of
1631 # our buildtype build directories (e.g. '[builddir]_debug').
1632 # This will at least allow the user to open the files of generated sources listed in the solution explorer,
1633 # once a build/compile has generated these sources.
1634 #
1635 # This modifies the paths in 'gen_files' in place, as opposed to returning a new list of modified paths.
1636 def relocate_generated_file_paths_to_concrete_build_dir(self, gen_files: T.List[str], target: build.AnyTargetType) -> None:
1637 (_, build_dir_tail) = os.path.split(self.src_to_build)
1638 meson_build_dir_for_buildtype = build_dir_tail[:-2] + coredata.get_genvs_default_buildtype_list()[0] # Get the first buildtype suffixed dir (i.e. '[builddir]_debug') from '[builddir]_vs'
1639 # Relative path from this .vcxproj to the directory containing the set of '..._[debug/debugoptimized/release]' setup meson build dirs.
1640 proj_to_build_root = self.target_to_build_root(target)
1641 proj_to_multiconfigured_builds_parent_dir = os.path.join(proj_to_build_root, '..')
1642 proj_to_build_dir_for_buildtype = str(os.path.join(proj_to_multiconfigured_builds_parent_dir, meson_build_dir_for_buildtype))
1643 relocate_to_concrete_builddir_target = os.path.normpath(os.path.join(proj_to_build_dir_for_buildtype, self.get_target_dir(target)))
1644 for idx, file_path in enumerate(gen_files):
1645 gen_files[idx] = os.path.normpath(os.path.join(relocate_to_concrete_builddir_target, file_path))
1646
1647 # Returns bool indicating whether the .vcxproj has been generated.
1648 # Under some circumstances, it's unnecessary to create some .vcxprojs, so, when generating the .sln,
1649 # we need to respect that not all targets will have generated a project.
1650 def gen_vcxproj(self, target: build.Target, ofname: str, guid: str, vslite_ctx: _VSLITE_CTX | None = None) -> bool:
1651 mlog.debug(f'Generating vcxproj {target.name}.')
1652 subsystem: str | None = None
1653 version: str | None = None
1654 self.handled_target_deps[target.get_id()] = []
1655
1656 # vs backend does not support link_early_args
1657 if isinstance(target, build.BuildTarget) and not isinstance(target, build.StaticLibrary) and target.link_early_args:
1658 raise MesonException(f'Visual Studio backend does not support link_early_args for {target.get_basename()}')
1659
1660 if self.gen_lite:
1661 if not isinstance(target, build.BuildTarget):
1662 # Since we're going to delegate all building to the one true meson build command, we don't need
1663 # to generate .vcxprojs for targets that don't add any source files or just perform custom build
1664 # commands. These are targets of types CustomTarget or RunTarget. So let's just skip generating
1665 # these otherwise insubstantial non-BuildTarget targets.
1666 return False
1667 conftype = 'Makefile'
1668 elif isinstance(target, build.Executable):
1669 conftype = 'Application'
1670 subsystem, _, version = target.win_subsystem.partition(',')
1671 elif isinstance(target, build.StaticLibrary):
1672 conftype = 'StaticLibrary'
1673 elif isinstance(target, build.SharedLibrary):
1674 conftype = 'DynamicLibrary'
1675 subsystem, _, version = target.win_subsystem.partition(',')
1676 elif isinstance(target, build.CustomTarget):
1677 self.gen_custom_target_vcxproj(target, ofname, guid)
1678 return True
1679 elif isinstance(target, build.RunTarget):
1680 self.gen_run_target_vcxproj(target, ofname, guid)
1681 return True
1682 elif isinstance(target, build.CompileTarget):
1683 self.gen_compile_target_vcxproj(target, ofname, guid)
1684 return True
1685 else:
1686 raise MesonException(f'Unknown target type for {target.get_basename()}')
1687
1688 (sources, headers, objects, _languages) = self.split_sources(target.sources)
1689 if self.is_unity(target):
1690 sources = self.generate_unity_files(target, sources)
1691 if target.for_machine is MachineChoice.BUILD:
1692 platform = self.build_platform
1693 else:
1694 platform = self.platform
1695
1696 masm = self.get_masm_type(target)
1697
1698 tfilename = os.path.splitext(target.get_filename())
1699
1700 (root, type_config) = self.create_basic_project(tfilename[0],
1701 temp_dir=target.get_id(),
1702 guid=guid,
1703 conftype=conftype,
1704 target_ext=tfilename[1],
1705 target_platform=platform,
1706 gen_manifest=self.get_gen_manifest(target),
1707 masm_type=masm)
1708
1709 generated_files, custom_target_output_files, generated_files_include_dirs = self.generate_custom_generator_commands(
1710 target, root)
1711 (gen_src, gen_hdrs, gen_objs, _gen_langs) = self.split_sources(generated_files)
1712 (custom_src, custom_hdrs, custom_objs, _custom_langs) = self.split_sources(custom_target_output_files)
1713 gen_src += custom_src
1714 gen_hdrs += custom_hdrs
1715
1716 compiler = self._get_cl_compiler(target)
1717 build_args = self.get_build_args(target, compiler, self.optimization, self.debug, self.sanitize)
1718
1719 assert isinstance(target, (build.Executable, build.SharedLibrary, build.StaticLibrary, build.SharedModule)), 'for mypy'
1720 # Prefix to use to access the build root from the vcxproj dir
1721 proj_to_build_root = self.target_to_build_root(target)
1722 # Prefix to use to access the source tree's root from the vcxproj dir
1723 proj_to_src_root = os.path.join(proj_to_build_root, self.build_to_src)
1724 # Prefix to use to access the source tree's subdir from the vcxproj dir
1725 proj_to_src_dir = os.path.join(proj_to_src_root, self.get_target_dir(target))
1726
1727 (target_args, file_args), (target_defines, file_defines), (target_inc_dirs, file_inc_dirs) = self.get_args_defines_and_inc_dirs(
1728 target, compiler, generated_files_include_dirs, proj_to_src_root, proj_to_src_dir, build_args)
1729
1730 if self.gen_lite:
1731 assert vslite_ctx is not None
1732 primary_src_lang = get_primary_source_lang(target.sources, custom_src)
1733 self.add_gen_lite_makefile_vcxproj_elements(root, platform, tfilename[1], vslite_ctx, target, proj_to_build_root, primary_src_lang)
1734 else:
1735 self.add_non_makefile_vcxproj_elements(root, type_config, target, platform, subsystem, version, build_args, target_args, target_defines, target_inc_dirs, file_args)
1736
1737 meson_file_group = ET.SubElement(root, 'ItemGroup')
1738 ET.SubElement(meson_file_group, 'None', Include=os.path.join(proj_to_src_dir, build_filename))
1739
1740 # Visual Studio can't load projects that present duplicated items. Filter them out
1741 # by keeping track of already added paths.
1742 def path_normalize_add(path: str, lis: T.List[str]) -> bool:
1743 normalized = os.path.normcase(os.path.normpath(path))
1744 if normalized not in lis:
1745 lis.append(normalized)
1746 return True
1747 else:
1748 return False
1749
1750 pch_sources: T.Dict[Language, T.Tuple[str, T.Optional[str], str, T.Optional[str]]] = {}
1751 if self.target_uses_pch(target):
1752 for lang in T.cast('T.Tuple[Language]', ('c', 'cpp')):
1753 pch = target.pch[lang]
1754 if not pch:
1755 continue
1756 if compiler.id == 'msvc':
1757 if pch[1] is None:
1758 # Auto generate PCH.
1759 src = os.path.join(proj_to_build_root, self.create_msvc_pch_implementation(target, lang, pch[0]))
1760 pch_header_dir = os.path.dirname(os.path.join(proj_to_src_dir, pch[0]))
1761 else:
1762 src = os.path.join(proj_to_src_dir, pch[1])
1763 pch_header_dir = None
1764 pch_sources[lang] = (pch[0], src, lang, pch_header_dir)
1765 else:
1766 # I don't know whether its relevant but let's handle other compilers
1767 # used with a vs backend
1768 pch_sources[lang] = (pch[0], None, lang, None)
1769
1770 previous_includes: list[str] = []
1771 if len(headers) + len(gen_hdrs) + len(target.extra_files) + len(pch_sources) > 0:
1772 if self.gen_lite and gen_hdrs:
1773 # Although we're constructing our .vcxproj under our '..._vs' directory, we want to reference generated files
1774 # in our concrete build directories (e.g. '..._debug'), where generated files will exist after building.
1775 self.relocate_generated_file_paths_to_concrete_build_dir(gen_hdrs, target)
1776
1777 inc_hdrs = ET.SubElement(root, 'ItemGroup')
1778 for h in headers:
1779 relpath = os.path.join(proj_to_build_root, h.rel_to_builddir(self.build_to_src))
1780 if path_normalize_add(relpath, previous_includes):
1781 ET.SubElement(inc_hdrs, 'CLInclude', Include=relpath)
1782 for h in gen_hdrs:
1783 if path_normalize_add(h, previous_includes):
1784 ET.SubElement(inc_hdrs, 'CLInclude', Include=h)
1785 for h in target.extra_files:
1786 relpath = os.path.join(proj_to_build_root, h.rel_to_builddir(self.build_to_src))
1787 if path_normalize_add(relpath, previous_includes):
1788 ET.SubElement(inc_hdrs, 'CLInclude', Include=relpath)
1789 for headers in pch_sources.values():
1790 path = os.path.join(proj_to_src_dir, headers[0])
1791 if path_normalize_add(path, previous_includes):
1792 ET.SubElement(inc_hdrs, 'CLInclude', Include=path)
1793
1794 previous_sources: list[str] = []
1795 if len(sources) + len(gen_src) + len(pch_sources) > 0:
1796 if self.gen_lite:
1797 # Get data to fill in intellisense fields for sources that can't reference the project-wide values
1798 defs_paths_opts_per_lang_and_buildtype = get_non_primary_lang_intellisense_fields(
1799 vslite_ctx,
1800 target.get_id(),
1801 primary_src_lang)
1802 if gen_src:
1803 # Although we're constructing our .vcxproj under our '..._vs' directory, we want to reference generated files
1804 # in our concrete build directories (e.g. '..._debug'), where generated files will exist after building.
1805 self.relocate_generated_file_paths_to_concrete_build_dir(gen_src, target)
1806
1807 inc_src = ET.SubElement(root, 'ItemGroup')
1808 for s in sources:
1809 relpath = os.path.join(proj_to_build_root, s.rel_to_builddir(self.build_to_src))
1810 if path_normalize_add(relpath, previous_sources):
1811 lang = Vs2010Backend.lang_from_source_file(s)
1812 if lang == 'masm' and masm:
1813 inc_cl = ET.SubElement(inc_src, masm.upper(), Include=relpath)
1814 else:
1815 inc_cl = ET.SubElement(inc_src, 'CLCompile', Include=relpath)
1816
1817 if self.gen_lite:
1818 self.add_project_nmake_defs_incs_and_opts(inc_cl, relpath, defs_paths_opts_per_lang_and_buildtype, platform)
1819 else:
1820 if lang != 'masm':
1821 self.add_pch(pch_sources, lang, inc_cl)
1822 self.add_additional_options(lang, inc_cl, file_args)
1823 self.add_preprocessor_defines(lang, inc_cl, file_defines)
1824 self.add_include_dirs(lang, inc_cl, file_inc_dirs)
1825 ET.SubElement(inc_cl, 'ObjectFileName').text = "$(IntDir)" + \
1826 self.object_filename_from_source(target, compiler, s)
1827 for s in gen_src:
1828 if path_normalize_add(s, previous_sources):
1829 lang = Vs2010Backend.lang_from_source_file(s)
1830 if lang == 'masm' and masm:
1831 inc_cl = ET.SubElement(inc_src, masm.upper(), Include=s)
1832 else:
1833 inc_cl = ET.SubElement(inc_src, 'CLCompile', Include=s)
1834
1835 if self.gen_lite:
1836 self.add_project_nmake_defs_incs_and_opts(inc_cl, s, defs_paths_opts_per_lang_and_buildtype, platform)
1837 else:
1838 if lang != 'masm':
1839 self.add_pch(pch_sources, lang, inc_cl)
1840 self.add_additional_options(lang, inc_cl, file_args)
1841 self.add_preprocessor_defines(lang, inc_cl, file_defines)
1842 self.add_include_dirs(lang, inc_cl, file_inc_dirs)
1843 s = File.from_built_file(target.get_builddir(), s)
1844 ET.SubElement(inc_cl, 'ObjectFileName').text = "$(IntDir)" + \
1845 self.object_filename_from_source(target, compiler, s)
1846 for lang, headers in pch_sources.items():
1847 impl = headers[1]
1848 if impl and path_normalize_add(impl, previous_sources):
1849 inc_cl = ET.SubElement(inc_src, 'CLCompile', Include=impl)
1850 self.create_pch(pch_sources, lang, inc_cl)
1851 if self.gen_lite:
1852 self.add_project_nmake_defs_incs_and_opts(inc_cl, impl, defs_paths_opts_per_lang_and_buildtype, platform)
1853 else:
1854 self.add_additional_options(lang, inc_cl, file_args)
1855 self.add_preprocessor_defines(lang, inc_cl, file_defines)
1856 pch_header_dir = pch_sources[lang][3]
1857 if pch_header_dir:
1858 inc_dirs = copy.deepcopy(file_inc_dirs)
1859 inc_dirs[lang] = [pch_header_dir] + inc_dirs[lang]
1860 else:
1861 inc_dirs = file_inc_dirs
1862 self.add_include_dirs(lang, inc_cl, inc_dirs)
1863 # XXX: Do we need to set the object file name here too?
1864
1865 additional_objects = []
1866 for o in self.flatten_object_list(target, proj_to_build_root)[0]:
1867 assert isinstance(o, str)
1868 additional_objects.append(o)
1869 for o in custom_objs:
1870 additional_objects.append(o)
1871
1872 # VS automatically links CustomBuild outputs whose name ends in .obj or .res,
1873 # but the others need to be included explicitly
1874 explicit_link_gen_objs = [obj for obj in gen_objs if not obj.endswith(('.obj', '.res'))]
1875
1876 previous_objects: list[str] = []
1877 if len(objects) + len(additional_objects) + len(explicit_link_gen_objs) > 0:
1878 inc_objs = ET.SubElement(root, 'ItemGroup')
1879 for s in objects:
1880 relpath = os.path.join(proj_to_build_root, s.rel_to_builddir(self.build_to_src))
1881 if path_normalize_add(relpath, previous_objects):
1882 ET.SubElement(inc_objs, 'Object', Include=relpath)
1883 for s in additional_objects + explicit_link_gen_objs:
1884 if path_normalize_add(s, previous_objects):
1885 ET.SubElement(inc_objs, 'Object', Include=s)
1886
1887 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.targets')
1888 ext_tgt_grp = ET.SubElement(root, 'ImportGroup', Label='ExtensionTargets')
1889 if masm:
1890 ET.SubElement(ext_tgt_grp, 'Import', Project=rf'$(VCTargetsPath)\BuildCustomizations\{masm}.targets')
1891 self.add_regen_dependency(root)
1892 if not self.gen_lite:
1893 # Injecting further target dependencies into this vcxproj implies and forces a Visual Studio BUILD dependency,
1894 # which we don't want when using 'genvslite'. A gen_lite build as little involvement with the visual studio's
1895 # build system as possible.
1896 self.add_target_deps(root, target)
1897 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
1898 if self.environment.coredata.optstore.get_value_for(OptionKey('layout')) == 'mirror':
1899 self.gen_vcxproj_filters(target, ofname)
1900 return True
1901
1902 def gen_vcxproj_filters(self, target: build.BuildTarget, ofname: str) -> None:
1903 # Generate pitchfork of filters based on directory structure.
1904 root = ET.Element('Project', {'ToolsVersion': '4.0',
1905 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'})
1906 filter_folders = ET.SubElement(root, 'ItemGroup')
1907 filter_items = ET.SubElement(root, 'ItemGroup')
1908 mlog.debug(f'Generating vcxproj filters {target.name}.')
1909
1910 def relative_to_defined_in(file: File) -> str:
1911 # Get the relative path to file's directory from the location of the meson.build that defines this target.
1912 return os.path.dirname(self.relpath(PureWindowsPath(file.subdir, file.fname), self.get_target_dir(target)))
1913
1914 found_folders_to_filter = {}
1915 all_files = target.sources + target.extra_files
1916
1917 # Build a dictionary of all used relative paths (i.e. from the meson.build defining this target)
1918 # for all sources.
1919 for i in all_files:
1920 if not os.path.isabs(i.fname):
1921 dirname = relative_to_defined_in(i)
1922 if dirname:
1923 found_folders_to_filter[dirname] = ''
1924
1925 # Now walk up each of those relative paths checking for empty intermediate dirs to generate the filter.
1926 for folder in found_folders_to_filter:
1927 dirname = folder
1928 filter = ''
1929
1930 while dirname:
1931 basename = os.path.basename(dirname)
1932
1933 if filter == '':
1934 filter = basename
1935 else:
1936 # Use '/' to squash empty dirs. To actually get a '\', use '%255c'.
1937 filter = basename + ('\\' if dirname in found_folders_to_filter else '/') + filter
1938
1939 dirname = os.path.dirname(dirname)
1940
1941 # Don't add an empty filter, breaks all other (?) filters.
1942 if filter != '':
1943 found_folders_to_filter[folder] = filter
1944 filter_element = ET.SubElement(filter_folders, 'Filter', {'Include': filter})
1945 uuid_element = ET.SubElement(filter_element, 'UniqueIdentifier')
1946 uuid_element.text = '{' + str(uuid.uuid4()).upper() + '}'
1947
1948 sources, headers, objects, _ = self.split_sources(all_files)
1949 down = self.target_to_build_root(target)
1950
1951 def add_element(type_name: str, elements: list[File]) -> None:
1952 for i in elements:
1953 if not os.path.isabs(i.fname):
1954 dirname = relative_to_defined_in(i)
1955
1956 if dirname and dirname in found_folders_to_filter:
1957 relpath = os.path.join(down, i.rel_to_builddir(self.build_to_src))
1958 target_element = ET.SubElement(filter_items, type_name, {'Include': relpath})
1959 filter_element = ET.SubElement(target_element, 'Filter')
1960 filter_element.text = found_folders_to_filter[dirname]
1961
1962 add_element('ClCompile', sources)
1963 add_element('ClInclude', headers)
1964 add_element('Object', objects)
1965
1966 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname + '.filters')
1967
1968 def gen_regenproj(self) -> None:
1969 # To fully adapt the REGEN work for a 'genvslite' solution, to check timestamps, settings, and regenerate the
1970 # '[builddir]_vs' solution/vcxprojs, as well as regenerating the accompanying buildtype-suffixed ninja build
1971 # directories (from which we need to first collect correct, updated preprocessor defs and compiler options in
1972 # order to fill in the regenerated solution's intellisense settings) would require some non-trivial intrusion
1973 # into the 'meson --internal regencheck ./meson-private' execution path (and perhaps also the '--internal
1974 # regenerate' and even 'meson setup --reconfigure' code). So, for now, we'll instead give the user a simpler
1975 # 'reconfigure' utility project that just runs 'meson setup --reconfigure [builddir]_[buildtype] [srcdir]' on
1976 # each of the ninja build dirs.
1977 #
1978 # FIXME: That will keep the building and compiling correctly configured but obviously won't update the
1979 # solution and vcxprojs, which may allow solution src files and intellisense options to go out-of-date; the
1980 # user would still have to manually 'meson setup --genvslite [vsxxxx] [builddir] [srcdir]' to fully regenerate
1981 # a complete and correct solution.
1982 if self.gen_lite:
1983 project_name = 'RECONFIGURE'
1984 ofname = os.path.join(self.environment.get_build_dir(), 'RECONFIGURE.vcxproj')
1985 conftype = 'Makefile'
1986 # I find the REGEN project doesn't work; it fails to invoke the appropriate -
1987 # python meson.py --internal regencheck builddir\meson-private
1988 # command, despite the fact that manually running such a command in a shell runs just fine.
1989 # Running/building the regen project produces the error -
1990 # ...Microsoft.CppBuild.targets(460,5): error MSB8020: The build tools for ClangCL (Platform Toolset = 'ClangCL') cannot be found. To build using the ClangCL build tools, please install ...
1991 # Not sure why but a simple makefile-style project that executes the full '...regencheck...' command actually works (and seems a little simpler).
1992 # Although I've limited this change to only happen under '--genvslite', perhaps ...
1993 # FIXME : Should all utility projects use the simpler and less problematic makefile-style project?
1994 else:
1995 project_name = 'REGEN'
1996 ofname = os.path.join(self.environment.get_build_dir(), 'REGEN.vcxproj')
1997 conftype = 'Utility'
1998
1999 guid = self.environment.coredata.regen_guid
2000 (root, type_config) = self.create_basic_project(project_name,
2001 temp_dir='regen-temp',
2002 guid=guid,
2003 conftype=conftype
2004 )
2005
2006 if self.gen_lite:
2007 (nmake_base_meson_command, exe_search_paths) = Vs2010Backend.get_nmake_base_meson_command_and_exe_search_paths()
2008 all_configs_prop_group = ET.SubElement(root, 'PropertyGroup')
2009
2010 # Multi-line command to reconfigure all buildtype-suffixed build dirs
2011 multi_config_buildtype_list = coredata.get_genvs_default_buildtype_list()
2012 (_, build_dir_tail) = os.path.split(self.src_to_build)
2013 proj_to_multiconfigured_builds_parent_dir = '..' # We know this RECONFIGURE.vcxproj will always be in the '[buildir]_vs' dir.
2014 proj_to_src_dir = self.build_to_src
2015 reconfigure_all_cmd = ''
2016 for buildtype in multi_config_buildtype_list:
2017 meson_build_dir_for_buildtype = build_dir_tail[:-2] + buildtype # Get the buildtype suffixed 'builddir_[debug/release/etc]' from 'builddir_vs', for example.
2018 proj_to_build_dir_for_buildtype = str(os.path.join(proj_to_multiconfigured_builds_parent_dir, meson_build_dir_for_buildtype))
2019 reconfigure_all_cmd += f'{nmake_base_meson_command} setup --reconfigure "{proj_to_build_dir_for_buildtype}" "{proj_to_src_dir}"\n'
2020 ET.SubElement(all_configs_prop_group, 'NMakeBuildCommandLine').text = reconfigure_all_cmd
2021 ET.SubElement(all_configs_prop_group, 'NMakeReBuildCommandLine').text = reconfigure_all_cmd
2022 ET.SubElement(all_configs_prop_group, 'NMakeCleanCommandLine').text = ''
2023
2024 #Need to set the 'ExecutablePath' element for the above NMake... commands to be able to execute
2025 ET.SubElement(all_configs_prop_group, 'ExecutablePath').text = exe_search_paths
2026 else:
2027 action = ET.SubElement(root, 'ItemDefinitionGroup')
2028 midl = ET.SubElement(action, 'Midl')
2029 ET.SubElement(midl, "AdditionalIncludeDirectories").text = '%(AdditionalIncludeDirectories)'
2030 ET.SubElement(midl, "OutputDirectory").text = '$(IntDir)'
2031 ET.SubElement(midl, 'HeaderFileName').text = '%(Filename).h'
2032 ET.SubElement(midl, 'TypeLibraryName').text = '%(Filename).tlb'
2033 ET.SubElement(midl, 'InterfaceIdentifierFilename').text = '%(Filename)_i.c'
2034 ET.SubElement(midl, 'ProxyFileName').text = '%(Filename)_p.c'
2035 regen_command = self.environment.get_build_command() + ['--internal', 'regencheck']
2036 cmd_templ = '''call %s > NUL
2037 "%s" "%s"'''
2038 regen_command = cmd_templ % \
2039 (self.get_vcvars_command(), '" "'.join(regen_command), self.environment.get_scratch_dir())
2040 self.add_custom_build(root, 'regen', regen_command, deps=self.get_regen_filelist(),
2041 outputs=[Vs2010Backend.get_regen_stampfile(self.environment.get_build_dir())],
2042 msg='Checking whether solution needs to be regenerated.')
2043
2044 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.targets')
2045 ET.SubElement(root, 'ImportGroup', Label='ExtensionTargets')
2046 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
2047
2048 def gen_testproj(self) -> None:
2049 project_name = 'RUN_TESTS'
2050 ofname = os.path.join(self.environment.get_build_dir(), f'{project_name}.vcxproj')
2051 guid = self.environment.coredata.test_guid
2052 if self.gen_lite:
2053 (root, type_config) = self.create_basic_project(project_name,
2054 temp_dir='install-temp',
2055 guid=guid,
2056 conftype='Makefile'
2057 )
2058 (nmake_base_meson_command, exe_search_paths) = Vs2010Backend.get_nmake_base_meson_command_and_exe_search_paths()
2059 multi_config_buildtype_list = coredata.get_genvs_default_buildtype_list()
2060 (_, build_dir_tail) = os.path.split(self.src_to_build)
2061 proj_to_multiconfigured_builds_parent_dir = '..' # We know this .vcxproj will always be in the '[buildir]_vs' dir.
2062 # Add appropriate 'test' commands for the 'build' action of this project, for all buildtypes
2063 for buildtype in multi_config_buildtype_list:
2064 meson_build_dir_for_buildtype = build_dir_tail[:-2] + buildtype # Get the buildtype suffixed 'builddir_[debug/release/etc]' from 'builddir_vs', for example.
2065 proj_to_build_dir_for_buildtype = str(os.path.join(proj_to_multiconfigured_builds_parent_dir, meson_build_dir_for_buildtype))
2066 test_cmd = f'{nmake_base_meson_command} test -C "{proj_to_build_dir_for_buildtype}" --no-rebuild'
2067 if not self.environment.coredata.optstore.get_value_for(OptionKey('stdsplit')):
2068 test_cmd += ' --no-stdsplit'
2069 if self.environment.coredata.optstore.get_value_for(OptionKey('errorlogs')):
2070 test_cmd += ' --print-errorlogs'
2071 condition = f'\'$(Configuration)|$(Platform)\'==\'{buildtype}|{self.platform}\''
2072 prop_group = ET.SubElement(root, 'PropertyGroup', Condition=condition)
2073 ET.SubElement(prop_group, 'NMakeBuildCommandLine').text = test_cmd
2074 #Need to set the 'ExecutablePath' element for the NMake... commands to be able to execute
2075 ET.SubElement(prop_group, 'ExecutablePath').text = exe_search_paths
2076 else:
2077 (root, type_config) = self.create_basic_project(project_name,
2078 temp_dir='test-temp',
2079 guid=guid)
2080
2081 action = ET.SubElement(root, 'ItemDefinitionGroup')
2082 midl = ET.SubElement(action, 'Midl')
2083 ET.SubElement(midl, "AdditionalIncludeDirectories").text = '%(AdditionalIncludeDirectories)'
2084 ET.SubElement(midl, "OutputDirectory").text = '$(IntDir)'
2085 ET.SubElement(midl, 'HeaderFileName').text = '%(Filename).h'
2086 ET.SubElement(midl, 'TypeLibraryName').text = '%(Filename).tlb'
2087 ET.SubElement(midl, 'InterfaceIdentifierFilename').text = '%(Filename)_i.c'
2088 ET.SubElement(midl, 'ProxyFileName').text = '%(Filename)_p.c'
2089 # FIXME: No benchmarks?
2090 test_command = self.environment.get_build_command() + ['test', '--no-rebuild']
2091 if not self.environment.coredata.optstore.get_value_for(OptionKey('stdsplit')):
2092 test_command += ['--no-stdsplit']
2093 if self.environment.coredata.optstore.get_value_for(OptionKey('errorlogs')):
2094 test_command += ['--print-errorlogs']
2095 self.serialize_tests()
2096 self.add_custom_build(root, 'run_tests', '"%s"' % ('" "'.join(test_command)))
2097
2098 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.targets')
2099 self.add_regen_dependency(root)
2100 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
2101
2102 def gen_installproj(self) -> None:
2103 project_name = 'RUN_INSTALL'
2104 ofname = os.path.join(self.environment.get_build_dir(), f'{project_name}.vcxproj')
2105 guid = self.environment.coredata.install_guid
2106 if self.gen_lite:
2107 (root, type_config) = self.create_basic_project(project_name,
2108 temp_dir='install-temp',
2109 guid=guid,
2110 conftype='Makefile'
2111 )
2112 (nmake_base_meson_command, exe_search_paths) = Vs2010Backend.get_nmake_base_meson_command_and_exe_search_paths()
2113 multi_config_buildtype_list = coredata.get_genvs_default_buildtype_list()
2114 (_, build_dir_tail) = os.path.split(self.src_to_build)
2115 proj_to_multiconfigured_builds_parent_dir = '..' # We know this .vcxproj will always be in the '[buildir]_vs' dir.
2116 # Add appropriate 'install' commands for the 'build' action of this project, for all buildtypes
2117 for buildtype in multi_config_buildtype_list:
2118 meson_build_dir_for_buildtype = build_dir_tail[:-2] + buildtype # Get the buildtype suffixed 'builddir_[debug/release/etc]' from 'builddir_vs', for example.
2119 proj_to_build_dir_for_buildtype = str(os.path.join(proj_to_multiconfigured_builds_parent_dir, meson_build_dir_for_buildtype))
2120 install_cmd = f'{nmake_base_meson_command} install -C "{proj_to_build_dir_for_buildtype}" --no-rebuild'
2121 condition = f'\'$(Configuration)|$(Platform)\'==\'{buildtype}|{self.platform}\''
2122 prop_group = ET.SubElement(root, 'PropertyGroup', Condition=condition)
2123 ET.SubElement(prop_group, 'NMakeBuildCommandLine').text = install_cmd
2124 #Need to set the 'ExecutablePath' element for the NMake... commands to be able to execute
2125 ET.SubElement(prop_group, 'ExecutablePath').text = exe_search_paths
2126 else:
2127 self.create_install_data_files()
2128
2129 (root, type_config) = self.create_basic_project(project_name,
2130 temp_dir='install-temp',
2131 guid=guid)
2132
2133 action = ET.SubElement(root, 'ItemDefinitionGroup')
2134 midl = ET.SubElement(action, 'Midl')
2135 ET.SubElement(midl, "AdditionalIncludeDirectories").text = '%(AdditionalIncludeDirectories)'
2136 ET.SubElement(midl, "OutputDirectory").text = '$(IntDir)'
2137 ET.SubElement(midl, 'HeaderFileName').text = '%(Filename).h'
2138 ET.SubElement(midl, 'TypeLibraryName').text = '%(Filename).tlb'
2139 ET.SubElement(midl, 'InterfaceIdentifierFilename').text = '%(Filename)_i.c'
2140 ET.SubElement(midl, 'ProxyFileName').text = '%(Filename)_p.c'
2141 install_command = self.environment.get_build_command() + ['install', '--no-rebuild']
2142 self.add_custom_build(root, 'run_install', '"%s"' % ('" "'.join(install_command)))
2143
2144 ET.SubElement(root, 'Import', Project=r'$(VCTargetsPath)\Microsoft.Cpp.targets')
2145 self.add_regen_dependency(root)
2146 self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
2147
2148 def add_custom_build(self, node: ET.Element, rulename: str, command: str, deps: T.Optional[T.List[str]] = None,
2149 outputs: T.Optional[T.List[str]] = None, msg: T.Optional[str] = None, verify_files: bool = True) -> None:
2150 igroup = ET.SubElement(node, 'ItemGroup')
2151 rulefile = os.path.join(self.environment.get_scratch_dir(), rulename + '.rule')
2152 if not os.path.exists(rulefile):
2153 with open(rulefile, 'w', encoding='utf-8') as f:
2154 f.write("# Meson regen file.")
2155 custombuild = ET.SubElement(igroup, 'CustomBuild', Include=rulefile)
2156 if msg:
2157 message = ET.SubElement(custombuild, 'Message')
2158 message.text = msg
2159 if not verify_files:
2160 ET.SubElement(custombuild, 'VerifyInputsAndOutputsExist').text = 'false'
2161
2162 # If a command ever were to change the current directory or set local
2163 # variables this would need to be more complicated, as msbuild by
2164 # default executes all CustomBuilds in a project using the same
2165 # shell. Right now such tasks are all done inside the meson_exe
2166 # wrapper. The trailing newline appears to be necessary to allow
2167 # parallel custom builds to work.
2168 ET.SubElement(custombuild, 'Command').text = f"{command}\n"
2169
2170 if not outputs:
2171 # Use a nonexistent file to always consider the target out-of-date.
2172 outputs = [self.nonexistent_file(os.path.join(self.environment.get_scratch_dir(),
2173 'outofdate.file'))]
2174 ET.SubElement(custombuild, 'Outputs').text = ';'.join(outputs)
2175 if deps:
2176 ET.SubElement(custombuild, 'AdditionalInputs').text = ';'.join(deps)
2177
2178 @staticmethod
2179 def nonexistent_file(prefix: str) -> str:
2180 i = 0
2181 file = prefix
2182 while os.path.exists(file):
2183 file = '%s%d' % (prefix, i)
2184 return file
2185
2186 def generate_debug_information(self, link: ET.Element) -> None:
2187 # valid values for vs2015 is 'false', 'true', 'DebugFastLink'
2188 ET.SubElement(link, 'GenerateDebugInformation').text = 'true'
2189
2190 def add_regen_dependency(self, root: ET.Element) -> None:
2191 # For now, with 'genvslite' solutions, REGEN is replaced by the lighter-weight RECONFIGURE utility that is
2192 # no longer a forced build dependency. See comment in 'gen_regenproj'
2193 if not self.gen_lite:
2194 regen_vcxproj = os.path.join(self.environment.get_build_dir(), 'REGEN.vcxproj')
2195 self.add_project_reference(root, regen_vcxproj, self.environment.coredata.regen_guid)
2196
2197 def generate_lang_standard_info(self, file_args: T.Dict[Language, CompilerArgs], clconf: ET.Element) -> None:
2198 pass
2199
2200 # Returns if a target generates a manifest or not.
2201 # Returns 'embed' if the generated manifest is embedded.
2202 def get_gen_manifest(self, target: T.Optional[build.Target]) -> bool | T.Literal['embed']:
2203 if not isinstance(target, build.BuildTarget):
2204 return True
2205
2206 compiler = self._get_cl_compiler(target)
2207 link_args = compiler.compiler_args()
2208 if not isinstance(target, build.StaticLibrary):
2209 link_args += compiler.get_build_link_args(target, self.build)
2210 link_args += target.link_args
2211
2212 for arg in reversed(link_args):
2213 arg = arg.upper()
2214 if arg == '/MANIFEST:NO':
2215 return False
2216 if arg.startswith('/MANIFEST:EMBED'):
2217 return 'embed'
2218 if arg == '/MANIFEST' or arg.startswith('/MANIFEST:'):
2219 break
2220 return True
2221
2222 # FIXME: add a way to distinguish between arm64ec+marmasm (written in ARM assembly)
2223 # and arm64ec+masm (written in x64 assembly).
2224 #
2225 # For now, assume it's the native ones. (same behavior as ninja backend)
2226 def get_masm_type(self, target: build.BuildTarget) -> T.Literal['marmasm', 'masm'] | None:
2227 if not isinstance(target, build.BuildTarget):
2228 return None
2229
2230 if 'masm' not in target.compilers:
2231 return None
2232
2233 if target.for_machine == MachineChoice.BUILD:
2234 platform = self.build_platform
2235 elif target.for_machine == MachineChoice.HOST:
2236 platform = self.platform
2237 else:
2238 return None
2239
2240 if platform in {'ARM', 'arm64', 'arm64ec'}:
2241 return 'marmasm'
2242 else:
2243 return 'masm'