xref: /llvm-project/lldb/packages/Python/lldbsuite/test/lldbinline.py (revision fdfeefd6c29b2f26b69c63bd0a90a9915b94d956)
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        makefilePath = self.getBuildArtifact("Makefile")
101        if os.path.exists(makefilePath):
102            return
103
104        categories = {}
105
106        for f in os.listdir(self.getSourceDir()):
107            t = source_type(f)
108            if t:
109                if t in list(categories.keys()):
110                    categories[t].append(f)
111                else:
112                    categories[t] = [f]
113
114        makefile = open(makefilePath, 'w+')
115
116        level = os.sep.join(
117            [".."] * len(self.mydir.split(os.sep))) + os.sep + "make"
118
119        makefile.write("LEVEL = " + level + "\n")
120
121        for t in list(categories.keys()):
122            line = t + " := " + " ".join(categories[t])
123            makefile.write(line + "\n")
124
125        if ('OBJCXX_SOURCES' in list(categories.keys())) or (
126                'OBJC_SOURCES' in list(categories.keys())):
127            makefile.write(
128                "LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n")
129
130        if ('CXX_SOURCES' in list(categories.keys())):
131            makefile.write("CXXFLAGS += -std=c++11\n")
132
133        makefile.write("include $(LEVEL)/Makefile.rules\n")
134        makefile.write("\ncleanup:\n\trm -f Makefile *.d\n\n")
135        makefile.flush()
136        makefile.close()
137
138    @add_test_categories(["dsym"])
139    def __test_with_dsym(self):
140        self.using_dsym = True
141        self.BuildMakefile()
142        self.build()
143        self.do_test()
144    __test_with_dsym.debug_info = "dsym"
145
146    @add_test_categories(["dwarf"])
147    def __test_with_dwarf(self):
148        self.using_dsym = False
149        self.BuildMakefile()
150        self.build()
151        self.do_test()
152    __test_with_dwarf.debug_info = "dwarf"
153
154    @add_test_categories(["dwo"])
155    def __test_with_dwo(self):
156        self.using_dsym = False
157        self.BuildMakefile()
158        self.build()
159        self.do_test()
160    __test_with_dwo.debug_info = "dwo"
161
162    @add_test_categories(["gmodules"])
163    def __test_with_gmodules(self):
164        self.using_dsym = False
165        self.BuildMakefile()
166        self.build()
167        self.do_test()
168    __test_with_gmodules.debug_info = "gmodules"
169
170    def execute_user_command(self, __command):
171        exec(__command, globals(), locals())
172
173    def do_test(self):
174        exe = self.getBuildArtifact("a.out")
175        source_files = [f for f in os.listdir(self.getSourceDir())
176                        if source_type(f)]
177        target = self.dbg.CreateTarget(exe)
178
179        parser = CommandParser()
180        parser.parse_source_files(source_files)
181        parser.set_breakpoints(target)
182
183        process = target.LaunchSimple(None, None, self.get_process_working_directory())
184        hit_breakpoints = 0
185
186        while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint):
187            hit_breakpoints += 1
188            thread = lldbutil.get_stopped_thread(
189                process, lldb.eStopReasonBreakpoint)
190            breakpoint_id = thread.GetStopReasonDataAtIndex(0)
191            parser.handle_breakpoint(self, breakpoint_id)
192            process.Continue()
193
194        self.assertTrue(hit_breakpoints > 0,
195                        "inline test did not hit a single breakpoint")
196        # Either the process exited or the stepping plan is complete.
197        self.assertTrue(process.GetState() in [lldb.eStateStopped,
198                                               lldb.eStateExited],
199                        PROCESS_EXITED)
200
201    # Utilities for testcases
202
203    def check_expression(self, expression, expected_result, use_summary=True):
204        value = self.frame().EvaluateExpression(expression)
205        self.assertTrue(value.IsValid(), expression + "returned a valid value")
206        if self.TraceOn():
207            print(value.GetSummary())
208            print(value.GetValue())
209        if use_summary:
210            answer = value.GetSummary()
211        else:
212            answer = value.GetValue()
213        report_str = "%s expected: %s got: %s" % (
214            expression, expected_result, answer)
215        self.assertTrue(answer == expected_result, report_str)
216
217
218def ApplyDecoratorsToFunction(func, decorators):
219    tmp = func
220    if isinstance(decorators, list):
221        for decorator in decorators:
222            tmp = decorator(tmp)
223    elif hasattr(decorators, '__call__'):
224        tmp = decorators(tmp)
225    return tmp
226
227
228def MakeInlineTest(__file, __globals, decorators=None):
229    # Adjust the filename if it ends in .pyc.  We want filenames to
230    # reflect the source python file, not the compiled variant.
231    if __file is not None and __file.endswith(".pyc"):
232        # Strip the trailing "c"
233        __file = __file[0:-1]
234
235    # Derive the test name from the current file name
236    file_basename = os.path.basename(__file)
237    InlineTest.mydir = TestBase.compute_mydir(__file)
238
239    test_name, _ = os.path.splitext(file_basename)
240    # Build the test case
241    test = type(test_name, (InlineTest,), {'using_dsym': None})
242    test.name = test_name
243
244    test.test_with_dsym = ApplyDecoratorsToFunction(
245        test._InlineTest__test_with_dsym, decorators)
246    test.test_with_dwarf = ApplyDecoratorsToFunction(
247        test._InlineTest__test_with_dwarf, decorators)
248    test.test_with_dwo = ApplyDecoratorsToFunction(
249        test._InlineTest__test_with_dwo, decorators)
250    test.test_with_gmodules = ApplyDecoratorsToFunction(
251        test._InlineTest__test_with_gmodules, decorators)
252
253    # Add the test case to the globals, and hide InlineTest
254    __globals.update({test_name: test})
255
256    # Keep track of the original test filename so we report it
257    # correctly in test results.
258    test.test_filename = __file
259    return test
260