MSVSVersion.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. # Copyright (c) 2013 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. """Handle version information related to Visual Stuio."""
  5. import errno
  6. import os
  7. import re
  8. import subprocess
  9. import sys
  10. import gyp
  11. import glob
  12. class VisualStudioVersion(object):
  13. """Information regarding a version of Visual Studio."""
  14. def __init__(self, short_name, description,
  15. solution_version, project_version, flat_sln, uses_vcxproj,
  16. path, sdk_based, default_toolset=None):
  17. self.short_name = short_name
  18. self.description = description
  19. self.solution_version = solution_version
  20. self.project_version = project_version
  21. self.flat_sln = flat_sln
  22. self.uses_vcxproj = uses_vcxproj
  23. self.path = path
  24. self.sdk_based = sdk_based
  25. self.default_toolset = default_toolset
  26. def ShortName(self):
  27. return self.short_name
  28. def Description(self):
  29. """Get the full description of the version."""
  30. return self.description
  31. def SolutionVersion(self):
  32. """Get the version number of the sln files."""
  33. return self.solution_version
  34. def ProjectVersion(self):
  35. """Get the version number of the vcproj or vcxproj files."""
  36. return self.project_version
  37. def FlatSolution(self):
  38. return self.flat_sln
  39. def UsesVcxproj(self):
  40. """Returns true if this version uses a vcxproj file."""
  41. return self.uses_vcxproj
  42. def ProjectExtension(self):
  43. """Returns the file extension for the project."""
  44. return self.uses_vcxproj and '.vcxproj' or '.vcproj'
  45. def Path(self):
  46. """Returns the path to Visual Studio installation."""
  47. return self.path
  48. def ToolPath(self, tool):
  49. """Returns the path to a given compiler tool. """
  50. return os.path.normpath(os.path.join(self.path, "VC/bin", tool))
  51. def DefaultToolset(self):
  52. """Returns the msbuild toolset version that will be used in the absence
  53. of a user override."""
  54. return self.default_toolset
  55. def SetupScript(self, target_arch):
  56. """Returns a command (with arguments) to be used to set up the
  57. environment."""
  58. # Check if we are running in the SDK command line environment and use
  59. # the setup script from the SDK if so. |target_arch| should be either
  60. # 'x86' or 'x64'.
  61. assert target_arch in ('x86', 'x64')
  62. sdk_dir = os.environ.get('WindowsSDKDir')
  63. if self.sdk_based and sdk_dir:
  64. return [os.path.normpath(os.path.join(sdk_dir, 'Bin/SetEnv.Cmd')),
  65. '/' + target_arch]
  66. else:
  67. # We don't use VC/vcvarsall.bat for x86 because vcvarsall calls
  68. # vcvars32, which it can only find if VS??COMNTOOLS is set, which it
  69. # isn't always.
  70. if target_arch == 'x86':
  71. if self.short_name >= '2013' and self.short_name[-1] != 'e' and (
  72. os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64' or
  73. os.environ.get('PROCESSOR_ARCHITEW6432') == 'AMD64'):
  74. # VS2013 and later, non-Express have a x64-x86 cross that we want
  75. # to prefer.
  76. return [os.path.normpath(
  77. os.path.join(self.path, 'VC/vcvarsall.bat')), 'amd64_x86']
  78. # Otherwise, the standard x86 compiler.
  79. return [os.path.normpath(
  80. os.path.join(self.path, 'Common7/Tools/vsvars32.bat'))]
  81. else:
  82. assert target_arch == 'x64'
  83. arg = 'x86_amd64'
  84. # Use the 64-on-64 compiler if we're not using an express
  85. # edition and we're running on a 64bit OS.
  86. if self.short_name[-1] != 'e' and (
  87. os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64' or
  88. os.environ.get('PROCESSOR_ARCHITEW6432') == 'AMD64'):
  89. arg = 'amd64'
  90. return [os.path.normpath(
  91. os.path.join(self.path, 'VC/vcvarsall.bat')), arg]
  92. def _RegistryQueryBase(sysdir, key, value):
  93. """Use reg.exe to read a particular key.
  94. While ideally we might use the win32 module, we would like gyp to be
  95. python neutral, so for instance cygwin python lacks this module.
  96. Arguments:
  97. sysdir: The system subdirectory to attempt to launch reg.exe from.
  98. key: The registry key to read from.
  99. value: The particular value to read.
  100. Return:
  101. stdout from reg.exe, or None for failure.
  102. """
  103. # Skip if not on Windows or Python Win32 setup issue
  104. if sys.platform not in ('win32', 'cygwin'):
  105. return None
  106. # Setup params to pass to and attempt to launch reg.exe
  107. cmd = [os.path.join(os.environ.get('WINDIR', ''), sysdir, 'reg.exe'),
  108. 'query', key]
  109. if value:
  110. cmd.extend(['/v', value])
  111. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  112. # Obtain the stdout from reg.exe, reading to the end so p.returncode is valid
  113. # Note that the error text may be in [1] in some cases
  114. text = p.communicate()[0]
  115. # Check return code from reg.exe; officially 0==success and 1==error
  116. if p.returncode:
  117. return None
  118. return text
  119. def _RegistryQuery(key, value=None):
  120. r"""Use reg.exe to read a particular key through _RegistryQueryBase.
  121. First tries to launch from %WinDir%\Sysnative to avoid WoW64 redirection. If
  122. that fails, it falls back to System32. Sysnative is available on Vista and
  123. up and available on Windows Server 2003 and XP through KB patch 942589. Note
  124. that Sysnative will always fail if using 64-bit python due to it being a
  125. virtual directory and System32 will work correctly in the first place.
  126. KB 942589 - http://support.microsoft.com/kb/942589/en-us.
  127. Arguments:
  128. key: The registry key.
  129. value: The particular registry value to read (optional).
  130. Return:
  131. stdout from reg.exe, or None for failure.
  132. """
  133. text = None
  134. try:
  135. text = _RegistryQueryBase('Sysnative', key, value)
  136. except OSError, e:
  137. if e.errno == errno.ENOENT:
  138. text = _RegistryQueryBase('System32', key, value)
  139. else:
  140. raise
  141. return text
  142. def _RegistryGetValueUsingWinReg(key, value):
  143. """Use the _winreg module to obtain the value of a registry key.
  144. Args:
  145. key: The registry key.
  146. value: The particular registry value to read.
  147. Return:
  148. contents of the registry key's value, or None on failure. Throws
  149. ImportError if _winreg is unavailable.
  150. """
  151. import _winreg
  152. try:
  153. root, subkey = key.split('\\', 1)
  154. assert root == 'HKLM' # Only need HKLM for now.
  155. with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) as hkey:
  156. return _winreg.QueryValueEx(hkey, value)[0]
  157. except WindowsError:
  158. return None
  159. def _RegistryGetValue(key, value):
  160. """Use _winreg or reg.exe to obtain the value of a registry key.
  161. Using _winreg is preferable because it solves an issue on some corporate
  162. environments where access to reg.exe is locked down. However, we still need
  163. to fallback to reg.exe for the case where the _winreg module is not available
  164. (for example in cygwin python).
  165. Args:
  166. key: The registry key.
  167. value: The particular registry value to read.
  168. Return:
  169. contents of the registry key's value, or None on failure.
  170. """
  171. try:
  172. return _RegistryGetValueUsingWinReg(key, value)
  173. except ImportError:
  174. pass
  175. # Fallback to reg.exe if we fail to import _winreg.
  176. text = _RegistryQuery(key, value)
  177. if not text:
  178. return None
  179. # Extract value.
  180. match = re.search(r'REG_\w+\s+([^\r]+)\r\n', text)
  181. if not match:
  182. return None
  183. return match.group(1)
  184. def _CreateVersion(name, path, sdk_based=False):
  185. """Sets up MSVS project generation.
  186. Setup is based off the GYP_MSVS_VERSION environment variable or whatever is
  187. autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is
  188. passed in that doesn't match a value in versions python will throw a error.
  189. """
  190. if path:
  191. path = os.path.normpath(path)
  192. versions = {
  193. '2015': VisualStudioVersion('2015',
  194. 'Visual Studio 2015',
  195. solution_version='12.00',
  196. project_version='14.0',
  197. flat_sln=False,
  198. uses_vcxproj=True,
  199. path=path,
  200. sdk_based=sdk_based,
  201. default_toolset='v140'),
  202. '2013': VisualStudioVersion('2013',
  203. 'Visual Studio 2013',
  204. solution_version='13.00',
  205. project_version='12.0',
  206. flat_sln=False,
  207. uses_vcxproj=True,
  208. path=path,
  209. sdk_based=sdk_based,
  210. default_toolset='v120'),
  211. '2013e': VisualStudioVersion('2013e',
  212. 'Visual Studio 2013',
  213. solution_version='13.00',
  214. project_version='12.0',
  215. flat_sln=True,
  216. uses_vcxproj=True,
  217. path=path,
  218. sdk_based=sdk_based,
  219. default_toolset='v120'),
  220. '2012': VisualStudioVersion('2012',
  221. 'Visual Studio 2012',
  222. solution_version='12.00',
  223. project_version='4.0',
  224. flat_sln=False,
  225. uses_vcxproj=True,
  226. path=path,
  227. sdk_based=sdk_based,
  228. default_toolset='v110'),
  229. '2012e': VisualStudioVersion('2012e',
  230. 'Visual Studio 2012',
  231. solution_version='12.00',
  232. project_version='4.0',
  233. flat_sln=True,
  234. uses_vcxproj=True,
  235. path=path,
  236. sdk_based=sdk_based,
  237. default_toolset='v110'),
  238. '2010': VisualStudioVersion('2010',
  239. 'Visual Studio 2010',
  240. solution_version='11.00',
  241. project_version='4.0',
  242. flat_sln=False,
  243. uses_vcxproj=True,
  244. path=path,
  245. sdk_based=sdk_based),
  246. '2010e': VisualStudioVersion('2010e',
  247. 'Visual C++ Express 2010',
  248. solution_version='11.00',
  249. project_version='4.0',
  250. flat_sln=True,
  251. uses_vcxproj=True,
  252. path=path,
  253. sdk_based=sdk_based),
  254. '2008': VisualStudioVersion('2008',
  255. 'Visual Studio 2008',
  256. solution_version='10.00',
  257. project_version='9.00',
  258. flat_sln=False,
  259. uses_vcxproj=False,
  260. path=path,
  261. sdk_based=sdk_based),
  262. '2008e': VisualStudioVersion('2008e',
  263. 'Visual Studio 2008',
  264. solution_version='10.00',
  265. project_version='9.00',
  266. flat_sln=True,
  267. uses_vcxproj=False,
  268. path=path,
  269. sdk_based=sdk_based),
  270. '2005': VisualStudioVersion('2005',
  271. 'Visual Studio 2005',
  272. solution_version='9.00',
  273. project_version='8.00',
  274. flat_sln=False,
  275. uses_vcxproj=False,
  276. path=path,
  277. sdk_based=sdk_based),
  278. '2005e': VisualStudioVersion('2005e',
  279. 'Visual Studio 2005',
  280. solution_version='9.00',
  281. project_version='8.00',
  282. flat_sln=True,
  283. uses_vcxproj=False,
  284. path=path,
  285. sdk_based=sdk_based),
  286. }
  287. return versions[str(name)]
  288. def _ConvertToCygpath(path):
  289. """Convert to cygwin path if we are using cygwin."""
  290. if sys.platform == 'cygwin':
  291. p = subprocess.Popen(['cygpath', path], stdout=subprocess.PIPE)
  292. path = p.communicate()[0].strip()
  293. return path
  294. def _DetectVisualStudioVersions(versions_to_check, force_express):
  295. """Collect the list of installed visual studio versions.
  296. Returns:
  297. A list of visual studio versions installed in descending order of
  298. usage preference.
  299. Base this on the registry and a quick check if devenv.exe exists.
  300. Only versions 8-10 are considered.
  301. Possibilities are:
  302. 2005(e) - Visual Studio 2005 (8)
  303. 2008(e) - Visual Studio 2008 (9)
  304. 2010(e) - Visual Studio 2010 (10)
  305. 2012(e) - Visual Studio 2012 (11)
  306. 2013(e) - Visual Studio 2013 (12)
  307. 2015 - Visual Studio 2015 (14)
  308. Where (e) is e for express editions of MSVS and blank otherwise.
  309. """
  310. version_to_year = {
  311. '8.0': '2005',
  312. '9.0': '2008',
  313. '10.0': '2010',
  314. '11.0': '2012',
  315. '12.0': '2013',
  316. '14.0': '2015',
  317. }
  318. versions = []
  319. for version in versions_to_check:
  320. # Old method of searching for which VS version is installed
  321. # We don't use the 2010-encouraged-way because we also want to get the
  322. # path to the binaries, which it doesn't offer.
  323. keys = [r'HKLM\Software\Microsoft\VisualStudio\%s' % version,
  324. r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s' % version,
  325. r'HKLM\Software\Microsoft\VCExpress\%s' % version,
  326. r'HKLM\Software\Wow6432Node\Microsoft\VCExpress\%s' % version]
  327. for index in range(len(keys)):
  328. path = _RegistryGetValue(keys[index], 'InstallDir')
  329. if not path:
  330. continue
  331. path = _ConvertToCygpath(path)
  332. # Check for full.
  333. full_path = os.path.join(path, 'devenv.exe')
  334. express_path = os.path.join(path, '*express.exe')
  335. if not force_express and os.path.exists(full_path):
  336. # Add this one.
  337. versions.append(_CreateVersion(version_to_year[version],
  338. os.path.join(path, '..', '..')))
  339. # Check for express.
  340. elif glob.glob(express_path):
  341. # Add this one.
  342. versions.append(_CreateVersion(version_to_year[version] + 'e',
  343. os.path.join(path, '..', '..')))
  344. # The old method above does not work when only SDK is installed.
  345. keys = [r'HKLM\Software\Microsoft\VisualStudio\SxS\VC7',
  346. r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\SxS\VC7']
  347. for index in range(len(keys)):
  348. path = _RegistryGetValue(keys[index], version)
  349. if not path:
  350. continue
  351. path = _ConvertToCygpath(path)
  352. if version != '14.0': # There is no Express edition for 2015.
  353. versions.append(_CreateVersion(version_to_year[version] + 'e',
  354. os.path.join(path, '..'), sdk_based=True))
  355. return versions
  356. def SelectVisualStudioVersion(version='auto', allow_fallback=True):
  357. """Select which version of Visual Studio projects to generate.
  358. Arguments:
  359. version: Hook to allow caller to force a particular version (vs auto).
  360. Returns:
  361. An object representing a visual studio project format version.
  362. """
  363. # In auto mode, check environment variable for override.
  364. if version == 'auto':
  365. version = os.environ.get('GYP_MSVS_VERSION', 'auto')
  366. version_map = {
  367. 'auto': ('14.0', '12.0', '10.0', '9.0', '8.0', '11.0'),
  368. '2005': ('8.0',),
  369. '2005e': ('8.0',),
  370. '2008': ('9.0',),
  371. '2008e': ('9.0',),
  372. '2010': ('10.0',),
  373. '2010e': ('10.0',),
  374. '2012': ('11.0',),
  375. '2012e': ('11.0',),
  376. '2013': ('12.0',),
  377. '2013e': ('12.0',),
  378. '2015': ('14.0',),
  379. }
  380. override_path = os.environ.get('GYP_MSVS_OVERRIDE_PATH')
  381. if override_path:
  382. msvs_version = os.environ.get('GYP_MSVS_VERSION')
  383. if not msvs_version:
  384. raise ValueError('GYP_MSVS_OVERRIDE_PATH requires GYP_MSVS_VERSION to be '
  385. 'set to a particular version (e.g. 2010e).')
  386. return _CreateVersion(msvs_version, override_path, sdk_based=True)
  387. version = str(version)
  388. versions = _DetectVisualStudioVersions(version_map[version], 'e' in version)
  389. if not versions:
  390. if not allow_fallback:
  391. raise ValueError('Could not locate Visual Studio installation.')
  392. if version == 'auto':
  393. # Default to 2005 if we couldn't find anything
  394. return _CreateVersion('2005', None)
  395. else:
  396. return _CreateVersion(version, None)
  397. return versions[0]