Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
setup_toolchain.py
Go to the documentation of this file.
1# Copyright 2013 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4#
5# Copies the given "win tool" (which the toolchain uses to wrap compiler
6# invocations) and the environment blocks for the 32-bit and 64-bit builds on
7# Windows to the build directory.
8#
9# The arguments are the visual studio install location and the location of the
10# win tool. The script assumes that the root build directory is the current dir
11# and the files will be written to the current directory.
12
13
14import errno
15import json
16import os
17import re
18import subprocess
19import sys
20
21sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
22import gn_helpers
23
24SCRIPT_DIR = os.path.dirname(__file__)
25SDK_VERSION = '10.0.22621.0'
26
27
29 """Extracts environment variables required for the toolchain to run from
30 a textual dump output by the cmd.exe 'set' command."""
31 envvars_to_save = (
32 'cipd_cache_dir', # needed by vpython
33 'homedrive', # needed by vpython
34 'homepath', # needed by vpython
35 'goma_.*', # TODO(scottmg): This is ugly, but needed for goma.
36 'include',
37 'lib',
38 'libpath',
39 'luci_context', # needed by vpython
40 'path',
41 'pathext',
42 'rbe_cfg', # Dart specific patch: RBE_cfg is needed by reclient.
43 'rbe_server_address', # Dart specific patch: RBE_server_address ditto.
44 'systemroot',
45 'temp',
46 'tmp',
47 'userprofile', # needed by vpython
48 'vpython_virtualenv_root' # needed by vpython
49 )
50 env = {}
51 # This occasionally happens and leads to misleading SYSTEMROOT error messages
52 # if not caught here.
53 if output_of_set.count('=') == 0:
54 raise Exception('Invalid output_of_set. Value is:\n%s' % output_of_set)
55 for line in output_of_set.splitlines():
56 for envvar in envvars_to_save:
57 if re.match(envvar + '=', line.lower()):
58 var, setting = line.split('=', 1)
59 if envvar == 'path':
60 # Our own rules and actions in Chromium rely on python being in the
61 # path. Add the path to this python here so that if it's not in the
62 # path when ninja is run later, python will still be found.
63 setting = os.path.dirname(sys.executable) + os.pathsep + setting
64 # Dart specific patch: Ensure the environment variables use relative
65 # paths to the toolchain such that RBE commands can be cached
66 # remotely due to no absolute paths. Rewrite libpath as well although
67 # don't use it remotely at the moment.
68 if envvar in ['include', 'lib', 'libpath']:
69 exec_root_abs = os.path.dirname(os.path.dirname(os.getcwd()))
70 exec_root_rel = os.path.join('..', '..')
71 # Make sure that the include and lib paths point to directories that
72 # exist. This ensures a (relatively) clear error message if the
73 # required SDK is not installed.
74 parts = []
75 for part in setting.split(';'):
76 part = part.replace(exec_root_abs, exec_root_rel)
77 if not os.path.exists(part) and len(part) != 0:
78 raise Exception(
79 'Path "%s" from environment variable "%s" does not exist. '
80 'Make sure the necessary SDK is installed.' % (part, envvar))
81 parts.append(part)
82 setting = ';'.join(parts)
83 env[var.upper()] = setting
84 break
85 if sys.platform in ('win32', 'cygwin'):
86 for required in ('SYSTEMROOT', 'TEMP', 'TMP'):
87 if required not in env:
88 raise Exception('Environment variable "%s" '
89 'required to be set to valid path' % required)
90 return env
91
92
94 """Return path to the installed Visual Studio.
95 """
96
97 # Use the code in build/vs_toolchain.py to avoid duplicating code.
98 chromium_dir = os.path.abspath(os.path.join(SCRIPT_DIR, '..', '..', '..'))
99 sys.path.append(os.path.join(chromium_dir, 'build'))
100 import vs_toolchain
102
103
105 """Given a bat command, runs it and returns env vars set by it."""
106 args = args[:]
107 args.extend(('&&', 'set'))
108 popen = subprocess.Popen(
109 args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
110 variables, _ = popen.communicate()
111 if popen.returncode != 0:
112 raise Exception('"%s" failed with error %d' % (args, popen.returncode))
113 return variables.decode(errors='ignore')
114
115
116def _LoadToolchainEnv(cpu, toolchain_root, sdk_dir, target_store):
117 """Returns a dictionary with environment variables that must be set while
118 running binaries from the toolchain (e.g. INCLUDE and PATH for cl.exe)."""
119 # Check if we are running in the SDK command line environment and use
120 # the setup script from the SDK if so. |cpu| should be either
121 # 'x86' or 'x64' or 'arm' or 'arm64'.
122 assert cpu in ('x86', 'x64', 'arm', 'arm64')
123 if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', 1))) and sdk_dir:
124 # Load environment from json file.
125 env = os.path.normpath(os.path.join(sdk_dir, 'bin/SetEnv.%s.json' % cpu))
126 env = json.load(open(env))['env']
127 if env['VSINSTALLDIR'] == [["..", "..\\"]]:
128 # Old-style paths were relative to the win_sdk\bin directory.
129 json_relative_dir = os.path.join(sdk_dir, 'bin')
130 else:
131 # New-style paths are relative to the toolchain directory.
132 json_relative_dir = toolchain_root
133 for k in env:
134 entries = [os.path.join(*([json_relative_dir] + e)) for e in env[k]]
135 # clang-cl wants INCLUDE to be ;-separated even on non-Windows,
136 # lld-link wants LIB to be ;-separated even on non-Windows. Path gets :.
137 # The separator for INCLUDE here must match the one used in main() below.
138 sep = os.pathsep if k == 'PATH' else ';'
139 env[k] = sep.join(entries)
140 # PATH is a bit of a special case, it's in addition to the current PATH.
141 env['PATH'] = env['PATH'] + os.pathsep + os.environ['PATH']
142 # Augment with the current env to pick up TEMP and friends.
143 for k in os.environ:
144 if k not in env:
145 env[k] = os.environ[k]
146
147 varlines = []
148 for k in sorted(env.keys()):
149 varlines.append('%s=%s' % (str(k), str(env[k])))
150 variables = '\n'.join(varlines)
151
152 # Check that the json file contained the same environment as the .cmd file.
153 if sys.platform in ('win32', 'cygwin'):
154 script = os.path.normpath(os.path.join(sdk_dir, 'Bin/SetEnv.cmd'))
155 arg = '/' + cpu
156 json_env = _ExtractImportantEnvironment(variables)
157 cmd_env = _ExtractImportantEnvironment(_LoadEnvFromBat([script, arg]))
158 assert _LowercaseDict(json_env) == _LowercaseDict(cmd_env)
159 else:
160 if 'GYP_MSVS_OVERRIDE_PATH' not in os.environ:
161 os.environ['GYP_MSVS_OVERRIDE_PATH'] = _DetectVisualStudioPath()
162 # We only support x64-hosted tools.
163 script_path = os.path.normpath(os.path.join(
164 os.environ['GYP_MSVS_OVERRIDE_PATH'],
165 'VC/vcvarsall.bat'))
166 if not os.path.exists(script_path):
167 # vcvarsall.bat for VS 2017 fails if run after running vcvarsall.bat from
168 # VS 2013 or VS 2015. Fix this by clearing the vsinstalldir environment
169 # variable. Since vcvarsall.bat appends to the INCLUDE, LIB, and LIBPATH
170 # environment variables we need to clear those to avoid getting double
171 # entries when vcvarsall.bat has been run before gn gen. vcvarsall.bat
172 # also adds to PATH, but there is no clean way of clearing that and it
173 # doesn't seem to cause problems.
174 if 'VSINSTALLDIR' in os.environ:
175 del os.environ['VSINSTALLDIR']
176 if 'INCLUDE' in os.environ:
177 del os.environ['INCLUDE']
178 if 'LIB' in os.environ:
179 del os.environ['LIB']
180 if 'LIBPATH' in os.environ:
181 del os.environ['LIBPATH']
182 other_path = os.path.normpath(os.path.join(
183 os.environ['GYP_MSVS_OVERRIDE_PATH'],
184 'VC/Auxiliary/Build/vcvarsall.bat'))
185 if not os.path.exists(other_path):
186 raise Exception('%s is missing - make sure VC++ tools are installed.' %
187 script_path)
188 script_path = other_path
189 cpu_arg = "amd64"
190 if (cpu != 'x64'):
191 # x64 is default target CPU thus any other CPU requires a target set
192 cpu_arg += '_' + cpu
193 args = [script_path, cpu_arg, ]
194 # Store target must come before any SDK version declaration
195 if (target_store):
196 args.append('store')
197 # Explicitly specifying the SDK version to build with to avoid accidentally
198 # building with a new and untested SDK. This should stay in sync with the
199 # packaged toolchain in build/vs_toolchain.py.
200 args.append(SDK_VERSION)
201 variables = _LoadEnvFromBat(args)
202 return _ExtractImportantEnvironment(variables)
203
204
206 """Format as an 'environment block' directly suitable for CreateProcess.
207 Briefly this is a list of key=value\0, terminated by an additional \0. See
208 CreateProcess documentation for more details."""
209 block = ''
210 nul = '\0'
211 for key, value in envvar_dict.items():
212 block += key + '=' + value + nul
213 block += nul
214 return block
215
216
218 """Returns a copy of `d` with both key and values lowercased.
219
220 Args:
221 d: dict to lowercase (e.g. {'A': 'BcD'}).
222
223 Returns:
224 A dict with both keys and values lowercased (e.g.: {'a': 'bcd'}).
225 """
226 return {k.lower(): d[k].lower() for k in d}
227
228
229def FindFileInEnvList(env, env_name, separator, file_name, optional=False):
230 parts = env[env_name].split(separator)
231 for path in parts:
232 if os.path.exists(os.path.join(path, file_name)):
233 return os.path.realpath(path)
234 assert optional, "%s is not found in %s:\n%s\nCheck if it is installed." % (
235 file_name, env_name, '\n'.join(parts))
236 return ''
237
238
239def main():
240 if len(sys.argv) != 7:
241 print('Usage setup_toolchain.py '
242 '<visual studio path> <win sdk path> '
243 '<runtime dirs> <target_os> <target_cpu> '
244 '<environment block name|none>')
245 sys.exit(2)
246 # toolchain_root and win_sdk_path are only read if the hermetic Windows
247 # toolchain is set, that is if DEPOT_TOOLS_WIN_TOOLCHAIN is not set to 0.
248 # With the hermetic Windows toolchain, the visual studio path in argv[1]
249 # is the root of the Windows toolchain directory.
250 toolchain_root = sys.argv[1]
251 win_sdk_path = sys.argv[2]
252
253 runtime_dirs = sys.argv[3]
254 target_os = sys.argv[4]
255 target_cpu = sys.argv[5]
256 environment_block_name = sys.argv[6]
257 if (environment_block_name == 'none'):
258 environment_block_name = ''
259
260 if (target_os == 'winuwp'):
261 target_store = True
262 else:
263 target_store = False
264
265 cpus = ('x86', 'x64', 'arm', 'arm64')
266 assert target_cpu in cpus
267 vc_bin_dir = ''
268 include = ''
269 lib = ''
270
271 # TODO(scottmg|goma): Do we need an equivalent of
272 # ninja_use_custom_environment_files?
273
274 def relflag(s): # Make s relative to builddir when cwd and sdk on same drive.
275 try:
276 return os.path.relpath(s).replace('\\', '/')
277 except ValueError:
278 return s
279
280 def q(s): # Quote s if it contains spaces or other weird characters.
281 return s if re.match(r'^[a-zA-Z0-9._/\\:-]*$', s) else '"' + s + '"'
282
283 for cpu in cpus:
284 if cpu == target_cpu:
285 # Extract environment variables for subprocesses.
286 env = _LoadToolchainEnv(cpu, toolchain_root, win_sdk_path, target_store)
287 env['PATH'] = runtime_dirs + os.pathsep + env['PATH']
288
289 vc_bin_dir = FindFileInEnvList(env, 'PATH', os.pathsep, 'cl.exe')
290
291 # The separator for INCLUDE here must match the one used in
292 # _LoadToolchainEnv() above.
293 include = [p.replace('"', r'\"') for p in env['INCLUDE'].split(';') if p]
294 include = list(map(relflag, include))
295
296 lib = [p.replace('"', r'\"') for p in env['LIB'].split(';') if p]
297 lib = list(map(relflag, lib))
298
299 include_I = ['/I' + i for i in include]
300 include_imsvc = ['-imsvc' + i for i in include]
301 libpath_flags = ['-libpath:' + i for i in lib]
302
303 if (environment_block_name != ''):
304 env_block = _FormatAsEnvironmentBlock(env)
305 with open(environment_block_name, 'w', encoding='utf8') as f:
306 f.write(env_block)
307
308 def ListToArgString(x):
309 return gn_helpers.ToGNString(' '.join(q(i) for i in x))
310
311 def ListToArgList(x):
312 return f'[{", ".join(gn_helpers.ToGNString(i) for i in x)}]'
313
314 print('vc_bin_dir = ' + gn_helpers.ToGNString(vc_bin_dir))
315 assert include_I
316 print(f'include_flags_I = {ListToArgString(include_I)}')
317 print(f'include_flags_I_list = {ListToArgList(include_I)}')
318 assert include_imsvc
319 if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', 1))) and win_sdk_path:
320 flags = ['/winsysroot' + relflag(toolchain_root)]
321 print(f'include_flags_imsvc = {ListToArgString(flags)}')
322 print(f'include_flags_imsvc_list = {ListToArgList(flags)}')
323 else:
324 print(f'include_flags_imsvc = {ListToArgString(include_imsvc)}')
325 print(f'include_flags_imsvc_list = {ListToArgList(include_imsvc)}')
326 print('paths = ' + gn_helpers.ToGNString(env['PATH']))
327 assert libpath_flags
328 print(f'libpath_flags = {ListToArgString(libpath_flags)}')
329 print(f'libpath_flags_list = {ListToArgList(libpath_flags)}')
330 if bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', 1))) and win_sdk_path:
331 flags = ['/winsysroot:' + relflag(toolchain_root)]
332 print(f'libpath_lldlink_flags = {ListToArgString(flags)}')
333 print(f'libpath_lldlink_flags_list = {ListToArgList(flags)}')
334 else:
335 print(f'libpath_lldlink_flags = {ListToArgString(libpath_flags)}')
336 print(f'libpath_lldlink_flags_list = {ListToArgList(libpath_flags)}')
337
338
339if __name__ == '__main__':
340 main()
Type::kYUV Type::kRGBA() int(0.7 *637)
void print(void *str)
Definition bridge.cpp:126
ToGNString(value, allow_dicts=True)
Definition gn_helpers.py:30
Definition main.py:1
_FormatAsEnvironmentBlock(envvar_dict)
_LoadToolchainEnv(cpu, toolchain_root, sdk_dir, target_store)
_ExtractImportantEnvironment(output_of_set)
FindFileInEnvList(env, env_name, separator, file_name, optional=False)