21sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
24SCRIPT_DIR = os.path.dirname(__file__)
25SDK_VERSION =
'10.0.22621.0'
28def _ExtractImportantEnvironment(output_of_set):
29 """Extracts environment variables required for the toolchain to run from
30 a textual dump output by the cmd.exe 'set' command.
"""
48 'vpython_virtualenv_root'
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)
63 setting = os.path.dirname(sys.executable) + os.pathsep + setting
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(
'..',
'..')
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:
79 'Path "%s" from environment variable "%s" does not exist. '
80 'Make sure the necessary SDK is installed.' % (part, envvar))
82 setting =
';'.
join(parts)
83 env[var.upper()] = setting
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)
93def _DetectVisualStudioPath():
94 """Return path to the installed Visual Studio.
98 chromium_dir = os.path.abspath(os.path.join(SCRIPT_DIR,
'..',
'..',
'..'))
99 sys.path.append(os.path.join(chromium_dir,
'build'))
104def _LoadEnvFromBat(args):
105 """Given a bat command, runs it and returns env vars set by it."""
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')
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).
"""
122 assert cpu
in (
'x86',
'x64',
'arm',
'arm64')
123 if bool(
int(os.environ.get(
'DEPOT_TOOLS_WIN_TOOLCHAIN', 1)))
and sdk_dir:
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'] == [[
"..",
"..\\"]]:
129 json_relative_dir = os.path.join(sdk_dir,
'bin')
132 json_relative_dir = toolchain_root
134 entries = [os.path.join(*([json_relative_dir] + e))
for e
in env[k]]
138 sep = os.pathsep
if k ==
'PATH' else ';'
139 env[k] = sep.join(entries)
141 env[
'PATH'] = env[
'PATH'] + os.pathsep + os.environ[
'PATH']
145 env[k] = os.environ[k]
148 for k
in sorted(env.keys()):
149 varlines.append(
'%s=%s' % (str(k), str(env[k])))
150 variables =
'\n'.
join(varlines)
153 if sys.platform
in (
'win32',
'cygwin'):
154 script = os.path.normpath(os.path.join(sdk_dir,
'Bin/SetEnv.cmd'))
156 json_env = _ExtractImportantEnvironment(variables)
157 cmd_env = _ExtractImportantEnvironment(_LoadEnvFromBat([script, arg]))
158 assert _LowercaseDict(json_env) == _LowercaseDict(cmd_env)
160 if 'GYP_MSVS_OVERRIDE_PATH' not in os.environ:
161 os.environ[
'GYP_MSVS_OVERRIDE_PATH'] = _DetectVisualStudioPath()
163 script_path = os.path.normpath(os.path.join(
164 os.environ[
'GYP_MSVS_OVERRIDE_PATH'],
166 if not os.path.exists(script_path):
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.' %
188 script_path = other_path
193 args = [script_path, cpu_arg, ]
200 args.append(SDK_VERSION)
201 variables = _LoadEnvFromBat(args)
202 return _ExtractImportantEnvironment(variables)
205def _FormatAsEnvironmentBlock(envvar_dict):
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.
"""
211 for key, value
in envvar_dict.items():
212 block += key +
'=' + value + nul
217def _LowercaseDict(d):
218 """Returns a copy of `d` with both key and values lowercased.
221 d: dict to lowercase (e.g. {'A':
'BcD'}).
224 A dict
with both keys
and values lowercased (e.g.: {
'a':
'bcd'}).
226 return {k.lower(): d[k].
lower()
for k
in d}
230 parts = env[env_name].split(separator)
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))
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>')
250 toolchain_root = sys.argv[1]
251 win_sdk_path = sys.argv[2]
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 =
''
260 if (target_os ==
'winuwp'):
265 cpus = (
'x86',
'x64',
'arm',
'arm64')
266 assert target_cpu
in cpus
276 return os.path.relpath(s).replace(
'\\',
'/')
281 return s
if re.match(
r'^[a-zA-Z0-9._/\\:-]*$', s)
else '"' + s +
'"'
284 if cpu == target_cpu:
286 env = _LoadToolchainEnv(cpu, toolchain_root, win_sdk_path, target_store)
287 env[
'PATH'] = runtime_dirs + os.pathsep + env[
'PATH']
293 include = [p.replace(
'"',
r'\"')
for p
in env[
'INCLUDE'].split(
';')
if p]
294 include = list(
map(relflag, include))
296 lib = [p.replace(
'"',
r'\"')
for p
in env[
'LIB'].split(
';')
if p]
297 lib = list(
map(relflag, lib))
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]
303 if (environment_block_name !=
''):
304 env_block = _FormatAsEnvironmentBlock(env)
305 with open(environment_block_name,
'w', encoding=
'utf8')
as f:
308 def ListToArgString(x):
311 def ListToArgList(x):
312 return f
'[{", ".join(gn_helpers.ToGNString(i) for i in x)}]'
316 print(f
'include_flags_I = {ListToArgString(include_I)}')
317 print(f
'include_flags_I_list = {ListToArgList(include_I)}')
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)}')
324 print(f
'include_flags_imsvc = {ListToArgString(include_imsvc)}')
325 print(f
'include_flags_imsvc_list = {ListToArgList(include_imsvc)}')
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)}')
335 print(f
'libpath_lldlink_flags = {ListToArgString(libpath_flags)}')
336 print(f
'libpath_lldlink_flags_list = {ListToArgList(libpath_flags)}')
339if __name__ ==
'__main__':
def ToGNString(value, allow_dicts=True)
def print(*args, **kwargs)
SI auto map(std::index_sequence< I... >, Fn &&fn, const Args &... args) -> skvx::Vec< sizeof...(I), decltype(fn(args[0]...))>
static SkString join(const CommandLineFlags::StringArray &)