1import unittest2
2import os
3import lldb
4from lldbsuite.test.decorators import *
5from lldbsuite.test.lldbtest import *
6from lldbsuite.test import lldbutil
7
8def haswellOrLater():
9    features = subprocess.check_output(["sysctl", "machdep.cpu"])
10    return "AVX2" in features.split()
11
12class UniversalTestCase(TestBase):
13    """Test aspects of lldb commands on universal binaries."""
14
15    NO_DEBUG_INFO_TESTCASE = True
16    mydir = TestBase.compute_mydir(__file__)
17
18    def setUp(self):
19        # Call super's setUp().
20        TestBase.setUp(self)
21        # Find the line number to break inside main().
22        self.line = line_number('main.c', '// Set break point at this line.')
23
24    @add_test_categories(['pyapi'])
25    @skipUnlessDarwin
26    @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in
27                          ['x86_64'], "requires x86_64")
28    @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system
29    @skipIf(compiler="clang", compiler_version=['<', '7.0'])
30    def test_sbdebugger_create_target_with_file_and_target_triple(self):
31        """Test the SBDebugger.CreateTargetWithFileAndTargetTriple() API."""
32        # Invoke the default build rule.
33        self.build()
34
35        # Note that "testit" is a universal binary.
36        exe = self.getBuildArtifact("testit")
37
38        # Create a target by the debugger.
39        target = self.dbg.CreateTargetWithFileAndTargetTriple(
40            exe, "x86_64-apple-macosx10.10")
41        self.assertTrue(target, VALID_TARGET)
42        self.expect("image list -t -b", substrs=["x86_64-apple-macosx10.9.0 testit"])
43        self.expect("target list", substrs=["testit", "arch=x86_64-apple-macosx10.10"])
44
45        # Now launch the process, and do not stop at entry point.
46        process = target.LaunchSimple(
47            None, None, self.get_process_working_directory())
48        self.assertTrue(process, PROCESS_IS_VALID)
49
50    @skipUnlessDarwin
51    @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in
52                          ['x86_64'], "requires x86_64")
53    @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system
54    @skipIf(compiler="clang", compiler_version=['<', '7.0'])
55    def test_process_launch_for_universal(self):
56        """Test process launch of a universal binary."""
57        from lldbsuite.test.lldbutil import print_registers
58
59        if not haswellOrLater():
60            return
61
62        # Invoke the default build rule.
63        self.build()
64
65        # Note that "testit" is a universal binary.
66        exe = self.getBuildArtifact("testit")
67
68        # By default, x86_64 is assumed if no architecture is specified.
69        self.expect("file " + exe, CURRENT_EXECUTABLE_SET,
70                    startstr="Current executable set to ",
71                    substrs=["testit' (x86_64h)."])
72
73        # Break inside the main.
74        lldbutil.run_break_set_by_file_and_line(
75            self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
76
77        # We should be able to launch the x86_64h executable.
78        self.runCmd("run", RUN_SUCCEEDED)
79
80        # Check whether we have a x86_64h process launched.
81        target = self.dbg.GetSelectedTarget()
82        process = target.GetProcess()
83        self.expect("image list -A -b", substrs=["x86_64h testit"])
84        self.runCmd("continue")
85
86        # Now specify x86_64 as the architecture for "testit".
87        self.expect("file -a x86_64 " + exe, CURRENT_EXECUTABLE_SET,
88                    startstr="Current executable set to ",
89                    substrs=["testit' (x86_64)."])
90
91        # Break inside the main.
92        lldbutil.run_break_set_by_file_and_line(
93            self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
94
95        # We should be able to launch the x86_64 executable as well.
96        self.runCmd("run", RUN_SUCCEEDED)
97
98        # Check whether we have a x86_64 process launched.
99
100        # FIXME: This wrong. We are expecting x86_64, but spawning a
101        # new process currently doesn't allow specifying a *sub*-architecture.
102        # <rdar://problem/46101466>
103        self.expect("image list -A -b", substrs=["x86_64h testit"])
104        self.runCmd("continue")
105
106    @skipUnlessDarwin
107    @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in
108                          ['x86_64'], "requires x86_64")
109    @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system
110    def test_process_attach_with_wrong_arch(self):
111        """Test that when we attach to a binary from the wrong fork of
112            a universal binary, we fix up the ABI correctly."""
113        if not haswellOrLater():
114            return
115
116        # Now keep the architecture at x86_64, but switch the binary
117        # we launch to x86_64h, and make sure on attach we switch to
118        # the correct architecture.
119
120        # Invoke the default build rule.
121        self.build()
122
123        # Note that "testit" is a universal binary.
124        exe = self.getBuildArtifact("testit")
125
126        # Create a target by the debugger.
127        target = self.dbg.CreateTargetWithFileAndTargetTriple(
128            exe, "x86_64-apple-macosx")
129        self.assertTrue(target, VALID_TARGET)
130        self.expect("image list -A -b", substrs=["x86_64 testit"])
131
132        bkpt = target.BreakpointCreateBySourceRegex(
133            "sleep", lldb.SBFileSpec("main.c"))
134        self.assertTrue(bkpt.IsValid(), "Valid breakpoint")
135        self.assertTrue(
136            bkpt.GetNumLocations() >= 1,
137            "Our main breakpoint has locations.")
138
139        popen = self.spawnSubprocess(exe, ["keep_waiting"])
140
141        error = lldb.SBError()
142        empty_listener = lldb.SBListener()
143        process = target.AttachToProcessWithID(
144            empty_listener, popen.pid, error)
145        self.assertTrue(error.Success(), "Attached to process.")
146
147        self.expect("image list -A -b", substrs=["x86_64h testit"])
148
149        # It may seem odd to check the number of frames, but the bug
150        # that motivated this test was that we eventually fixed the
151        # architecture, but we left the ABI set to the original value.
152        # In that case, if you asked the process for its architecture,
153        # it would look right, but since the ABI was wrong,
154        # backtracing failed.
155
156        threads = lldbutil.continue_to_breakpoint(process, bkpt)
157        self.assertEquals(len(threads), 1)
158        thread = threads[0]
159        self.assertTrue(
160            thread.GetNumFrames() > 1,
161            "We were able to backtrace.")
162