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