xref: /llvm-project/lldb/test/API/python_api/target/TestTargetAPI.py (revision 99451b4453688a94c6014cac233d371ab4cc342d)
1"""
2Test SBTarget APIs.
3"""
4
5from __future__ import print_function
6
7
8import unittest2
9import os
10import lldb
11from lldbsuite.test.decorators import *
12from lldbsuite.test.lldbtest import *
13from lldbsuite.test import lldbutil
14
15
16class TargetAPITestCase(TestBase):
17
18    mydir = TestBase.compute_mydir(__file__)
19
20    def setUp(self):
21        # Call super's setUp().
22        TestBase.setUp(self)
23        # Find the line number to of function 'c'.
24        self.line1 = line_number(
25            'main.c', '// Find the line number for breakpoint 1 here.')
26        self.line2 = line_number(
27            'main.c', '// Find the line number for breakpoint 2 here.')
28        self.line_main = line_number(
29            "main.c", "// Set a break at entry to main.")
30
31    # rdar://problem/9700873
32    # Find global variable value fails for dwarf if inferior not started
33    # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)
34    #
35    # It does not segfaults now.  But for dwarf, the variable value is None if
36    # the inferior process does not exist yet.  The radar has been updated.
37    #@unittest232.skip("segmentation fault -- skipping")
38    @add_test_categories(['pyapi'])
39    def test_find_global_variables(self):
40        """Exercise SBTarget.FindGlobalVariables() API."""
41        d = {'EXE': 'b.out'}
42        self.build(dictionary=d)
43        self.setTearDownCleanup(dictionary=d)
44        self.find_global_variables('b.out')
45
46    @add_test_categories(['pyapi'])
47    def test_find_compile_units(self):
48        """Exercise SBTarget.FindCompileUnits() API."""
49        d = {'EXE': 'b.out'}
50        self.build(dictionary=d)
51        self.setTearDownCleanup(dictionary=d)
52        self.find_compile_units(self.getBuildArtifact('b.out'))
53
54    @add_test_categories(['pyapi'])
55    @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778")
56    def test_find_functions(self):
57        """Exercise SBTarget.FindFunctions() API."""
58        d = {'EXE': 'b.out'}
59        self.build(dictionary=d)
60        self.setTearDownCleanup(dictionary=d)
61        self.find_functions('b.out')
62
63    @add_test_categories(['pyapi'])
64    def test_get_description(self):
65        """Exercise SBTarget.GetDescription() API."""
66        self.build()
67        self.get_description()
68
69    @add_test_categories(['pyapi'])
70    @expectedFailureAll(oslist=["windows"], bugnumber='llvm.org/pr21765')
71    def test_resolve_symbol_context_with_address(self):
72        """Exercise SBTarget.ResolveSymbolContextForAddress() API."""
73        self.build()
74        self.resolve_symbol_context_with_address()
75
76    @add_test_categories(['pyapi'])
77    def test_get_platform(self):
78        d = {'EXE': 'b.out'}
79        self.build(dictionary=d)
80        self.setTearDownCleanup(dictionary=d)
81        target = self.create_simple_target('b.out')
82        platform = target.platform
83        self.assertTrue(platform, VALID_PLATFORM)
84
85    @add_test_categories(['pyapi'])
86    def test_get_data_byte_size(self):
87        d = {'EXE': 'b.out'}
88        self.build(dictionary=d)
89        self.setTearDownCleanup(dictionary=d)
90        target = self.create_simple_target('b.out')
91        self.assertEqual(target.data_byte_size, 1)
92
93    @add_test_categories(['pyapi'])
94    def test_get_code_byte_size(self):
95        d = {'EXE': 'b.out'}
96        self.build(dictionary=d)
97        self.setTearDownCleanup(dictionary=d)
98        target = self.create_simple_target('b.out')
99        self.assertEqual(target.code_byte_size, 1)
100
101    @add_test_categories(['pyapi'])
102    def test_resolve_file_address(self):
103        d = {'EXE': 'b.out'}
104        self.build(dictionary=d)
105        self.setTearDownCleanup(dictionary=d)
106        target = self.create_simple_target('b.out')
107
108        # find the file address in the .data section of the main
109        # module
110        data_section = self.find_data_section(target)
111        data_section_addr = data_section.file_addr
112
113        # resolve the above address, and compare the address produced
114        # by the resolution against the original address/section
115        res_file_addr = target.ResolveFileAddress(data_section_addr)
116        self.assertTrue(res_file_addr.IsValid())
117
118        self.assertEqual(data_section_addr, res_file_addr.file_addr)
119
120        data_section2 = res_file_addr.section
121        self.assertIsNotNone(data_section2)
122        self.assertEqual(data_section.name, data_section2.name)
123
124    @add_test_categories(['pyapi'])
125    def test_read_memory(self):
126        d = {'EXE': 'b.out'}
127        self.build(dictionary=d)
128        self.setTearDownCleanup(dictionary=d)
129        target = self.create_simple_target('b.out')
130
131        breakpoint = target.BreakpointCreateByLocation(
132            "main.c", self.line_main)
133        self.assertTrue(breakpoint, VALID_BREAKPOINT)
134
135        # Put debugger into synchronous mode so when we target.LaunchSimple returns
136        # it will guaranteed to be at the breakpoint
137        self.dbg.SetAsync(False)
138
139        # Launch the process, and do not stop at the entry point.
140        process = target.LaunchSimple(
141            None, None, self.get_process_working_directory())
142
143        # find the file address in the .data section of the main
144        # module
145        data_section = self.find_data_section(target)
146        sb_addr = lldb.SBAddress(data_section, 0)
147        error = lldb.SBError()
148        content = target.ReadMemory(sb_addr, 1, error)
149        self.assertTrue(error.Success(), "Make sure memory read succeeded")
150        self.assertEqual(len(content), 1)
151
152    def create_simple_target(self, fn):
153        exe = self.getBuildArtifact(fn)
154        target = self.dbg.CreateTarget(exe)
155        self.assertTrue(target, VALID_TARGET)
156        return target
157
158    def find_data_section(self, target):
159        mod = target.GetModuleAtIndex(0)
160        data_section = None
161        for s in mod.sections:
162            sect_type = s.GetSectionType()
163            if sect_type == lldb.eSectionTypeData:
164                data_section = s
165                break
166            elif sect_type == lldb.eSectionTypeContainer:
167                for i in range(s.GetNumSubSections()):
168                    ss = s.GetSubSectionAtIndex(i)
169                    sect_type = ss.GetSectionType()
170                    if sect_type == lldb.eSectionTypeData:
171                        data_section = ss
172                        break
173
174        self.assertIsNotNone(data_section)
175        return data_section
176
177    def find_global_variables(self, exe_name):
178        """Exercise SBTaget.FindGlobalVariables() API."""
179        exe = self.getBuildArtifact(exe_name)
180
181        # Create a target by the debugger.
182        target = self.dbg.CreateTarget(exe)
183        self.assertTrue(target, VALID_TARGET)
184
185        # rdar://problem/9700873
186        # Find global variable value fails for dwarf if inferior not started
187        # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)
188        #
189        # Remove the lines to create a breakpoint and to start the inferior
190        # which are workarounds for the dwarf case.
191
192        breakpoint = target.BreakpointCreateByLocation('main.c', self.line1)
193        self.assertTrue(breakpoint, VALID_BREAKPOINT)
194
195        # Now launch the process, and do not stop at entry point.
196        process = target.LaunchSimple(
197            None, None, self.get_process_working_directory())
198        self.assertTrue(process, PROCESS_IS_VALID)
199        # Make sure we hit our breakpoint:
200        thread_list = lldbutil.get_threads_stopped_at_breakpoint(
201            process, breakpoint)
202        self.assertTrue(len(thread_list) == 1)
203
204        value_list = target.FindGlobalVariables(
205            'my_global_var_of_char_type', 3)
206        self.assertTrue(value_list.GetSize() == 1)
207        my_global_var = value_list.GetValueAtIndex(0)
208        self.DebugSBValue(my_global_var)
209        self.assertTrue(my_global_var)
210        self.expect(my_global_var.GetName(), exe=False,
211                    startstr="my_global_var_of_char_type")
212        self.expect(my_global_var.GetTypeName(), exe=False,
213                    startstr="char")
214        self.expect(my_global_var.GetValue(), exe=False,
215                    startstr="'X'")
216
217        # While we are at it, let's also exercise the similar
218        # SBModule.FindGlobalVariables() API.
219        for m in target.module_iter():
220            if os.path.normpath(m.GetFileSpec().GetDirectory()) == self.getBuildDir() and m.GetFileSpec().GetFilename() == exe_name:
221                value_list = m.FindGlobalVariables(
222                    target, 'my_global_var_of_char_type', 3)
223                self.assertTrue(value_list.GetSize() == 1)
224                self.assertTrue(
225                    value_list.GetValueAtIndex(0).GetValue() == "'X'")
226                break
227
228    def find_compile_units(self, exe):
229        """Exercise SBTarget.FindCompileUnits() API."""
230        source_name = "main.c"
231
232        # Create a target by the debugger.
233        target = self.dbg.CreateTarget(exe)
234        self.assertTrue(target, VALID_TARGET)
235
236        list = target.FindCompileUnits(lldb.SBFileSpec(source_name, False))
237        # Executable has been built just from one source file 'main.c',
238        # so we may check only the first element of list.
239        self.assertTrue(
240            list[0].GetCompileUnit().GetFileSpec().GetFilename() == source_name)
241
242    def find_functions(self, exe_name):
243        """Exercise SBTaget.FindFunctions() API."""
244        exe = self.getBuildArtifact(exe_name)
245
246        # Create a target by the debugger.
247        target = self.dbg.CreateTarget(exe)
248        self.assertTrue(target, VALID_TARGET)
249
250        list = target.FindFunctions('c', lldb.eFunctionNameTypeAuto)
251        self.assertTrue(list.GetSize() == 1)
252
253        for sc in list:
254            self.assertTrue(
255                sc.GetModule().GetFileSpec().GetFilename() == exe_name)
256            self.assertTrue(sc.GetSymbol().GetName() == 'c')
257
258    def get_description(self):
259        """Exercise SBTaget.GetDescription() API."""
260        exe = self.getBuildArtifact("a.out")
261
262        # Create a target by the debugger.
263        target = self.dbg.CreateTarget(exe)
264        self.assertTrue(target, VALID_TARGET)
265
266        from lldbsuite.test.lldbutil import get_description
267
268        # get_description() allows no option to mean
269        # lldb.eDescriptionLevelBrief.
270        desc = get_description(target)
271        #desc = get_description(target, option=lldb.eDescriptionLevelBrief)
272        if not desc:
273            self.fail("SBTarget.GetDescription() failed")
274        self.expect(desc, exe=False,
275                    substrs=['a.out'])
276        self.expect(desc, exe=False, matching=False,
277                    substrs=['Target', 'Module', 'Breakpoint'])
278
279        desc = get_description(target, option=lldb.eDescriptionLevelFull)
280        if not desc:
281            self.fail("SBTarget.GetDescription() failed")
282        self.expect(desc, exe=False,
283                    substrs=['a.out', 'Target', 'Module', 'Breakpoint'])
284
285    @not_remote_testsuite_ready
286    @add_test_categories(['pyapi'])
287    @no_debug_info_test
288    def test_launch_new_process_and_redirect_stdout(self):
289        """Exercise SBTaget.Launch() API with redirected stdout."""
290        self.build()
291        exe = self.getBuildArtifact("a.out")
292
293        # Create a target by the debugger.
294        target = self.dbg.CreateTarget(exe)
295        self.assertTrue(target, VALID_TARGET)
296
297        # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done.
298        # We should still see the entire stdout redirected once the process is
299        # finished.
300        line = line_number('main.c', '// a(3) -> c(3)')
301        breakpoint = target.BreakpointCreateByLocation('main.c', line)
302
303        # Now launch the process, do not stop at entry point, and redirect stdout to "stdout.txt" file.
304        # The inferior should run to completion after "process.Continue()"
305        # call.
306        local_path = self.getBuildArtifact("stdout.txt")
307        if os.path.exists(local_path):
308            os.remove(local_path)
309
310        if lldb.remote_platform:
311            stdout_path = lldbutil.append_to_process_working_directory(self,
312                "lldb-stdout-redirect.txt")
313        else:
314            stdout_path = local_path
315        error = lldb.SBError()
316        process = target.Launch(
317            self.dbg.GetListener(),
318            None,
319            None,
320            None,
321            stdout_path,
322            None,
323            None,
324            0,
325            False,
326            error)
327        process.Continue()
328        #self.runCmd("process status")
329        if lldb.remote_platform:
330            # copy output file to host
331            lldb.remote_platform.Get(
332                lldb.SBFileSpec(stdout_path),
333                lldb.SBFileSpec(local_path))
334
335        # The 'stdout.txt' file should now exist.
336        self.assertTrue(
337            os.path.isfile(local_path),
338            "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.")
339
340        # Read the output file produced by running the program.
341        with open(local_path, 'r') as f:
342            output = f.read()
343
344        self.expect(output, exe=False,
345                    substrs=["a(1)", "b(2)", "a(3)"])
346
347    def resolve_symbol_context_with_address(self):
348        """Exercise SBTaget.ResolveSymbolContextForAddress() API."""
349        exe = self.getBuildArtifact("a.out")
350
351        # Create a target by the debugger.
352        target = self.dbg.CreateTarget(exe)
353        self.assertTrue(target, VALID_TARGET)
354
355        # Now create the two breakpoints inside function 'a'.
356        breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
357        breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
358        #print("breakpoint1:", breakpoint1)
359        #print("breakpoint2:", breakpoint2)
360        self.assertTrue(breakpoint1 and
361                        breakpoint1.GetNumLocations() == 1,
362                        VALID_BREAKPOINT)
363        self.assertTrue(breakpoint2 and
364                        breakpoint2.GetNumLocations() == 1,
365                        VALID_BREAKPOINT)
366
367        # Now launch the process, and do not stop at entry point.
368        process = target.LaunchSimple(
369            None, None, self.get_process_working_directory())
370        self.assertTrue(process, PROCESS_IS_VALID)
371
372        # Frame #0 should be on self.line1.
373        self.assertTrue(process.GetState() == lldb.eStateStopped)
374        thread = lldbutil.get_stopped_thread(
375            process, lldb.eStopReasonBreakpoint)
376        self.assertTrue(
377            thread.IsValid(),
378            "There should be a thread stopped due to breakpoint condition")
379        #self.runCmd("process status")
380        frame0 = thread.GetFrameAtIndex(0)
381        lineEntry = frame0.GetLineEntry()
382        self.assertTrue(lineEntry.GetLine() == self.line1)
383
384        address1 = lineEntry.GetStartAddress()
385
386        # Continue the inferior, the breakpoint 2 should be hit.
387        process.Continue()
388        self.assertTrue(process.GetState() == lldb.eStateStopped)
389        thread = lldbutil.get_stopped_thread(
390            process, lldb.eStopReasonBreakpoint)
391        self.assertTrue(
392            thread.IsValid(),
393            "There should be a thread stopped due to breakpoint condition")
394        #self.runCmd("process status")
395        frame0 = thread.GetFrameAtIndex(0)
396        lineEntry = frame0.GetLineEntry()
397        self.assertTrue(lineEntry.GetLine() == self.line2)
398
399        address2 = lineEntry.GetStartAddress()
400
401        #print("address1:", address1)
402        #print("address2:", address2)
403
404        # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses
405        # from our line entry.
406        context1 = target.ResolveSymbolContextForAddress(
407            address1, lldb.eSymbolContextEverything)
408        context2 = target.ResolveSymbolContextForAddress(
409            address2, lldb.eSymbolContextEverything)
410
411        self.assertTrue(context1 and context2)
412        #print("context1:", context1)
413        #print("context2:", context2)
414
415        # Verify that the context point to the same function 'a'.
416        symbol1 = context1.GetSymbol()
417        symbol2 = context2.GetSymbol()
418        self.assertTrue(symbol1 and symbol2)
419        #print("symbol1:", symbol1)
420        #print("symbol2:", symbol2)
421
422        from lldbsuite.test.lldbutil import get_description
423        desc1 = get_description(symbol1)
424        desc2 = get_description(symbol2)
425        self.assertTrue(desc1 and desc2 and desc1 == desc2,
426                        "The two addresses should resolve to the same symbol")
427