get_toolchain_if_necessary.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #!/usr/bin/env python3
  2. # Copyright 2013 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. """Downloads and unpacks a toolchain for building on Windows. The contents are
  6. matched by sha1 which will be updated when the toolchain is updated.
  7. Having a toolchain script in depot_tools means that it's not versioned
  8. directly with the source code. That is, if the toolchain is upgraded, but
  9. you're trying to build an historical version of Chromium from before the
  10. toolchain upgrade, this will cause you to build with a newer toolchain than
  11. was available when that code was committed. This is done for a two main
  12. reasons: 1) it would likely be annoying to have the up-to-date toolchain
  13. removed and replaced by one without a service pack applied); 2) it would
  14. require maintaining scripts that can build older not-up-to-date revisions of
  15. the toolchain. This is likely to be a poorly tested code path that probably
  16. won't be properly maintained. See http://crbug.com/323300.
  17. """
  18. import argparse
  19. from contextlib import closing
  20. import hashlib
  21. import filecmp
  22. import json
  23. import os
  24. import shutil
  25. import subprocess
  26. import sys
  27. import tempfile
  28. import time
  29. from urllib.request import urlopen
  30. from urllib.parse import urljoin
  31. from urllib.error import URLError
  32. import zipfile
  33. # Environment variable that, if set, specifies the default Visual Studio
  34. # toolchain root directory to use.
  35. ENV_TOOLCHAIN_ROOT = 'DEPOT_TOOLS_WIN_TOOLCHAIN_ROOT'
  36. # winreg isn't natively available under CygWin
  37. if sys.platform == "win32":
  38. try:
  39. import winreg
  40. except ImportError:
  41. import _winreg as winreg
  42. elif sys.platform == "cygwin":
  43. try:
  44. import cygwinreg as winreg
  45. except ImportError:
  46. print('')
  47. print(
  48. 'CygWin does not natively support winreg but a replacement exists.')
  49. print('https://pypi.python.org/pypi/cygwinreg/')
  50. print('')
  51. print('Try: easy_install cygwinreg')
  52. print('')
  53. raise
  54. BASEDIR = os.path.dirname(os.path.abspath(__file__))
  55. DEPOT_TOOLS_PATH = os.path.join(BASEDIR, '..')
  56. sys.path.append(DEPOT_TOOLS_PATH)
  57. try:
  58. import download_from_google_storage
  59. except ImportError:
  60. # Allow use of utility functions in this script from package_from_installed
  61. # on bare VM that doesn't have a full depot_tools.
  62. pass
  63. def GetFileList(root):
  64. """Gets a normalized list of files under |root|."""
  65. assert not os.path.isabs(root)
  66. assert os.path.normpath(root) == root
  67. file_list = []
  68. # Ignore WER ReportQueue entries that vctip/cl leave in the bin dir if/when
  69. # they crash. Also ignores the content of the
  70. # Windows Kits/10/debuggers/x(86|64)/(sym|src)/ directories as this is just
  71. # the temporarily location that Windbg might use to store the symbol files
  72. # and downloaded sources.
  73. #
  74. # Note: These files are only created on a Windows host, so the
  75. # ignored_directories list isn't relevant on non-Windows hosts.
  76. # The Windows SDK is either in `win_sdk` or in `Windows Kits\10`. This
  77. # script must work with both layouts, so check which one it is.
  78. # This can be different in each |root|.
  79. if os.path.isdir(os.path.join(root, 'Windows Kits', '10')):
  80. win_sdk = 'Windows Kits\\10'
  81. else:
  82. win_sdk = 'win_sdk'
  83. ignored_directories = [
  84. 'wer\\reportqueue', win_sdk + '\\debuggers\\x86\\sym\\',
  85. win_sdk + '\\debuggers\\x64\\sym\\',
  86. win_sdk + '\\debuggers\\x86\\src\\', win_sdk + '\\debuggers\\x64\\src\\'
  87. ]
  88. ignored_directories = [d.lower() for d in ignored_directories]
  89. for base, _, files in os.walk(root):
  90. paths = [os.path.join(base, f) for f in files]
  91. for p in paths:
  92. if any(ignored_dir in p.lower()
  93. for ignored_dir in ignored_directories):
  94. continue
  95. file_list.append(p)
  96. return sorted(file_list, key=lambda s: s.replace('/', '\\').lower())
  97. def MakeTimestampsFileName(root, sha1):
  98. return os.path.join(root, os.pardir, '%s.timestamps' % sha1)
  99. def CalculateHash(root, expected_hash):
  100. """Calculates the sha1 of the paths to all files in the given |root| and the
  101. contents of those files, and returns as a hex string.
  102. |expected_hash| is the expected hash value for this toolchain if it has
  103. already been installed.
  104. """
  105. if expected_hash:
  106. full_root_path = os.path.join(root, expected_hash)
  107. else:
  108. full_root_path = root
  109. file_list = GetFileList(full_root_path)
  110. # Check whether we previously saved timestamps in
  111. # $root/../{sha1}.timestamps. If we didn't, or they don't match, then do the
  112. # full calculation, otherwise return the saved value.
  113. timestamps_file = MakeTimestampsFileName(root, expected_hash)
  114. timestamps_data = {'files': [], 'sha1': ''}
  115. if os.path.exists(timestamps_file):
  116. with open(timestamps_file, 'rb') as f:
  117. try:
  118. timestamps_data = json.load(f)
  119. except ValueError:
  120. # json couldn't be loaded, empty data will force a re-hash.
  121. pass
  122. matches = len(file_list) == len(timestamps_data['files'])
  123. # Don't check the timestamp of the version file as we touch this file to
  124. # indicates which versions of the toolchain are still being used.
  125. vc_dir = os.path.join(full_root_path, 'VC').lower()
  126. if matches:
  127. for disk, cached in zip(file_list, timestamps_data['files']):
  128. if disk != cached[0] or (disk != vc_dir
  129. and os.path.getmtime(disk) != cached[1]):
  130. matches = False
  131. break
  132. elif os.path.exists(timestamps_file):
  133. # Print some information about the extra/missing files. Don't do this if
  134. # we don't have a timestamp file, as all the files will be considered as
  135. # missing.
  136. timestamps_data_files = []
  137. for f in timestamps_data['files']:
  138. timestamps_data_files.append(f[0])
  139. missing_files = [f for f in timestamps_data_files if f not in file_list]
  140. if len(missing_files):
  141. print('%d files missing from the %s version of the toolchain:' %
  142. (len(missing_files), expected_hash))
  143. for f in missing_files[:10]:
  144. print('\t%s' % f)
  145. if len(missing_files) > 10:
  146. print('\t...')
  147. extra_files = [f for f in file_list if f not in timestamps_data_files]
  148. if len(extra_files):
  149. print('%d extra files in the %s version of the toolchain:' %
  150. (len(extra_files), expected_hash))
  151. for f in extra_files[:10]:
  152. print('\t%s' % f)
  153. if len(extra_files) > 10:
  154. print('\t...')
  155. if matches:
  156. return timestamps_data['sha1']
  157. # Make long hangs when updating the toolchain less mysterious.
  158. print('Calculating hash of toolchain in %s. Please wait...' %
  159. full_root_path)
  160. sys.stdout.flush()
  161. digest = hashlib.sha1()
  162. for path in file_list:
  163. path_without_hash = str(path).replace('/', '\\')
  164. if expected_hash:
  165. path_without_hash = path_without_hash.replace(
  166. os.path.join(root, expected_hash).replace('/', '\\'), root)
  167. digest.update(bytes(path_without_hash.lower(), 'utf-8'))
  168. with open(path, 'rb') as f:
  169. digest.update(f.read())
  170. # Save the timestamp file if the calculated hash is the expected one.
  171. # The expected hash may be shorter, to reduce path lengths, in which case
  172. # just compare that many characters.
  173. if expected_hash and digest.hexdigest().startswith(expected_hash):
  174. SaveTimestampsAndHash(root, digest.hexdigest())
  175. # Return the (potentially truncated) expected_hash.
  176. return expected_hash
  177. return digest.hexdigest()
  178. def CalculateToolchainHashes(root, remove_corrupt_toolchains):
  179. """Calculate the hash of the different toolchains installed in the |root|
  180. directory."""
  181. hashes = []
  182. dir_list = [
  183. d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))
  184. ]
  185. for d in dir_list:
  186. toolchain_hash = CalculateHash(root, d)
  187. if toolchain_hash != d:
  188. print(
  189. 'The hash of a version of the toolchain has an unexpected value ('
  190. '%s instead of %s)%s.' %
  191. (toolchain_hash, d,
  192. ', removing it' if remove_corrupt_toolchains else ''))
  193. if remove_corrupt_toolchains:
  194. RemoveToolchain(root, d, True)
  195. else:
  196. hashes.append(toolchain_hash)
  197. return hashes
  198. def SaveTimestampsAndHash(root, sha1):
  199. """Saves timestamps and the final hash to be able to early-out more quickly
  200. next time."""
  201. file_list = GetFileList(os.path.join(root, sha1))
  202. timestamps_data = {
  203. 'files': [[f, os.path.getmtime(f)] for f in file_list],
  204. 'sha1': sha1,
  205. }
  206. with open(MakeTimestampsFileName(root, sha1), 'wb') as f:
  207. f.write(json.dumps(timestamps_data).encode('utf-8'))
  208. def HaveSrcInternalAccess():
  209. """Checks whether access to src-internal is available."""
  210. with open(os.devnull, 'w') as nul:
  211. # This is required to avoid modal dialog boxes after Git 2.14.1 and Git
  212. # Credential Manager for Windows 1.12. See https://crbug.com/755694 and
  213. # https://github.com/Microsoft/Git-Credential-Manager-for-Windows/issues/482.
  214. child_env = dict(os.environ, GCM_INTERACTIVE='NEVER')
  215. # If this script is run from an embedded terminal in VSCode, VSCode may
  216. # intercept the git call and show an easily-missable username/passsword
  217. # prompt. To ensure we can run without user input, just return false if
  218. # we don't get a response quickly. See crbug.com/376067358.
  219. try:
  220. return subprocess.call(
  221. [
  222. 'git', '-c', 'core.askpass=true', 'remote', 'show',
  223. 'https://chrome-internal.googlesource.com/chrome/src-internal/'
  224. ],
  225. shell=True,
  226. stdin=nul,
  227. stdout=nul,
  228. stderr=nul,
  229. timeout=10, # seconds
  230. env=child_env) == 0
  231. except subprocess.TimeoutExpired:
  232. return False
  233. def LooksLikeGoogler():
  234. """Checks for a USERDOMAIN environment variable of 'GOOGLE', which
  235. probably implies the current user is a Googler."""
  236. return os.environ.get('USERDOMAIN', '').upper() == 'GOOGLE'
  237. def CanAccessToolchainBucket():
  238. """Checks whether the user has access to gs://chrome-wintoolchain/."""
  239. gsutil = download_from_google_storage.Gsutil(
  240. download_from_google_storage.GSUTIL_DEFAULT_PATH, boto_path=None)
  241. code, stdout, stderr = gsutil.check_call('ls', 'gs://chrome-wintoolchain/')
  242. if code != 0:
  243. # Make sure any error messages are made visible to the user.
  244. print(stderr, file=sys.stderr, end='')
  245. print(stdout, end='')
  246. return code == 0
  247. def ToolchainBaseURL():
  248. base_url = os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN_BASE_URL', '')
  249. if base_url.startswith('file://'):
  250. base_url = base_url[len('file://'):]
  251. return base_url
  252. def UsesToolchainFromFile():
  253. return os.path.isdir(ToolchainBaseURL())
  254. def UsesToolchainFromHttp():
  255. url = ToolchainBaseURL()
  256. return url.startswith('http://') or url.startswith('https://')
  257. def RequestGsAuthentication():
  258. """Requests that the user authenticate to be able to access gs:// as a
  259. Googler. This allows much faster downloads, and pulling (old) toolchains
  260. that match src/ revisions.
  261. """
  262. print('Access to gs://chrome-wintoolchain/ not configured.')
  263. print('-----------------------------------------------------------------')
  264. print()
  265. print('You appear to be a Googler.')
  266. print()
  267. print('I\'m sorry for the hassle, but you need to do a one-time manual')
  268. print('authentication. Please run:')
  269. print()
  270. print(' download_from_google_storage --config')
  271. print()
  272. print('and follow the instructions.')
  273. print()
  274. print('NOTE 1: Use your google.com credentials, not chromium.org.')
  275. print('NOTE 2: Enter 0 when asked for a "project-id".')
  276. print()
  277. print('-----------------------------------------------------------------')
  278. print()
  279. sys.stdout.flush()
  280. sys.exit(1)
  281. def DelayBeforeRemoving(target_dir):
  282. """A grace period before deleting the out of date toolchain directory."""
  283. if (os.path.isdir(target_dir)
  284. and not bool(int(os.environ.get('CHROME_HEADLESS', '0')))):
  285. for i in range(9, 0, -1):
  286. sys.stdout.write(
  287. '\rRemoving old toolchain in %ds... (Ctrl-C to cancel)' % i)
  288. sys.stdout.flush()
  289. time.sleep(1)
  290. print()
  291. def DownloadUsingHttp(filename):
  292. """Downloads the given file from a url defined in
  293. DEPOT_TOOLS_WIN_TOOLCHAIN_BASE_URL environment variable."""
  294. temp_dir = tempfile.mkdtemp()
  295. assert os.path.basename(filename) == filename
  296. target_path = os.path.join(temp_dir, filename)
  297. base_url = ToolchainBaseURL()
  298. src_url = urljoin(base_url, filename)
  299. try:
  300. with closing(urlopen(src_url)) as fsrc, \
  301. open(target_path, 'wb') as fdst:
  302. shutil.copyfileobj(fsrc, fdst)
  303. except URLError as e:
  304. RmDir(temp_dir)
  305. sys.exit('Failed to retrieve file: %s' % e)
  306. return temp_dir, target_path
  307. def DownloadUsingGsutil(filename):
  308. """Downloads the given file from Google Storage chrome-wintoolchain bucket."""
  309. temp_dir = tempfile.mkdtemp()
  310. assert os.path.basename(filename) == filename
  311. target_path = os.path.join(temp_dir, filename)
  312. gsutil = download_from_google_storage.Gsutil(
  313. download_from_google_storage.GSUTIL_DEFAULT_PATH, boto_path=None)
  314. code = gsutil.call('cp', 'gs://chrome-wintoolchain/' + filename,
  315. target_path)
  316. if code != 0:
  317. sys.exit('gsutil failed')
  318. return temp_dir, target_path
  319. def RmDir(path):
  320. """Deletes path and all the files it contains."""
  321. if sys.platform != 'win32':
  322. shutil.rmtree(path, ignore_errors=True)
  323. else:
  324. # shutil.rmtree() doesn't delete read-only files on Windows.
  325. subprocess.check_call('rmdir /s/q "%s"' % path, shell=True)
  326. def DoTreeMirror(target_dir, tree_sha1):
  327. """In order to save temporary space on bots that do not have enough space to
  328. download ISOs, unpack them, and copy to the target location, the whole tree
  329. is uploaded as a zip to internal storage, and then mirrored here."""
  330. if UsesToolchainFromFile():
  331. temp_dir = None
  332. local_zip = os.path.join(ToolchainBaseURL(), tree_sha1 + '.zip')
  333. if not os.path.isfile(local_zip):
  334. sys.exit('%s is not a valid file.' % local_zip)
  335. elif UsesToolchainFromHttp():
  336. temp_dir, local_zip = DownloadUsingHttp(tree_sha1 + '.zip')
  337. else:
  338. temp_dir, local_zip = DownloadUsingGsutil(tree_sha1 + '.zip')
  339. sys.stdout.write('Extracting %s...\n' % local_zip)
  340. sys.stdout.flush()
  341. with zipfile.ZipFile(local_zip, 'r', zipfile.ZIP_DEFLATED, True) as zf:
  342. zf.extractall(target_dir)
  343. if temp_dir:
  344. RmDir(temp_dir)
  345. def RemoveToolchain(root, sha1, delay_before_removing):
  346. """Remove the |sha1| version of the toolchain from |root|."""
  347. toolchain_target_dir = os.path.join(root, sha1)
  348. if delay_before_removing:
  349. DelayBeforeRemoving(toolchain_target_dir)
  350. if sys.platform == 'win32':
  351. # These stay resident and will make the rmdir below fail.
  352. kill_list = [
  353. 'mspdbsrv.exe',
  354. 'vctip.exe', # Compiler and tools experience improvement data uploader.
  355. ]
  356. for process_name in kill_list:
  357. with open(os.devnull, 'wb') as nul:
  358. subprocess.call(['taskkill', '/f', '/im', process_name],
  359. stdin=nul,
  360. stdout=nul,
  361. stderr=nul)
  362. if os.path.isdir(toolchain_target_dir):
  363. RmDir(toolchain_target_dir)
  364. timestamp_file = MakeTimestampsFileName(root, sha1)
  365. if os.path.exists(timestamp_file):
  366. os.remove(timestamp_file)
  367. def RemoveUnusedToolchains(root):
  368. """Remove the versions of the toolchain that haven't been used recently."""
  369. valid_toolchains = []
  370. dirs_to_remove = []
  371. for d in os.listdir(root):
  372. full_path = os.path.join(root, d)
  373. if os.path.isdir(full_path):
  374. if not os.path.exists(MakeTimestampsFileName(root, d)):
  375. dirs_to_remove.append(d)
  376. else:
  377. vc_dir = os.path.join(full_path, 'VC')
  378. valid_toolchains.append((os.path.getmtime(vc_dir), d))
  379. elif os.path.isfile(full_path):
  380. os.remove(full_path)
  381. for d in dirs_to_remove:
  382. print('Removing %s as it doesn\'t correspond to any known toolchain.' %
  383. os.path.join(root, d))
  384. # Use the RemoveToolchain function to remove these directories as they
  385. # might contain an older version of the toolchain.
  386. RemoveToolchain(root, d, False)
  387. # Remove the versions of the toolchains that haven't been used in the past
  388. # 30 days.
  389. toolchain_expiration_time = 60 * 60 * 24 * 30
  390. for toolchain in valid_toolchains:
  391. toolchain_age_in_sec = time.time() - toolchain[0]
  392. if toolchain_age_in_sec > toolchain_expiration_time:
  393. print(
  394. 'Removing version %s of the Win toolchain as it hasn\'t been used'
  395. ' in the past %d days.' %
  396. (toolchain[1], toolchain_age_in_sec / 60 / 60 / 24))
  397. RemoveToolchain(root, toolchain[1], True)
  398. def EnableCrashDumpCollection():
  399. """Tell Windows Error Reporting to record crash dumps so that we can diagnose
  400. linker crashes and other toolchain failures. Documented at:
  401. https://msdn.microsoft.com/en-us/library/windows/desktop/bb787181.aspx
  402. """
  403. if sys.platform == 'win32' and os.environ.get('CHROME_HEADLESS') == '1':
  404. key_name = r'SOFTWARE\Microsoft\Windows\Windows Error Reporting'
  405. try:
  406. key = winreg.CreateKeyEx(
  407. winreg.HKEY_LOCAL_MACHINE, key_name, 0,
  408. winreg.KEY_WOW64_64KEY | winreg.KEY_ALL_ACCESS)
  409. # Merely creating LocalDumps is sufficient to enable the defaults.
  410. winreg.CreateKey(key, "LocalDumps")
  411. # Disable the WER UI, as documented here:
  412. # https://msdn.microsoft.com/en-us/library/windows/desktop/bb513638.aspx
  413. winreg.SetValueEx(key, "DontShowUI", 0, winreg.REG_DWORD, 1)
  414. # Trap OSError instead of WindowsError so pylint will succeed on Linux.
  415. # Catching errors is important because some build machines are not
  416. # elevated and writing to HKLM requires elevation.
  417. except OSError:
  418. pass
  419. def SetupJunction(target_dir):
  420. """Sets up junction for toolchain dir."""
  421. junction_dir = os.path.join(BASEDIR, 'vs_files')
  422. if junction_dir == target_dir:
  423. return target_dir
  424. if not sys.platform.startswith('win32'):
  425. # build/vs_toolchain.py sets up ciopfs on vs_files,
  426. # so using different target_dir won't work on Linux?
  427. return target_dir
  428. if os.path.exists(junction_dir):
  429. try:
  430. if os.path.samefile(os.readlink(junction_dir), target_dir):
  431. return junction_dir
  432. except:
  433. # os.readlink may fail if junction_dir is not junction or symlink
  434. pass
  435. RmDir(junction_dir)
  436. print('Setup a directory junction %s to %s' % (junction_dir, target_dir))
  437. subprocess.run(['mklink', '/J', junction_dir, target_dir],
  438. shell=True,
  439. check=True)
  440. return junction_dir
  441. def main():
  442. parser = argparse.ArgumentParser(
  443. description=__doc__,
  444. formatter_class=argparse.RawDescriptionHelpFormatter,
  445. )
  446. parser.add_argument('--output-json',
  447. metavar='FILE',
  448. help='write information about toolchain to FILE')
  449. parser.add_argument('--force',
  450. action='store_true',
  451. help='force script to run on non-Windows hosts')
  452. parser.add_argument('--no-download',
  453. action='store_true',
  454. help='configure if present but don\'t download')
  455. parser.add_argument('--toolchain-dir',
  456. default=os.getenv(ENV_TOOLCHAIN_ROOT, BASEDIR),
  457. help='directory to install toolchain into')
  458. parser.add_argument('desired_hash',
  459. metavar='desired-hash',
  460. help='toolchain hash to download')
  461. parser.add_argument(
  462. '--no-junction',
  463. action='store_true',
  464. help='don\'t setup junction for toolchain dir on Windows')
  465. args = parser.parse_args()
  466. if not (sys.platform.startswith(('cygwin', 'win32')) or args.force):
  467. return 0
  468. if sys.platform == 'cygwin':
  469. # This script requires Windows Python, so invoke with depot_tools'
  470. # Python.
  471. def winpath(path):
  472. return subprocess.check_output(['cygpath', '-w', path]).strip()
  473. python = os.path.join(DEPOT_TOOLS_PATH, 'python3.bat')
  474. cmd = [python, winpath(__file__)]
  475. if args.output_json:
  476. cmd.extend(['--output-json', winpath(args.output_json)])
  477. cmd.append(args.desired_hash)
  478. sys.exit(subprocess.call(cmd))
  479. assert sys.platform != 'cygwin'
  480. # Create our toolchain destination and "chdir" to it.
  481. toolchain_dir = os.path.abspath(args.toolchain_dir)
  482. if not os.path.isdir(toolchain_dir):
  483. os.makedirs(toolchain_dir)
  484. abs_target_dir = os.path.join(toolchain_dir, 'vs_files')
  485. if not os.path.isdir(abs_target_dir):
  486. os.mkdir(abs_target_dir)
  487. if not args.no_junction:
  488. # Set up a directory junction in BASEDIR to toolchain_dir
  489. # so toolchain files can be accessible under exec root.
  490. abs_target_dir = SetupJunction(abs_target_dir)
  491. # Move to depot_tools\win_toolchain where we'll store our files, and where
  492. # the downloader script is.
  493. os.chdir(os.path.dirname(abs_target_dir))
  494. target_dir = 'vs_files'
  495. toolchain_target_dir = os.path.join('vs_files', args.desired_hash)
  496. abs_toolchain_target_dir = os.path.join(abs_target_dir, args.desired_hash)
  497. got_new_toolchain = False
  498. # If the current hash doesn't match what we want in the file, nuke and pave.
  499. # Typically this script is only run when the .sha1 one file is updated, but
  500. # directly calling "gclient runhooks" will also run it, so we cache
  501. # based on timestamps to make that case fast.
  502. current_hashes = CalculateToolchainHashes(target_dir, True)
  503. if args.desired_hash not in current_hashes:
  504. if args.no_download:
  505. raise SystemExit(
  506. 'Toolchain is out of date. Run "gclient runhooks" to '
  507. 'update the toolchain, or set '
  508. 'DEPOT_TOOLS_WIN_TOOLCHAIN=0 to use the locally '
  509. 'installed toolchain.\n'
  510. 'Note: DEPOT_TOOLS_WIN_TOOLCHAIN=0 does not work with '
  511. 'remote execution.')
  512. should_use_file = False
  513. should_use_http = False
  514. should_use_gs = False
  515. if UsesToolchainFromFile():
  516. should_use_file = True
  517. elif UsesToolchainFromHttp():
  518. should_use_http = True
  519. elif (HaveSrcInternalAccess() or LooksLikeGoogler()
  520. or CanAccessToolchainBucket()):
  521. should_use_gs = True
  522. if not CanAccessToolchainBucket():
  523. RequestGsAuthentication()
  524. if not should_use_file and not should_use_gs and not should_use_http:
  525. if sys.platform not in ('win32', 'cygwin'):
  526. doc = 'https://chromium.googlesource.com/chromium/src/+/HEAD/docs/' \
  527. 'win_cross.md'
  528. print('\n\n\nPlease follow the instructions at %s\n\n' % doc)
  529. else:
  530. doc = 'https://chromium.googlesource.com/chromium/src/+/HEAD/docs/' \
  531. 'windows_build_instructions.md'
  532. print(
  533. '\n\n\nNo downloadable toolchain found. In order to use your '
  534. 'locally installed version of Visual Studio to build Chrome '
  535. 'please set DEPOT_TOOLS_WIN_TOOLCHAIN=0.\n'
  536. 'Note: DEPOT_TOOLS_WIN_TOOLCHAIN=0 does not work with '
  537. 'remote execution.\n'
  538. 'For details search for DEPOT_TOOLS_WIN_TOOLCHAIN in the '
  539. 'instructions at %s\n\n' % doc)
  540. return 1
  541. print(
  542. 'Windows toolchain out of date or doesn\'t exist, updating (Pro)...'
  543. )
  544. print(' current_hashes: %s' % ', '.join(current_hashes))
  545. print(' desired_hash: %s' % args.desired_hash)
  546. sys.stdout.flush()
  547. DoTreeMirror(toolchain_target_dir, args.desired_hash)
  548. got_new_toolchain = True
  549. # The Windows SDK is either in `win_sdk` or in `Windows Kits\10`. This
  550. # script must work with both layouts, so check which one it is.
  551. win_sdk_in_windows_kits = os.path.isdir(
  552. os.path.join(abs_toolchain_target_dir, 'Windows Kits', '10'))
  553. if win_sdk_in_windows_kits:
  554. win_sdk = os.path.join(abs_toolchain_target_dir, 'Windows Kits', '10')
  555. else:
  556. win_sdk = os.path.join(abs_toolchain_target_dir, 'win_sdk')
  557. version_file = os.path.join(toolchain_target_dir, 'VS_VERSION')
  558. vc_dir = os.path.join(toolchain_target_dir, 'VC')
  559. with open(version_file, 'rb') as f:
  560. vs_version = f.read().decode('utf-8').strip()
  561. # Touch the VC directory so we can use its timestamp to know when this
  562. # version of the toolchain has been used for the last time.
  563. os.utime(vc_dir, None)
  564. data = {
  565. 'path':
  566. abs_toolchain_target_dir,
  567. 'version':
  568. vs_version,
  569. 'win_sdk':
  570. win_sdk,
  571. 'wdk':
  572. os.path.join(abs_toolchain_target_dir, 'wdk'),
  573. 'runtime_dirs': [
  574. os.path.join(abs_toolchain_target_dir, 'sys64'),
  575. os.path.join(abs_toolchain_target_dir, 'sys32'),
  576. os.path.join(abs_toolchain_target_dir, 'sysarm64'),
  577. ],
  578. }
  579. data_json = json.dumps(data, indent=2)
  580. data_path = os.path.join(target_dir, '..', 'data.json')
  581. if not os.path.exists(data_path) or open(data_path).read() != data_json:
  582. with open(data_path, 'w') as f:
  583. f.write(data_json)
  584. if got_new_toolchain:
  585. current_hashes = CalculateToolchainHashes(target_dir, False)
  586. if args.desired_hash not in current_hashes:
  587. print('Got wrong hash after pulling a new toolchain. '
  588. 'Wanted \'%s\', got one of \'%s\'.' %
  589. (args.desired_hash, ', '.join(current_hashes)),
  590. file=sys.stderr)
  591. return 1
  592. SaveTimestampsAndHash(target_dir, args.desired_hash)
  593. if args.output_json:
  594. if (not os.path.exists(args.output_json)
  595. or not filecmp.cmp(data_path, args.output_json)):
  596. shutil.copyfile(data_path, args.output_json)
  597. EnableCrashDumpCollection()
  598. RemoveUnusedToolchains(target_dir)
  599. return 0
  600. if __name__ == '__main__':
  601. sys.exit(main())