e79b224b50941b20de977b8ca33bedc73c0f28d8a00742ea04987d533993084887816b49cdf99c462e3741effbb6ebc4b109fd2b97d196cd243df0811a9d3d 53 KB

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