xref: /llvm-project/lldb/test/API/python_api/thread/TestThreadAPI.py (revision 0f821339dad1bf45dd71a1cac32b6352ba251ecb)
1"""
2Test SBThread APIs.
3"""
4
5from __future__ import print_function
6
7
8import lldb
9from lldbsuite.test.decorators import *
10from lldbsuite.test.lldbtest import *
11from lldbsuite.test import lldbutil
12from lldbsuite.test.lldbutil import get_stopped_thread, get_caller_symbol
13
14
15class ThreadAPITestCase(TestBase):
16
17    def test_get_process(self):
18        """Test Python SBThread.GetProcess() API."""
19        self.build()
20        self.get_process()
21
22    def test_get_stop_description(self):
23        """Test Python SBThread.GetStopDescription() API."""
24        self.build()
25        self.get_stop_description()
26
27    def test_run_to_address(self):
28        """Test Python SBThread.RunToAddress() API."""
29        # We build a different executable than the default build() does.
30        d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name}
31        self.build(dictionary=d)
32        self.setTearDownCleanup(dictionary=d)
33        self.run_to_address(self.exe_name)
34
35    @skipIfAsan # The output looks different under ASAN.
36    @expectedFailureAll(oslist=["linux"], archs=['arm'], bugnumber="llvm.org/pr45892")
37    @expectedFailureAll(oslist=["windows"])
38    def test_step_out_of_malloc_into_function_b(self):
39        """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b()."""
40        # We build a different executable than the default build() does.
41        d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name}
42        self.build(dictionary=d)
43        self.setTearDownCleanup(dictionary=d)
44        self.step_out_of_malloc_into_function_b(self.exe_name)
45
46    def test_step_over_3_times(self):
47        """Test Python SBThread.StepOver() API."""
48        # We build a different executable than the default build() does.
49        d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name}
50        self.build(dictionary=d)
51        self.setTearDownCleanup(dictionary=d)
52        self.step_over_3_times(self.exe_name)
53
54    def setUp(self):
55        # Call super's setUp().
56        TestBase.setUp(self)
57        # Find the line number within main.cpp to break inside main().
58        self.break_line = line_number(
59            "main.cpp", "// Set break point at this line and check variable 'my_char'.")
60        # Find the line numbers within main2.cpp for
61        # step_out_of_malloc_into_function_b() and step_over_3_times().
62        self.step_out_of_malloc = line_number(
63            "main2.cpp", "// thread step-out of malloc into function b.")
64        self.after_3_step_overs = line_number(
65            "main2.cpp", "// we should reach here after 3 step-over's.")
66
67        # We'll use the test method name as the exe_name for executable
68        # compiled from main2.cpp.
69        self.exe_name = self.testMethodName
70
71    def get_process(self):
72        """Test Python SBThread.GetProcess() API."""
73        exe = self.getBuildArtifact("a.out")
74
75        target = self.dbg.CreateTarget(exe)
76        self.assertTrue(target, VALID_TARGET)
77
78        breakpoint = target.BreakpointCreateByLocation(
79            "main.cpp", self.break_line)
80        self.assertTrue(breakpoint, VALID_BREAKPOINT)
81        self.runCmd("breakpoint list")
82
83        # Launch the process, and do not stop at the entry point.
84        process = target.LaunchSimple(
85            None, None, self.get_process_working_directory())
86
87        thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
88        self.assertTrue(
89            thread.IsValid(),
90            "There should be a thread stopped due to breakpoint")
91        self.runCmd("process status")
92
93        proc_of_thread = thread.GetProcess()
94        self.trace("proc_of_thread:", proc_of_thread)
95        self.assertEqual(proc_of_thread.GetProcessID(), process.GetProcessID())
96
97    def get_stop_description(self):
98        """Test Python SBThread.GetStopDescription() API."""
99        exe = self.getBuildArtifact("a.out")
100
101        target = self.dbg.CreateTarget(exe)
102        self.assertTrue(target, VALID_TARGET)
103
104        breakpoint = target.BreakpointCreateByLocation(
105            "main.cpp", self.break_line)
106        self.assertTrue(breakpoint, VALID_BREAKPOINT)
107        #self.runCmd("breakpoint list")
108
109        # Launch the process, and do not stop at the entry point.
110        process = target.LaunchSimple(
111            None, None, self.get_process_working_directory())
112
113        thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
114        self.assertTrue(
115            thread.IsValid(),
116            "There should be a thread stopped due to breakpoint")
117
118        # Get the stop reason. GetStopDescription expects that we pass in the size of the description
119        # we expect plus an additional byte for the null terminator.
120
121        # Test with a buffer that is exactly as large as the expected stop reason.
122        self.assertEqual("breakpoint 1.1", thread.GetStopDescription(len('breakpoint 1.1') + 1))
123
124        # Test some smaller buffer sizes.
125        self.assertEqual("breakpoint", thread.GetStopDescription(len('breakpoint') + 1))
126        self.assertEqual("break", thread.GetStopDescription(len('break') + 1))
127        self.assertEqual("b", thread.GetStopDescription(len('b') + 1))
128
129        # Test that we can pass in a much larger size and still get the right output.
130        self.assertEqual("breakpoint 1.1", thread.GetStopDescription(len('breakpoint 1.1') + 100))
131
132    def step_out_of_malloc_into_function_b(self, exe_name):
133        """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b()."""
134        exe = self.getBuildArtifact(exe_name)
135
136        target = self.dbg.CreateTarget(exe)
137        self.assertTrue(target, VALID_TARGET)
138
139        breakpoint = target.BreakpointCreateByName('malloc')
140        self.assertTrue(breakpoint, VALID_BREAKPOINT)
141
142        # Launch the process, and do not stop at the entry point.
143        process = target.LaunchSimple(
144            None, None, self.get_process_working_directory())
145
146        while True:
147            thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
148            self.assertTrue(
149                thread.IsValid(),
150                "There should be a thread stopped due to breakpoint")
151            caller_symbol = get_caller_symbol(thread)
152            if not caller_symbol:
153                self.fail(
154                    "Test failed: could not locate the caller symbol of malloc")
155
156            # Our top frame may be an inlined function in malloc() (e.g., on
157            # FreeBSD).  Apply a simple heuristic of stepping out until we find
158            # a non-malloc caller
159            while caller_symbol.startswith("malloc"):
160                thread.StepOut()
161                self.assertTrue(thread.IsValid(),
162                                "Thread valid after stepping to outer malloc")
163                caller_symbol = get_caller_symbol(thread)
164
165            if caller_symbol == "b(int)":
166                break
167            process.Continue()
168
169        # On Linux malloc calls itself in some case. Remove the breakpoint because we don't want
170        # to hit it during step-out.
171        target.BreakpointDelete(breakpoint.GetID())
172
173        thread.StepOut()
174        self.runCmd("thread backtrace")
175        self.assertEqual(
176            thread.GetFrameAtIndex(0).GetLineEntry().GetLine(), self.step_out_of_malloc,
177            "step out of malloc into function b is successful")
178
179    def step_over_3_times(self, exe_name):
180        """Test Python SBThread.StepOver() API."""
181        exe = self.getBuildArtifact(exe_name)
182
183        target = self.dbg.CreateTarget(exe)
184        self.assertTrue(target, VALID_TARGET)
185
186        breakpoint = target.BreakpointCreateByLocation(
187            'main2.cpp', self.step_out_of_malloc)
188        self.assertTrue(breakpoint, VALID_BREAKPOINT)
189        self.runCmd("breakpoint list")
190
191        # Launch the process, and do not stop at the entry point.
192        process = target.LaunchSimple(
193            None, None, self.get_process_working_directory())
194
195        self.assertTrue(process, PROCESS_IS_VALID)
196
197        # Frame #0 should be on self.step_out_of_malloc.
198        self.assertState(process.GetState(), lldb.eStateStopped)
199        thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
200        self.assertTrue(
201            thread.IsValid(),
202            "There should be a thread stopped due to breakpoint condition")
203        self.runCmd("thread backtrace")
204        frame0 = thread.GetFrameAtIndex(0)
205        lineEntry = frame0.GetLineEntry()
206        self.assertEqual(lineEntry.GetLine(), self.step_out_of_malloc)
207
208        thread.StepOver()
209        thread.StepOver()
210        thread.StepOver()
211        self.runCmd("thread backtrace")
212
213        # Verify that we are stopped at the correct source line number in
214        # main2.cpp.
215        frame0 = thread.GetFrameAtIndex(0)
216        lineEntry = frame0.GetLineEntry()
217        self.assertStopReason(thread.GetStopReason(), lldb.eStopReasonPlanComplete)
218        # Expected failure with clang as the compiler.
219        # rdar://problem/9223880
220        #
221        # Which has been fixed on the lldb by compensating for inaccurate line
222        # table information with r140416.
223        self.assertEqual(lineEntry.GetLine(), self.after_3_step_overs)
224
225    def run_to_address(self, exe_name):
226        """Test Python SBThread.RunToAddress() API."""
227        exe = self.getBuildArtifact(exe_name)
228
229        target = self.dbg.CreateTarget(exe)
230        self.assertTrue(target, VALID_TARGET)
231
232        breakpoint = target.BreakpointCreateByLocation(
233            'main2.cpp', self.step_out_of_malloc)
234        self.assertTrue(breakpoint, VALID_BREAKPOINT)
235        self.runCmd("breakpoint list")
236
237        # Launch the process, and do not stop at the entry point.
238        process = target.LaunchSimple(
239            None, None, self.get_process_working_directory())
240
241        self.assertTrue(process, PROCESS_IS_VALID)
242
243        # Frame #0 should be on self.step_out_of_malloc.
244        self.assertState(process.GetState(), lldb.eStateStopped)
245        thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
246        self.assertTrue(
247            thread.IsValid(),
248            "There should be a thread stopped due to breakpoint condition")
249        self.runCmd("thread backtrace")
250        frame0 = thread.GetFrameAtIndex(0)
251        lineEntry = frame0.GetLineEntry()
252        self.assertEqual(lineEntry.GetLine(), self.step_out_of_malloc)
253
254        # Get the start/end addresses for this line entry.
255        start_addr = lineEntry.GetStartAddress().GetLoadAddress(target)
256        end_addr = lineEntry.GetEndAddress().GetLoadAddress(target)
257        if self.TraceOn():
258            print("start addr:", hex(start_addr))
259            print("end addr:", hex(end_addr))
260
261        # Disable the breakpoint.
262        self.assertTrue(target.DisableAllBreakpoints())
263        self.runCmd("breakpoint list")
264
265        thread.StepOver()
266        thread.StepOver()
267        thread.StepOver()
268        self.runCmd("thread backtrace")
269
270        # Now ask SBThread to run to the address 'start_addr' we got earlier, which
271        # corresponds to self.step_out_of_malloc line entry's start address.
272        thread.RunToAddress(start_addr)
273        self.runCmd("process status")
274        #self.runCmd("thread backtrace")
275