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