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