1"""
2Test the lldb disassemble command on lib stdc++.
3"""
4
5from __future__ import print_function
6
7
8import unittest2
9import os
10import lldb
11from lldbsuite.test.lldbtest import *
12import lldbsuite.test.lldbutil as lldbutil
13from lldbsuite.test.decorators import *
14
15class StdCXXDisassembleTestCase(TestBase):
16
17    mydir = TestBase.compute_mydir(__file__)
18
19    def setUp(self):
20        # Call super's setUp().
21        TestBase.setUp(self)
22        # Find the line number to break inside main().
23        self.line = line_number('main.cpp', '// Set break point at this line.')
24
25    @skipIfWindows
26    @expectedFailureNetBSD
27    def test_stdcxx_disasm(self):
28        """Do 'disassemble' on each and every 'Code' symbol entry from the std c++ lib."""
29        self.build()
30        exe = self.getBuildArtifact("a.out")
31        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
32
33        # rdar://problem/8543077
34        # test/stl: clang built binaries results in the breakpoint locations = 3,
35        # is this a problem with clang generated debug info?
36        #
37        # Break on line 13 of main.cpp.
38        lldbutil.run_break_set_by_file_and_line(
39            self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
40
41        self.runCmd("run", RUN_SUCCEEDED)
42
43        # Now let's get the target as well as the process objects.
44        target = self.dbg.GetSelectedTarget()
45        process = target.GetProcess()
46
47        # The process should be in a 'stopped' state.
48        self.expect(
49            str(process),
50            STOPPED_DUE_TO_BREAKPOINT,
51            exe=False,
52            substrs=[
53                "stopped",
54                "a.out",
55            ])
56
57        # Disassemble the functions on the call stack.
58        self.runCmd("thread backtrace")
59        thread = lldbutil.get_stopped_thread(
60            process, lldb.eStopReasonBreakpoint)
61        self.assertIsNotNone(thread)
62        depth = thread.GetNumFrames()
63        for i in range(depth - 1):
64            frame = thread.GetFrameAtIndex(i)
65            function = frame.GetFunction()
66            if function.GetName():
67                self.runCmd("disassemble -n '%s'" % function.GetName())
68
69        lib_stdcxx = "FAILHORRIBLYHERE"
70        # Iterate through the available modules, looking for stdc++ library...
71        for i in range(target.GetNumModules()):
72            module = target.GetModuleAtIndex(i)
73            fs = module.GetFileSpec()
74            if (fs.GetFilename().startswith("libstdc++")
75                    or fs.GetFilename().startswith("libc++")):
76                lib_stdcxx = str(fs)
77                break
78
79        # At this point, lib_stdcxx is the full path to the stdc++ library and
80        # module is the corresponding SBModule.
81
82        self.expect(lib_stdcxx, "Libraray StdC++ is located", exe=False,
83                    substrs=["lib"])
84
85        self.runCmd("image dump symtab '%s'" % lib_stdcxx)
86        raw_output = self.res.GetOutput()
87        # Now, look for every 'Code' symbol and feed its load address into the
88        # command: 'disassemble -s load_address -e end_address', where the
89        # end_address is taken from the next consecutive 'Code' symbol entry's
90        # load address.
91        #
92        # The load address column comes after the file address column, with both
93        # looks like '0xhhhhhhhh', i.e., 8 hexadecimal digits.
94        codeRE = re.compile(r"""
95                             \ Code\ {9}      # ' Code' followed by 9 SPCs,
96                             0x[0-9a-f]{16}   # the file address column, and
97                             \                # a SPC, and
98                             (0x[0-9a-f]{16}) # the load address column, and
99                             .*               # the rest.
100                             """, re.VERBOSE)
101        # Maintain a start address variable; if we arrive at a consecutive Code
102        # entry, then the load address of the that entry is fed as the end
103        # address to the 'disassemble -s SA -e LA' command.
104        SA = None
105        for line in raw_output.split(os.linesep):
106            match = codeRE.search(line)
107            if match:
108                LA = match.group(1)
109                if self.TraceOn():
110                    print("line:", line)
111                    print("load address:", LA)
112                    print("SA:", SA)
113                if SA and LA:
114                    if int(LA, 16) > int(SA, 16):
115                        self.runCmd("disassemble -s %s -e %s" % (SA, LA))
116                SA = LA
117            else:
118                # This entry is not a Code entry.  Reset SA = None.
119                SA = None
120