aboutsummaryrefslogtreecommitdiff
path: root/lldb/packages/Python/lldbsuite/test/builders/builder.py
blob: 96c7b3987d8a1f03c01d34e999a0cf710b7c2706 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import os
import pathlib
import platform
import subprocess
import sys
import itertools

import lldbsuite.test.lldbtest as lldbtest
import lldbsuite.test.lldbplatformutil as lldbplatformutil
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test import configuration
from lldbsuite.test_event import build_exception
from lldbsuite.support import seven


class Builder:
    def getArchitecture(self):
        """Returns the architecture in effect the test suite is running with."""
        return configuration.arch if configuration.arch else ""

    def getCompiler(self):
        """Returns the compiler in effect the test suite is running with."""
        compiler = configuration.compiler if configuration.compiler else "clang"
        compiler = lldbutil.which(compiler)
        return os.path.abspath(compiler)

    def getTriple(self, arch):
        """Returns the triple for the given architecture or None."""
        return configuration.triple

    def getExtraMakeArgs(self):
        """
        Helper function to return extra argumentsfor the make system. This
        method is meant to be overridden by platform specific builders.
        """
        return []

    def getArchCFlags(self, architecture):
        """Returns the ARCH_CFLAGS for the make system."""
        triple = self.getTriple(architecture)
        if triple:
            return ["ARCH_CFLAGS=-target {}".format(triple)]
        return []

    def getMake(self, test_subdir, test_name):
        """Returns the invocation for GNU make.
        The first argument is a tuple of the relative path to the testcase
        and its filename stem."""
        # Construct the base make invocation.
        lldb_test = os.environ["LLDB_TEST"]
        if not (
            lldb_test
            and configuration.test_build_dir
            and test_subdir
            and test_name
            and (not os.path.isabs(test_subdir))
        ):
            raise Exception("Could not derive test directories")
        build_dir = os.path.join(configuration.test_build_dir, test_subdir, test_name)
        src_dir = os.path.join(configuration.test_src_root, test_subdir)
        # This is a bit of a hack to make inline testcases work.
        makefile = os.path.join(src_dir, "Makefile")
        if not os.path.isfile(makefile):
            makefile = os.path.join(build_dir, "Makefile")
        return [
            configuration.make_path,
            "VPATH=" + src_dir,
            "-C",
            build_dir,
            "-I",
            src_dir,
            "-I",
            os.path.join(lldb_test, "make"),
            "-f",
            makefile,
        ]

    def getCmdLine(self, d):
        """
        Helper function to return a command line argument string used for the
        make system.
        """

        # If d is None or an empty mapping, just return an empty list.
        if not d:
            return []

        def setOrAppendVariable(k, v):
            append_vars = ["CFLAGS", "CFLAGS_EXTRAS", "LD_EXTRAS"]
            if k in append_vars and k in os.environ:
                v = os.environ[k] + " " + v
            return "%s=%s" % (k, v)

        cmdline = [setOrAppendVariable(k, v) for k, v in list(d.items())]

        return cmdline

    def getArchSpec(self, architecture):
        """
        Helper function to return the key-value string to specify the architecture
        used for the make system.
        """
        return ["ARCH=" + architecture] if architecture else []

    def getToolchainSpec(self, compiler):
        """
        Helper function to return the key-value strings to specify the toolchain
        used for the make system.
        """
        cc = compiler if compiler else None
        if not cc and configuration.compiler:
            cc = configuration.compiler

        if not cc:
            return []

        exe_ext = ""
        if lldbplatformutil.getHostPlatform() == "windows":
            exe_ext = ".exe"

        cc = cc.strip()
        cc_path = pathlib.Path(cc)

        # We can get CC compiler string in the following formats:
        #  [<tool>] <compiler>    - such as 'xrun clang', 'xrun /usr/bin/clang' & etc
        #
        # Where <compiler> could contain the following parts:
        #   <simple-name>[.<exe-ext>]                           - sucn as 'clang', 'clang.exe' ('clang-cl.exe'?)
        #   <target-triple>-<simple-name>[.<exe-ext>]           - such as 'armv7-linux-gnueabi-gcc'
        #   <path>/<simple-name>[.<exe-ext>]                    - such as '/usr/bin/clang', 'c:\path\to\compiler\clang,exe'
        #   <path>/<target-triple>-<simple-name>[.<exe-ext>]    - such as '/usr/bin/clang', 'c:\path\to\compiler\clang,exe'

        cc_ext = cc_path.suffix
        # Compiler name without extension
        cc_name = cc_path.stem.split(" ")[-1]

        # A kind of compiler (canonical name): clang, gcc, cc & etc.
        cc_type = cc_name
        # A triple prefix of compiler name: <armv7-none-linux-gnu->gcc
        cc_prefix = ""
        if not "clang-cl" in cc_name and not "llvm-gcc" in cc_name:
            cc_name_parts = cc_name.split("-")
            cc_type = cc_name_parts[-1]
            if len(cc_name_parts) > 1:
                cc_prefix = "-".join(cc_name_parts[:-1]) + "-"

        # A kind of C++ compiler.
        cxx_types = {
            "icc": "icpc",
            "llvm-gcc": "llvm-g++",
            "gcc": "g++",
            "cc": "c++",
            "clang": "clang++",
        }
        cxx_type = cxx_types.get(cc_type, cc_type)

        cc_dir = cc_path.parent

        def getToolchainUtil(util_name):
            return os.path.join(configuration.llvm_tools_dir, util_name + exe_ext)

        cxx = cc_dir / (cc_prefix + cxx_type + cc_ext)

        util_names = {
            "OBJCOPY": "objcopy",
            "STRIP": "strip",
            "ARCHIVER": "ar",
            "DWP": "dwp",
        }
        utils = []

        # Required by API TestBSDArchives.py tests.
        if not os.getenv("LLVM_AR"):
            utils.extend(["LLVM_AR=%s" % getToolchainUtil("llvm-ar")])

        if cc_type in ["clang", "cc", "gcc"]:
            util_paths = {}
            # Assembly a toolchain side tool cmd based on passed CC.
            for var, name in util_names.items():
                # Do not override explicity specified tool from the cmd line.
                if not os.getenv(var):
                    util_paths[var] = getToolchainUtil("llvm-" + name)
                else:
                    util_paths[var] = os.getenv(var)
            utils.extend(["AR=%s" % util_paths["ARCHIVER"]])

            # Look for llvm-dwp or gnu dwp
            if not lldbutil.which(util_paths["DWP"]):
                util_paths["DWP"] = getToolchainUtil("llvm-dwp")
            if not lldbutil.which(util_paths["DWP"]):
                util_paths["DWP"] = lldbutil.which("llvm-dwp")
            if not util_paths["DWP"]:
                util_paths["DWP"] = lldbutil.which("dwp")
                if not util_paths["DWP"]:
                    del util_paths["DWP"]

            if lldbplatformutil.platformIsDarwin():
                util_paths["STRIP"] = seven.get_command_output("xcrun -f strip")

            for var, path in util_paths.items():
                utils.append("%s=%s" % (var, path))

        if lldbplatformutil.platformIsDarwin():
            utils.extend(["AR=%slibtool" % os.getenv("CROSS_COMPILE", "")])

        return [
            "CC=%s" % cc,
            "CC_TYPE=%s" % cc_type,
            "CXX=%s" % cxx,
        ] + utils

    def getSDKRootSpec(self):
        """
        Helper function to return the key-value string to specify the SDK root
        used for the make system.
        """
        if configuration.sdkroot:
            return ["SDKROOT={}".format(configuration.sdkroot)]
        return []

    def getModuleCacheSpec(self):
        """
        Helper function to return the key-value string to specify the clang
        module cache used for the make system.
        """
        if configuration.clang_module_cache_dir:
            return [
                "CLANG_MODULE_CACHE_DIR={}".format(configuration.clang_module_cache_dir)
            ]
        return []

    def getLibCxxArgs(self):
        if configuration.libcxx_include_dir and configuration.libcxx_library_dir:
            libcpp_args = [
                "LIBCPP_INCLUDE_DIR={}".format(configuration.libcxx_include_dir),
                "LIBCPP_LIBRARY_DIR={}".format(configuration.libcxx_library_dir),
            ]
            if configuration.libcxx_include_target_dir:
                libcpp_args.append(
                    "LIBCPP_INCLUDE_TARGET_DIR={}".format(
                        configuration.libcxx_include_target_dir
                    )
                )
            return libcpp_args
        return []

    def getLLDBObjRoot(self):
        return ["LLDB_OBJ_ROOT={}".format(configuration.lldb_obj_root)]

    def _getDebugInfoArgs(self, debug_info):
        if debug_info is None:
            return []

        debug_options = debug_info if isinstance(debug_info, list) else [debug_info]
        option_flags = {
            "dwarf": {"MAKE_DSYM": "NO"},
            "dwo": {"MAKE_DSYM": "NO", "MAKE_DWO": "YES"},
            "gmodules": {"MAKE_DSYM": "NO", "MAKE_GMODULES": "YES"},
            "debug_names": {"MAKE_DEBUG_NAMES": "YES"},
            "dwp": {"MAKE_DSYM": "NO", "MAKE_DWP": "YES"},
        }

        # Collect all flags, with later options overriding earlier ones
        flags = {}

        for option in debug_options:
            if not option or option not in option_flags:
                return None  # Invalid options
            flags.update(option_flags[option])

        return [f"{key}={value}" for key, value in flags.items()]

    def getBuildCommand(
        self,
        debug_info,
        architecture=None,
        compiler=None,
        dictionary=None,
        testdir=None,
        testname=None,
        make_targets=None,
    ):
        debug_info_args = self._getDebugInfoArgs(debug_info)
        if debug_info_args is None:
            return None
        if make_targets is None:
            make_targets = ["all"]
        command_parts = [
            self.getMake(testdir, testname),
            debug_info_args,
            make_targets,
            self.getArchCFlags(architecture),
            self.getArchSpec(architecture),
            self.getToolchainSpec(compiler),
            self.getExtraMakeArgs(),
            self.getSDKRootSpec(),
            self.getModuleCacheSpec(),
            self.getLibCxxArgs(),
            self.getLLDBObjRoot(),
            self.getCmdLine(dictionary),
        ]
        command = list(itertools.chain(*command_parts))

        return command

    def cleanup(self, dictionary=None):
        """Perform a platform-specific cleanup after the test."""
        return True