1import os
2import itertools
3import platform
4import subprocess
5import sys
6
7import lit.util
8from lit.llvm import llvm_config
9from lit.llvm.subst import FindTool
10from lit.llvm.subst import ToolSubst
11
12
13def _get_lldb_init_path(config):
14    return os.path.join(config.test_exec_root, 'lit-lldb-init')
15
16
17def _disallow(config, execName):
18  warning = '''
19    echo '*** Do not use \'{0}\' in tests; use \'%''{0}\'. ***' &&
20    exit 1 && echo
21  '''
22  config.substitutions.append((' {0} '.format(execName),
23                               warning.format(execName)))
24
25
26def use_lldb_substitutions(config):
27    # Set up substitutions for primary tools.  These tools must come from config.lldb_tools_dir
28    # which is basically the build output directory.  We do not want to find these in path or
29    # anywhere else, since they are specifically the programs which are actually being tested.
30
31    dsname = 'debugserver' if platform.system() in ['Darwin'] else 'lldb-server'
32    dsargs = [] if platform.system() in ['Darwin'] else ['gdbserver']
33
34    build_script = os.path.dirname(__file__)
35    build_script = os.path.join(build_script, 'build.py')
36    build_script_args = [build_script,
37                        '--compiler=any', # Default to best compiler
38                        '--arch=' + str(config.lldb_bitness)]
39    if config.lldb_lit_tools_dir:
40        build_script_args.append('--tools-dir={0}'.format(config.lldb_lit_tools_dir))
41    if config.lldb_tools_dir:
42        build_script_args.append('--tools-dir={0}'.format(config.lldb_tools_dir))
43    if config.llvm_libs_dir:
44        build_script_args.append('--libs-dir={0}'.format(config.llvm_libs_dir))
45
46    lldb_init = _get_lldb_init_path(config)
47
48    primary_tools = [
49        ToolSubst('%lldb',
50                  command=FindTool('lldb'),
51                  extra_args=['--no-lldbinit', '-S', lldb_init],
52                  unresolved='fatal'),
53        ToolSubst('%lldb-init',
54                  command=FindTool('lldb'),
55                  extra_args=['-S', lldb_init],
56                  unresolved='fatal'),
57        ToolSubst('%lldb-noinit',
58                  command=FindTool('lldb'),
59                  extra_args=['--no-lldbinit'],
60                  unresolved='fatal'),
61        ToolSubst('%lldb-server',
62                  command=FindTool("lldb-server"),
63                  extra_args=[],
64                  unresolved='ignore'),
65        ToolSubst('%debugserver',
66                  command=FindTool(dsname),
67                  extra_args=dsargs,
68                  unresolved='ignore'),
69        ToolSubst('%platformserver',
70                  command=FindTool('lldb-server'),
71                  extra_args=['platform'],
72                  unresolved='ignore'),
73        'lldb-test',
74        'lldb-instr',
75        'lldb-vscode',
76        ToolSubst('%build',
77                  command="'" + sys.executable + "'",
78                  extra_args=build_script_args)
79        ]
80
81    _disallow(config, 'lldb')
82    _disallow(config, 'lldb-server')
83    _disallow(config, 'debugserver')
84    _disallow(config, 'platformserver')
85
86    llvm_config.add_tool_substitutions(primary_tools, [config.lldb_tools_dir])
87
88def _use_msvc_substitutions(config):
89    # If running from a Visual Studio Command prompt (e.g. vcvars), this will
90    # detect the include and lib paths, and find cl.exe and link.exe and create
91    # substitutions for each of them that explicitly specify /I and /L paths
92    cl = lit.util.which('cl')
93
94    if not cl:
95        return
96
97    # Don't use lit.util.which() for link.exe: In `git bash`, it will pick
98    # up /usr/bin/link (another name for ln).
99    link = os.path.join(os.path.dirname(cl), 'link.exe')
100
101    cl = '"' + cl + '"'
102    link = '"' + link + '"'
103    includes = os.getenv('INCLUDE', '').split(';')
104    libs = os.getenv('LIB', '').split(';')
105
106    config.available_features.add('msvc')
107    compiler_flags = ['"/I{}"'.format(x) for x in includes if os.path.exists(x)]
108    linker_flags = ['"/LIBPATH:{}"'.format(x) for x in libs if os.path.exists(x)]
109
110    tools = [
111        ToolSubst('%msvc_cl', command=cl, extra_args=compiler_flags),
112        ToolSubst('%msvc_link', command=link, extra_args=linker_flags)]
113    llvm_config.add_tool_substitutions(tools)
114    return
115
116def use_support_substitutions(config):
117    # Set up substitutions for support tools.  These tools can be overridden at the CMake
118    # level (by specifying -DLLDB_LIT_TOOLS_DIR), installed, or as a last resort, we can use
119    # the just-built version.
120    host_flags = ['--target=' + config.host_triple]
121    if platform.system() in ['Darwin']:
122        try:
123            out = subprocess.check_output(['xcrun', '--show-sdk-path']).strip()
124            res = 0
125        except OSError:
126            res = -1
127        if res == 0 and out:
128            sdk_path = lit.util.to_string(out)
129            llvm_config.lit_config.note('using SDKROOT: %r' % sdk_path)
130            host_flags += ['-isysroot', sdk_path]
131    elif sys.platform != 'win32':
132        host_flags += ['-pthread']
133
134    if sys.platform.startswith('netbsd'):
135        # needed e.g. to use freshly built libc++
136        host_flags += ['-L' + config.llvm_libs_dir,
137                  '-Wl,-rpath,' + config.llvm_libs_dir]
138
139    # The clang module cache is used for building inferiors.
140    host_flags += ['-fmodules-cache-path={}'.format(config.clang_module_cache)]
141
142    host_flags = ' '.join(host_flags)
143    config.substitutions.append(('%clang_host', '%clang ' + host_flags))
144    config.substitutions.append(('%clangxx_host', '%clangxx ' + host_flags))
145    config.substitutions.append(('%clang_cl_host', '%clang_cl --target='+config.host_triple))
146
147    additional_tool_dirs=[]
148    if config.lldb_lit_tools_dir:
149        additional_tool_dirs.append(config.lldb_lit_tools_dir)
150
151    llvm_config.use_clang(additional_flags=['--target=specify-a-target-or-use-a-_host-substitution'],
152                          additional_tool_dirs=additional_tool_dirs,
153                          required=True, use_installed=True)
154
155
156    if sys.platform == 'win32':
157        _use_msvc_substitutions(config)
158
159    have_lld = llvm_config.use_lld(additional_tool_dirs=additional_tool_dirs,
160                                   required=False, use_installed=True)
161    if have_lld:
162        config.available_features.add('lld')
163
164
165    support_tools = ['yaml2obj', 'obj2yaml', 'llvm-dwp', 'llvm-pdbutil',
166                     'llvm-mc', 'llvm-readobj', 'llvm-objdump',
167                     'llvm-objcopy', 'lli']
168    additional_tool_dirs += [config.lldb_tools_dir, config.llvm_tools_dir]
169    llvm_config.add_tool_substitutions(support_tools, additional_tool_dirs)
170
171    _disallow(config, 'clang')
172
173def use_lldb_repro_substitutions(config, mode):
174    lldb_init = _get_lldb_init_path(config)
175    substitutions = [
176        ToolSubst(
177            '%lldb',
178            command=FindTool('lldb-repro'),
179            extra_args=[mode, '--no-lldbinit', '-S', lldb_init]),
180        ToolSubst(
181            '%lldb-init',
182            command=FindTool('lldb-repro'),
183            extra_args=[mode, '-S', lldb_init]),
184    ]
185    llvm_config.add_tool_substitutions(substitutions, [config.lldb_tools_dir])
186