xref: /llvm-project/lldb/packages/Python/lldbsuite/test/lldbinline.py (revision 9bdd03f7da67b60a099237e4885c10d70ff30a7c)
1from __future__ import print_function
2from __future__ import absolute_import
3
4# System modules
5import os
6
7# Third-party modules
8
9# LLDB modules
10import lldb
11from .lldbtest import *
12from . import configuration
13from . import lldbutil
14from .decorators import *
15
16
17def source_type(filename):
18    _, extension = os.path.splitext(filename)
19    return {
20        '.c': 'C_SOURCES',
21        '.cpp': 'CXX_SOURCES',
22        '.cxx': 'CXX_SOURCES',
23        '.cc': 'CXX_SOURCES',
24        '.m': 'OBJC_SOURCES',
25        '.mm': 'OBJCXX_SOURCES'
26    }.get(extension, None)
27
28
29class CommandParser:
30
31    def __init__(self):
32        self.breakpoints = []
33
34    def parse_one_command(self, line):
35        parts = line.split('//%')
36
37        command = None
38        new_breakpoint = True
39
40        if len(parts) == 2:
41            command = parts[1].strip()  # take off whitespace
42            new_breakpoint = parts[0].strip() != ""
43
44        return (command, new_breakpoint)
45
46    def parse_source_files(self, source_files):
47        for source_file in source_files:
48            file_handle = open(source_file)
49            lines = file_handle.readlines()
50            line_number = 0
51            # non-NULL means we're looking through whitespace to find
52            # additional commands
53            current_breakpoint = None
54            for line in lines:
55                line_number = line_number + 1  # 1-based, so we do this first
56                (command, new_breakpoint) = self.parse_one_command(line)
57
58                if new_breakpoint:
59                    current_breakpoint = None
60
61                if command is not None:
62                    if current_breakpoint is None:
63                        current_breakpoint = {}
64                        current_breakpoint['file_name'] = source_file
65                        current_breakpoint['line_number'] = line_number
66                        current_breakpoint['command'] = command
67                        self.breakpoints.append(current_breakpoint)
68                    else:
69                        current_breakpoint['command'] = current_breakpoint[
70                            'command'] + "\n" + command
71
72    def set_breakpoints(self, target):
73        for breakpoint in self.breakpoints:
74            breakpoint['breakpoint'] = target.BreakpointCreateByLocation(
75                breakpoint['file_name'], breakpoint['line_number'])
76
77    def handle_breakpoint(self, test, breakpoint_id):
78        for breakpoint in self.breakpoints:
79            if breakpoint['breakpoint'].GetID() == breakpoint_id:
80                test.execute_user_command(breakpoint['command'])
81                return
82
83
84class InlineTest(TestBase):
85    # Internal implementation
86
87    def getRerunArgs(self):
88        # The -N option says to NOT run a if it matches the option argument, so
89        # if we are using dSYM we say to NOT run dwarf (-N dwarf) and vice
90        # versa.
91        if self.using_dsym is None:
92            # The test was skipped altogether.
93            return ""
94        elif self.using_dsym:
95            return "-N dwarf " + self.mydir
96        else:
97            return "-N dsym " + self.mydir
98
99    def BuildMakefile(self):
100        self.makeBuildDir()
101        makefilePath = self.getBuildArtifact("Makefile")
102        if os.path.exists(makefilePath):
103            return
104
105        categories = {}
106
107        for f in os.listdir(self.getSourceDir()):
108            t = source_type(f)
109            if t:
110                if t in list(categories.keys()):
111                    categories[t].append(f)
112                else:
113                    categories[t] = [f]
114
115        makefile = open(makefilePath, 'w+')
116
117        level = os.sep.join(
118            [".."] * len(self.mydir.split(os.sep))) + os.sep + "make"
119
120        makefile.write("LEVEL = " + level + "\n")
121
122        for t in list(categories.keys()):
123            line = t + " := " + " ".join(categories[t])
124            makefile.write(line + "\n")
125
126        if ('OBJCXX_SOURCES' in list(categories.keys())) or (
127                'OBJC_SOURCES' in list(categories.keys())):
128            makefile.write(
129                "LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n")
130
131        if ('CXX_SOURCES' in list(categories.keys())):
132            makefile.write("CXXFLAGS += -std=c++11\n")
133
134        makefile.write("include $(LEVEL)/Makefile.rules\n")
135        makefile.write("\ncleanup:\n\trm -f Makefile *.d\n\n")
136        makefile.flush()
137        makefile.close()
138
139    @add_test_categories(["dsym"])
140    def __test_with_dsym(self):
141        self.using_dsym = True
142        self.BuildMakefile()
143        self.build()
144        self.do_test()
145    __test_with_dsym.debug_info = "dsym"
146
147    @add_test_categories(["dwarf"])
148    def __test_with_dwarf(self):
149        self.using_dsym = False
150        self.BuildMakefile()
151        self.build()
152        self.do_test()
153    __test_with_dwarf.debug_info = "dwarf"
154
155    @add_test_categories(["dwo"])
156    def __test_with_dwo(self):
157        self.using_dsym = False
158        self.BuildMakefile()
159        self.build()
160        self.do_test()
161    __test_with_dwo.debug_info = "dwo"
162
163    @add_test_categories(["gmodules"])
164    def __test_with_gmodules(self):
165        self.using_dsym = False
166        self.BuildMakefile()
167        self.build()
168        self.do_test()
169    __test_with_gmodules.debug_info = "gmodules"
170
171    def execute_user_command(self, __command):
172        exec(__command, globals(), locals())
173
174    def do_test(self):
175        exe = self.getBuildArtifact("a.out")
176        source_files = [f for f in os.listdir(self.getSourceDir())
177                        if source_type(f)]
178        target = self.dbg.CreateTarget(exe)
179
180        parser = CommandParser()
181        parser.parse_source_files(source_files)
182        parser.set_breakpoints(target)
183
184        process = target.LaunchSimple(None, None, self.get_process_working_directory())
185        hit_breakpoints = 0
186
187        while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint):
188            hit_breakpoints += 1
189            thread = lldbutil.get_stopped_thread(
190                process, lldb.eStopReasonBreakpoint)
191            breakpoint_id = thread.GetStopReasonDataAtIndex(0)
192            parser.handle_breakpoint(self, breakpoint_id)
193            process.Continue()
194
195        self.assertTrue(hit_breakpoints > 0,
196                        "inline test did not hit a single breakpoint")
197        # Either the process exited or the stepping plan is complete.
198        self.assertTrue(process.GetState() in [lldb.eStateStopped,
199                                               lldb.eStateExited],
200                        PROCESS_EXITED)
201
202    # Utilities for testcases
203
204    def check_expression(self, expression, expected_result, use_summary=True):
205        value = self.frame().EvaluateExpression(expression)
206        self.assertTrue(value.IsValid(), expression + "returned a valid value")
207        if self.TraceOn():
208            print(value.GetSummary())
209            print(value.GetValue())
210        if use_summary:
211            answer = value.GetSummary()
212        else:
213            answer = value.GetValue()
214        report_str = "%s expected: %s got: %s" % (
215            expression, expected_result, answer)
216        self.assertTrue(answer == expected_result, report_str)
217
218
219def ApplyDecoratorsToFunction(func, decorators):
220    tmp = func
221    if isinstance(decorators, list):
222        for decorator in decorators:
223            tmp = decorator(tmp)
224    elif hasattr(decorators, '__call__'):
225        tmp = decorators(tmp)
226    return tmp
227
228
229def MakeInlineTest(__file, __globals, decorators=None):
230    # Adjust the filename if it ends in .pyc.  We want filenames to
231    # reflect the source python file, not the compiled variant.
232    if __file is not None and __file.endswith(".pyc"):
233        # Strip the trailing "c"
234        __file = __file[0:-1]
235
236    # Derive the test name from the current file name
237    file_basename = os.path.basename(__file)
238    InlineTest.mydir = TestBase.compute_mydir(__file)
239
240    test_name, _ = os.path.splitext(file_basename)
241    # Build the test case
242    test = type(test_name, (InlineTest,), {'using_dsym': None})
243    test.name = test_name
244
245    target_platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
246    if test_categories.is_supported_on_platform(
247            "dsym", target_platform, configuration.compiler):
248        test.test_with_dsym = ApplyDecoratorsToFunction(
249            test._InlineTest__test_with_dsym, decorators)
250    if test_categories.is_supported_on_platform(
251            "dwarf", target_platform, configuration.compiler):
252        test.test_with_dwarf = ApplyDecoratorsToFunction(
253            test._InlineTest__test_with_dwarf, decorators)
254    if test_categories.is_supported_on_platform(
255            "dwo", target_platform, configuration.compiler):
256        test.test_with_dwo = ApplyDecoratorsToFunction(
257            test._InlineTest__test_with_dwo, decorators)
258    if test_categories.is_supported_on_platform(
259            "gmodules", target_platform, configuration.compiler):
260        test.test_with_gmodules = ApplyDecoratorsToFunction(
261            test._InlineTest__test_with_gmodules, decorators)
262
263    # Add the test case to the globals, and hide InlineTest
264    __globals.update({test_name: test})
265
266    # Keep track of the original test filename so we report it
267    # correctly in test results.
268    test.test_filename = __file
269    return test
270