23fd97d6cb9f50a621252b6528194da731f244ff85333eb820fa66c79ea51eeba8afba32cd0a801185b5380164dfdb17eb5b20e2e105dfad96a36d7bcaaef2 19 KB

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