1# Copyright 2015 The BoringSSL Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import json
16import os
17import os.path
18import subprocess
19import sys
20
21script_dir = os.path.dirname(os.path.realpath(__file__))
22sdk_root = os.path.join(script_dir, 'windows_sdk')
23
24def SetEnvironmentForCPU(cpu):
25  """Sets the environment to build with the selected toolchain for |cpu|."""
26  assert cpu in ('x86', 'x64', 'arm', 'arm64')
27  sdk_dir = os.path.join(sdk_root, 'Windows Kits', '10')
28  os.environ['WINDOWSSDKDIR'] = sdk_dir
29  # Include the VS runtime in the PATH in case it's not machine-installed.
30  runtime_dirs = \
31      [os.path.join(sdk_root, d) for d in ['sys64', 'sys32', 'sysarm64']]
32  os.environ['PATH'] = \
33      os.pathsep.join(runtime_dirs) + os.pathsep + os.environ['PATH']
34
35  # Set up the architecture-specific environment from the SetEnv files. See
36  # _LoadToolchainEnv() from setup_toolchain.py in Chromium.
37  with open(os.path.join(sdk_dir, 'bin', 'SetEnv.%s.json' % cpu)) as f:
38    env = json.load(f)['env']
39  if env['VSINSTALLDIR'] == [["..", "..\\"]]:
40    # Old-style paths were relative to the win_sdk\bin directory.
41    json_relative_dir = os.path.join(sdk_dir, 'bin')
42  else:
43    # New-style paths are relative to the toolchain directory.
44    json_relative_dir = sdk_root
45  for k in env:
46    entries = [os.path.join(*([json_relative_dir] + e)) for e in env[k]]
47    # clang-cl wants INCLUDE to be ;-separated even on non-Windows,
48    # lld-link wants LIB to be ;-separated even on non-Windows.  Path gets :.
49    sep = os.pathsep if k == 'PATH' else ';'
50    env[k] = sep.join(entries)
51  # PATH is a bit of a special case, it's in addition to the current PATH.
52  env['PATH'] = env['PATH'] + os.pathsep + os.environ['PATH']
53
54  for k, v in env.items():
55    os.environ[k] = v
56
57if len(sys.argv) < 2:
58  print("Usage: vs_env.py TARGET_ARCH CMD...", file=sys.stderr)
59  sys.exit(1)
60
61target_arch = sys.argv[1]
62cmd = sys.argv[2:]
63
64SetEnvironmentForCPU(target_arch)
65sys.exit(subprocess.call(cmd))
66