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