PageRenderTime 28ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/front/node_modules/node-gyp/gyp/pylib/gyp/msvs_emulation.py

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