vs2010backend.py 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. # Copyright 2014-2016 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import os, sys
  12. import pickle
  13. import xml.dom.minidom
  14. import xml.etree.ElementTree as ET
  15. from . import backends
  16. from .. import build
  17. from .. import dependencies
  18. from .. import mlog
  19. from .. import compilers
  20. from ..build import BuildTarget
  21. from ..compilers import CompilerArgs
  22. from ..mesonlib import MesonException, File, get_meson_script
  23. from ..environment import Environment
  24. def autodetect_vs_version(build):
  25. vs_version = os.getenv('VisualStudioVersion', None)
  26. vs_install_dir = os.getenv('VSINSTALLDIR', None)
  27. if not vs_version and not vs_install_dir:
  28. raise MesonException('Could not detect Visual Studio: VisualStudioVersion and VSINSTALLDIR are unset!\n'
  29. 'Are we inside a Visual Studio build environment? '
  30. 'You can also try specifying the exact backend to use.')
  31. # VisualStudioVersion is set since Visual Studio 12.0, but sometimes
  32. # vcvarsall.bat doesn't set it, so also use VSINSTALLDIR
  33. if vs_version == '14.0' or 'Visual Studio 14' in vs_install_dir:
  34. from mesonbuild.backend.vs2015backend import Vs2015Backend
  35. return Vs2015Backend(build)
  36. if vs_version == '15.0' or 'Visual Studio 17' in vs_install_dir or \
  37. 'Visual Studio\\2017' in vs_install_dir:
  38. from mesonbuild.backend.vs2017backend import Vs2017Backend
  39. return Vs2017Backend(build)
  40. if 'Visual Studio 10.0' in vs_install_dir:
  41. return Vs2010Backend(build)
  42. raise MesonException('Could not detect Visual Studio using VisualStudioVersion: {!r} or VSINSTALLDIR: {!r}!\n'
  43. 'Please specify the exact backend to use.'.format(vs_version, vs_install_dir))
  44. def split_o_flags_args(args):
  45. """
  46. Splits any /O args and returns them. Does not take care of flags overriding
  47. previous ones. Skips non-O flag arguments.
  48. ['/Ox', '/Ob1'] returns ['/Ox', '/Ob1']
  49. ['/Oxj', '/MP'] returns ['/Ox', '/Oj']
  50. """
  51. o_flags = []
  52. for arg in args:
  53. if not arg.startswith('/O'):
  54. continue
  55. flags = list(arg[2:])
  56. # Assume that this one can't be clumped with the others since it takes
  57. # an argument itself
  58. if 'b' in flags:
  59. o_flags.append(arg)
  60. else:
  61. o_flags += ['/O' + f for f in flags]
  62. return o_flags
  63. class RegenInfo:
  64. def __init__(self, source_dir, build_dir, depfiles):
  65. self.source_dir = source_dir
  66. self.build_dir = build_dir
  67. self.depfiles = depfiles
  68. class Vs2010Backend(backends.Backend):
  69. def __init__(self, build):
  70. super().__init__(build)
  71. self.name = 'vs2010'
  72. self.project_file_version = '10.0.30319.1'
  73. self.sources_conflicts = {}
  74. self.platform_toolset = None
  75. self.vs_version = '2010'
  76. self.windows_target_platform_version = None
  77. def object_filename_from_source(self, target, source, is_unity=False):
  78. basename = os.path.basename(source.fname)
  79. filename_without_extension = '.'.join(basename.split('.')[:-1])
  80. if basename in self.sources_conflicts[target.get_id()]:
  81. # If there are multiple source files with the same basename, we must resolve the conflict
  82. # by giving each a unique object output file.
  83. filename_without_extension = '.'.join(source.fname.split('.')[:-1]).replace('/', '_').replace('\\', '_')
  84. return filename_without_extension + '.' + self.environment.get_object_suffix()
  85. def resolve_source_conflicts(self):
  86. for name, target in self.build.targets.items():
  87. if not isinstance(target, BuildTarget):
  88. continue
  89. conflicts = {}
  90. for s in target.get_sources():
  91. if hasattr(s, 'held_object'):
  92. s = s.held_object
  93. if not isinstance(s, File):
  94. continue
  95. basename = os.path.basename(s.fname)
  96. conflicting_sources = conflicts.get(basename, None)
  97. if conflicting_sources is None:
  98. conflicting_sources = []
  99. conflicts[basename] = conflicting_sources
  100. conflicting_sources.append(s)
  101. self.sources_conflicts[target.get_id()] = {name: src_conflicts for name, src_conflicts in conflicts.items()
  102. if len(src_conflicts) > 1}
  103. def generate_custom_generator_commands(self, target, parent_node):
  104. generator_output_files = []
  105. custom_target_include_dirs = []
  106. custom_target_output_files = []
  107. target_private_dir = self.relpath(self.get_target_private_dir(target), self.get_target_dir(target))
  108. source_target_dir = self.get_target_source_dir(target)
  109. down = self.target_to_build_root(target)
  110. for genlist in target.get_generated_sources():
  111. if isinstance(genlist, build.CustomTarget):
  112. for i in genlist.get_outputs():
  113. # Path to the generated source from the current vcxproj dir via the build root
  114. ipath = os.path.join(down, self.get_target_dir(genlist), i)
  115. custom_target_output_files.append(ipath)
  116. idir = self.relpath(self.get_target_dir(genlist), self.get_target_dir(target))
  117. if idir not in custom_target_include_dirs:
  118. custom_target_include_dirs.append(idir)
  119. else:
  120. generator = genlist.get_generator()
  121. exe = generator.get_exe()
  122. infilelist = genlist.get_inputs()
  123. outfilelist = genlist.get_outputs()
  124. exe_arr = self.exe_object_to_cmd_array(exe)
  125. base_args = generator.get_arglist()
  126. idgroup = ET.SubElement(parent_node, 'ItemGroup')
  127. for i in range(len(infilelist)):
  128. if len(infilelist) == len(outfilelist):
  129. sole_output = os.path.join(target_private_dir, outfilelist[i])
  130. else:
  131. sole_output = ''
  132. curfile = infilelist[i]
  133. infilename = os.path.join(down, curfile.rel_to_builddir(self.build_to_src))
  134. outfiles_rel = genlist.get_outputs_for(curfile)
  135. outfiles = [os.path.join(target_private_dir, of) for of in outfiles_rel]
  136. generator_output_files += outfiles
  137. args = [x.replace("@INPUT@", infilename).replace('@OUTPUT@', sole_output)
  138. for x in base_args]
  139. args = self.replace_outputs(args, target_private_dir, outfiles_rel)
  140. args = [x.replace("@SOURCE_DIR@", self.environment.get_source_dir())
  141. .replace("@BUILD_DIR@", target_private_dir)
  142. for x in args]
  143. args = [x.replace("@CURRENT_SOURCE_DIR@", source_target_dir) for x in args]
  144. args = [x.replace("@SOURCE_ROOT@", self.environment.get_source_dir())
  145. .replace("@BUILD_ROOT@", self.environment.get_build_dir())
  146. for x in args]
  147. cmd = exe_arr + self.replace_extra_args(args, genlist)
  148. cbs = ET.SubElement(idgroup, 'CustomBuild', Include=infilename)
  149. ET.SubElement(cbs, 'Command').text = ' '.join(self.quote_arguments(cmd))
  150. ET.SubElement(cbs, 'Outputs').text = ';'.join(outfiles)
  151. return generator_output_files, custom_target_output_files, custom_target_include_dirs
  152. def generate(self, interp):
  153. self.resolve_source_conflicts()
  154. self.interpreter = interp
  155. target_machine = self.interpreter.builtin['target_machine'].cpu_family_method(None, None)
  156. if target_machine.endswith('64'):
  157. # amd64 or x86_64
  158. self.platform = 'x64'
  159. elif target_machine == 'x86':
  160. # x86
  161. self.platform = 'Win32'
  162. elif 'arm' in target_machine.lower():
  163. self.platform = 'ARM'
  164. else:
  165. raise MesonException('Unsupported Visual Studio platform: ' + target_machine)
  166. self.buildtype = self.environment.coredata.get_builtin_option('buildtype')
  167. sln_filename = os.path.join(self.environment.get_build_dir(), self.build.project_name + '.sln')
  168. projlist = self.generate_projects()
  169. self.gen_testproj('RUN_TESTS', os.path.join(self.environment.get_build_dir(), 'RUN_TESTS.vcxproj'))
  170. self.gen_regenproj('REGEN', os.path.join(self.environment.get_build_dir(), 'REGEN.vcxproj'))
  171. self.generate_solution(sln_filename, projlist)
  172. self.generate_regen_info()
  173. Vs2010Backend.touch_regen_timestamp(self.environment.get_build_dir())
  174. @staticmethod
  175. def get_regen_stampfile(build_dir):
  176. return os.path.join(os.path.join(build_dir, Environment.private_dir), 'regen.stamp')
  177. @staticmethod
  178. def touch_regen_timestamp(build_dir):
  179. with open(Vs2010Backend.get_regen_stampfile(build_dir), 'w'):
  180. pass
  181. def generate_regen_info(self):
  182. deps = self.get_regen_filelist()
  183. regeninfo = RegenInfo(self.environment.get_source_dir(),
  184. self.environment.get_build_dir(),
  185. deps)
  186. filename = os.path.join(self.environment.get_scratch_dir(),
  187. 'regeninfo.dump')
  188. with open(filename, 'wb') as f:
  189. pickle.dump(regeninfo, f)
  190. def get_obj_target_deps(self, obj_list):
  191. result = {}
  192. for o in obj_list:
  193. if isinstance(o, build.ExtractedObjects):
  194. result[o.target.get_id()] = o.target
  195. return result.items()
  196. def get_target_deps(self, t, recursive=False):
  197. all_deps = {}
  198. for target in t.values():
  199. if isinstance(target, build.CustomTarget):
  200. for d in target.get_target_dependencies():
  201. all_deps[d.get_id()] = d
  202. elif isinstance(target, build.RunTarget):
  203. for d in [target.command] + target.args:
  204. if isinstance(d, (build.BuildTarget, build.CustomTarget)):
  205. all_deps[d.get_id()] = d
  206. elif isinstance(target, build.BuildTarget):
  207. for ldep in target.link_targets:
  208. all_deps[ldep.get_id()] = ldep
  209. for ldep in target.link_whole_targets:
  210. all_deps[ldep.get_id()] = ldep
  211. for obj_id, objdep in self.get_obj_target_deps(target.objects):
  212. all_deps[obj_id] = objdep
  213. for gendep in target.get_generated_sources():
  214. if isinstance(gendep, build.CustomTarget):
  215. all_deps[gendep.get_id()] = gendep
  216. else:
  217. gen_exe = gendep.generator.get_exe()
  218. if isinstance(gen_exe, build.Executable):
  219. all_deps[gen_exe.get_id()] = gen_exe
  220. else:
  221. raise MesonException('Unknown target type for target %s' % target)
  222. if not t or not recursive:
  223. return all_deps
  224. ret = self.get_target_deps(all_deps, recursive)
  225. ret.update(all_deps)
  226. return ret
  227. def generate_solution(self, sln_filename, projlist):
  228. default_projlist = self.get_build_by_default_targets()
  229. with open(sln_filename, 'w') as ofile:
  230. ofile.write('Microsoft Visual Studio Solution File, Format '
  231. 'Version 11.00\n')
  232. ofile.write('# Visual Studio ' + self.vs_version + '\n')
  233. prj_templ = 'Project("{%s}") = "%s", "%s", "{%s}"\n'
  234. for p in projlist:
  235. prj_line = prj_templ % (self.environment.coredata.guid,
  236. p[0], p[1], p[2])
  237. ofile.write(prj_line)
  238. target = self.build.targets[p[0]]
  239. t = {target.get_id(): target}
  240. # Get direct deps
  241. all_deps = self.get_target_deps(t)
  242. # Get recursive deps
  243. recursive_deps = self.get_target_deps(t, recursive=True)
  244. ofile.write('\tProjectSection(ProjectDependencies) = '
  245. 'postProject\n')
  246. regen_guid = self.environment.coredata.regen_guid
  247. ofile.write('\t\t{%s} = {%s}\n' % (regen_guid, regen_guid))
  248. for dep in all_deps.keys():
  249. guid = self.environment.coredata.target_guids[dep]
  250. ofile.write('\t\t{%s} = {%s}\n' % (guid, guid))
  251. ofile.write('EndProjectSection\n')
  252. ofile.write('EndProject\n')
  253. for dep, target in recursive_deps.items():
  254. if p[0] in default_projlist:
  255. default_projlist[dep] = target
  256. test_line = prj_templ % (self.environment.coredata.guid,
  257. 'RUN_TESTS', 'RUN_TESTS.vcxproj',
  258. self.environment.coredata.test_guid)
  259. ofile.write(test_line)
  260. ofile.write('EndProject\n')
  261. regen_line = prj_templ % (self.environment.coredata.guid,
  262. 'REGEN', 'REGEN.vcxproj',
  263. self.environment.coredata.regen_guid)
  264. ofile.write(regen_line)
  265. ofile.write('EndProject\n')
  266. ofile.write('Global\n')
  267. ofile.write('\tGlobalSection(SolutionConfigurationPlatforms) = '
  268. 'preSolution\n')
  269. ofile.write('\t\t%s|%s = %s|%s\n' %
  270. (self.buildtype, self.platform, self.buildtype,
  271. self.platform))
  272. ofile.write('\tEndGlobalSection\n')
  273. ofile.write('\tGlobalSection(ProjectConfigurationPlatforms) = '
  274. 'postSolution\n')
  275. ofile.write('\t\t{%s}.%s|%s.ActiveCfg = %s|%s\n' %
  276. (self.environment.coredata.regen_guid, self.buildtype,
  277. self.platform, self.buildtype, self.platform))
  278. ofile.write('\t\t{%s}.%s|%s.Build.0 = %s|%s\n' %
  279. (self.environment.coredata.regen_guid, self.buildtype,
  280. self.platform, self.buildtype, self.platform))
  281. # Create the solution configuration
  282. for p in projlist:
  283. # Add to the list of projects in this solution
  284. ofile.write('\t\t{%s}.%s|%s.ActiveCfg = %s|%s\n' %
  285. (p[2], self.buildtype, self.platform,
  286. self.buildtype, self.platform))
  287. if p[0] in default_projlist and \
  288. not isinstance(self.build.targets[p[0]], build.RunTarget):
  289. # Add to the list of projects to be built
  290. ofile.write('\t\t{%s}.%s|%s.Build.0 = %s|%s\n' %
  291. (p[2], self.buildtype, self.platform,
  292. self.buildtype, self.platform))
  293. ofile.write('\t\t{%s}.%s|%s.ActiveCfg = %s|%s\n' %
  294. (self.environment.coredata.test_guid, self.buildtype,
  295. self.platform, self.buildtype, self.platform))
  296. ofile.write('\tEndGlobalSection\n')
  297. ofile.write('\tGlobalSection(SolutionProperties) = preSolution\n')
  298. ofile.write('\t\tHideSolutionNode = FALSE\n')
  299. ofile.write('\tEndGlobalSection\n')
  300. ofile.write('EndGlobal\n')
  301. def generate_projects(self):
  302. projlist = []
  303. for name, target in self.build.targets.items():
  304. outdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
  305. fname = name + '.vcxproj'
  306. relname = os.path.join(target.subdir, fname)
  307. projfile = os.path.join(outdir, fname)
  308. uuid = self.environment.coredata.target_guids[name]
  309. self.gen_vcxproj(target, projfile, uuid)
  310. projlist.append((name, relname, uuid))
  311. return projlist
  312. def split_sources(self, srclist):
  313. sources = []
  314. headers = []
  315. objects = []
  316. languages = []
  317. for i in srclist:
  318. if self.environment.is_header(i):
  319. headers.append(i)
  320. elif self.environment.is_object(i):
  321. objects.append(i)
  322. elif self.environment.is_source(i):
  323. sources.append(i)
  324. lang = self.lang_from_source_file(i)
  325. if lang not in languages:
  326. languages.append(lang)
  327. elif self.environment.is_library(i):
  328. pass
  329. else:
  330. # Everything that is not an object or source file is considered a header.
  331. headers.append(i)
  332. return sources, headers, objects, languages
  333. def target_to_build_root(self, target):
  334. if target.subdir == '':
  335. return ''
  336. directories = os.path.normpath(target.subdir).split(os.sep)
  337. return os.sep.join(['..'] * len(directories))
  338. def quote_arguments(self, arr):
  339. return ['"%s"' % i for i in arr]
  340. def create_basic_crap(self, target):
  341. project_name = target.name
  342. root = ET.Element('Project', {'DefaultTargets': "Build",
  343. 'ToolsVersion': '4.0',
  344. 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'})
  345. confitems = ET.SubElement(root, 'ItemGroup', {'Label': 'ProjectConfigurations'})
  346. prjconf = ET.SubElement(confitems, 'ProjectConfiguration',
  347. {'Include': self.buildtype + '|' + self.platform})
  348. p = ET.SubElement(prjconf, 'Configuration')
  349. p.text = self.buildtype
  350. pl = ET.SubElement(prjconf, 'Platform')
  351. pl.text = self.platform
  352. globalgroup = ET.SubElement(root, 'PropertyGroup', Label='Globals')
  353. guidelem = ET.SubElement(globalgroup, 'ProjectGuid')
  354. guidelem.text = '{%s}' % self.environment.coredata.test_guid
  355. kw = ET.SubElement(globalgroup, 'Keyword')
  356. kw.text = self.platform + 'Proj'
  357. p = ET.SubElement(globalgroup, 'Platform')
  358. p.text = self.platform
  359. pname = ET.SubElement(globalgroup, 'ProjectName')
  360. pname.text = project_name
  361. if self.windows_target_platform_version:
  362. ET.SubElement(globalgroup, 'WindowsTargetPlatformVersion').text = self.windows_target_platform_version
  363. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.Default.props')
  364. type_config = ET.SubElement(root, 'PropertyGroup', Label='Configuration')
  365. ET.SubElement(type_config, 'ConfigurationType')
  366. ET.SubElement(type_config, 'CharacterSet').text = 'MultiByte'
  367. ET.SubElement(type_config, 'UseOfMfc').text = 'false'
  368. if self.platform_toolset:
  369. ET.SubElement(type_config, 'PlatformToolset').text = self.platform_toolset
  370. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.props')
  371. direlem = ET.SubElement(root, 'PropertyGroup')
  372. fver = ET.SubElement(direlem, '_ProjectFileVersion')
  373. fver.text = self.project_file_version
  374. outdir = ET.SubElement(direlem, 'OutDir')
  375. outdir.text = '.\\'
  376. intdir = ET.SubElement(direlem, 'IntDir')
  377. intdir.text = target.get_id() + '\\'
  378. tname = ET.SubElement(direlem, 'TargetName')
  379. tname.text = target.name
  380. return root
  381. def gen_run_target_vcxproj(self, target, ofname, guid):
  382. root = self.create_basic_crap(target)
  383. action = ET.SubElement(root, 'ItemDefinitionGroup')
  384. customstep = ET.SubElement(action, 'PostBuildEvent')
  385. cmd_raw = [target.command] + target.args
  386. cmd = [sys.executable, os.path.join(self.environment.get_script_dir(), 'commandrunner.py'),
  387. self.environment.get_build_dir(),
  388. self.environment.get_source_dir(),
  389. self.get_target_dir(target),
  390. get_meson_script(self.environment, 'mesonintrospect')]
  391. for i in cmd_raw:
  392. if isinstance(i, build.BuildTarget):
  393. cmd.append(os.path.join(self.environment.get_build_dir(), self.get_target_filename(i)))
  394. elif isinstance(i, dependencies.ExternalProgram):
  395. cmd += i.get_command()
  396. elif isinstance(i, File):
  397. relfname = i.rel_to_builddir(self.build_to_src)
  398. cmd.append(os.path.join(self.environment.get_build_dir(), relfname))
  399. else:
  400. cmd.append(i)
  401. cmd_templ = '''"%s" ''' * len(cmd)
  402. ET.SubElement(customstep, 'Command').text = cmd_templ % tuple(cmd)
  403. ET.SubElement(customstep, 'Message').text = 'Running custom command.'
  404. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.targets')
  405. self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
  406. def gen_custom_target_vcxproj(self, target, ofname, guid):
  407. root = self.create_basic_crap(target)
  408. action = ET.SubElement(root, 'ItemDefinitionGroup')
  409. customstep = ET.SubElement(action, 'CustomBuildStep')
  410. # We need to always use absolute paths because our invocation is always
  411. # from the target dir, not the build root.
  412. target.absolute_paths = True
  413. (srcs, ofilenames, cmd) = self.eval_custom_target_command(target, True)
  414. depend_files = self.get_custom_target_depend_files(target, True)
  415. # Always use a wrapper because MSBuild eats random characters when
  416. # there are many arguments.
  417. tdir_abs = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
  418. exe_data = self.serialize_executable(target.command[0], cmd[1:],
  419. # All targets run from the target dir
  420. tdir_abs,
  421. capture=ofilenames[0] if target.capture else None)
  422. wrapper_cmd = [sys.executable, self.environment.get_build_command(),
  423. '--internal', 'exe', exe_data]
  424. ET.SubElement(customstep, 'Command').text = ' '.join(self.quote_arguments(wrapper_cmd))
  425. ET.SubElement(customstep, 'Outputs').text = ';'.join(ofilenames)
  426. ET.SubElement(customstep, 'Inputs').text = ';'.join([exe_data] + srcs + depend_files)
  427. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.targets')
  428. self.generate_custom_generator_commands(target, root)
  429. self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
  430. @classmethod
  431. def lang_from_source_file(cls, src):
  432. ext = src.split('.')[-1]
  433. if ext in compilers.c_suffixes:
  434. return 'c'
  435. if ext in compilers.cpp_suffixes:
  436. return 'cpp'
  437. raise MesonException('Could not guess language from source file %s.' % src)
  438. def add_pch(self, inc_cl, proj_to_src_dir, pch_sources, source_file):
  439. if len(pch_sources) <= 1:
  440. # We only need per file precompiled headers if we have more than 1 language.
  441. return
  442. lang = Vs2010Backend.lang_from_source_file(source_file)
  443. header = os.path.join(proj_to_src_dir, pch_sources[lang][0])
  444. pch_file = ET.SubElement(inc_cl, 'PrecompiledHeaderFile')
  445. pch_file.text = header
  446. pch_include = ET.SubElement(inc_cl, 'ForcedIncludeFiles')
  447. pch_include.text = header + ';%(ForcedIncludeFiles)'
  448. pch_out = ET.SubElement(inc_cl, 'PrecompiledHeaderOutputFile')
  449. pch_out.text = '$(IntDir)$(TargetName)-%s.pch' % lang
  450. def add_additional_options(self, lang, parent_node, file_args):
  451. args = []
  452. for arg in file_args[lang].to_native():
  453. if arg == '%(AdditionalOptions)':
  454. args.append(arg)
  455. else:
  456. args.append(self.escape_additional_option(arg))
  457. ET.SubElement(parent_node, "AdditionalOptions").text = ' '.join(args)
  458. def add_preprocessor_defines(self, lang, parent_node, file_defines):
  459. defines = []
  460. for define in file_defines[lang]:
  461. if define == '%(PreprocessorDefinitions)':
  462. defines.append(define)
  463. else:
  464. defines.append(self.escape_preprocessor_define(define))
  465. ET.SubElement(parent_node, "PreprocessorDefinitions").text = ';'.join(defines)
  466. def add_include_dirs(self, lang, parent_node, file_inc_dirs):
  467. dirs = file_inc_dirs[lang]
  468. ET.SubElement(parent_node, "AdditionalIncludeDirectories").text = ';'.join(dirs)
  469. @staticmethod
  470. def has_objects(objects, additional_objects, generated_objects):
  471. # Ignore generated objects, those are automatically used by MSBuild because they are part of
  472. # the CustomBuild Outputs.
  473. return len(objects) + len(additional_objects) > 0
  474. @staticmethod
  475. def add_generated_objects(node, generated_objects):
  476. # Do not add generated objects to project file. Those are automatically used by MSBuild, because
  477. # they are part of the CustomBuild Outputs.
  478. return
  479. @staticmethod
  480. def escape_preprocessor_define(define):
  481. # See: https://msdn.microsoft.com/en-us/library/bb383819.aspx
  482. table = str.maketrans({'%': '%25', '$': '%24', '@': '%40',
  483. "'": '%27', ';': '%3B', '?': '%3F', '*': '%2A',
  484. # We need to escape backslash because it'll be un-escaped by
  485. # Windows during process creation when it parses the arguments
  486. # Basically, this converts `\` to `\\`.
  487. '\\': '\\\\'})
  488. return define.translate(table)
  489. @staticmethod
  490. def escape_additional_option(option):
  491. # See: https://msdn.microsoft.com/en-us/library/bb383819.aspx
  492. table = str.maketrans({'%': '%25', '$': '%24', '@': '%40',
  493. "'": '%27', ';': '%3B', '?': '%3F', '*': '%2A', ' ': '%20'})
  494. option = option.translate(table)
  495. # Since we're surrounding the option with ", if it ends in \ that will
  496. # escape the " when the process arguments are parsed and the starting
  497. # " will not terminate. So we escape it if that's the case. I'm not
  498. # kidding, this is how escaping works for process args on Windows.
  499. if option.endswith('\\'):
  500. option += '\\'
  501. return '"{}"'.format(option)
  502. @staticmethod
  503. def split_link_args(args):
  504. """
  505. Split a list of link arguments into three lists:
  506. * library search paths
  507. * library filenames (or paths)
  508. * other link arguments
  509. """
  510. lpaths = []
  511. libs = []
  512. other = []
  513. for arg in args:
  514. if arg.startswith('/LIBPATH:'):
  515. lpath = arg[9:]
  516. # De-dup library search paths by removing older entries when
  517. # a new one is found. This is necessary because unlike other
  518. # search paths such as the include path, the library is
  519. # searched for in the newest (right-most) search path first.
  520. if lpath in lpaths:
  521. lpaths.remove(lpath)
  522. lpaths.append(lpath)
  523. # It's ok if we miss libraries with non-standard extensions here.
  524. # They will go into the general link arguments.
  525. elif arg.endswith('.lib') or arg.endswith('.a'):
  526. # De-dup
  527. if arg not in libs:
  528. libs.append(arg)
  529. else:
  530. other.append(arg)
  531. return lpaths, libs, other
  532. def _get_cl_compiler(self, target):
  533. for lang, c in target.compilers.items():
  534. if lang in ('c', 'cpp'):
  535. return c
  536. # No source files, only objects, but we still need a compiler, so
  537. # return a found compiler
  538. if len(target.objects) > 0:
  539. for lang, c in self.environment.coredata.compilers.items():
  540. if lang in ('c', 'cpp'):
  541. return c
  542. raise MesonException('Could not find a C or C++ compiler. MSVC can only build C/C++ projects.')
  543. def _prettyprint_vcxproj_xml(self, tree, ofname):
  544. tree.write(ofname, encoding='utf-8', xml_declaration=True)
  545. # ElementTree can not do prettyprinting so do it manually
  546. doc = xml.dom.minidom.parse(ofname)
  547. with open(ofname, 'w') as of:
  548. of.write(doc.toprettyxml())
  549. def gen_vcxproj(self, target, ofname, guid):
  550. mlog.debug('Generating vcxproj %s.' % target.name)
  551. entrypoint = 'WinMainCRTStartup'
  552. subsystem = 'Windows'
  553. if isinstance(target, build.Executable):
  554. conftype = 'Application'
  555. if not target.gui_app:
  556. subsystem = 'Console'
  557. entrypoint = 'mainCRTStartup'
  558. elif isinstance(target, build.StaticLibrary):
  559. conftype = 'StaticLibrary'
  560. elif isinstance(target, build.SharedLibrary):
  561. conftype = 'DynamicLibrary'
  562. entrypoint = '_DllMainCrtStartup'
  563. elif isinstance(target, build.CustomTarget):
  564. return self.gen_custom_target_vcxproj(target, ofname, guid)
  565. elif isinstance(target, build.RunTarget):
  566. return self.gen_run_target_vcxproj(target, ofname, guid)
  567. else:
  568. raise MesonException('Unknown target type for %s' % target.get_basename())
  569. # Prefix to use to access the build root from the vcxproj dir
  570. down = self.target_to_build_root(target)
  571. # Prefix to use to access the source tree's root from the vcxproj dir
  572. proj_to_src_root = os.path.join(down, self.build_to_src)
  573. # Prefix to use to access the source tree's subdir from the vcxproj dir
  574. proj_to_src_dir = os.path.join(proj_to_src_root, target.subdir)
  575. (sources, headers, objects, languages) = self.split_sources(target.sources)
  576. if self.is_unity(target):
  577. sources = self.generate_unity_files(target, sources)
  578. compiler = self._get_cl_compiler(target)
  579. buildtype_args = compiler.get_buildtype_args(self.buildtype)
  580. buildtype_link_args = compiler.get_buildtype_linker_args(self.buildtype)
  581. project_name = target.name
  582. target_name = target.name
  583. root = ET.Element('Project', {'DefaultTargets': "Build",
  584. 'ToolsVersion': '4.0',
  585. 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'})
  586. confitems = ET.SubElement(root, 'ItemGroup', {'Label': 'ProjectConfigurations'})
  587. prjconf = ET.SubElement(confitems, 'ProjectConfiguration',
  588. {'Include': self.buildtype + '|' + self.platform})
  589. p = ET.SubElement(prjconf, 'Configuration')
  590. p.text = self.buildtype
  591. pl = ET.SubElement(prjconf, 'Platform')
  592. pl.text = self.platform
  593. # Globals
  594. globalgroup = ET.SubElement(root, 'PropertyGroup', Label='Globals')
  595. guidelem = ET.SubElement(globalgroup, 'ProjectGuid')
  596. guidelem.text = '{%s}' % guid
  597. kw = ET.SubElement(globalgroup, 'Keyword')
  598. kw.text = self.platform + 'Proj'
  599. ns = ET.SubElement(globalgroup, 'RootNamespace')
  600. ns.text = target_name
  601. p = ET.SubElement(globalgroup, 'Platform')
  602. p.text = self.platform
  603. pname = ET.SubElement(globalgroup, 'ProjectName')
  604. pname.text = project_name
  605. if self.windows_target_platform_version:
  606. ET.SubElement(globalgroup, 'WindowsTargetPlatformVersion').text = self.windows_target_platform_version
  607. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.Default.props')
  608. # Start configuration
  609. type_config = ET.SubElement(root, 'PropertyGroup', Label='Configuration')
  610. ET.SubElement(type_config, 'ConfigurationType').text = conftype
  611. ET.SubElement(type_config, 'CharacterSet').text = 'MultiByte'
  612. if self.platform_toolset:
  613. ET.SubElement(type_config, 'PlatformToolset').text = self.platform_toolset
  614. # FIXME: Meson's LTO support needs to be integrated here
  615. ET.SubElement(type_config, 'WholeProgramOptimization').text = 'false'
  616. # Let VS auto-set the RTC level
  617. ET.SubElement(type_config, 'BasicRuntimeChecks').text = 'Default'
  618. o_flags = split_o_flags_args(buildtype_args)
  619. if '/Oi' in o_flags:
  620. ET.SubElement(type_config, 'IntrinsicFunctions').text = 'true'
  621. if '/Ob1' in o_flags:
  622. ET.SubElement(type_config, 'InlineFunctionExpansion').text = 'OnlyExplicitInline'
  623. elif '/Ob2' in o_flags:
  624. ET.SubElement(type_config, 'InlineFunctionExpansion').text = 'AnySuitable'
  625. # Size-preserving flags
  626. if '/Os' in o_flags:
  627. ET.SubElement(type_config, 'FavorSizeOrSpeed').text = 'Size'
  628. else:
  629. ET.SubElement(type_config, 'FavorSizeOrSpeed').text = 'Speed'
  630. # Incremental linking increases code size
  631. if '/INCREMENTAL:NO' in buildtype_link_args:
  632. ET.SubElement(type_config, 'LinkIncremental').text = 'false'
  633. # CRT type; debug or release
  634. if '/MDd' in buildtype_args:
  635. ET.SubElement(type_config, 'UseDebugLibraries').text = 'true'
  636. ET.SubElement(type_config, 'RuntimeLibrary').text = 'MultiThreadedDebugDLL'
  637. else:
  638. ET.SubElement(type_config, 'UseDebugLibraries').text = 'false'
  639. ET.SubElement(type_config, 'RuntimeLibrary').text = 'MultiThreadedDLL'
  640. # Debug format
  641. if '/ZI' in buildtype_args:
  642. ET.SubElement(type_config, 'DebugInformationFormat').text = 'EditAndContinue'
  643. elif '/Zi' in buildtype_args:
  644. ET.SubElement(type_config, 'DebugInformationFormat').text = 'ProgramDatabase'
  645. elif '/Z7' in buildtype_args:
  646. ET.SubElement(type_config, 'DebugInformationFormat').text = 'OldStyle'
  647. # Generate Debug info
  648. if '/DEBUG' in buildtype_link_args:
  649. ET.SubElement(type_config, 'GenerateDebugInformation').text = 'true'
  650. # Runtime checks
  651. if '/RTC1' in buildtype_args:
  652. ET.SubElement(type_config, 'BasicRuntimeChecks').text = 'EnableFastChecks'
  653. elif '/RTCu' in buildtype_args:
  654. ET.SubElement(type_config, 'BasicRuntimeChecks').text = 'UninitializedLocalUsageCheck'
  655. elif '/RTCs' in buildtype_args:
  656. ET.SubElement(type_config, 'BasicRuntimeChecks').text = 'StackFrameRuntimeCheck'
  657. # Optimization flags
  658. if '/Ox' in o_flags:
  659. ET.SubElement(type_config, 'Optimization').text = 'Full'
  660. elif '/O2' in o_flags:
  661. ET.SubElement(type_config, 'Optimization').text = 'MaxSpeed'
  662. elif '/O1' in o_flags:
  663. ET.SubElement(type_config, 'Optimization').text = 'MinSpace'
  664. elif '/Od' in o_flags:
  665. ET.SubElement(type_config, 'Optimization').text = 'Disabled'
  666. # End configuration
  667. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.props')
  668. generated_files, custom_target_output_files, generated_files_include_dirs = self.generate_custom_generator_commands(target, root)
  669. (gen_src, gen_hdrs, gen_objs, gen_langs) = self.split_sources(generated_files)
  670. (custom_src, custom_hdrs, custom_objs, custom_langs) = self.split_sources(custom_target_output_files)
  671. gen_src += custom_src
  672. gen_hdrs += custom_hdrs
  673. gen_langs += custom_langs
  674. # Project information
  675. direlem = ET.SubElement(root, 'PropertyGroup')
  676. fver = ET.SubElement(direlem, '_ProjectFileVersion')
  677. fver.text = self.project_file_version
  678. outdir = ET.SubElement(direlem, 'OutDir')
  679. outdir.text = '.\\'
  680. intdir = ET.SubElement(direlem, 'IntDir')
  681. intdir.text = target.get_id() + '\\'
  682. tfilename = os.path.splitext(target.get_filename())
  683. ET.SubElement(direlem, 'TargetName').text = tfilename[0]
  684. ET.SubElement(direlem, 'TargetExt').text = tfilename[1]
  685. # Build information
  686. compiles = ET.SubElement(root, 'ItemDefinitionGroup')
  687. clconf = ET.SubElement(compiles, 'ClCompile')
  688. # Arguments, include dirs, defines for all files in the current target
  689. target_args = []
  690. target_defines = []
  691. target_inc_dirs = []
  692. # Arguments, include dirs, defines passed to individual files in
  693. # a target; perhaps because the args are language-specific
  694. #
  695. # file_args is also later split out into defines and include_dirs in
  696. # case someone passed those in there
  697. file_args = dict((lang, CompilerArgs(comp)) for lang, comp in target.compilers.items())
  698. file_defines = dict((lang, []) for lang in target.compilers)
  699. file_inc_dirs = dict((lang, []) for lang in target.compilers)
  700. # The order in which these compile args are added must match
  701. # generate_single_compile() and generate_basic_compiler_args()
  702. for l, comp in target.compilers.items():
  703. if l in file_args:
  704. file_args[l] += compilers.get_base_compile_args(self.environment.coredata.base_options, comp)
  705. file_args[l] += comp.get_option_compile_args(self.environment.coredata.compiler_options)
  706. # Add compile args added using add_project_arguments()
  707. for l, args in self.build.projects_args.get(target.subproject, {}).items():
  708. if l in file_args:
  709. file_args[l] += args
  710. # Add compile args added using add_global_arguments()
  711. # These override per-project arguments
  712. for l, args in self.build.global_args.items():
  713. if l in file_args:
  714. file_args[l] += args
  715. if not target.is_cross:
  716. # Compile args added from the env: CFLAGS/CXXFLAGS, etc. We want these
  717. # to override all the defaults, but not the per-target compile args.
  718. for l, args in self.environment.coredata.external_args.items():
  719. if l in file_args:
  720. file_args[l] += args
  721. for args in file_args.values():
  722. # This is where Visual Studio will insert target_args, target_defines,
  723. # etc, which are added later from external deps (see below).
  724. args += ['%(AdditionalOptions)', '%(PreprocessorDefinitions)', '%(AdditionalIncludeDirectories)']
  725. # Add include dirs from the `include_directories:` kwarg on the target
  726. # and from `include_directories:` of internal deps of the target.
  727. #
  728. # Target include dirs should override internal deps include dirs.
  729. # This is handled in BuildTarget.process_kwargs()
  730. #
  731. # Include dirs from internal deps should override include dirs from
  732. # external deps and must maintain the order in which they are
  733. # specified. Hence, we must reverse so that the order is preserved.
  734. #
  735. # These are per-target, but we still add them as per-file because we
  736. # need them to be looked in first.
  737. for d in reversed(target.get_include_dirs()):
  738. for i in d.get_incdirs():
  739. curdir = os.path.join(d.get_curdir(), i)
  740. args.append('-I' + self.relpath(curdir, target.subdir)) # build dir
  741. args.append('-I' + os.path.join(proj_to_src_root, curdir)) # src dir
  742. for i in d.get_extra_build_dirs():
  743. curdir = os.path.join(d.get_curdir(), i)
  744. args.append('-I' + self.relpath(curdir, target.subdir)) # build dir
  745. # Add per-target compile args, f.ex, `c_args : ['/DFOO']`. We set these
  746. # near the end since these are supposed to override everything else.
  747. for l, args in target.extra_args.items():
  748. if l in file_args:
  749. file_args[l] += args
  750. # The highest priority includes. In order of directory search:
  751. # target private dir, target build dir, generated sources include dirs,
  752. # target source dir
  753. for args in file_args.values():
  754. t_inc_dirs = ['.', self.relpath(self.get_target_private_dir(target),
  755. self.get_target_dir(target))]
  756. t_inc_dirs += generated_files_include_dirs + [proj_to_src_dir]
  757. args += ['-I' + arg for arg in t_inc_dirs]
  758. # Split preprocessor defines and include directories out of the list of
  759. # all extra arguments. The rest go into %(AdditionalOptions).
  760. for l, args in file_args.items():
  761. for arg in args[:]:
  762. if arg.startswith(('-D', '/D')) or arg == '%(PreprocessorDefinitions)':
  763. file_args[l].remove(arg)
  764. # Don't escape the marker
  765. if arg == '%(PreprocessorDefinitions)':
  766. define = arg
  767. else:
  768. define = arg[2:]
  769. # De-dup
  770. if define in file_defines[l]:
  771. file_defines[l].remove(define)
  772. file_defines[l].append(define)
  773. elif arg.startswith(('-I', '/I')) or arg == '%(AdditionalIncludeDirectories)':
  774. file_args[l].remove(arg)
  775. # Don't escape the marker
  776. if arg == '%(AdditionalIncludeDirectories)':
  777. inc_dir = arg
  778. else:
  779. inc_dir = arg[2:]
  780. # De-dup
  781. if inc_dir not in file_inc_dirs[l]:
  782. file_inc_dirs[l].append(inc_dir)
  783. # Split compile args needed to find external dependencies
  784. # Link args are added while generating the link command
  785. for d in reversed(target.get_external_deps()):
  786. # Cflags required by external deps might have UNIX-specific flags,
  787. # so filter them out if needed
  788. d_compile_args = compiler.unix_args_to_native(d.get_compile_args())
  789. for arg in d_compile_args:
  790. if arg.startswith(('-D', '/D')):
  791. define = arg[2:]
  792. # De-dup
  793. if define in target_defines:
  794. target_defines.remove(define)
  795. target_defines.append(define)
  796. elif arg.startswith(('-I', '/I')):
  797. inc_dir = arg[2:]
  798. # De-dup
  799. if inc_dir not in target_inc_dirs:
  800. target_inc_dirs.append(inc_dir)
  801. else:
  802. target_args.append(arg)
  803. languages += gen_langs
  804. if len(target_args) > 0:
  805. target_args.append('%(AdditionalOptions)')
  806. ET.SubElement(clconf, "AdditionalOptions").text = ' '.join(target_args)
  807. target_inc_dirs.append('%(AdditionalIncludeDirectories)')
  808. ET.SubElement(clconf, 'AdditionalIncludeDirectories').text = ';'.join(target_inc_dirs)
  809. target_defines.append('%(PreprocessorDefinitions)')
  810. ET.SubElement(clconf, 'PreprocessorDefinitions').text = ';'.join(target_defines)
  811. ET.SubElement(clconf, 'MinimalRebuild').text = 'true'
  812. ET.SubElement(clconf, 'FunctionLevelLinking').text = 'true'
  813. pch_node = ET.SubElement(clconf, 'PrecompiledHeader')
  814. # Warning level
  815. warning_level = self.get_option_for_target('warning_level', target)
  816. ET.SubElement(clconf, 'WarningLevel').text = 'Level' + str(1 + int(warning_level))
  817. if self.get_option_for_target('werror', target):
  818. ET.SubElement(clconf, 'TreatWarningAsError').text = 'true'
  819. # Note: SuppressStartupBanner is /NOLOGO and is 'true' by default
  820. pch_sources = {}
  821. for lang in ['c', 'cpp']:
  822. pch = target.get_pch(lang)
  823. if not pch:
  824. continue
  825. pch_node.text = 'Use'
  826. pch_sources[lang] = [pch[0], pch[1], lang]
  827. if len(pch_sources) == 1:
  828. # If there is only 1 language with precompiled headers, we can use it for the entire project, which
  829. # is cleaner than specifying it for each source file.
  830. pch_source = list(pch_sources.values())[0]
  831. header = os.path.join(proj_to_src_dir, pch_source[0])
  832. pch_file = ET.SubElement(clconf, 'PrecompiledHeaderFile')
  833. pch_file.text = header
  834. pch_include = ET.SubElement(clconf, 'ForcedIncludeFiles')
  835. pch_include.text = header + ';%(ForcedIncludeFiles)'
  836. pch_out = ET.SubElement(clconf, 'PrecompiledHeaderOutputFile')
  837. pch_out.text = '$(IntDir)$(TargetName)-%s.pch' % pch_source[2]
  838. resourcecompile = ET.SubElement(compiles, 'ResourceCompile')
  839. ET.SubElement(resourcecompile, 'PreprocessorDefinitions')
  840. # Linker options
  841. link = ET.SubElement(compiles, 'Link')
  842. extra_link_args = CompilerArgs(compiler)
  843. # FIXME: Can these buildtype linker args be added as tags in the
  844. # vcxproj file (similar to buildtype compiler args) instead of in
  845. # AdditionalOptions?
  846. extra_link_args += compiler.get_buildtype_linker_args(self.buildtype)
  847. if not isinstance(target, build.StaticLibrary):
  848. if isinstance(target, build.SharedModule):
  849. extra_link_args += compiler.get_std_shared_module_link_args()
  850. # Add link args added using add_project_link_arguments()
  851. extra_link_args += self.build.get_project_link_args(compiler, target.subproject)
  852. # Add link args added using add_global_link_arguments()
  853. # These override per-project link arguments
  854. extra_link_args += self.build.get_global_link_args(compiler)
  855. if not target.is_cross:
  856. # Link args added from the env: LDFLAGS. We want these to
  857. # override all the defaults but not the per-target link args.
  858. extra_link_args += self.environment.coredata.external_link_args[compiler.get_language()]
  859. # Only non-static built targets need link args and link dependencies
  860. extra_link_args += target.link_args
  861. # External deps must be last because target link libraries may depend on them.
  862. for dep in target.get_external_deps():
  863. # Extend without reordering or de-dup to preserve `-L -l` sets
  864. # https://github.com/mesonbuild/meson/issues/1718
  865. extra_link_args.extend_direct(dep.get_link_args())
  866. for d in target.get_dependencies():
  867. if isinstance(d, build.StaticLibrary):
  868. for dep in d.get_external_deps():
  869. extra_link_args.extend_direct(dep.get_link_args())
  870. # Add link args for c_* or cpp_* build options. Currently this only
  871. # adds c_winlibs and cpp_winlibs when building for Windows. This needs
  872. # to be after all internal and external libraries so that unresolved
  873. # symbols from those can be found here. This is needed when the
  874. # *_winlibs that we want to link to are static mingw64 libraries.
  875. extra_link_args += compiler.get_option_link_args(self.environment.coredata.compiler_options)
  876. (additional_libpaths, additional_links, extra_link_args) = self.split_link_args(extra_link_args.to_native())
  877. if len(extra_link_args) > 0:
  878. extra_link_args.append('%(AdditionalOptions)')
  879. ET.SubElement(link, "AdditionalOptions").text = ' '.join(extra_link_args)
  880. if len(additional_libpaths) > 0:
  881. additional_libpaths.insert(0, '%(AdditionalLibraryDirectories)')
  882. ET.SubElement(link, 'AdditionalLibraryDirectories').text = ';'.join(additional_libpaths)
  883. # Add more libraries to be linked if needed
  884. for t in target.get_dependencies():
  885. lobj = self.build.targets[t.get_id()]
  886. linkname = os.path.join(down, self.get_target_filename_for_linking(lobj))
  887. if t in target.link_whole_targets:
  888. linkname = compiler.get_link_whole_for(linkname)[0]
  889. additional_links.append(linkname)
  890. for lib in self.get_custom_target_provided_libraries(target):
  891. additional_links.append(self.relpath(lib, self.get_target_dir(target)))
  892. additional_objects = []
  893. for o in self.flatten_object_list(target, down):
  894. assert(isinstance(o, str))
  895. additional_objects.append(o)
  896. for o in custom_objs:
  897. additional_objects.append(o)
  898. if len(additional_links) > 0:
  899. additional_links.append('%(AdditionalDependencies)')
  900. ET.SubElement(link, 'AdditionalDependencies').text = ';'.join(additional_links)
  901. ofile = ET.SubElement(link, 'OutputFile')
  902. ofile.text = '$(OutDir)%s' % target.get_filename()
  903. subsys = ET.SubElement(link, 'SubSystem')
  904. subsys.text = subsystem
  905. if (isinstance(target, build.SharedLibrary) or
  906. isinstance(target, build.Executable)) and target.get_import_filename():
  907. # DLLs built with MSVC always have an import library except when
  908. # they're data-only DLLs, but we don't support those yet.
  909. ET.SubElement(link, 'ImportLibrary').text = target.get_import_filename()
  910. if isinstance(target, build.SharedLibrary):
  911. # Add module definitions file, if provided
  912. if target.vs_module_defs:
  913. relpath = os.path.join(down, target.vs_module_defs.rel_to_builddir(self.build_to_src))
  914. ET.SubElement(link, 'ModuleDefinitionFile').text = relpath
  915. if '/ZI' in buildtype_args or '/Zi' in buildtype_args:
  916. pdb = ET.SubElement(link, 'ProgramDataBaseFileName')
  917. pdb.text = '$(OutDir}%s.pdb' % target_name
  918. if isinstance(target, build.Executable):
  919. ET.SubElement(link, 'EntryPointSymbol').text = entrypoint
  920. targetmachine = ET.SubElement(link, 'TargetMachine')
  921. targetplatform = self.platform.lower()
  922. if targetplatform == 'win32':
  923. targetmachine.text = 'MachineX86'
  924. elif targetplatform == 'x64':
  925. targetmachine.text = 'MachineX64'
  926. elif targetplatform == 'arm':
  927. targetmachine.text = 'MachineARM'
  928. else:
  929. raise MesonException('Unsupported Visual Studio target machine: ' + targetmachine)
  930. extra_files = target.extra_files
  931. if len(headers) + len(gen_hdrs) + len(extra_files) > 0:
  932. inc_hdrs = ET.SubElement(root, 'ItemGroup')
  933. for h in headers:
  934. relpath = os.path.join(down, h.rel_to_builddir(self.build_to_src))
  935. ET.SubElement(inc_hdrs, 'CLInclude', Include=relpath)
  936. for h in gen_hdrs:
  937. ET.SubElement(inc_hdrs, 'CLInclude', Include=h)
  938. for h in target.extra_files:
  939. relpath = os.path.join(down, h.rel_to_builddir(self.build_to_src))
  940. ET.SubElement(inc_hdrs, 'CLInclude', Include=relpath)
  941. if len(sources) + len(gen_src) + len(pch_sources) > 0:
  942. inc_src = ET.SubElement(root, 'ItemGroup')
  943. for s in sources:
  944. relpath = os.path.join(down, s.rel_to_builddir(self.build_to_src))
  945. inc_cl = ET.SubElement(inc_src, 'CLCompile', Include=relpath)
  946. lang = Vs2010Backend.lang_from_source_file(s)
  947. self.add_pch(inc_cl, proj_to_src_dir, pch_sources, s)
  948. self.add_additional_options(lang, inc_cl, file_args)
  949. self.add_preprocessor_defines(lang, inc_cl, file_defines)
  950. self.add_include_dirs(lang, inc_cl, file_inc_dirs)
  951. basename = os.path.basename(s.fname)
  952. if basename in self.sources_conflicts[target.get_id()]:
  953. ET.SubElement(inc_cl, 'ObjectFileName').text = "$(IntDir)" + self.object_filename_from_source(target, s)
  954. for s in gen_src:
  955. inc_cl = ET.SubElement(inc_src, 'CLCompile', Include=s)
  956. lang = Vs2010Backend.lang_from_source_file(s)
  957. self.add_pch(inc_cl, proj_to_src_dir, pch_sources, s)
  958. self.add_additional_options(lang, inc_cl, file_args)
  959. self.add_preprocessor_defines(lang, inc_cl, file_defines)
  960. self.add_include_dirs(lang, inc_cl, file_inc_dirs)
  961. for lang in pch_sources:
  962. header, impl, suffix = pch_sources[lang]
  963. relpath = os.path.join(proj_to_src_dir, impl)
  964. inc_cl = ET.SubElement(inc_src, 'CLCompile', Include=relpath)
  965. pch = ET.SubElement(inc_cl, 'PrecompiledHeader')
  966. pch.text = 'Create'
  967. pch_out = ET.SubElement(inc_cl, 'PrecompiledHeaderOutputFile')
  968. pch_out.text = '$(IntDir)$(TargetName)-%s.pch' % suffix
  969. pch_file = ET.SubElement(inc_cl, 'PrecompiledHeaderFile')
  970. # MSBuild searches for the header relative from the implementation, so we have to use
  971. # just the file name instead of the relative path to the file.
  972. pch_file.text = os.path.split(header)[1]
  973. self.add_additional_options(lang, inc_cl, file_args)
  974. self.add_preprocessor_defines(lang, inc_cl, file_defines)
  975. self.add_include_dirs(lang, inc_cl, file_inc_dirs)
  976. if self.has_objects(objects, additional_objects, gen_objs):
  977. inc_objs = ET.SubElement(root, 'ItemGroup')
  978. for s in objects:
  979. relpath = os.path.join(down, s.rel_to_builddir(self.build_to_src))
  980. ET.SubElement(inc_objs, 'Object', Include=relpath)
  981. for s in additional_objects:
  982. ET.SubElement(inc_objs, 'Object', Include=s)
  983. self.add_generated_objects(inc_objs, gen_objs)
  984. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.targets')
  985. # Reference the regen target.
  986. ig = ET.SubElement(root, 'ItemGroup')
  987. pref = ET.SubElement(ig, 'ProjectReference', Include=os.path.join(self.environment.get_build_dir(), 'REGEN.vcxproj'))
  988. ET.SubElement(pref, 'Project').text = self.environment.coredata.regen_guid
  989. self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
  990. def gen_regenproj(self, project_name, ofname):
  991. root = ET.Element('Project', {'DefaultTargets': 'Build',
  992. 'ToolsVersion': '4.0',
  993. 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'})
  994. confitems = ET.SubElement(root, 'ItemGroup', {'Label': 'ProjectConfigurations'})
  995. prjconf = ET.SubElement(confitems, 'ProjectConfiguration',
  996. {'Include': self.buildtype + '|' + self.platform})
  997. p = ET.SubElement(prjconf, 'Configuration')
  998. p.text = self.buildtype
  999. pl = ET.SubElement(prjconf, 'Platform')
  1000. pl.text = self.platform
  1001. globalgroup = ET.SubElement(root, 'PropertyGroup', Label='Globals')
  1002. guidelem = ET.SubElement(globalgroup, 'ProjectGuid')
  1003. guidelem.text = '{%s}' % self.environment.coredata.test_guid
  1004. kw = ET.SubElement(globalgroup, 'Keyword')
  1005. kw.text = self.platform + 'Proj'
  1006. p = ET.SubElement(globalgroup, 'Platform')
  1007. p.text = self.platform
  1008. pname = ET.SubElement(globalgroup, 'ProjectName')
  1009. pname.text = project_name
  1010. if self.windows_target_platform_version:
  1011. ET.SubElement(globalgroup, 'WindowsTargetPlatformVersion').text = self.windows_target_platform_version
  1012. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.Default.props')
  1013. type_config = ET.SubElement(root, 'PropertyGroup', Label='Configuration')
  1014. ET.SubElement(type_config, 'ConfigurationType').text = "Utility"
  1015. ET.SubElement(type_config, 'CharacterSet').text = 'MultiByte'
  1016. ET.SubElement(type_config, 'UseOfMfc').text = 'false'
  1017. if self.platform_toolset:
  1018. ET.SubElement(type_config, 'PlatformToolset').text = self.platform_toolset
  1019. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.props')
  1020. direlem = ET.SubElement(root, 'PropertyGroup')
  1021. fver = ET.SubElement(direlem, '_ProjectFileVersion')
  1022. fver.text = self.project_file_version
  1023. outdir = ET.SubElement(direlem, 'OutDir')
  1024. outdir.text = '.\\'
  1025. intdir = ET.SubElement(direlem, 'IntDir')
  1026. intdir.text = 'regen-temp\\'
  1027. tname = ET.SubElement(direlem, 'TargetName')
  1028. tname.text = project_name
  1029. action = ET.SubElement(root, 'ItemDefinitionGroup')
  1030. midl = ET.SubElement(action, 'Midl')
  1031. ET.SubElement(midl, "AdditionalIncludeDirectories").text = '%(AdditionalIncludeDirectories)'
  1032. ET.SubElement(midl, "OutputDirectory").text = '$(IntDir)'
  1033. ET.SubElement(midl, 'HeaderFileName').text = '%(Filename).h'
  1034. ET.SubElement(midl, 'TypeLibraryName').text = '%(Filename).tlb'
  1035. ET.SubElement(midl, 'InterfaceIdentifierFilename').text = '%(Filename)_i.c'
  1036. ET.SubElement(midl, 'ProxyFileName').text = '%(Filename)_p.c'
  1037. regen_command = [sys.executable,
  1038. self.environment.get_build_command(),
  1039. '--internal',
  1040. 'regencheck']
  1041. private_dir = self.environment.get_scratch_dir()
  1042. cmd_templ = '''setlocal
  1043. "%s" "%s"
  1044. if %%errorlevel%% neq 0 goto :cmEnd
  1045. :cmEnd
  1046. endlocal & call :cmErrorLevel %%errorlevel%% & goto :cmDone
  1047. :cmErrorLevel
  1048. exit /b %%1
  1049. :cmDone
  1050. if %%errorlevel%% neq 0 goto :VCEnd'''
  1051. igroup = ET.SubElement(root, 'ItemGroup')
  1052. rulefile = os.path.join(self.environment.get_scratch_dir(), 'regen.rule')
  1053. if not os.path.exists(rulefile):
  1054. with open(rulefile, 'w') as f:
  1055. f.write("# Meson regen file.")
  1056. custombuild = ET.SubElement(igroup, 'CustomBuild', Include=rulefile)
  1057. message = ET.SubElement(custombuild, 'Message')
  1058. message.text = 'Checking whether solution needs to be regenerated.'
  1059. ET.SubElement(custombuild, 'Command').text = cmd_templ % \
  1060. ('" "'.join(regen_command), private_dir)
  1061. ET.SubElement(custombuild, 'Outputs').text = Vs2010Backend.get_regen_stampfile(self.environment.get_build_dir())
  1062. deps = self.get_regen_filelist()
  1063. ET.SubElement(custombuild, 'AdditionalInputs').text = ';'.join(deps)
  1064. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.targets')
  1065. ET.SubElement(root, 'ImportGroup', Label='ExtensionTargets')
  1066. self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)
  1067. def gen_testproj(self, target_name, ofname):
  1068. project_name = target_name
  1069. root = ET.Element('Project', {'DefaultTargets': "Build",
  1070. 'ToolsVersion': '4.0',
  1071. 'xmlns': 'http://schemas.microsoft.com/developer/msbuild/2003'})
  1072. confitems = ET.SubElement(root, 'ItemGroup', {'Label': 'ProjectConfigurations'})
  1073. prjconf = ET.SubElement(confitems, 'ProjectConfiguration',
  1074. {'Include': self.buildtype + '|' + self.platform})
  1075. p = ET.SubElement(prjconf, 'Configuration')
  1076. p.text = self.buildtype
  1077. pl = ET.SubElement(prjconf, 'Platform')
  1078. pl.text = self.platform
  1079. globalgroup = ET.SubElement(root, 'PropertyGroup', Label='Globals')
  1080. guidelem = ET.SubElement(globalgroup, 'ProjectGuid')
  1081. guidelem.text = '{%s}' % self.environment.coredata.test_guid
  1082. kw = ET.SubElement(globalgroup, 'Keyword')
  1083. kw.text = self.platform + 'Proj'
  1084. p = ET.SubElement(globalgroup, 'Platform')
  1085. p.text = self.platform
  1086. pname = ET.SubElement(globalgroup, 'ProjectName')
  1087. pname.text = project_name
  1088. if self.windows_target_platform_version:
  1089. ET.SubElement(globalgroup, 'WindowsTargetPlatformVersion').text = self.windows_target_platform_version
  1090. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.Default.props')
  1091. type_config = ET.SubElement(root, 'PropertyGroup', Label='Configuration')
  1092. ET.SubElement(type_config, 'ConfigurationType')
  1093. ET.SubElement(type_config, 'CharacterSet').text = 'MultiByte'
  1094. ET.SubElement(type_config, 'UseOfMfc').text = 'false'
  1095. if self.platform_toolset:
  1096. ET.SubElement(type_config, 'PlatformToolset').text = self.platform_toolset
  1097. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.props')
  1098. direlem = ET.SubElement(root, 'PropertyGroup')
  1099. fver = ET.SubElement(direlem, '_ProjectFileVersion')
  1100. fver.text = self.project_file_version
  1101. outdir = ET.SubElement(direlem, 'OutDir')
  1102. outdir.text = '.\\'
  1103. intdir = ET.SubElement(direlem, 'IntDir')
  1104. intdir.text = 'test-temp\\'
  1105. tname = ET.SubElement(direlem, 'TargetName')
  1106. tname.text = target_name
  1107. action = ET.SubElement(root, 'ItemDefinitionGroup')
  1108. midl = ET.SubElement(action, 'Midl')
  1109. ET.SubElement(midl, "AdditionalIncludeDirectories").text = '%(AdditionalIncludeDirectories)'
  1110. ET.SubElement(midl, "OutputDirectory").text = '$(IntDir)'
  1111. ET.SubElement(midl, 'HeaderFileName').text = '%(Filename).h'
  1112. ET.SubElement(midl, 'TypeLibraryName').text = '%(Filename).tlb'
  1113. ET.SubElement(midl, 'InterfaceIdentifierFilename').text = '%(Filename)_i.c'
  1114. ET.SubElement(midl, 'ProxyFileName').text = '%(Filename)_p.c'
  1115. postbuild = ET.SubElement(action, 'PostBuildEvent')
  1116. ET.SubElement(postbuild, 'Message')
  1117. # FIXME: No benchmarks?
  1118. test_command = [sys.executable,
  1119. get_meson_script(self.environment, 'mesontest'),
  1120. '--no-rebuild']
  1121. if not self.environment.coredata.get_builtin_option('stdsplit'):
  1122. test_command += ['--no-stdsplit']
  1123. if self.environment.coredata.get_builtin_option('errorlogs'):
  1124. test_command += ['--print-errorlogs']
  1125. cmd_templ = '''setlocal
  1126. "%s"
  1127. if %%errorlevel%% neq 0 goto :cmEnd
  1128. :cmEnd
  1129. endlocal & call :cmErrorLevel %%errorlevel%% & goto :cmDone
  1130. :cmErrorLevel
  1131. exit /b %%1
  1132. :cmDone
  1133. if %%errorlevel%% neq 0 goto :VCEnd'''
  1134. self.serialize_tests()
  1135. ET.SubElement(postbuild, 'Command').text =\
  1136. cmd_templ % ('" "'.join(test_command))
  1137. ET.SubElement(root, 'Import', Project='$(VCTargetsPath)\Microsoft.Cpp.targets')
  1138. self._prettyprint_vcxproj_xml(ET.ElementTree(root), ofname)