xref: /llvm-project/lldb/packages/Python/lldbsuite/test/lldbinline.py (revision 89c77054a245e932091e05da35f38faae6e42b06)
1from __future__ import print_function
2from __future__ import absolute_import
3
4# System modules
5import os
6
7# Third-party modules
8import io
9
10# LLDB modules
11import lldb
12from .lldbtest import *
13from . import configuration
14from . import lldbutil
15from .decorators import *
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 = io.open(source_file, encoding='utf-8')
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 BuildMakefile(self):
88        makefilePath = self.getBuildArtifact("Makefile")
89        if os.path.exists(makefilePath):
90            return
91
92        categories = {}
93
94        for f in os.listdir(self.getSourceDir()):
95            t = source_type(f)
96            if t:
97                if t in list(categories.keys()):
98                    categories[t].append(f)
99                else:
100                    categories[t] = [f]
101
102        makefile = open(makefilePath, 'w+')
103
104        level = os.sep.join(
105            [".."] * len(self.mydir.split(os.sep))) + os.sep + "make"
106
107        makefile.write("LEVEL = " + level + "\n")
108
109        for t in list(categories.keys()):
110            line = t + " := " + " ".join(categories[t])
111            makefile.write(line + "\n")
112
113        if ('OBJCXX_SOURCES' in list(categories.keys())) or (
114                'OBJC_SOURCES' in list(categories.keys())):
115            makefile.write(
116                "LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n")
117
118        if ('CXX_SOURCES' in list(categories.keys())):
119            makefile.write("CXXFLAGS += -std=c++11\n")
120
121        makefile.write("include $(LEVEL)/Makefile.rules\n")
122        makefile.write("\ncleanup:\n\trm -f Makefile *.d\n\n")
123        makefile.flush()
124        makefile.close()
125
126    def _test(self):
127        self.BuildMakefile()
128        self.build()
129        self.do_test()
130
131    def execute_user_command(self, __command):
132        exec(__command, globals(), locals())
133
134    def do_test(self):
135        exe = self.getBuildArtifact("a.out")
136        source_files = [f for f in os.listdir(self.getSourceDir())
137                        if source_type(f)]
138        target = self.dbg.CreateTarget(exe)
139
140        parser = CommandParser()
141        parser.parse_source_files(source_files)
142        parser.set_breakpoints(target)
143
144        process = target.LaunchSimple(None, None, self.get_process_working_directory())
145        hit_breakpoints = 0
146
147        while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint):
148            hit_breakpoints += 1
149            thread = lldbutil.get_stopped_thread(
150                process, lldb.eStopReasonBreakpoint)
151            breakpoint_id = thread.GetStopReasonDataAtIndex(0)
152            parser.handle_breakpoint(self, breakpoint_id)
153            process.Continue()
154
155        self.assertTrue(hit_breakpoints > 0,
156                        "inline test did not hit a single breakpoint")
157        # Either the process exited or the stepping plan is complete.
158        self.assertTrue(process.GetState() in [lldb.eStateStopped,
159                                               lldb.eStateExited],
160                        PROCESS_EXITED)
161
162    # Utilities for testcases
163
164    def check_expression(self, expression, expected_result, use_summary=True):
165        value = self.frame().EvaluateExpression(expression)
166        self.assertTrue(value.IsValid(), expression + "returned a valid value")
167        if self.TraceOn():
168            print(value.GetSummary())
169            print(value.GetValue())
170        if use_summary:
171            answer = value.GetSummary()
172        else:
173            answer = value.GetValue()
174        report_str = "%s expected: %s got: %s" % (
175            expression, expected_result, answer)
176        self.assertTrue(answer == expected_result, report_str)
177
178
179def ApplyDecoratorsToFunction(func, decorators):
180    tmp = func
181    if isinstance(decorators, list):
182        for decorator in decorators:
183            tmp = decorator(tmp)
184    elif hasattr(decorators, '__call__'):
185        tmp = decorators(tmp)
186    return tmp
187
188
189def MakeInlineTest(__file, __globals, decorators=None):
190    # Adjust the filename if it ends in .pyc.  We want filenames to
191    # reflect the source python file, not the compiled variant.
192    if __file is not None and __file.endswith(".pyc"):
193        # Strip the trailing "c"
194        __file = __file[0:-1]
195
196    # Derive the test name from the current file name
197    file_basename = os.path.basename(__file)
198
199    test_name, _ = os.path.splitext(file_basename)
200
201    test_func = ApplyDecoratorsToFunction(InlineTest._test, decorators)
202    # Build the test case
203    test_class = type(test_name, (InlineTest,), dict(test=test_func, name=test_name))
204
205    # Add the test case to the globals, and hide InlineTest
206    __globals.update({test_name: test_class})
207
208    # Keep track of the original test filename so we report it
209    # correctly in test results.
210    test_class.test_filename = __file
211    test_class.mydir = TestBase.compute_mydir(__file)
212    return test_class
213