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