vs_toolchain.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. #!/usr/bin/env python
  2. # Copyright 2014 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. from __future__ import print_function
  6. import collections
  7. import glob
  8. import json
  9. import os
  10. import pipes
  11. import platform
  12. import re
  13. import shutil
  14. import stat
  15. import subprocess
  16. import sys
  17. from gn_helpers import ToGNString
  18. # VS 2019 16.61 with 10.0.20348.0 SDK, 10.0.19041 version of Debuggers
  19. # with ARM64 libraries and UWP support.
  20. # See go/chromium-msvc-toolchain for instructions about how to update the
  21. # toolchain.
  22. #
  23. # When updating the toolchain, consider the following areas impacted by the
  24. # toolchain version:
  25. #
  26. # * //base/win/windows_version.cc NTDDI preprocessor check
  27. # Triggers a compiler error if the available SDK is older than the minimum.
  28. # * //build/config/win/BUILD.gn NTDDI_VERSION value
  29. # Affects the availability of APIs in the toolchain headers.
  30. # * //docs/windows_build_instructions.md mentions of VS or Windows SDK.
  31. # Keeps the document consistent with the toolchain version.
  32. TOOLCHAIN_HASH = '1023ce2e82'
  33. script_dir = os.path.dirname(os.path.realpath(__file__))
  34. json_data_file = os.path.join(script_dir, 'win_toolchain.json')
  35. # VS versions are listed in descending order of priority (highest first).
  36. # The first version is assumed by this script to be the one that is packaged,
  37. # which makes a difference for the arm64 runtime.
  38. MSVS_VERSIONS = collections.OrderedDict([
  39. ('2019', '16.0'), # Default and packaged version of Visual Studio.
  40. ('2022', '17.0'),
  41. ('2017', '15.0'),
  42. ])
  43. # List of preferred VC toolset version based on MSVS
  44. # Order is not relevant for this dictionary.
  45. MSVC_TOOLSET_VERSION = {
  46. '2022': 'VC143',
  47. '2019': 'VC142',
  48. '2017': 'VC141',
  49. }
  50. def _HostIsWindows():
  51. """Returns True if running on a Windows host (including under cygwin)."""
  52. return sys.platform in ('win32', 'cygwin')
  53. def SetEnvironmentAndGetRuntimeDllDirs():
  54. """Sets up os.environ to use the depot_tools VS toolchain with gyp, and
  55. returns the location of the VC runtime DLLs so they can be copied into
  56. the output directory after gyp generation.
  57. Return value is [x64path, x86path, 'Arm64Unused'] or None. arm64path is
  58. generated separately because there are multiple folders for the arm64 VC
  59. runtime.
  60. """
  61. vs_runtime_dll_dirs = None
  62. depot_tools_win_toolchain = \
  63. bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1')))
  64. # When running on a non-Windows host, only do this if the SDK has explicitly
  65. # been downloaded before (in which case json_data_file will exist).
  66. if ((_HostIsWindows() or os.path.exists(json_data_file))
  67. and depot_tools_win_toolchain):
  68. if ShouldUpdateToolchain():
  69. if len(sys.argv) > 1 and sys.argv[1] == 'update':
  70. update_result = Update()
  71. else:
  72. update_result = Update(no_download=True)
  73. if update_result != 0:
  74. raise Exception('Failed to update, error code %d.' % update_result)
  75. with open(json_data_file, 'r') as tempf:
  76. toolchain_data = json.load(tempf)
  77. toolchain = toolchain_data['path']
  78. version = toolchain_data['version']
  79. win_sdk = toolchain_data.get('win_sdk')
  80. wdk = toolchain_data['wdk']
  81. # TODO(scottmg): The order unfortunately matters in these. They should be
  82. # split into separate keys for x64/x86/arm64. (See CopyDlls call below).
  83. # http://crbug.com/345992
  84. vs_runtime_dll_dirs = toolchain_data['runtime_dirs']
  85. # The number of runtime_dirs in the toolchain_data was two (x64/x86) but
  86. # changed to three (x64/x86/arm64) and this code needs to handle both
  87. # possibilities, which can change independently from this code.
  88. if len(vs_runtime_dll_dirs) == 2:
  89. vs_runtime_dll_dirs.append('Arm64Unused')
  90. os.environ['GYP_MSVS_OVERRIDE_PATH'] = toolchain
  91. os.environ['WINDOWSSDKDIR'] = win_sdk
  92. os.environ['WDK_DIR'] = wdk
  93. # Include the VS runtime in the PATH in case it's not machine-installed.
  94. runtime_path = os.path.pathsep.join(vs_runtime_dll_dirs)
  95. os.environ['PATH'] = runtime_path + os.path.pathsep + os.environ['PATH']
  96. elif sys.platform == 'win32' and not depot_tools_win_toolchain:
  97. if not 'GYP_MSVS_OVERRIDE_PATH' in os.environ:
  98. os.environ['GYP_MSVS_OVERRIDE_PATH'] = DetectVisualStudioPath()
  99. # When using an installed toolchain these files aren't needed in the output
  100. # directory in order to run binaries locally, but they are needed in order
  101. # to create isolates or the mini_installer. Copying them to the output
  102. # directory ensures that they are available when needed.
  103. bitness = platform.architecture()[0]
  104. # When running 64-bit python the x64 DLLs will be in System32
  105. # ARM64 binaries will not be available in the system directories because we
  106. # don't build on ARM64 machines.
  107. x64_path = 'System32' if bitness == '64bit' else 'Sysnative'
  108. x64_path = os.path.join(os.path.expandvars('%windir%'), x64_path)
  109. vs_runtime_dll_dirs = [x64_path,
  110. os.path.join(os.path.expandvars('%windir%'),
  111. 'SysWOW64'),
  112. 'Arm64Unused']
  113. return vs_runtime_dll_dirs
  114. def _RegistryGetValueUsingWinReg(key, value):
  115. """Use the _winreg module to obtain the value of a registry key.
  116. Args:
  117. key: The registry key.
  118. value: The particular registry value to read.
  119. Return:
  120. contents of the registry key's value, or None on failure. Throws
  121. ImportError if _winreg is unavailable.
  122. """
  123. import _winreg
  124. try:
  125. root, subkey = key.split('\\', 1)
  126. assert root == 'HKLM' # Only need HKLM for now.
  127. with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) as hkey:
  128. return _winreg.QueryValueEx(hkey, value)[0]
  129. except WindowsError:
  130. return None
  131. def _RegistryGetValue(key, value):
  132. try:
  133. return _RegistryGetValueUsingWinReg(key, value)
  134. except ImportError:
  135. raise Exception('The python library _winreg not found.')
  136. def GetVisualStudioVersion():
  137. """Return best available version of Visual Studio.
  138. """
  139. supported_versions = list(MSVS_VERSIONS.keys())
  140. # VS installed in depot_tools for Googlers
  141. if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1'))):
  142. return supported_versions[0]
  143. # VS installed in system for external developers
  144. supported_versions_str = ', '.join('{} ({})'.format(v,k)
  145. for k,v in MSVS_VERSIONS.items())
  146. available_versions = []
  147. for version in supported_versions:
  148. # Checking vs%s_install environment variables.
  149. # For example, vs2019_install could have the value
  150. # "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community".
  151. # Only vs2017_install, vs2019_install and vs2022_install are supported.
  152. path = os.environ.get('vs%s_install' % version)
  153. if path and os.path.exists(path):
  154. available_versions.append(version)
  155. break
  156. # Detecting VS under possible paths.
  157. if version >= '2022':
  158. program_files_path_variable = '%ProgramFiles%'
  159. else:
  160. program_files_path_variable = '%ProgramFiles(x86)%'
  161. path = os.path.expandvars(program_files_path_variable +
  162. '/Microsoft Visual Studio/%s' % version)
  163. if path and any(
  164. os.path.exists(os.path.join(path, edition))
  165. for edition in ('Enterprise', 'Professional', 'Community', 'Preview',
  166. 'BuildTools')):
  167. available_versions.append(version)
  168. break
  169. if not available_versions:
  170. raise Exception('No supported Visual Studio can be found.'
  171. ' Supported versions are: %s.' % supported_versions_str)
  172. return available_versions[0]
  173. def DetectVisualStudioPath():
  174. """Return path to the installed Visual Studio.
  175. """
  176. # Note that this code is used from
  177. # build/toolchain/win/setup_toolchain.py as well.
  178. version_as_year = GetVisualStudioVersion()
  179. # The VC++ >=2017 install location needs to be located using COM instead of
  180. # the registry. For details see:
  181. # https://blogs.msdn.microsoft.com/heaths/2016/09/15/changes-to-visual-studio-15-setup/
  182. # For now we use a hardcoded default with an environment variable override.
  183. if version_as_year >= '2022':
  184. program_files_path_variable = '%ProgramFiles%'
  185. else:
  186. program_files_path_variable = '%ProgramFiles(x86)%'
  187. for path in (os.environ.get('vs%s_install' % version_as_year),
  188. os.path.expandvars(program_files_path_variable +
  189. '/Microsoft Visual Studio/%s/Enterprise' %
  190. version_as_year),
  191. os.path.expandvars(program_files_path_variable +
  192. '/Microsoft Visual Studio/%s/Professional' %
  193. version_as_year),
  194. os.path.expandvars(program_files_path_variable +
  195. '/Microsoft Visual Studio/%s/Community' %
  196. version_as_year),
  197. os.path.expandvars(program_files_path_variable +
  198. '/Microsoft Visual Studio/%s/Preview' %
  199. version_as_year),
  200. os.path.expandvars(program_files_path_variable +
  201. '/Microsoft Visual Studio/%s/BuildTools' %
  202. version_as_year)):
  203. if path and os.path.exists(path):
  204. return path
  205. raise Exception('Visual Studio Version %s not found.' % version_as_year)
  206. def _CopyRuntimeImpl(target, source, verbose=True):
  207. """Copy |source| to |target| if it doesn't already exist or if it needs to be
  208. updated (comparing last modified time as an approximate float match as for
  209. some reason the values tend to differ by ~1e-07 despite being copies of the
  210. same file... https://crbug.com/603603).
  211. """
  212. if (os.path.isdir(os.path.dirname(target)) and
  213. (not os.path.isfile(target) or
  214. abs(os.stat(target).st_mtime - os.stat(source).st_mtime) >= 0.01)):
  215. if verbose:
  216. print('Copying %s to %s...' % (source, target))
  217. if os.path.exists(target):
  218. # Make the file writable so that we can delete it now, and keep it
  219. # readable.
  220. os.chmod(target, stat.S_IWRITE | stat.S_IREAD)
  221. os.unlink(target)
  222. shutil.copy2(source, target)
  223. # Make the file writable so that we can overwrite or delete it later,
  224. # keep it readable.
  225. os.chmod(target, stat.S_IWRITE | stat.S_IREAD)
  226. def _SortByHighestVersionNumberFirst(list_of_str_versions):
  227. """This sorts |list_of_str_versions| according to version number rules
  228. so that version "1.12" is higher than version "1.9". Does not work
  229. with non-numeric versions like 1.4.a8 which will be higher than
  230. 1.4.a12. It does handle the versions being embedded in file paths.
  231. """
  232. def to_int_if_int(x):
  233. try:
  234. return int(x)
  235. except ValueError:
  236. return x
  237. def to_number_sequence(x):
  238. part_sequence = re.split(r'[\\/\.]', x)
  239. return [to_int_if_int(x) for x in part_sequence]
  240. list_of_str_versions.sort(key=to_number_sequence, reverse=True)
  241. def _CopyUCRTRuntime(target_dir, source_dir, target_cpu, suffix):
  242. """Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't
  243. exist, but the target directory does exist."""
  244. if target_cpu == 'arm64':
  245. # Windows ARM64 VCRuntime is located at {toolchain_root}/VC/Redist/MSVC/
  246. # {x.y.z}/[debug_nonredist/]arm64/Microsoft.VC14x.CRT/.
  247. # Select VC toolset directory based on Visual Studio version
  248. vc_redist_root = FindVCRedistRoot()
  249. if suffix.startswith('.'):
  250. vc_toolset_dir = 'Microsoft.{}.CRT' \
  251. .format(MSVC_TOOLSET_VERSION[GetVisualStudioVersion()])
  252. source_dir = os.path.join(vc_redist_root,
  253. 'arm64', vc_toolset_dir)
  254. else:
  255. vc_toolset_dir = 'Microsoft.{}.DebugCRT' \
  256. .format(MSVC_TOOLSET_VERSION[GetVisualStudioVersion()])
  257. source_dir = os.path.join(vc_redist_root, 'debug_nonredist',
  258. 'arm64', vc_toolset_dir)
  259. file_parts = ('msvcp140', 'vccorlib140', 'vcruntime140')
  260. if target_cpu == 'x64' and GetVisualStudioVersion() != '2017':
  261. file_parts = file_parts + ('vcruntime140_1', )
  262. for file_part in file_parts:
  263. dll = file_part + suffix
  264. target = os.path.join(target_dir, dll)
  265. source = os.path.join(source_dir, dll)
  266. _CopyRuntimeImpl(target, source)
  267. # Copy the UCRT files from the Windows SDK. This location includes the
  268. # api-ms-win-crt-*.dll files that are not found in the Windows directory.
  269. # These files are needed for component builds. If WINDOWSSDKDIR is not set
  270. # use the default SDK path. This will be the case when
  271. # DEPOT_TOOLS_WIN_TOOLCHAIN=0 and vcvarsall.bat has not been run.
  272. win_sdk_dir = os.path.normpath(
  273. os.environ.get('WINDOWSSDKDIR',
  274. os.path.expandvars('%ProgramFiles(x86)%'
  275. '\\Windows Kits\\10')))
  276. # ARM64 doesn't have a redist for the ucrt DLLs because they are always
  277. # present in the OS.
  278. if target_cpu != 'arm64':
  279. # Starting with the 10.0.17763 SDK the ucrt files are in a version-named
  280. # directory - this handles both cases.
  281. redist_dir = os.path.join(win_sdk_dir, 'Redist')
  282. version_dirs = glob.glob(os.path.join(redist_dir, '10.*'))
  283. if len(version_dirs) > 0:
  284. _SortByHighestVersionNumberFirst(version_dirs)
  285. redist_dir = version_dirs[0]
  286. ucrt_dll_dirs = os.path.join(redist_dir, 'ucrt', 'DLLs', target_cpu)
  287. ucrt_files = glob.glob(os.path.join(ucrt_dll_dirs, 'api-ms-win-*.dll'))
  288. assert len(ucrt_files) > 0
  289. for ucrt_src_file in ucrt_files:
  290. file_part = os.path.basename(ucrt_src_file)
  291. ucrt_dst_file = os.path.join(target_dir, file_part)
  292. _CopyRuntimeImpl(ucrt_dst_file, ucrt_src_file, False)
  293. # We must copy ucrtbase.dll for x64/x86, and ucrtbased.dll for all CPU types.
  294. if target_cpu != 'arm64' or not suffix.startswith('.'):
  295. if not suffix.startswith('.'):
  296. # ucrtbased.dll is located at {win_sdk_dir}/bin/{a.b.c.d}/{target_cpu}/
  297. # ucrt/.
  298. sdk_bin_root = os.path.join(win_sdk_dir, 'bin')
  299. sdk_bin_sub_dirs = glob.glob(os.path.join(sdk_bin_root, '10.*'))
  300. # Select the most recent SDK if there are multiple versions installed.
  301. _SortByHighestVersionNumberFirst(sdk_bin_sub_dirs)
  302. for directory in sdk_bin_sub_dirs:
  303. sdk_redist_root_version = os.path.join(sdk_bin_root, directory)
  304. if not os.path.isdir(sdk_redist_root_version):
  305. continue
  306. source_dir = os.path.join(sdk_redist_root_version, target_cpu, 'ucrt')
  307. break
  308. _CopyRuntimeImpl(os.path.join(target_dir, 'ucrtbase' + suffix),
  309. os.path.join(source_dir, 'ucrtbase' + suffix))
  310. def FindVCComponentRoot(component):
  311. """Find the most recent Tools or Redist or other directory in an MSVC install.
  312. Typical results are {toolchain_root}/VC/{component}/MSVC/{x.y.z}. The {x.y.z}
  313. version number part changes frequently so the highest version number found is
  314. used.
  315. """
  316. SetEnvironmentAndGetRuntimeDllDirs()
  317. assert ('GYP_MSVS_OVERRIDE_PATH' in os.environ)
  318. vc_component_msvc_root = os.path.join(os.environ['GYP_MSVS_OVERRIDE_PATH'],
  319. 'VC', component, 'MSVC')
  320. vc_component_msvc_contents = glob.glob(
  321. os.path.join(vc_component_msvc_root, '14.*'))
  322. # Select the most recent toolchain if there are several.
  323. _SortByHighestVersionNumberFirst(vc_component_msvc_contents)
  324. for directory in vc_component_msvc_contents:
  325. if os.path.isdir(directory):
  326. return directory
  327. raise Exception('Unable to find the VC %s directory.' % component)
  328. def FindVCRedistRoot():
  329. """In >=VS2017, Redist binaries are located in
  330. {toolchain_root}/VC/Redist/MSVC/{x.y.z}/{target_cpu}/.
  331. This returns the '{toolchain_root}/VC/Redist/MSVC/{x.y.z}/' path.
  332. """
  333. return FindVCComponentRoot('Redist')
  334. def _CopyRuntime(target_dir, source_dir, target_cpu, debug):
  335. """Copy the VS runtime DLLs, only if the target doesn't exist, but the target
  336. directory does exist. Handles VS 2015, 2017 and 2019."""
  337. suffix = 'd.dll' if debug else '.dll'
  338. # VS 2015, 2017 and 2019 use the same CRT DLLs.
  339. _CopyUCRTRuntime(target_dir, source_dir, target_cpu, suffix)
  340. def CopyDlls(target_dir, configuration, target_cpu):
  341. """Copy the VS runtime DLLs into the requested directory as needed.
  342. configuration is one of 'Debug' or 'Release'.
  343. target_cpu is one of 'x86', 'x64' or 'arm64'.
  344. The debug configuration gets both the debug and release DLLs; the
  345. release config only the latter.
  346. """
  347. vs_runtime_dll_dirs = SetEnvironmentAndGetRuntimeDllDirs()
  348. if not vs_runtime_dll_dirs:
  349. return
  350. x64_runtime, x86_runtime, arm64_runtime = vs_runtime_dll_dirs
  351. if target_cpu == 'x64':
  352. runtime_dir = x64_runtime
  353. elif target_cpu == 'x86':
  354. runtime_dir = x86_runtime
  355. elif target_cpu == 'arm64':
  356. runtime_dir = arm64_runtime
  357. else:
  358. raise Exception('Unknown target_cpu: ' + target_cpu)
  359. _CopyRuntime(target_dir, runtime_dir, target_cpu, debug=False)
  360. if configuration == 'Debug':
  361. _CopyRuntime(target_dir, runtime_dir, target_cpu, debug=True)
  362. _CopyDebugger(target_dir, target_cpu)
  363. def _CopyDebugger(target_dir, target_cpu):
  364. """Copy dbghelp.dll and dbgcore.dll into the requested directory as needed.
  365. target_cpu is one of 'x86', 'x64' or 'arm64'.
  366. dbghelp.dll is used when Chrome needs to symbolize stacks. Copying this file
  367. from the SDK directory avoids using the system copy of dbghelp.dll which then
  368. ensures compatibility with recent debug information formats, such as VS
  369. 2017 /debug:fastlink PDBs.
  370. dbgcore.dll is needed when using some functions from dbghelp.dll (like
  371. MinidumpWriteDump).
  372. """
  373. win_sdk_dir = SetEnvironmentAndGetSDKDir()
  374. if not win_sdk_dir:
  375. return
  376. # List of debug files that should be copied, the first element of the tuple is
  377. # the name of the file and the second indicates if it's optional.
  378. debug_files = [('dbghelp.dll', False), ('dbgcore.dll', True)]
  379. # The UCRT is not a redistributable component on arm64.
  380. if target_cpu != 'arm64':
  381. debug_files.extend([('api-ms-win-downlevel-kernel32-l2-1-0.dll', False),
  382. ('api-ms-win-eventing-provider-l1-1-0.dll', False)])
  383. for debug_file, is_optional in debug_files:
  384. full_path = os.path.join(win_sdk_dir, 'Debuggers', target_cpu, debug_file)
  385. if not os.path.exists(full_path):
  386. if is_optional:
  387. continue
  388. else:
  389. raise Exception('%s not found in "%s"\r\nYou must install '
  390. 'Windows 10 SDK version 10.0.20348.0 including the '
  391. '"Debugging Tools for Windows" feature.' %
  392. (debug_file, full_path))
  393. target_path = os.path.join(target_dir, debug_file)
  394. _CopyRuntimeImpl(target_path, full_path)
  395. def _GetDesiredVsToolchainHashes():
  396. """Load a list of SHA1s corresponding to the toolchains that we want installed
  397. to build with."""
  398. # Third parties that do not have access to the canonical toolchain can map
  399. # canonical toolchain version to their own toolchain versions.
  400. toolchain_hash_mapping_key = 'GYP_MSVS_HASH_%s' % TOOLCHAIN_HASH
  401. return [os.environ.get(toolchain_hash_mapping_key, TOOLCHAIN_HASH)]
  402. def ShouldUpdateToolchain():
  403. """Check if the toolchain should be upgraded."""
  404. if not os.path.exists(json_data_file):
  405. return True
  406. with open(json_data_file, 'r') as tempf:
  407. toolchain_data = json.load(tempf)
  408. version = toolchain_data['version']
  409. env_version = GetVisualStudioVersion()
  410. # If there's a mismatch between the version set in the environment and the one
  411. # in the json file then the toolchain should be updated.
  412. return version != env_version
  413. def Update(force=False, no_download=False):
  414. """Requests an update of the toolchain to the specific hashes we have at
  415. this revision. The update outputs a .json of the various configuration
  416. information required to pass to gyp which we use in |GetToolchainDir()|.
  417. If no_download is true then the toolchain will be configured if present but
  418. will not be downloaded.
  419. """
  420. if force != False and force != '--force':
  421. print('Unknown parameter "%s"' % force, file=sys.stderr)
  422. return 1
  423. if force == '--force' or os.path.exists(json_data_file):
  424. force = True
  425. depot_tools_win_toolchain = \
  426. bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1')))
  427. if (_HostIsWindows() or force) and depot_tools_win_toolchain:
  428. import find_depot_tools
  429. depot_tools_path = find_depot_tools.add_depot_tools_to_path()
  430. # On Linux, the file system is usually case-sensitive while the Windows
  431. # SDK only works on case-insensitive file systems. If it doesn't already
  432. # exist, set up a ciopfs fuse mount to put the SDK in a case-insensitive
  433. # part of the file system.
  434. toolchain_dir = os.path.join(depot_tools_path, 'win_toolchain', 'vs_files')
  435. # For testing this block, unmount existing mounts with
  436. # fusermount -u third_party/depot_tools/win_toolchain/vs_files
  437. if sys.platform.startswith('linux') and not os.path.ismount(toolchain_dir):
  438. import distutils.spawn
  439. ciopfs = distutils.spawn.find_executable('ciopfs')
  440. if not ciopfs:
  441. # ciopfs not found in PATH; try the one downloaded from the DEPS hook.
  442. ciopfs = os.path.join(script_dir, 'ciopfs')
  443. if not os.path.isdir(toolchain_dir):
  444. os.mkdir(toolchain_dir)
  445. if not os.path.isdir(toolchain_dir + '.ciopfs'):
  446. os.mkdir(toolchain_dir + '.ciopfs')
  447. # Without use_ino, clang's #pragma once and Wnonportable-include-path
  448. # both don't work right, see https://llvm.org/PR34931
  449. # use_ino doesn't slow down builds, so it seems there's no drawback to
  450. # just using it always.
  451. subprocess.check_call([
  452. ciopfs, '-o', 'use_ino', toolchain_dir + '.ciopfs', toolchain_dir])
  453. get_toolchain_args = [
  454. sys.executable,
  455. os.path.join(depot_tools_path,
  456. 'win_toolchain',
  457. 'get_toolchain_if_necessary.py'),
  458. '--output-json', json_data_file,
  459. ] + _GetDesiredVsToolchainHashes()
  460. if force:
  461. get_toolchain_args.append('--force')
  462. if no_download:
  463. get_toolchain_args.append('--no-download')
  464. subprocess.check_call(get_toolchain_args)
  465. return 0
  466. def NormalizePath(path):
  467. while path.endswith('\\'):
  468. path = path[:-1]
  469. return path
  470. def SetEnvironmentAndGetSDKDir():
  471. """Gets location information about the current sdk (must have been
  472. previously updated by 'update'). This is used for the GN build."""
  473. SetEnvironmentAndGetRuntimeDllDirs()
  474. # If WINDOWSSDKDIR is not set, search the default SDK path and set it.
  475. if not 'WINDOWSSDKDIR' in os.environ:
  476. default_sdk_path = os.path.expandvars('%ProgramFiles(x86)%'
  477. '\\Windows Kits\\10')
  478. if os.path.isdir(default_sdk_path):
  479. os.environ['WINDOWSSDKDIR'] = default_sdk_path
  480. return NormalizePath(os.environ['WINDOWSSDKDIR'])
  481. def GetToolchainDir():
  482. """Gets location information about the current toolchain (must have been
  483. previously updated by 'update'). This is used for the GN build."""
  484. runtime_dll_dirs = SetEnvironmentAndGetRuntimeDllDirs()
  485. win_sdk_dir = SetEnvironmentAndGetSDKDir()
  486. print('''vs_path = %s
  487. sdk_path = %s
  488. vs_version = %s
  489. wdk_dir = %s
  490. runtime_dirs = %s
  491. ''' % (ToGNString(NormalizePath(os.environ['GYP_MSVS_OVERRIDE_PATH'])),
  492. ToGNString(win_sdk_dir), ToGNString(GetVisualStudioVersion()),
  493. ToGNString(NormalizePath(os.environ.get('WDK_DIR', ''))),
  494. ToGNString(os.path.pathsep.join(runtime_dll_dirs or ['None']))))
  495. def main():
  496. commands = {
  497. 'update': Update,
  498. 'get_toolchain_dir': GetToolchainDir,
  499. 'copy_dlls': CopyDlls,
  500. }
  501. if len(sys.argv) < 2 or sys.argv[1] not in commands:
  502. print('Expected one of: %s' % ', '.join(commands), file=sys.stderr)
  503. return 1
  504. return commands[sys.argv[1]](*sys.argv[2:])
  505. if __name__ == '__main__':
  506. sys.exit(main())