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