xref: /llvm-project/lldb/test/API/python_api/target/TestTargetAPI.py (revision dbf44b833067cfe59056d07130e7afcb8fc149c7)
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    @skipIfReproducer # SBTarget::ReadMemory is not instrumented.
126    def test_read_memory(self):
127        d = {'EXE': 'b.out'}
128        self.build(dictionary=d)
129        self.setTearDownCleanup(dictionary=d)
130        target = self.create_simple_target('b.out')
131
132        breakpoint = target.BreakpointCreateByLocation(
133            "main.c", self.line_main)
134        self.assertTrue(breakpoint, VALID_BREAKPOINT)
135
136        # Put debugger into synchronous mode so when we target.LaunchSimple returns
137        # it will guaranteed to be at the breakpoint
138        self.dbg.SetAsync(False)
139
140        # Launch the process, and do not stop at the entry point.
141        process = target.LaunchSimple(
142            None, None, self.get_process_working_directory())
143
144        # find the file address in the .data section of the main
145        # module
146        data_section = self.find_data_section(target)
147        sb_addr = lldb.SBAddress(data_section, 0)
148        error = lldb.SBError()
149        content = target.ReadMemory(sb_addr, 1, error)
150        self.assertTrue(error.Success(), "Make sure memory read succeeded")
151        self.assertEqual(len(content), 1)
152
153
154    @add_test_categories(['pyapi'])
155    @skipIfWindows  # stdio manipulation unsupported on Windows
156    @skipIfRemote   # stdio manipulation unsupported on remote iOS devices<rdar://problem/54581135>
157    @skipIf(oslist=["linux"], archs=["arm", "aarch64"])
158    @no_debug_info_test
159    def test_launch_simple(self):
160        d = {'EXE': 'b.out'}
161        self.build(dictionary=d)
162        self.setTearDownCleanup(dictionary=d)
163        target = self.create_simple_target('b.out')
164
165        process = target.LaunchSimple(
166            ['foo', 'bar'], ['baz'], self.get_process_working_directory())
167        self.runCmd("run")
168        output = process.GetSTDOUT(9999)
169        self.assertIn('arg: foo', output)
170        self.assertIn('arg: bar', output)
171        self.assertIn('env: baz', output)
172
173        self.runCmd("setting set target.run-args foo")
174        self.runCmd("setting set target.env-vars bar=baz")
175        process = target.LaunchSimple(None, None,
176                                      self.get_process_working_directory())
177        self.runCmd("run")
178        output = process.GetSTDOUT(9999)
179        self.assertIn('arg: foo', output)
180        self.assertIn('env: bar=baz', output)
181
182        self.runCmd("settings set target.disable-stdio true")
183        process = target.LaunchSimple(
184            None, None, self.get_process_working_directory())
185        self.runCmd("run")
186        output = process.GetSTDOUT(9999)
187        self.assertEqual(output, "")
188
189    def create_simple_target(self, fn):
190        exe = self.getBuildArtifact(fn)
191        target = self.dbg.CreateTarget(exe)
192        self.assertTrue(target, VALID_TARGET)
193        return target
194
195    def find_data_section(self, target):
196        mod = target.GetModuleAtIndex(0)
197        data_section = None
198        for s in mod.sections:
199            sect_type = s.GetSectionType()
200            if sect_type == lldb.eSectionTypeData:
201                data_section = s
202                break
203            elif sect_type == lldb.eSectionTypeContainer:
204                for i in range(s.GetNumSubSections()):
205                    ss = s.GetSubSectionAtIndex(i)
206                    sect_type = ss.GetSectionType()
207                    if sect_type == lldb.eSectionTypeData:
208                        data_section = ss
209                        break
210
211        self.assertIsNotNone(data_section)
212        return data_section
213
214    def find_global_variables(self, exe_name):
215        """Exercise SBTaget.FindGlobalVariables() API."""
216        exe = self.getBuildArtifact(exe_name)
217
218        # Create a target by the debugger.
219        target = self.dbg.CreateTarget(exe)
220        self.assertTrue(target, VALID_TARGET)
221
222        # rdar://problem/9700873
223        # Find global variable value fails for dwarf if inferior not started
224        # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)
225        #
226        # Remove the lines to create a breakpoint and to start the inferior
227        # which are workarounds for the dwarf case.
228
229        breakpoint = target.BreakpointCreateByLocation('main.c', self.line1)
230        self.assertTrue(breakpoint, VALID_BREAKPOINT)
231
232        # Now launch the process, and do not stop at entry point.
233        process = target.LaunchSimple(
234            None, None, self.get_process_working_directory())
235        self.assertTrue(process, PROCESS_IS_VALID)
236        # Make sure we hit our breakpoint:
237        thread_list = lldbutil.get_threads_stopped_at_breakpoint(
238            process, breakpoint)
239        self.assertTrue(len(thread_list) == 1)
240
241        value_list = target.FindGlobalVariables(
242            'my_global_var_of_char_type', 3)
243        self.assertTrue(value_list.GetSize() == 1)
244        my_global_var = value_list.GetValueAtIndex(0)
245        self.DebugSBValue(my_global_var)
246        self.assertTrue(my_global_var)
247        self.expect(my_global_var.GetName(), exe=False,
248                    startstr="my_global_var_of_char_type")
249        self.expect(my_global_var.GetTypeName(), exe=False,
250                    startstr="char")
251        self.expect(my_global_var.GetValue(), exe=False,
252                    startstr="'X'")
253
254
255        if not configuration.is_reproducer():
256            # While we are at it, let's also exercise the similar
257            # SBModule.FindGlobalVariables() API.
258            for m in target.module_iter():
259                if os.path.normpath(m.GetFileSpec().GetDirectory()) == self.getBuildDir() and m.GetFileSpec().GetFilename() == exe_name:
260                    value_list = m.FindGlobalVariables(
261                        target, 'my_global_var_of_char_type', 3)
262                    self.assertTrue(value_list.GetSize() == 1)
263                    self.assertTrue(
264                        value_list.GetValueAtIndex(0).GetValue() == "'X'")
265                    break
266
267    def find_compile_units(self, exe):
268        """Exercise SBTarget.FindCompileUnits() API."""
269        source_name = "main.c"
270
271        # Create a target by the debugger.
272        target = self.dbg.CreateTarget(exe)
273        self.assertTrue(target, VALID_TARGET)
274
275        list = target.FindCompileUnits(lldb.SBFileSpec(source_name, False))
276        # Executable has been built just from one source file 'main.c',
277        # so we may check only the first element of list.
278        self.assertTrue(
279            list[0].GetCompileUnit().GetFileSpec().GetFilename() == source_name)
280
281    def find_functions(self, exe_name):
282        """Exercise SBTaget.FindFunctions() API."""
283        exe = self.getBuildArtifact(exe_name)
284
285        # Create a target by the debugger.
286        target = self.dbg.CreateTarget(exe)
287        self.assertTrue(target, VALID_TARGET)
288
289        # Try it with a null name:
290        list = target.FindFunctions(None, lldb.eFunctionNameTypeAuto)
291        self.assertTrue(list.GetSize() == 0)
292
293        list = target.FindFunctions('c', lldb.eFunctionNameTypeAuto)
294        self.assertTrue(list.GetSize() == 1)
295
296        for sc in list:
297            self.assertTrue(
298                sc.GetModule().GetFileSpec().GetFilename() == exe_name)
299            self.assertTrue(sc.GetSymbol().GetName() == 'c')
300
301    def get_description(self):
302        """Exercise SBTaget.GetDescription() API."""
303        exe = self.getBuildArtifact("a.out")
304
305        # Create a target by the debugger.
306        target = self.dbg.CreateTarget(exe)
307        self.assertTrue(target, VALID_TARGET)
308
309        from lldbsuite.test.lldbutil import get_description
310
311        # get_description() allows no option to mean
312        # lldb.eDescriptionLevelBrief.
313        desc = get_description(target)
314        #desc = get_description(target, option=lldb.eDescriptionLevelBrief)
315        if not desc:
316            self.fail("SBTarget.GetDescription() failed")
317        self.expect(desc, exe=False,
318                    substrs=['a.out'])
319        self.expect(desc, exe=False, matching=False,
320                    substrs=['Target', 'Module', 'Breakpoint'])
321
322        desc = get_description(target, option=lldb.eDescriptionLevelFull)
323        if not desc:
324            self.fail("SBTarget.GetDescription() failed")
325        self.expect(desc, exe=False,
326                    substrs=['a.out', 'Target', 'Module', 'Breakpoint'])
327
328    @not_remote_testsuite_ready
329    @add_test_categories(['pyapi'])
330    @no_debug_info_test
331    @skipIfReproducer # Inferior doesn't run during replay.
332    def test_launch_new_process_and_redirect_stdout(self):
333        """Exercise SBTaget.Launch() API with redirected stdout."""
334        self.build()
335        exe = self.getBuildArtifact("a.out")
336
337        # Create a target by the debugger.
338        target = self.dbg.CreateTarget(exe)
339        self.assertTrue(target, VALID_TARGET)
340
341        # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done.
342        # We should still see the entire stdout redirected once the process is
343        # finished.
344        line = line_number('main.c', '// a(3) -> c(3)')
345        breakpoint = target.BreakpointCreateByLocation('main.c', line)
346
347        # Now launch the process, do not stop at entry point, and redirect stdout to "stdout.txt" file.
348        # The inferior should run to completion after "process.Continue()"
349        # call.
350        local_path = self.getBuildArtifact("stdout.txt")
351        if os.path.exists(local_path):
352            os.remove(local_path)
353
354        if lldb.remote_platform:
355            stdout_path = lldbutil.append_to_process_working_directory(self,
356                "lldb-stdout-redirect.txt")
357        else:
358            stdout_path = local_path
359        error = lldb.SBError()
360        process = target.Launch(
361            self.dbg.GetListener(),
362            None,
363            None,
364            None,
365            stdout_path,
366            None,
367            None,
368            0,
369            False,
370            error)
371        process.Continue()
372        #self.runCmd("process status")
373        if lldb.remote_platform:
374            # copy output file to host
375            lldb.remote_platform.Get(
376                lldb.SBFileSpec(stdout_path),
377                lldb.SBFileSpec(local_path))
378
379        # The 'stdout.txt' file should now exist.
380        self.assertTrue(
381            os.path.isfile(local_path),
382            "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.")
383
384        # Read the output file produced by running the program.
385        with open(local_path, 'r') as f:
386            output = f.read()
387
388        self.expect(output, exe=False,
389                    substrs=["a(1)", "b(2)", "a(3)"])
390
391    def resolve_symbol_context_with_address(self):
392        """Exercise SBTaget.ResolveSymbolContextForAddress() API."""
393        exe = self.getBuildArtifact("a.out")
394
395        # Create a target by the debugger.
396        target = self.dbg.CreateTarget(exe)
397        self.assertTrue(target, VALID_TARGET)
398
399        # Now create the two breakpoints inside function 'a'.
400        breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
401        breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
402        self.trace("breakpoint1:", breakpoint1)
403        self.trace("breakpoint2:", breakpoint2)
404        self.assertTrue(breakpoint1 and
405                        breakpoint1.GetNumLocations() == 1,
406                        VALID_BREAKPOINT)
407        self.assertTrue(breakpoint2 and
408                        breakpoint2.GetNumLocations() == 1,
409                        VALID_BREAKPOINT)
410
411        # Now launch the process, and do not stop at entry point.
412        process = target.LaunchSimple(
413            None, None, self.get_process_working_directory())
414        self.assertTrue(process, PROCESS_IS_VALID)
415
416        # Frame #0 should be on self.line1.
417        self.assertTrue(process.GetState() == lldb.eStateStopped)
418        thread = lldbutil.get_stopped_thread(
419            process, lldb.eStopReasonBreakpoint)
420        self.assertTrue(
421            thread.IsValid(),
422            "There should be a thread stopped due to breakpoint condition")
423        #self.runCmd("process status")
424        frame0 = thread.GetFrameAtIndex(0)
425        lineEntry = frame0.GetLineEntry()
426        self.assertTrue(lineEntry.GetLine() == self.line1)
427
428        address1 = lineEntry.GetStartAddress()
429
430        # Continue the inferior, the breakpoint 2 should be hit.
431        process.Continue()
432        self.assertTrue(process.GetState() == lldb.eStateStopped)
433        thread = lldbutil.get_stopped_thread(
434            process, lldb.eStopReasonBreakpoint)
435        self.assertTrue(
436            thread.IsValid(),
437            "There should be a thread stopped due to breakpoint condition")
438        #self.runCmd("process status")
439        frame0 = thread.GetFrameAtIndex(0)
440        lineEntry = frame0.GetLineEntry()
441        self.assertTrue(lineEntry.GetLine() == self.line2)
442
443        address2 = lineEntry.GetStartAddress()
444
445        self.trace("address1:", address1)
446        self.trace("address2:", address2)
447
448        # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses
449        # from our line entry.
450        context1 = target.ResolveSymbolContextForAddress(
451            address1, lldb.eSymbolContextEverything)
452        context2 = target.ResolveSymbolContextForAddress(
453            address2, lldb.eSymbolContextEverything)
454
455        self.assertTrue(context1 and context2)
456        self.trace("context1:", context1)
457        self.trace("context2:", context2)
458
459        # Verify that the context point to the same function 'a'.
460        symbol1 = context1.GetSymbol()
461        symbol2 = context2.GetSymbol()
462        self.assertTrue(symbol1 and symbol2)
463        self.trace("symbol1:", symbol1)
464        self.trace("symbol2:", symbol2)
465
466        from lldbsuite.test.lldbutil import get_description
467        desc1 = get_description(symbol1)
468        desc2 = get_description(symbol2)
469        self.assertTrue(desc1 and desc2 and desc1 == desc2,
470                        "The two addresses should resolve to the same symbol")
471