msvs_emulation.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. # Copyright (c) 2012 Google Inc. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """
  5. This module helps emulate Visual Studio 2008 behavior on top of other
  6. build systems, primarily ninja.
  7. """
  8. import collections
  9. import os
  10. import re
  11. import subprocess
  12. import sys
  13. from gyp.common import OrderedSet
  14. import gyp.MSVSUtil
  15. import gyp.MSVSVersion
  16. windows_quoter_regex = re.compile(r'(\\*)"')
  17. def QuoteForRspFile(arg, quote_cmd=True):
  18. """Quote a command line argument so that it appears as one argument when
  19. processed via cmd.exe and parsed by CommandLineToArgvW (as is typical for
  20. Windows programs)."""
  21. # See http://goo.gl/cuFbX and http://goo.gl/dhPnp including the comment
  22. # threads. This is actually the quoting rules for CommandLineToArgvW, not
  23. # for the shell, because the shell doesn't do anything in Windows. This
  24. # works more or less because most programs (including the compiler, etc.)
  25. # use that function to handle command line arguments.
  26. # Use a heuristic to try to find args that are paths, and normalize them
  27. if arg.find("/") > 0 or arg.count("/") > 1:
  28. arg = os.path.normpath(arg)
  29. # For a literal quote, CommandLineToArgvW requires 2n+1 backslashes
  30. # preceding it, and results in n backslashes + the quote. So we substitute
  31. # in 2* what we match, +1 more, plus the quote.
  32. if quote_cmd:
  33. arg = windows_quoter_regex.sub(lambda mo: 2 * mo.group(1) + '\\"', arg)
  34. # %'s also need to be doubled otherwise they're interpreted as batch
  35. # positional arguments. Also make sure to escape the % so that they're
  36. # passed literally through escaping so they can be singled to just the
  37. # original %. Otherwise, trying to pass the literal representation that
  38. # looks like an environment variable to the shell (e.g. %PATH%) would fail.
  39. arg = arg.replace("%", "%%")
  40. # These commands are used in rsp files, so no escaping for the shell (via ^)
  41. # is necessary.
  42. # As a workaround for programs that don't use CommandLineToArgvW, gyp
  43. # supports msvs_quote_cmd=0, which simply disables all quoting.
  44. if quote_cmd:
  45. # Finally, wrap the whole thing in quotes so that the above quote rule
  46. # applies and whitespace isn't a word break.
  47. return f'"{arg}"'
  48. return arg
  49. def EncodeRspFileList(args, quote_cmd):
  50. """Process a list of arguments using QuoteCmdExeArgument."""
  51. # Note that the first argument is assumed to be the command. Don't add
  52. # quotes around it because then built-ins like 'echo', etc. won't work.
  53. # Take care to normpath only the path in the case of 'call ../x.bat' because
  54. # otherwise the whole thing is incorrectly interpreted as a path and not
  55. # normalized correctly.
  56. if not args:
  57. return ""
  58. if args[0].startswith("call "):
  59. call, program = args[0].split(" ", 1)
  60. program = call + " " + os.path.normpath(program)
  61. else:
  62. program = os.path.normpath(args[0])
  63. return (program + " "
  64. + " ".join(QuoteForRspFile(arg, quote_cmd) for arg in args[1:]))
  65. def _GenericRetrieve(root, default, path):
  66. """Given a list of dictionary keys |path| and a tree of dicts |root|, find
  67. value at path, or return |default| if any of the path doesn't exist."""
  68. if not root:
  69. return default
  70. if not path:
  71. return root
  72. return _GenericRetrieve(root.get(path[0]), default, path[1:])
  73. def _AddPrefix(element, prefix):
  74. """Add |prefix| to |element| or each subelement if element is iterable."""
  75. if element is None:
  76. return element
  77. # Note, not Iterable because we don't want to handle strings like that.
  78. if isinstance(element, list) or isinstance(element, tuple):
  79. return [prefix + e for e in element]
  80. else:
  81. return prefix + element
  82. def _DoRemapping(element, map):
  83. """If |element| then remap it through |map|. If |element| is iterable then
  84. each item will be remapped. Any elements not found will be removed."""
  85. if map is not None and element is not None:
  86. if not callable(map):
  87. map = map.get # Assume it's a dict, otherwise a callable to do the remap.
  88. if isinstance(element, list) or isinstance(element, tuple):
  89. element = filter(None, [map(elem) for elem in element])
  90. else:
  91. element = map(element)
  92. return element
  93. def _AppendOrReturn(append, element):
  94. """If |append| is None, simply return |element|. If |append| is not None,
  95. then add |element| to it, adding each item in |element| if it's a list or
  96. tuple."""
  97. if append is not None and element is not None:
  98. if isinstance(element, list) or isinstance(element, tuple):
  99. append.extend(element)
  100. else:
  101. append.append(element)
  102. else:
  103. return element
  104. def _FindDirectXInstallation():
  105. """Try to find an installation location for the DirectX SDK. Check for the
  106. standard environment variable, and if that doesn't exist, try to find
  107. via the registry. May return None if not found in either location."""
  108. # Return previously calculated value, if there is one
  109. if hasattr(_FindDirectXInstallation, "dxsdk_dir"):
  110. return _FindDirectXInstallation.dxsdk_dir
  111. dxsdk_dir = os.environ.get("DXSDK_DIR")
  112. if not dxsdk_dir:
  113. # Setup params to pass to and attempt to launch reg.exe.
  114. cmd = ["reg.exe", "query", r"HKLM\Software\Microsoft\DirectX", "/s"]
  115. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  116. stdout = p.communicate()[0].decode("utf-8")
  117. for line in stdout.splitlines():
  118. if "InstallPath" in line:
  119. dxsdk_dir = line.split(" ")[3] + "\\"
  120. # Cache return value
  121. _FindDirectXInstallation.dxsdk_dir = dxsdk_dir
  122. return dxsdk_dir
  123. def GetGlobalVSMacroEnv(vs_version):
  124. """Get a dict of variables mapping internal VS macro names to their gyp
  125. equivalents. Returns all variables that are independent of the target."""
  126. env = {}
  127. # '$(VSInstallDir)' and '$(VCInstallDir)' are available when and only when
  128. # Visual Studio is actually installed.
  129. if vs_version.Path():
  130. env["$(VSInstallDir)"] = vs_version.Path()
  131. env["$(VCInstallDir)"] = os.path.join(vs_version.Path(), "VC") + "\\"
  132. # Chromium uses DXSDK_DIR in include/lib paths, but it may or may not be
  133. # set. This happens when the SDK is sync'd via src-internal, rather than
  134. # by typical end-user installation of the SDK. If it's not set, we don't
  135. # want to leave the unexpanded variable in the path, so simply strip it.
  136. dxsdk_dir = _FindDirectXInstallation()
  137. env["$(DXSDK_DIR)"] = dxsdk_dir if dxsdk_dir else ""
  138. # Try to find an installation location for the Windows DDK by checking
  139. # the WDK_DIR environment variable, may be None.
  140. env["$(WDK_DIR)"] = os.environ.get("WDK_DIR", "")
  141. return env
  142. def ExtractSharedMSVSSystemIncludes(configs, generator_flags):
  143. """Finds msvs_system_include_dirs that are common to all targets, removes
  144. them from all targets, and returns an OrderedSet containing them."""
  145. all_system_includes = OrderedSet(configs[0].get("msvs_system_include_dirs", []))
  146. for config in configs[1:]:
  147. system_includes = config.get("msvs_system_include_dirs", [])
  148. all_system_includes = all_system_includes & OrderedSet(system_includes)
  149. if not all_system_includes:
  150. return None
  151. # Expand macros in all_system_includes.
  152. env = GetGlobalVSMacroEnv(GetVSVersion(generator_flags))
  153. expanded_system_includes = OrderedSet(
  154. [ExpandMacros(include, env) for include in all_system_includes]
  155. )
  156. if any(["$" in include for include in expanded_system_includes]):
  157. # Some path relies on target-specific variables, bail.
  158. return None
  159. # Remove system includes shared by all targets from the targets.
  160. for config in configs:
  161. includes = config.get("msvs_system_include_dirs", [])
  162. if includes: # Don't insert a msvs_system_include_dirs key if not needed.
  163. # This must check the unexpanded includes list:
  164. new_includes = [i for i in includes if i not in all_system_includes]
  165. config["msvs_system_include_dirs"] = new_includes
  166. return expanded_system_includes
  167. class MsvsSettings:
  168. """A class that understands the gyp 'msvs_...' values (especially the
  169. msvs_settings field). They largely correpond to the VS2008 IDE DOM. This
  170. class helps map those settings to command line options."""
  171. def __init__(self, spec, generator_flags):
  172. self.spec = spec
  173. self.vs_version = GetVSVersion(generator_flags)
  174. supported_fields = [
  175. ("msvs_configuration_attributes", dict),
  176. ("msvs_settings", dict),
  177. ("msvs_system_include_dirs", list),
  178. ("msvs_disabled_warnings", list),
  179. ("msvs_precompiled_header", str),
  180. ("msvs_precompiled_source", str),
  181. ("msvs_configuration_platform", str),
  182. ("msvs_target_platform", str),
  183. ]
  184. configs = spec["configurations"]
  185. for field, default in supported_fields:
  186. setattr(self, field, {})
  187. for configname, config in configs.items():
  188. getattr(self, field)[configname] = config.get(field, default())
  189. self.msvs_cygwin_dirs = spec.get("msvs_cygwin_dirs", ["."])
  190. unsupported_fields = [
  191. "msvs_prebuild",
  192. "msvs_postbuild",
  193. ]
  194. unsupported = []
  195. for field in unsupported_fields:
  196. for config in configs.values():
  197. if field in config:
  198. unsupported += [
  199. "{} not supported (target {}).".format(
  200. field, spec["target_name"]
  201. )
  202. ]
  203. if unsupported:
  204. raise Exception("\n".join(unsupported))
  205. def GetExtension(self):
  206. """Returns the extension for the target, with no leading dot.
  207. Uses 'product_extension' if specified, otherwise uses MSVS defaults based on
  208. the target type.
  209. """
  210. ext = self.spec.get("product_extension", None)
  211. if ext:
  212. return ext
  213. return gyp.MSVSUtil.TARGET_TYPE_EXT.get(self.spec["type"], "")
  214. def GetVSMacroEnv(self, base_to_build=None, config=None):
  215. """Get a dict of variables mapping internal VS macro names to their gyp
  216. equivalents."""
  217. target_arch = self.GetArch(config)
  218. if target_arch == "x86":
  219. target_platform = "Win32"
  220. else:
  221. target_platform = target_arch
  222. target_name = self.spec.get("product_prefix", "") + self.spec.get(
  223. "product_name", self.spec["target_name"]
  224. )
  225. target_dir = base_to_build + "\\" if base_to_build else ""
  226. target_ext = "." + self.GetExtension()
  227. target_file_name = target_name + target_ext
  228. replacements = {
  229. "$(InputName)": "${root}",
  230. "$(InputPath)": "${source}",
  231. "$(IntDir)": "$!INTERMEDIATE_DIR",
  232. "$(OutDir)\\": target_dir,
  233. "$(PlatformName)": target_platform,
  234. "$(ProjectDir)\\": "",
  235. "$(ProjectName)": self.spec["target_name"],
  236. "$(TargetDir)\\": target_dir,
  237. "$(TargetExt)": target_ext,
  238. "$(TargetFileName)": target_file_name,
  239. "$(TargetName)": target_name,
  240. "$(TargetPath)": os.path.join(target_dir, target_file_name),
  241. }
  242. replacements.update(GetGlobalVSMacroEnv(self.vs_version))
  243. return replacements
  244. def ConvertVSMacros(self, s, base_to_build=None, config=None):
  245. """Convert from VS macro names to something equivalent."""
  246. env = self.GetVSMacroEnv(base_to_build, config=config)
  247. return ExpandMacros(s, env)
  248. def AdjustLibraries(self, libraries):
  249. """Strip -l from library if it's specified with that."""
  250. libs = [lib[2:] if lib.startswith("-l") else lib for lib in libraries]
  251. return [
  252. lib + ".lib"
  253. if not lib.lower().endswith(".lib") and not lib.lower().endswith(".obj")
  254. else lib
  255. for lib in libs
  256. ]
  257. def _GetAndMunge(self, field, path, default, prefix, append, map):
  258. """Retrieve a value from |field| at |path| or return |default|. If
  259. |append| is specified, and the item is found, it will be appended to that
  260. object instead of returned. If |map| is specified, results will be
  261. remapped through |map| before being returned or appended."""
  262. result = _GenericRetrieve(field, default, path)
  263. result = _DoRemapping(result, map)
  264. result = _AddPrefix(result, prefix)
  265. return _AppendOrReturn(append, result)
  266. class _GetWrapper:
  267. def __init__(self, parent, field, base_path, append=None):
  268. self.parent = parent
  269. self.field = field
  270. self.base_path = [base_path]
  271. self.append = append
  272. def __call__(self, name, map=None, prefix="", default=None):
  273. return self.parent._GetAndMunge(
  274. self.field,
  275. self.base_path + [name],
  276. default=default,
  277. prefix=prefix,
  278. append=self.append,
  279. map=map,
  280. )
  281. def GetArch(self, config):
  282. """Get architecture based on msvs_configuration_platform and
  283. msvs_target_platform. Returns either 'x86' or 'x64'."""
  284. configuration_platform = self.msvs_configuration_platform.get(config, "")
  285. platform = self.msvs_target_platform.get(config, "")
  286. if not platform: # If no specific override, use the configuration's.
  287. platform = configuration_platform
  288. # Map from platform to architecture.
  289. return {"Win32": "x86", "x64": "x64", "ARM64": "arm64"}.get(platform, "x86")
  290. def _TargetConfig(self, config):
  291. """Returns the target-specific configuration."""
  292. # There's two levels of architecture/platform specification in VS. The
  293. # first level is globally for the configuration (this is what we consider
  294. # "the" config at the gyp level, which will be something like 'Debug' or
  295. # 'Release'), VS2015 and later only use this level
  296. if int(self.vs_version.short_name) >= 2015:
  297. return config
  298. # and a second target-specific configuration, which is an
  299. # override for the global one. |config| is remapped here to take into
  300. # account the local target-specific overrides to the global configuration.
  301. arch = self.GetArch(config)
  302. if arch == "x64" and not config.endswith("_x64"):
  303. config += "_x64"
  304. if arch == "x86" and config.endswith("_x64"):
  305. config = config.rsplit("_", 1)[0]
  306. return config
  307. def _Setting(self, path, config, default=None, prefix="", append=None, map=None):
  308. """_GetAndMunge for msvs_settings."""
  309. return self._GetAndMunge(
  310. self.msvs_settings[config], path, default, prefix, append, map
  311. )
  312. def _ConfigAttrib(
  313. self, path, config, default=None, prefix="", append=None, map=None
  314. ):
  315. """_GetAndMunge for msvs_configuration_attributes."""
  316. return self._GetAndMunge(
  317. self.msvs_configuration_attributes[config],
  318. path,
  319. default,
  320. prefix,
  321. append,
  322. map,
  323. )
  324. def AdjustIncludeDirs(self, include_dirs, config):
  325. """Updates include_dirs to expand VS specific paths, and adds the system
  326. include dirs used for platform SDK and similar."""
  327. config = self._TargetConfig(config)
  328. includes = include_dirs + self.msvs_system_include_dirs[config]
  329. includes.extend(
  330. self._Setting(
  331. ("VCCLCompilerTool", "AdditionalIncludeDirectories"), config, default=[]
  332. )
  333. )
  334. return [self.ConvertVSMacros(p, config=config) for p in includes]
  335. def AdjustMidlIncludeDirs(self, midl_include_dirs, config):
  336. """Updates midl_include_dirs to expand VS specific paths, and adds the
  337. system include dirs used for platform SDK and similar."""
  338. config = self._TargetConfig(config)
  339. includes = midl_include_dirs + self.msvs_system_include_dirs[config]
  340. includes.extend(
  341. self._Setting(
  342. ("VCMIDLTool", "AdditionalIncludeDirectories"), config, default=[]
  343. )
  344. )
  345. return [self.ConvertVSMacros(p, config=config) for p in includes]
  346. def GetComputedDefines(self, config):
  347. """Returns the set of defines that are injected to the defines list based
  348. on other VS settings."""
  349. config = self._TargetConfig(config)
  350. defines = []
  351. if self._ConfigAttrib(["CharacterSet"], config) == "1":
  352. defines.extend(("_UNICODE", "UNICODE"))
  353. if self._ConfigAttrib(["CharacterSet"], config) == "2":
  354. defines.append("_MBCS")
  355. defines.extend(
  356. self._Setting(
  357. ("VCCLCompilerTool", "PreprocessorDefinitions"), config, default=[]
  358. )
  359. )
  360. return defines
  361. def GetCompilerPdbName(self, config, expand_special):
  362. """Get the pdb file name that should be used for compiler invocations, or
  363. None if there's no explicit name specified."""
  364. config = self._TargetConfig(config)
  365. pdbname = self._Setting(("VCCLCompilerTool", "ProgramDataBaseFileName"), config)
  366. if pdbname:
  367. pdbname = expand_special(self.ConvertVSMacros(pdbname))
  368. return pdbname
  369. def GetMapFileName(self, config, expand_special):
  370. """Gets the explicitly overridden map file name for a target or returns None
  371. if it's not set."""
  372. config = self._TargetConfig(config)
  373. map_file = self._Setting(("VCLinkerTool", "MapFileName"), config)
  374. if map_file:
  375. map_file = expand_special(self.ConvertVSMacros(map_file, config=config))
  376. return map_file
  377. def GetOutputName(self, config, expand_special):
  378. """Gets the explicitly overridden output name for a target or returns None
  379. if it's not overridden."""
  380. config = self._TargetConfig(config)
  381. type = self.spec["type"]
  382. root = "VCLibrarianTool" if type == "static_library" else "VCLinkerTool"
  383. # TODO(scottmg): Handle OutputDirectory without OutputFile.
  384. output_file = self._Setting((root, "OutputFile"), config)
  385. if output_file:
  386. output_file = expand_special(
  387. self.ConvertVSMacros(output_file, config=config)
  388. )
  389. return output_file
  390. def GetPDBName(self, config, expand_special, default):
  391. """Gets the explicitly overridden pdb name for a target or returns
  392. default if it's not overridden, or if no pdb will be generated."""
  393. config = self._TargetConfig(config)
  394. output_file = self._Setting(("VCLinkerTool", "ProgramDatabaseFile"), config)
  395. generate_debug_info = self._Setting(
  396. ("VCLinkerTool", "GenerateDebugInformation"), config
  397. )
  398. if generate_debug_info == "true":
  399. if output_file:
  400. return expand_special(self.ConvertVSMacros(output_file, config=config))
  401. else:
  402. return default
  403. else:
  404. return None
  405. def GetNoImportLibrary(self, config):
  406. """If NoImportLibrary: true, ninja will not expect the output to include
  407. an import library."""
  408. config = self._TargetConfig(config)
  409. noimplib = self._Setting(("NoImportLibrary",), config)
  410. return noimplib == "true"
  411. def GetAsmflags(self, config):
  412. """Returns the flags that need to be added to ml invocations."""
  413. config = self._TargetConfig(config)
  414. asmflags = []
  415. safeseh = self._Setting(("MASM", "UseSafeExceptionHandlers"), config)
  416. if safeseh == "true":
  417. asmflags.append("/safeseh")
  418. return asmflags
  419. def GetCflags(self, config):
  420. """Returns the flags that need to be added to .c and .cc compilations."""
  421. config = self._TargetConfig(config)
  422. cflags = []
  423. cflags.extend(["/wd" + w for w in self.msvs_disabled_warnings[config]])
  424. cl = self._GetWrapper(
  425. self, self.msvs_settings[config], "VCCLCompilerTool", append=cflags
  426. )
  427. cl(
  428. "Optimization",
  429. map={"0": "d", "1": "1", "2": "2", "3": "x"},
  430. prefix="/O",
  431. default="2",
  432. )
  433. cl("InlineFunctionExpansion", prefix="/Ob")
  434. cl("DisableSpecificWarnings", prefix="/wd")
  435. cl("StringPooling", map={"true": "/GF"})
  436. cl("EnableFiberSafeOptimizations", map={"true": "/GT"})
  437. cl("OmitFramePointers", map={"false": "-", "true": ""}, prefix="/Oy")
  438. cl("EnableIntrinsicFunctions", map={"false": "-", "true": ""}, prefix="/Oi")
  439. cl("FavorSizeOrSpeed", map={"1": "t", "2": "s"}, prefix="/O")
  440. cl(
  441. "FloatingPointModel",
  442. map={"0": "precise", "1": "strict", "2": "fast"},
  443. prefix="/fp:",
  444. default="0",
  445. )
  446. cl("CompileAsManaged", map={"false": "", "true": "/clr"})
  447. cl("WholeProgramOptimization", map={"true": "/GL"})
  448. cl("WarningLevel", prefix="/W")
  449. cl("WarnAsError", map={"true": "/WX"})
  450. cl(
  451. "CallingConvention",
  452. map={"0": "d", "1": "r", "2": "z", "3": "v"},
  453. prefix="/G",
  454. )
  455. cl("DebugInformationFormat", map={"1": "7", "3": "i", "4": "I"}, prefix="/Z")
  456. cl("RuntimeTypeInfo", map={"true": "/GR", "false": "/GR-"})
  457. cl("EnableFunctionLevelLinking", map={"true": "/Gy", "false": "/Gy-"})
  458. cl("MinimalRebuild", map={"true": "/Gm"})
  459. cl("BufferSecurityCheck", map={"true": "/GS", "false": "/GS-"})
  460. cl("BasicRuntimeChecks", map={"1": "s", "2": "u", "3": "1"}, prefix="/RTC")
  461. cl(
  462. "RuntimeLibrary",
  463. map={"0": "T", "1": "Td", "2": "D", "3": "Dd"},
  464. prefix="/M",
  465. )
  466. cl("ExceptionHandling", map={"1": "sc", "2": "a"}, prefix="/EH")
  467. cl("DefaultCharIsUnsigned", map={"true": "/J"})
  468. cl(
  469. "TreatWChar_tAsBuiltInType",
  470. map={"false": "-", "true": ""},
  471. prefix="/Zc:wchar_t",
  472. )
  473. cl("EnablePREfast", map={"true": "/analyze"})
  474. cl("AdditionalOptions", prefix="")
  475. cl(
  476. "EnableEnhancedInstructionSet",
  477. map={"1": "SSE", "2": "SSE2", "3": "AVX", "4": "IA32", "5": "AVX2"},
  478. prefix="/arch:",
  479. )
  480. cflags.extend(
  481. [
  482. "/FI" + f
  483. for f in self._Setting(
  484. ("VCCLCompilerTool", "ForcedIncludeFiles"), config, default=[]
  485. )
  486. ]
  487. )
  488. if float(self.vs_version.project_version) >= 12.0:
  489. # New flag introduced in VS2013 (project version 12.0) Forces writes to
  490. # the program database (PDB) to be serialized through MSPDBSRV.EXE.
  491. # https://msdn.microsoft.com/en-us/library/dn502518.aspx
  492. cflags.append("/FS")
  493. # ninja handles parallelism by itself, don't have the compiler do it too.
  494. cflags = [x for x in cflags if not x.startswith("/MP")]
  495. return cflags
  496. def _GetPchFlags(self, config, extension):
  497. """Get the flags to be added to the cflags for precompiled header support."""
  498. config = self._TargetConfig(config)
  499. # The PCH is only built once by a particular source file. Usage of PCH must
  500. # only be for the same language (i.e. C vs. C++), so only include the pch
  501. # flags when the language matches.
  502. if self.msvs_precompiled_header[config]:
  503. source_ext = os.path.splitext(self.msvs_precompiled_source[config])[1]
  504. if _LanguageMatchesForPch(source_ext, extension):
  505. pch = self.msvs_precompiled_header[config]
  506. pchbase = os.path.split(pch)[1]
  507. return ["/Yu" + pch, "/FI" + pch, "/Fp${pchprefix}." + pchbase + ".pch"]
  508. return []
  509. def GetCflagsC(self, config):
  510. """Returns the flags that need to be added to .c compilations."""
  511. config = self._TargetConfig(config)
  512. return self._GetPchFlags(config, ".c")
  513. def GetCflagsCC(self, config):
  514. """Returns the flags that need to be added to .cc compilations."""
  515. config = self._TargetConfig(config)
  516. return ["/TP"] + self._GetPchFlags(config, ".cc")
  517. def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path):
  518. """Get and normalize the list of paths in AdditionalLibraryDirectories
  519. setting."""
  520. config = self._TargetConfig(config)
  521. libpaths = self._Setting(
  522. (root, "AdditionalLibraryDirectories"), config, default=[]
  523. )
  524. libpaths = [
  525. os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(p, config=config)))
  526. for p in libpaths
  527. ]
  528. return ['/LIBPATH:"' + p + '"' for p in libpaths]
  529. def GetLibFlags(self, config, gyp_to_build_path):
  530. """Returns the flags that need to be added to lib commands."""
  531. config = self._TargetConfig(config)
  532. libflags = []
  533. lib = self._GetWrapper(
  534. self, self.msvs_settings[config], "VCLibrarianTool", append=libflags
  535. )
  536. libflags.extend(
  537. self._GetAdditionalLibraryDirectories(
  538. "VCLibrarianTool", config, gyp_to_build_path
  539. )
  540. )
  541. lib("LinkTimeCodeGeneration", map={"true": "/LTCG"})
  542. lib(
  543. "TargetMachine",
  544. map={"1": "X86", "17": "X64", "3": "ARM"},
  545. prefix="/MACHINE:",
  546. )
  547. lib("AdditionalOptions")
  548. return libflags
  549. def GetDefFile(self, gyp_to_build_path):
  550. """Returns the .def file from sources, if any. Otherwise returns None."""
  551. spec = self.spec
  552. if spec["type"] in ("shared_library", "loadable_module", "executable"):
  553. def_files = [
  554. s for s in spec.get("sources", []) if s.lower().endswith(".def")
  555. ]
  556. if len(def_files) == 1:
  557. return gyp_to_build_path(def_files[0])
  558. elif len(def_files) > 1:
  559. raise Exception("Multiple .def files")
  560. return None
  561. def _GetDefFileAsLdflags(self, ldflags, gyp_to_build_path):
  562. """.def files get implicitly converted to a ModuleDefinitionFile for the
  563. linker in the VS generator. Emulate that behaviour here."""
  564. def_file = self.GetDefFile(gyp_to_build_path)
  565. if def_file:
  566. ldflags.append('/DEF:"%s"' % def_file)
  567. def GetPGDName(self, config, expand_special):
  568. """Gets the explicitly overridden pgd name for a target or returns None
  569. if it's not overridden."""
  570. config = self._TargetConfig(config)
  571. output_file = self._Setting(("VCLinkerTool", "ProfileGuidedDatabase"), config)
  572. if output_file:
  573. output_file = expand_special(
  574. self.ConvertVSMacros(output_file, config=config)
  575. )
  576. return output_file
  577. def GetLdflags(
  578. self,
  579. config,
  580. gyp_to_build_path,
  581. expand_special,
  582. manifest_base_name,
  583. output_name,
  584. is_executable,
  585. build_dir,
  586. ):
  587. """Returns the flags that need to be added to link commands, and the
  588. manifest files."""
  589. config = self._TargetConfig(config)
  590. ldflags = []
  591. ld = self._GetWrapper(
  592. self, self.msvs_settings[config], "VCLinkerTool", append=ldflags
  593. )
  594. self._GetDefFileAsLdflags(ldflags, gyp_to_build_path)
  595. ld("GenerateDebugInformation", map={"true": "/DEBUG"})
  596. # TODO: These 'map' values come from machineTypeOption enum,
  597. # and does not have an official value for ARM64 in VS2017 (yet).
  598. # It needs to verify the ARM64 value when machineTypeOption is updated.
  599. ld(
  600. "TargetMachine",
  601. map={"1": "X86", "17": "X64", "3": "ARM", "18": "ARM64"},
  602. prefix="/MACHINE:",
  603. )
  604. ldflags.extend(
  605. self._GetAdditionalLibraryDirectories(
  606. "VCLinkerTool", config, gyp_to_build_path
  607. )
  608. )
  609. ld("DelayLoadDLLs", prefix="/DELAYLOAD:")
  610. ld("TreatLinkerWarningAsErrors", prefix="/WX", map={"true": "", "false": ":NO"})
  611. out = self.GetOutputName(config, expand_special)
  612. if out:
  613. ldflags.append("/OUT:" + out)
  614. pdb = self.GetPDBName(config, expand_special, output_name + ".pdb")
  615. if pdb:
  616. ldflags.append("/PDB:" + pdb)
  617. pgd = self.GetPGDName(config, expand_special)
  618. if pgd:
  619. ldflags.append("/PGD:" + pgd)
  620. map_file = self.GetMapFileName(config, expand_special)
  621. ld("GenerateMapFile", map={"true": "/MAP:" + map_file if map_file else "/MAP"})
  622. ld("MapExports", map={"true": "/MAPINFO:EXPORTS"})
  623. ld("AdditionalOptions", prefix="")
  624. minimum_required_version = self._Setting(
  625. ("VCLinkerTool", "MinimumRequiredVersion"), config, default=""
  626. )
  627. if minimum_required_version:
  628. minimum_required_version = "," + minimum_required_version
  629. ld(
  630. "SubSystem",
  631. map={
  632. "1": "CONSOLE%s" % minimum_required_version,
  633. "2": "WINDOWS%s" % minimum_required_version,
  634. },
  635. prefix="/SUBSYSTEM:",
  636. )
  637. stack_reserve_size = self._Setting(
  638. ("VCLinkerTool", "StackReserveSize"), config, default=""
  639. )
  640. if stack_reserve_size:
  641. stack_commit_size = self._Setting(
  642. ("VCLinkerTool", "StackCommitSize"), config, default=""
  643. )
  644. if stack_commit_size:
  645. stack_commit_size = "," + stack_commit_size
  646. ldflags.append(f"/STACK:{stack_reserve_size}{stack_commit_size}")
  647. ld("TerminalServerAware", map={"1": ":NO", "2": ""}, prefix="/TSAWARE")
  648. ld("LinkIncremental", map={"1": ":NO", "2": ""}, prefix="/INCREMENTAL")
  649. ld("BaseAddress", prefix="/BASE:")
  650. ld("FixedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/FIXED")
  651. ld("RandomizedBaseAddress", map={"1": ":NO", "2": ""}, prefix="/DYNAMICBASE")
  652. ld("DataExecutionPrevention", map={"1": ":NO", "2": ""}, prefix="/NXCOMPAT")
  653. ld("OptimizeReferences", map={"1": "NOREF", "2": "REF"}, prefix="/OPT:")
  654. ld("ForceSymbolReferences", prefix="/INCLUDE:")
  655. ld("EnableCOMDATFolding", map={"1": "NOICF", "2": "ICF"}, prefix="/OPT:")
  656. ld(
  657. "LinkTimeCodeGeneration",
  658. map={"1": "", "2": ":PGINSTRUMENT", "3": ":PGOPTIMIZE", "4": ":PGUPDATE"},
  659. prefix="/LTCG",
  660. )
  661. ld("IgnoreDefaultLibraryNames", prefix="/NODEFAULTLIB:")
  662. ld("ResourceOnlyDLL", map={"true": "/NOENTRY"})
  663. ld("EntryPointSymbol", prefix="/ENTRY:")
  664. ld("Profile", map={"true": "/PROFILE"})
  665. ld("LargeAddressAware", map={"1": ":NO", "2": ""}, prefix="/LARGEADDRESSAWARE")
  666. # TODO(scottmg): This should sort of be somewhere else (not really a flag).
  667. ld("AdditionalDependencies", prefix="")
  668. if self.GetArch(config) == "x86":
  669. safeseh_default = "true"
  670. else:
  671. safeseh_default = None
  672. ld(
  673. "ImageHasSafeExceptionHandlers",
  674. map={"false": ":NO", "true": ""},
  675. prefix="/SAFESEH",
  676. default=safeseh_default,
  677. )
  678. # If the base address is not specifically controlled, DYNAMICBASE should
  679. # be on by default.
  680. if not any("DYNAMICBASE" in flag or flag == "/FIXED" for flag in ldflags):
  681. ldflags.append("/DYNAMICBASE")
  682. # If the NXCOMPAT flag has not been specified, default to on. Despite the
  683. # documentation that says this only defaults to on when the subsystem is
  684. # Vista or greater (which applies to the linker), the IDE defaults it on
  685. # unless it's explicitly off.
  686. if not any("NXCOMPAT" in flag for flag in ldflags):
  687. ldflags.append("/NXCOMPAT")
  688. have_def_file = any(flag.startswith("/DEF:") for flag in ldflags)
  689. (
  690. manifest_flags,
  691. intermediate_manifest,
  692. manifest_files,
  693. ) = self._GetLdManifestFlags(
  694. config,
  695. manifest_base_name,
  696. gyp_to_build_path,
  697. is_executable and not have_def_file,
  698. build_dir,
  699. )
  700. ldflags.extend(manifest_flags)
  701. return ldflags, intermediate_manifest, manifest_files
  702. def _GetLdManifestFlags(
  703. self, config, name, gyp_to_build_path, allow_isolation, build_dir
  704. ):
  705. """Returns a 3-tuple:
  706. - the set of flags that need to be added to the link to generate
  707. a default manifest
  708. - the intermediate manifest that the linker will generate that should be
  709. used to assert it doesn't add anything to the merged one.
  710. - the list of all the manifest files to be merged by the manifest tool and
  711. included into the link."""
  712. generate_manifest = self._Setting(
  713. ("VCLinkerTool", "GenerateManifest"), config, default="true"
  714. )
  715. if generate_manifest != "true":
  716. # This means not only that the linker should not generate the intermediate
  717. # manifest but also that the manifest tool should do nothing even when
  718. # additional manifests are specified.
  719. return ["/MANIFEST:NO"], [], []
  720. output_name = name + ".intermediate.manifest"
  721. flags = [
  722. "/MANIFEST",
  723. "/ManifestFile:" + output_name,
  724. ]
  725. # Instead of using the MANIFESTUAC flags, we generate a .manifest to
  726. # include into the list of manifests. This allows us to avoid the need to
  727. # do two passes during linking. The /MANIFEST flag and /ManifestFile are
  728. # still used, and the intermediate manifest is used to assert that the
  729. # final manifest we get from merging all the additional manifest files
  730. # (plus the one we generate here) isn't modified by merging the
  731. # intermediate into it.
  732. # Always NO, because we generate a manifest file that has what we want.
  733. flags.append("/MANIFESTUAC:NO")
  734. config = self._TargetConfig(config)
  735. enable_uac = self._Setting(
  736. ("VCLinkerTool", "EnableUAC"), config, default="true"
  737. )
  738. manifest_files = []
  739. generated_manifest_outer = (
  740. "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"
  741. "<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>"
  742. "%s</assembly>"
  743. )
  744. if enable_uac == "true":
  745. execution_level = self._Setting(
  746. ("VCLinkerTool", "UACExecutionLevel"), config, default="0"
  747. )
  748. execution_level_map = {
  749. "0": "asInvoker",
  750. "1": "highestAvailable",
  751. "2": "requireAdministrator",
  752. }
  753. ui_access = self._Setting(
  754. ("VCLinkerTool", "UACUIAccess"), config, default="false"
  755. )
  756. inner = """
  757. <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  758. <security>
  759. <requestedPrivileges>
  760. <requestedExecutionLevel level='{}' uiAccess='{}' />
  761. </requestedPrivileges>
  762. </security>
  763. </trustInfo>""".format(
  764. execution_level_map[execution_level],
  765. ui_access,
  766. )
  767. else:
  768. inner = ""
  769. generated_manifest_contents = generated_manifest_outer % inner
  770. generated_name = name + ".generated.manifest"
  771. # Need to join with the build_dir here as we're writing it during
  772. # generation time, but we return the un-joined version because the build
  773. # will occur in that directory. We only write the file if the contents
  774. # have changed so that simply regenerating the project files doesn't
  775. # cause a relink.
  776. build_dir_generated_name = os.path.join(build_dir, generated_name)
  777. gyp.common.EnsureDirExists(build_dir_generated_name)
  778. f = gyp.common.WriteOnDiff(build_dir_generated_name)
  779. f.write(generated_manifest_contents)
  780. f.close()
  781. manifest_files = [generated_name]
  782. if allow_isolation:
  783. flags.append("/ALLOWISOLATION")
  784. manifest_files += self._GetAdditionalManifestFiles(config, gyp_to_build_path)
  785. return flags, output_name, manifest_files
  786. def _GetAdditionalManifestFiles(self, config, gyp_to_build_path):
  787. """Gets additional manifest files that are added to the default one
  788. generated by the linker."""
  789. files = self._Setting(
  790. ("VCManifestTool", "AdditionalManifestFiles"), config, default=[]
  791. )
  792. if isinstance(files, str):
  793. files = files.split(";")
  794. return [
  795. os.path.normpath(gyp_to_build_path(self.ConvertVSMacros(f, config=config)))
  796. for f in files
  797. ]
  798. def IsUseLibraryDependencyInputs(self, config):
  799. """Returns whether the target should be linked via Use Library Dependency
  800. Inputs (using component .objs of a given .lib)."""
  801. config = self._TargetConfig(config)
  802. uldi = self._Setting(("VCLinkerTool", "UseLibraryDependencyInputs"), config)
  803. return uldi == "true"
  804. def IsEmbedManifest(self, config):
  805. """Returns whether manifest should be linked into binary."""
  806. config = self._TargetConfig(config)
  807. embed = self._Setting(
  808. ("VCManifestTool", "EmbedManifest"), config, default="true"
  809. )
  810. return embed == "true"
  811. def IsLinkIncremental(self, config):
  812. """Returns whether the target should be linked incrementally."""
  813. config = self._TargetConfig(config)
  814. link_inc = self._Setting(("VCLinkerTool", "LinkIncremental"), config)
  815. return link_inc != "1"
  816. def GetRcflags(self, config, gyp_to_ninja_path):
  817. """Returns the flags that need to be added to invocations of the resource
  818. compiler."""
  819. config = self._TargetConfig(config)
  820. rcflags = []
  821. rc = self._GetWrapper(
  822. self, self.msvs_settings[config], "VCResourceCompilerTool", append=rcflags
  823. )
  824. rc("AdditionalIncludeDirectories", map=gyp_to_ninja_path, prefix="/I")
  825. rcflags.append("/I" + gyp_to_ninja_path("."))
  826. rc("PreprocessorDefinitions", prefix="/d")
  827. # /l arg must be in hex without leading '0x'
  828. rc("Culture", prefix="/l", map=lambda x: hex(int(x))[2:])
  829. return rcflags
  830. def BuildCygwinBashCommandLine(self, args, path_to_base):
  831. """Build a command line that runs args via cygwin bash. We assume that all
  832. incoming paths are in Windows normpath'd form, so they need to be
  833. converted to posix style for the part of the command line that's passed to
  834. bash. We also have to do some Visual Studio macro emulation here because
  835. various rules use magic VS names for things. Also note that rules that
  836. contain ninja variables cannot be fixed here (for example ${source}), so
  837. the outer generator needs to make sure that the paths that are written out
  838. are in posix style, if the command line will be used here."""
  839. cygwin_dir = os.path.normpath(
  840. os.path.join(path_to_base, self.msvs_cygwin_dirs[0])
  841. )
  842. cd = ("cd %s" % path_to_base).replace("\\", "/")
  843. args = [a.replace("\\", "/").replace('"', '\\"') for a in args]
  844. args = ["'%s'" % a.replace("'", "'\\''") for a in args]
  845. bash_cmd = " ".join(args)
  846. cmd = (
  847. 'call "%s\\setup_env.bat" && set CYGWIN=nontsec && ' % cygwin_dir
  848. + f'bash -c "{cd} ; {bash_cmd}"'
  849. )
  850. return cmd
  851. RuleShellFlags = collections.namedtuple("RuleShellFlags", ["cygwin", "quote"])
  852. def GetRuleShellFlags(self, rule):
  853. """Return RuleShellFlags about how the given rule should be run. This
  854. includes whether it should run under cygwin (msvs_cygwin_shell), and
  855. whether the commands should be quoted (msvs_quote_cmd)."""
  856. # If the variable is unset, or set to 1 we use cygwin
  857. cygwin = int(rule.get("msvs_cygwin_shell",
  858. self.spec.get("msvs_cygwin_shell", 1))) != 0
  859. # Default to quoting. There's only a few special instances where the
  860. # target command uses non-standard command line parsing and handle quotes
  861. # and quote escaping differently.
  862. quote_cmd = int(rule.get("msvs_quote_cmd", 1))
  863. assert quote_cmd != 0 or cygwin != 1, \
  864. "msvs_quote_cmd=0 only applicable for msvs_cygwin_shell=0"
  865. return MsvsSettings.RuleShellFlags(cygwin, quote_cmd)
  866. def _HasExplicitRuleForExtension(self, spec, extension):
  867. """Determine if there's an explicit rule for a particular extension."""
  868. for rule in spec.get("rules", []):
  869. if rule["extension"] == extension:
  870. return True
  871. return False
  872. def _HasExplicitIdlActions(self, spec):
  873. """Determine if an action should not run midl for .idl files."""
  874. return any(
  875. [action.get("explicit_idl_action", 0) for action in spec.get("actions", [])]
  876. )
  877. def HasExplicitIdlRulesOrActions(self, spec):
  878. """Determine if there's an explicit rule or action for idl files. When
  879. there isn't we need to generate implicit rules to build MIDL .idl files."""
  880. return self._HasExplicitRuleForExtension(
  881. spec, "idl"
  882. ) or self._HasExplicitIdlActions(spec)
  883. def HasExplicitAsmRules(self, spec):
  884. """Determine if there's an explicit rule for asm files. When there isn't we
  885. need to generate implicit rules to assemble .asm files."""
  886. return self._HasExplicitRuleForExtension(spec, "asm")
  887. def GetIdlBuildData(self, source, config):
  888. """Determine the implicit outputs for an idl file. Returns output
  889. directory, outputs, and variables and flags that are required."""
  890. config = self._TargetConfig(config)
  891. midl_get = self._GetWrapper(self, self.msvs_settings[config], "VCMIDLTool")
  892. def midl(name, default=None):
  893. return self.ConvertVSMacros(midl_get(name, default=default), config=config)
  894. tlb = midl("TypeLibraryName", default="${root}.tlb")
  895. header = midl("HeaderFileName", default="${root}.h")
  896. dlldata = midl("DLLDataFileName", default="dlldata.c")
  897. iid = midl("InterfaceIdentifierFileName", default="${root}_i.c")
  898. proxy = midl("ProxyFileName", default="${root}_p.c")
  899. # Note that .tlb is not included in the outputs as it is not always
  900. # generated depending on the content of the input idl file.
  901. outdir = midl("OutputDirectory", default="")
  902. output = [header, dlldata, iid, proxy]
  903. variables = [
  904. ("tlb", tlb),
  905. ("h", header),
  906. ("dlldata", dlldata),
  907. ("iid", iid),
  908. ("proxy", proxy),
  909. ]
  910. # TODO(scottmg): Are there configuration settings to set these flags?
  911. target_platform = self.GetArch(config)
  912. if target_platform == "x86":
  913. target_platform = "win32"
  914. flags = ["/char", "signed", "/env", target_platform, "/Oicf"]
  915. return outdir, output, variables, flags
  916. def _LanguageMatchesForPch(source_ext, pch_source_ext):
  917. c_exts = (".c",)
  918. cc_exts = (".cc", ".cxx", ".cpp")
  919. return (source_ext in c_exts and pch_source_ext in c_exts) or (
  920. source_ext in cc_exts and pch_source_ext in cc_exts
  921. )
  922. class PrecompiledHeader:
  923. """Helper to generate dependencies and build rules to handle generation of
  924. precompiled headers. Interface matches the GCH handler in xcode_emulation.py.
  925. """
  926. def __init__(
  927. self, settings, config, gyp_to_build_path, gyp_to_unique_output, obj_ext
  928. ):
  929. self.settings = settings
  930. self.config = config
  931. pch_source = self.settings.msvs_precompiled_source[self.config]
  932. self.pch_source = gyp_to_build_path(pch_source)
  933. filename, _ = os.path.splitext(pch_source)
  934. self.output_obj = gyp_to_unique_output(filename + obj_ext).lower()
  935. def _PchHeader(self):
  936. """Get the header that will appear in an #include line for all source
  937. files."""
  938. return self.settings.msvs_precompiled_header[self.config]
  939. def GetObjDependencies(self, sources, objs, arch):
  940. """Given a list of sources files and the corresponding object files,
  941. returns a list of the pch files that should be depended upon. The
  942. additional wrapping in the return value is for interface compatibility
  943. with make.py on Mac, and xcode_emulation.py."""
  944. assert arch is None
  945. if not self._PchHeader():
  946. return []
  947. pch_ext = os.path.splitext(self.pch_source)[1]
  948. for source in sources:
  949. if _LanguageMatchesForPch(os.path.splitext(source)[1], pch_ext):
  950. return [(None, None, self.output_obj)]
  951. return []
  952. def GetPchBuildCommands(self, arch):
  953. """Not used on Windows as there are no additional build steps required
  954. (instead, existing steps are modified in GetFlagsModifications below)."""
  955. return []
  956. def GetFlagsModifications(
  957. self, input, output, implicit, command, cflags_c, cflags_cc, expand_special
  958. ):
  959. """Get the modified cflags and implicit dependencies that should be used
  960. for the pch compilation step."""
  961. if input == self.pch_source:
  962. pch_output = ["/Yc" + self._PchHeader()]
  963. if command == "cxx":
  964. return (
  965. [("cflags_cc", map(expand_special, cflags_cc + pch_output))],
  966. self.output_obj,
  967. [],
  968. )
  969. elif command == "cc":
  970. return (
  971. [("cflags_c", map(expand_special, cflags_c + pch_output))],
  972. self.output_obj,
  973. [],
  974. )
  975. return [], output, implicit
  976. vs_version = None
  977. def GetVSVersion(generator_flags):
  978. global vs_version
  979. if not vs_version:
  980. vs_version = gyp.MSVSVersion.SelectVisualStudioVersion(
  981. generator_flags.get("msvs_version", "auto"), allow_fallback=False
  982. )
  983. return vs_version
  984. def _GetVsvarsSetupArgs(generator_flags, arch):
  985. vs = GetVSVersion(generator_flags)
  986. return vs.SetupScript()
  987. def ExpandMacros(string, expansions):
  988. """Expand $(Variable) per expansions dict. See MsvsSettings.GetVSMacroEnv
  989. for the canonical way to retrieve a suitable dict."""
  990. if "$" in string:
  991. for old, new in expansions.items():
  992. assert "$(" not in new, new
  993. string = string.replace(old, new)
  994. return string
  995. def _ExtractImportantEnvironment(output_of_set):
  996. """Extracts environment variables required for the toolchain to run from
  997. a textual dump output by the cmd.exe 'set' command."""
  998. envvars_to_save = (
  999. "goma_.*", # TODO(scottmg): This is ugly, but needed for goma.
  1000. "include",
  1001. "lib",
  1002. "libpath",
  1003. "path",
  1004. "pathext",
  1005. "systemroot",
  1006. "temp",
  1007. "tmp",
  1008. )
  1009. env = {}
  1010. # This occasionally happens and leads to misleading SYSTEMROOT error messages
  1011. # if not caught here.
  1012. if output_of_set.count("=") == 0:
  1013. raise Exception("Invalid output_of_set. Value is:\n%s" % output_of_set)
  1014. for line in output_of_set.splitlines():
  1015. for envvar in envvars_to_save:
  1016. if re.match(envvar + "=", line.lower()):
  1017. var, setting = line.split("=", 1)
  1018. if envvar == "path":
  1019. # Our own rules (for running gyp-win-tool) and other actions in
  1020. # Chromium rely on python being in the path. Add the path to this
  1021. # python here so that if it's not in the path when ninja is run
  1022. # later, python will still be found.
  1023. setting = os.path.dirname(sys.executable) + os.pathsep + setting
  1024. env[var.upper()] = setting
  1025. break
  1026. for required in ("SYSTEMROOT", "TEMP", "TMP"):
  1027. if required not in env:
  1028. raise Exception(
  1029. 'Environment variable "%s" '
  1030. "required to be set to valid path" % required
  1031. )
  1032. return env
  1033. def _FormatAsEnvironmentBlock(envvar_dict):
  1034. """Format as an 'environment block' directly suitable for CreateProcess.
  1035. Briefly this is a list of key=value\0, terminated by an additional \0. See
  1036. CreateProcess documentation for more details."""
  1037. block = ""
  1038. nul = "\0"
  1039. for key, value in envvar_dict.items():
  1040. block += key + "=" + value + nul
  1041. block += nul
  1042. return block
  1043. def _ExtractCLPath(output_of_where):
  1044. """Gets the path to cl.exe based on the output of calling the environment
  1045. setup batch file, followed by the equivalent of `where`."""
  1046. # Take the first line, as that's the first found in the PATH.
  1047. for line in output_of_where.strip().splitlines():
  1048. if line.startswith("LOC:"):
  1049. return line[len("LOC:") :].strip()
  1050. def GenerateEnvironmentFiles(
  1051. toplevel_build_dir, generator_flags, system_includes, open_out
  1052. ):
  1053. """It's not sufficient to have the absolute path to the compiler, linker,
  1054. etc. on Windows, as those tools rely on .dlls being in the PATH. We also
  1055. need to support both x86 and x64 compilers within the same build (to support
  1056. msvs_target_platform hackery). Different architectures require a different
  1057. compiler binary, and different supporting environment variables (INCLUDE,
  1058. LIB, LIBPATH). So, we extract the environment here, wrap all invocations
  1059. of compiler tools (cl, link, lib, rc, midl, etc.) via win_tool.py which
  1060. sets up the environment, and then we do not prefix the compiler with
  1061. an absolute path, instead preferring something like "cl.exe" in the rule
  1062. which will then run whichever the environment setup has put in the path.
  1063. When the following procedure to generate environment files does not
  1064. meet your requirement (e.g. for custom toolchains), you can pass
  1065. "-G ninja_use_custom_environment_files" to the gyp to suppress file
  1066. generation and use custom environment files prepared by yourself."""
  1067. archs = ("x86", "x64")
  1068. if generator_flags.get("ninja_use_custom_environment_files", 0):
  1069. cl_paths = {}
  1070. for arch in archs:
  1071. cl_paths[arch] = "cl.exe"
  1072. return cl_paths
  1073. vs = GetVSVersion(generator_flags)
  1074. cl_paths = {}
  1075. for arch in archs:
  1076. # Extract environment variables for subprocesses.
  1077. args = vs.SetupScript(arch)
  1078. args.extend(("&&", "set"))
  1079. popen = subprocess.Popen(
  1080. args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
  1081. )
  1082. variables = popen.communicate()[0].decode("utf-8")
  1083. if popen.returncode != 0:
  1084. raise Exception('"%s" failed with error %d' % (args, popen.returncode))
  1085. env = _ExtractImportantEnvironment(variables)
  1086. # Inject system includes from gyp files into INCLUDE.
  1087. if system_includes:
  1088. system_includes = system_includes | OrderedSet(
  1089. env.get("INCLUDE", "").split(";")
  1090. )
  1091. env["INCLUDE"] = ";".join(system_includes)
  1092. env_block = _FormatAsEnvironmentBlock(env)
  1093. f = open_out(os.path.join(toplevel_build_dir, "environment." + arch), "w")
  1094. f.write(env_block)
  1095. f.close()
  1096. # Find cl.exe location for this architecture.
  1097. args = vs.SetupScript(arch)
  1098. args.extend(
  1099. ("&&", "for", "%i", "in", "(cl.exe)", "do", "@echo", "LOC:%~$PATH:i")
  1100. )
  1101. popen = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
  1102. output = popen.communicate()[0].decode("utf-8")
  1103. cl_paths[arch] = _ExtractCLPath(output)
  1104. return cl_paths
  1105. def VerifyMissingSources(sources, build_dir, generator_flags, gyp_to_ninja):
  1106. """Emulate behavior of msvs_error_on_missing_sources present in the msvs
  1107. generator: Check that all regular source files, i.e. not created at run time,
  1108. exist on disk. Missing files cause needless recompilation when building via
  1109. VS, and we want this check to match for people/bots that build using ninja,
  1110. so they're not surprised when the VS build fails."""
  1111. if int(generator_flags.get("msvs_error_on_missing_sources", 0)):
  1112. no_specials = filter(lambda x: "$" not in x, sources)
  1113. relative = [os.path.join(build_dir, gyp_to_ninja(s)) for s in no_specials]
  1114. missing = [x for x in relative if not os.path.exists(x)]
  1115. if missing:
  1116. # They'll look like out\Release\..\..\stuff\things.cc, so normalize the
  1117. # path for a slightly less crazy looking output.
  1118. cleaned_up = [os.path.normpath(x) for x in missing]
  1119. raise Exception("Missing input files:\n%s" % "\n".join(cleaned_up))
  1120. # Sets some values in default_variables, which are required for many
  1121. # generators, run on Windows.
  1122. def CalculateCommonVariables(default_variables, params):
  1123. generator_flags = params.get("generator_flags", {})
  1124. # Set a variable so conditions can be based on msvs_version.
  1125. msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags)
  1126. default_variables["MSVS_VERSION"] = msvs_version.ShortName()
  1127. # To determine processor word size on Windows, in addition to checking
  1128. # PROCESSOR_ARCHITECTURE (which reflects the word size of the current
  1129. # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which
  1130. # contains the actual word size of the system when running thru WOW64).
  1131. if "64" in os.environ.get("PROCESSOR_ARCHITECTURE", "") or "64" in os.environ.get(
  1132. "PROCESSOR_ARCHITEW6432", ""
  1133. ):
  1134. default_variables["MSVS_OS_BITS"] = 64
  1135. else:
  1136. default_variables["MSVS_OS_BITS"] = 32