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