xref: /llvm-project/lldb/test/API/python_api/target/TestTargetAPI.py (revision 7c704c0f53bd7f785ec99fc6bedd71569816a28c)
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    def test_find_global_variables(self):
39        """Exercise SBTarget.FindGlobalVariables() API."""
40        d = {'EXE': 'b.out'}
41        self.build(dictionary=d)
42        self.setTearDownCleanup(dictionary=d)
43        self.find_global_variables('b.out')
44
45    def test_find_compile_units(self):
46        """Exercise SBTarget.FindCompileUnits() API."""
47        d = {'EXE': 'b.out'}
48        self.build(dictionary=d)
49        self.setTearDownCleanup(dictionary=d)
50        self.find_compile_units(self.getBuildArtifact('b.out'))
51
52    @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24778")
53    def test_find_functions(self):
54        """Exercise SBTarget.FindFunctions() API."""
55        d = {'EXE': 'b.out'}
56        self.build(dictionary=d)
57        self.setTearDownCleanup(dictionary=d)
58        self.find_functions('b.out')
59
60    def test_get_description(self):
61        """Exercise SBTarget.GetDescription() API."""
62        self.build()
63        self.get_description()
64
65    @expectedFailureAll(oslist=["windows"], bugnumber='llvm.org/pr21765')
66    def test_resolve_symbol_context_with_address(self):
67        """Exercise SBTarget.ResolveSymbolContextForAddress() API."""
68        self.build()
69        self.resolve_symbol_context_with_address()
70
71    def test_get_platform(self):
72        d = {'EXE': 'b.out'}
73        self.build(dictionary=d)
74        self.setTearDownCleanup(dictionary=d)
75        target = self.create_simple_target('b.out')
76        platform = target.platform
77        self.assertTrue(platform, VALID_PLATFORM)
78
79    def test_get_data_byte_size(self):
80        d = {'EXE': 'b.out'}
81        self.build(dictionary=d)
82        self.setTearDownCleanup(dictionary=d)
83        target = self.create_simple_target('b.out')
84        self.assertEqual(target.data_byte_size, 1)
85
86    def test_get_code_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.code_byte_size, 1)
92
93    def test_resolve_file_address(self):
94        d = {'EXE': 'b.out'}
95        self.build(dictionary=d)
96        self.setTearDownCleanup(dictionary=d)
97        target = self.create_simple_target('b.out')
98
99        # find the file address in the .data section of the main
100        # module
101        data_section = self.find_data_section(target)
102        data_section_addr = data_section.file_addr
103
104        # resolve the above address, and compare the address produced
105        # by the resolution against the original address/section
106        res_file_addr = target.ResolveFileAddress(data_section_addr)
107        self.assertTrue(res_file_addr.IsValid())
108
109        self.assertEqual(data_section_addr, res_file_addr.file_addr)
110
111        data_section2 = res_file_addr.section
112        self.assertIsNotNone(data_section2)
113        self.assertEqual(data_section.name, data_section2.name)
114
115    def test_read_memory(self):
116        d = {'EXE': 'b.out'}
117        self.build(dictionary=d)
118        self.setTearDownCleanup(dictionary=d)
119        target = self.create_simple_target('b.out')
120
121        breakpoint = target.BreakpointCreateByLocation(
122            "main.c", self.line_main)
123        self.assertTrue(breakpoint, VALID_BREAKPOINT)
124
125        # Put debugger into synchronous mode so when we target.LaunchSimple returns
126        # it will guaranteed to be at the breakpoint
127        self.dbg.SetAsync(False)
128
129        # Launch the process, and do not stop at the entry point.
130        process = target.LaunchSimple(
131            None, None, self.get_process_working_directory())
132
133        # find the file address in the .data section of the main
134        # module
135        data_section = self.find_data_section(target)
136        sb_addr = lldb.SBAddress(data_section, 0)
137        error = lldb.SBError()
138        content = target.ReadMemory(sb_addr, 1, error)
139        self.assertTrue(error.Success(), "Make sure memory read succeeded")
140        self.assertEqual(len(content), 1)
141
142
143    @skipIfWindows  # stdio manipulation unsupported on Windows
144    @skipIfRemote   # stdio manipulation unsupported on remote iOS devices<rdar://problem/54581135>
145    @skipIf(oslist=["linux"], archs=["arm", "aarch64"])
146    @no_debug_info_test
147    def test_launch_simple(self):
148        d = {'EXE': 'b.out'}
149        self.build(dictionary=d)
150        self.setTearDownCleanup(dictionary=d)
151        target = self.create_simple_target('b.out')
152
153        # Set the debugger to synchronous mode so we only continue after the
154        # process has exited.
155        self.dbg.SetAsync(False)
156
157        process = target.LaunchSimple(
158            ['foo', 'bar'], ['baz'], self.get_process_working_directory())
159        process.Continue()
160        self.assertEqual(process.GetState(), lldb.eStateExited)
161        output = process.GetSTDOUT(9999)
162        self.assertIn('arg: foo', output)
163        self.assertIn('arg: bar', output)
164        self.assertIn('env: baz', output)
165
166        self.runCmd("setting set target.run-args foo")
167        self.runCmd("setting set target.env-vars bar=baz")
168        process = target.LaunchSimple(None, None,
169                                      self.get_process_working_directory())
170        process.Continue()
171        self.assertEqual(process.GetState(), lldb.eStateExited)
172        output = process.GetSTDOUT(9999)
173        self.assertIn('arg: foo', output)
174        self.assertIn('env: bar=baz', output)
175
176        self.runCmd("settings set target.disable-stdio true")
177        process = target.LaunchSimple(
178            None, None, self.get_process_working_directory())
179        process.Continue()
180        self.assertEqual(process.GetState(), lldb.eStateExited)
181        output = process.GetSTDOUT(9999)
182        self.assertEqual(output, "")
183
184    def create_simple_target(self, fn):
185        exe = self.getBuildArtifact(fn)
186        target = self.dbg.CreateTarget(exe)
187        self.assertTrue(target, VALID_TARGET)
188        return target
189
190    def find_data_section(self, target):
191        mod = target.GetModuleAtIndex(0)
192        data_section = None
193        for s in mod.sections:
194            sect_type = s.GetSectionType()
195            if sect_type == lldb.eSectionTypeData:
196                data_section = s
197                break
198            elif sect_type == lldb.eSectionTypeContainer:
199                for i in range(s.GetNumSubSections()):
200                    ss = s.GetSubSectionAtIndex(i)
201                    sect_type = ss.GetSectionType()
202                    if sect_type == lldb.eSectionTypeData:
203                        data_section = ss
204                        break
205
206        self.assertIsNotNone(data_section)
207        return data_section
208
209    def find_global_variables(self, exe_name):
210        """Exercise SBTarget.FindGlobalVariables() API."""
211        exe = self.getBuildArtifact(exe_name)
212
213        # Create a target by the debugger.
214        target = self.dbg.CreateTarget(exe)
215        self.assertTrue(target, VALID_TARGET)
216
217        # rdar://problem/9700873
218        # Find global variable value fails for dwarf if inferior not started
219        # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)
220        #
221        # Remove the lines to create a breakpoint and to start the inferior
222        # which are workarounds for the dwarf case.
223
224        breakpoint = target.BreakpointCreateByLocation('main.c', self.line1)
225        self.assertTrue(breakpoint, VALID_BREAKPOINT)
226
227        # Now launch the process, and do not stop at entry point.
228        process = target.LaunchSimple(
229            None, None, self.get_process_working_directory())
230        self.assertTrue(process, PROCESS_IS_VALID)
231        # Make sure we hit our breakpoint:
232        thread_list = lldbutil.get_threads_stopped_at_breakpoint(
233            process, breakpoint)
234        self.assertEqual(len(thread_list), 1)
235
236        value_list = target.FindGlobalVariables(
237            'my_global_var_of_char_type', 3)
238        self.assertEqual(value_list.GetSize(), 1)
239        my_global_var = value_list.GetValueAtIndex(0)
240        self.DebugSBValue(my_global_var)
241        self.assertTrue(my_global_var)
242        self.expect(my_global_var.GetName(), exe=False,
243                    startstr="my_global_var_of_char_type")
244        self.expect(my_global_var.GetTypeName(), exe=False,
245                    startstr="char")
246        self.expect(my_global_var.GetValue(), exe=False,
247                    startstr="'X'")
248
249        # While we are at it, let's also exercise the similar
250        # SBModule.FindGlobalVariables() API.
251        for m in target.module_iter():
252            if os.path.normpath(m.GetFileSpec().GetDirectory()) == self.getBuildDir() and m.GetFileSpec().GetFilename() == exe_name:
253                value_list = m.FindGlobalVariables(
254                    target, 'my_global_var_of_char_type', 3)
255                self.assertEqual(value_list.GetSize(), 1)
256                self.assertEqual(
257                    value_list.GetValueAtIndex(0).GetValue(), "'X'")
258                break
259
260    def find_compile_units(self, exe):
261        """Exercise SBTarget.FindCompileUnits() API."""
262        source_name = "main.c"
263
264        # Create a target by the debugger.
265        target = self.dbg.CreateTarget(exe)
266        self.assertTrue(target, VALID_TARGET)
267
268        list = target.FindCompileUnits(lldb.SBFileSpec(source_name, False))
269        # Executable has been built just from one source file 'main.c',
270        # so we may check only the first element of list.
271        self.assertEqual(
272            list[0].GetCompileUnit().GetFileSpec().GetFilename(), source_name)
273
274    def find_functions(self, exe_name):
275        """Exercise SBTarget.FindFunctions() API."""
276        exe = self.getBuildArtifact(exe_name)
277
278        # Create a target by the debugger.
279        target = self.dbg.CreateTarget(exe)
280        self.assertTrue(target, VALID_TARGET)
281
282        # Try it with a null name:
283        list = target.FindFunctions(None, lldb.eFunctionNameTypeAuto)
284        self.assertEqual(list.GetSize(), 0)
285
286        list = target.FindFunctions('c', lldb.eFunctionNameTypeAuto)
287        self.assertEqual(list.GetSize(), 1)
288
289        for sc in list:
290            self.assertEqual(
291                sc.GetModule().GetFileSpec().GetFilename(), exe_name)
292            self.assertEqual(sc.GetSymbol().GetName(), 'c')
293
294    def get_description(self):
295        """Exercise SBTarget.GetDescription() API."""
296        exe = self.getBuildArtifact("a.out")
297
298        # Create a target by the debugger.
299        target = self.dbg.CreateTarget(exe)
300        self.assertTrue(target, VALID_TARGET)
301
302        from lldbsuite.test.lldbutil import get_description
303
304        # get_description() allows no option to mean
305        # lldb.eDescriptionLevelBrief.
306        desc = get_description(target)
307        #desc = get_description(target, option=lldb.eDescriptionLevelBrief)
308        if not desc:
309            self.fail("SBTarget.GetDescription() failed")
310        self.expect(desc, exe=False,
311                    substrs=['a.out'])
312        self.expect(desc, exe=False, matching=False,
313                    substrs=['Target', 'Module', 'Breakpoint'])
314
315        desc = get_description(target, option=lldb.eDescriptionLevelFull)
316        if not desc:
317            self.fail("SBTarget.GetDescription() failed")
318        self.expect(desc, exe=False,
319                    substrs=['Target', 'Module', 'a.out', 'Breakpoint'])
320
321    @skipIfRemote
322    @no_debug_info_test
323    def test_launch_new_process_and_redirect_stdout(self):
324        """Exercise SBTarget.Launch() API with redirected stdout."""
325        self.build()
326        exe = self.getBuildArtifact("a.out")
327
328        # Create a target by the debugger.
329        target = self.dbg.CreateTarget(exe)
330        self.assertTrue(target, VALID_TARGET)
331
332        # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done.
333        # We should still see the entire stdout redirected once the process is
334        # finished.
335        line = line_number('main.c', '// a(3) -> c(3)')
336        breakpoint = target.BreakpointCreateByLocation('main.c', line)
337
338        # Now launch the process, do not stop at entry point, and redirect stdout to "stdout.txt" file.
339        # The inferior should run to completion after "process.Continue()"
340        # call.
341        local_path = self.getBuildArtifact("stdout.txt")
342        if os.path.exists(local_path):
343            os.remove(local_path)
344
345        if lldb.remote_platform:
346            stdout_path = lldbutil.append_to_process_working_directory(self,
347                "lldb-stdout-redirect.txt")
348        else:
349            stdout_path = local_path
350        error = lldb.SBError()
351        process = target.Launch(
352            self.dbg.GetListener(),
353            None,
354            None,
355            None,
356            stdout_path,
357            None,
358            None,
359            0,
360            False,
361            error)
362        process.Continue()
363        #self.runCmd("process status")
364        if lldb.remote_platform:
365            # copy output file to host
366            lldb.remote_platform.Get(
367                lldb.SBFileSpec(stdout_path),
368                lldb.SBFileSpec(local_path))
369
370        # The 'stdout.txt' file should now exist.
371        self.assertTrue(
372            os.path.isfile(local_path),
373            "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.")
374
375        # Read the output file produced by running the program.
376        with open(local_path, 'r') as f:
377            output = f.read()
378
379        self.expect(output, exe=False,
380                    substrs=["a(1)", "b(2)", "a(3)"])
381
382    def resolve_symbol_context_with_address(self):
383        """Exercise SBTarget.ResolveSymbolContextForAddress() API."""
384        exe = self.getBuildArtifact("a.out")
385
386        # Create a target by the debugger.
387        target = self.dbg.CreateTarget(exe)
388        self.assertTrue(target, VALID_TARGET)
389
390        # Now create the two breakpoints inside function 'a'.
391        breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
392        breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
393        self.trace("breakpoint1:", breakpoint1)
394        self.trace("breakpoint2:", breakpoint2)
395        self.assertTrue(breakpoint1 and
396                        breakpoint1.GetNumLocations() == 1,
397                        VALID_BREAKPOINT)
398        self.assertTrue(breakpoint2 and
399                        breakpoint2.GetNumLocations() == 1,
400                        VALID_BREAKPOINT)
401
402        # Now launch the process, and do not stop at entry point.
403        process = target.LaunchSimple(
404            None, None, self.get_process_working_directory())
405        self.assertTrue(process, PROCESS_IS_VALID)
406
407        # Frame #0 should be on self.line1.
408        self.assertEqual(process.GetState(), lldb.eStateStopped)
409        thread = lldbutil.get_stopped_thread(
410            process, lldb.eStopReasonBreakpoint)
411        self.assertTrue(
412            thread.IsValid(),
413            "There should be a thread stopped due to breakpoint condition")
414        #self.runCmd("process status")
415        frame0 = thread.GetFrameAtIndex(0)
416        lineEntry = frame0.GetLineEntry()
417        self.assertEqual(lineEntry.GetLine(), self.line1)
418
419        address1 = lineEntry.GetStartAddress()
420
421        # Continue the inferior, the breakpoint 2 should be hit.
422        process.Continue()
423        self.assertEqual(process.GetState(), lldb.eStateStopped)
424        thread = lldbutil.get_stopped_thread(
425            process, lldb.eStopReasonBreakpoint)
426        self.assertTrue(
427            thread.IsValid(),
428            "There should be a thread stopped due to breakpoint condition")
429        #self.runCmd("process status")
430        frame0 = thread.GetFrameAtIndex(0)
431        lineEntry = frame0.GetLineEntry()
432        self.assertEqual(lineEntry.GetLine(), self.line2)
433
434        address2 = lineEntry.GetStartAddress()
435
436        self.trace("address1:", address1)
437        self.trace("address2:", address2)
438
439        # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses
440        # from our line entry.
441        context1 = target.ResolveSymbolContextForAddress(
442            address1, lldb.eSymbolContextEverything)
443        context2 = target.ResolveSymbolContextForAddress(
444            address2, lldb.eSymbolContextEverything)
445
446        self.assertTrue(context1 and context2)
447        self.trace("context1:", context1)
448        self.trace("context2:", context2)
449
450        # Verify that the context point to the same function 'a'.
451        symbol1 = context1.GetSymbol()
452        symbol2 = context2.GetSymbol()
453        self.assertTrue(symbol1 and symbol2)
454        self.trace("symbol1:", symbol1)
455        self.trace("symbol2:", symbol2)
456
457        from lldbsuite.test.lldbutil import get_description
458        desc1 = get_description(symbol1)
459        desc2 = get_description(symbol2)
460        self.assertTrue(desc1 and desc2 and desc1 == desc2,
461                        "The two addresses should resolve to the same symbol")
462
463    def test_default_arch(self):
464        """ Test the other two target create methods using LLDB_ARCH_DEFAULT. """
465        self.build()
466        exe = self.getBuildArtifact("a.out")
467        target = self.dbg.CreateTargetWithFileAndArch(exe, lldb.LLDB_ARCH_DEFAULT)
468        self.assertTrue(target.IsValid(), "Default arch made a valid target.")
469        # This should also work with the target's triple:
470        target2 = self.dbg.CreateTargetWithFileAndArch(exe, target.GetTriple())
471        self.assertTrue(target2.IsValid(), "Round trip with triple works")
472        # And this triple should work for the FileAndTriple API:
473        target3 = self.dbg.CreateTargetWithFileAndTargetTriple(exe, target.GetTriple())
474        self.assertTrue(target3.IsValid())
475
476
477    @skipIfWindows
478    def test_is_loaded(self):
479        """Exercise SBTarget.IsLoaded(SBModule&) API."""
480        d = {'EXE': 'b.out'}
481        self.build(dictionary=d)
482        self.setTearDownCleanup(dictionary=d)
483        target = self.create_simple_target('b.out')
484
485        self.assertFalse(target.IsLoaded(lldb.SBModule()))
486
487        num_modules = target.GetNumModules()
488        for i in range(num_modules):
489            module = target.GetModuleAtIndex(i)
490            self.assertFalse(target.IsLoaded(module), "Target that isn't "
491                             "running shouldn't have any module loaded.")
492
493        process = target.LaunchSimple(None, None,
494                                      self.get_process_working_directory())
495
496        for i in range(num_modules):
497            module = target.GetModuleAtIndex(i)
498            self.assertTrue(target.IsLoaded(module), "Running the target should "
499                            "have loaded its modules.")
500