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-vscode',
75        ToolSubst('%build',
76                  command="'" + sys.executable + "'",
77                  extra_args=build_script_args)
78        ]
79
80    _disallow(config, 'lldb')
81    _disallow(config, 'lldb-server')
82    _disallow(config, 'debugserver')
83    _disallow(config, 'platformserver')
84
85    llvm_config.add_tool_substitutions(primary_tools, [config.lldb_tools_dir])
86
87def _use_msvc_substitutions(config):
88    # If running from a Visual Studio Command prompt (e.g. vcvars), this will
89    # detect the include and lib paths, and find cl.exe and link.exe and create
90    # substitutions for each of them that explicitly specify /I and /L paths
91    cl = lit.util.which('cl')
92
93    if not cl:
94        return
95
96    # Don't use lit.util.which() for link.exe: In `git bash`, it will pick
97    # up /usr/bin/link (another name for ln).
98    link = os.path.join(os.path.dirname(cl), 'link.exe')
99
100    cl = '"' + cl + '"'
101    link = '"' + link + '"'
102    includes = os.getenv('INCLUDE', '').split(';')
103    libs = os.getenv('LIB', '').split(';')
104
105    config.available_features.add('msvc')
106    compiler_flags = ['"/I{}"'.format(x) for x in includes if os.path.exists(x)]
107    linker_flags = ['"/LIBPATH:{}"'.format(x) for x in libs if os.path.exists(x)]
108
109    tools = [
110        ToolSubst('%msvc_cl', command=cl, extra_args=compiler_flags),
111        ToolSubst('%msvc_link', command=link, extra_args=linker_flags)]
112    llvm_config.add_tool_substitutions(tools)
113    return
114
115def use_support_substitutions(config):
116    # Set up substitutions for support tools.  These tools can be overridden at the CMake
117    # level (by specifying -DLLDB_LIT_TOOLS_DIR), installed, or as a last resort, we can use
118    # the just-built version.
119    host_flags = ['--target=' + config.host_triple]
120    if platform.system() in ['Darwin']:
121        try:
122            out = subprocess.check_output(['xcrun', '--show-sdk-path']).strip()
123            res = 0
124        except OSError:
125            res = -1
126        if res == 0 and out:
127            sdk_path = lit.util.to_string(out)
128            llvm_config.lit_config.note('using SDKROOT: %r' % sdk_path)
129            host_flags += ['-isysroot', sdk_path]
130    elif sys.platform != 'win32':
131        host_flags += ['-pthread']
132
133    if sys.platform.startswith('netbsd'):
134        # needed e.g. to use freshly built libc++
135        host_flags += ['-L' + config.llvm_libs_dir,
136                  '-Wl,-rpath,' + config.llvm_libs_dir]
137
138    # The clang module cache is used for building inferiors.
139    host_flags += ['-fmodules-cache-path={}'.format(config.clang_module_cache)]
140
141    host_flags = ' '.join(host_flags)
142    config.substitutions.append(('%clang_host', '%clang ' + host_flags))
143    config.substitutions.append(('%clangxx_host', '%clangxx ' + host_flags))
144    config.substitutions.append(('%clang_cl_host', '%clang_cl --target='+config.host_triple))
145
146    additional_tool_dirs=[]
147    if config.lldb_lit_tools_dir:
148        additional_tool_dirs.append(config.lldb_lit_tools_dir)
149
150    llvm_config.use_clang(additional_flags=['--target=specify-a-target-or-use-a-_host-substitution'],
151                          additional_tool_dirs=additional_tool_dirs,
152                          required=True, use_installed=True)
153
154
155    if sys.platform == 'win32':
156        _use_msvc_substitutions(config)
157
158    have_lld = llvm_config.use_lld(additional_tool_dirs=additional_tool_dirs,
159                                   required=False, use_installed=True)
160    if have_lld:
161        config.available_features.add('lld')
162
163
164    support_tools = ['yaml2obj', 'obj2yaml', 'llvm-dwp', 'llvm-pdbutil',
165                     'llvm-mc', 'llvm-readobj', 'llvm-objdump',
166                     'llvm-objcopy', 'lli']
167    additional_tool_dirs += [config.lldb_tools_dir, config.llvm_tools_dir]
168    llvm_config.add_tool_substitutions(support_tools, additional_tool_dirs)
169
170    _disallow(config, 'clang')
171
172def use_lldb_repro_substitutions(config, mode):
173    lldb_init = _get_lldb_init_path(config)
174    substitutions = [
175        ToolSubst(
176            '%lldb',
177            command=FindTool('lldb-repro'),
178            extra_args=[mode, '--no-lldbinit', '-S', lldb_init]),
179        ToolSubst(
180            '%lldb-init',
181            command=FindTool('lldb-repro'),
182            extra_args=[mode, '-S', lldb_init]),
183    ]
184    llvm_config.add_tool_substitutions(substitutions, [config.lldb_tools_dir])
185