1"""Test aspects of lldb commands on universal binaries."""
2
3
4
5import unittest2
6import os
7import lldb
8from lldbsuite.test.decorators import *
9from lldbsuite.test.lldbtest import *
10from lldbsuite.test import lldbutil
11
12def haswellOrLater():
13    features = subprocess.check_output(["sysctl", "machdep.cpu"])
14    return "AVX2" in features.split()
15
16class UniversalTestCase(TestBase):
17
18    NO_DEBUG_INFO_TESTCASE = True
19    mydir = TestBase.compute_mydir(__file__)
20
21    def setUp(self):
22        # Call super's setUp().
23        TestBase.setUp(self)
24        # Find the line number to break inside main().
25        self.line = line_number('main.c', '// Set break point at this line.')
26
27    @add_test_categories(['pyapi'])
28    @skipUnlessDarwin
29    @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in
30                          ['x86_64'], "requires x86_64")
31    @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system
32    def test_sbdebugger_create_target_with_file_and_target_triple(self):
33        """Test the SBDebugger.CreateTargetWithFileAndTargetTriple() API."""
34        # Invoke the default build rule.
35        self.build()
36
37        # Note that "testit" is a universal binary.
38        exe = self.getBuildArtifact("testit")
39
40        # Create a target by the debugger.
41        target = self.dbg.CreateTargetWithFileAndTargetTriple(
42            exe, "x86_64-apple-macosx")
43        self.assertTrue(target, VALID_TARGET)
44        self.expect("image list -A -b", substrs=["x86_64 testit"])
45
46        # Now launch the process, and do not stop at entry point.
47        process = target.LaunchSimple(
48            None, None, self.get_process_working_directory())
49        self.assertTrue(process, PROCESS_IS_VALID)
50
51    @skipUnlessDarwin
52    @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in
53                          ['x86_64'], "requires x86_64")
54    @skipIfDarwinEmbedded # this test file assumes we're targetting an x86 system
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        self.addTearDownHook(self.cleanupSubprocesses)
141
142        error = lldb.SBError()
143        empty_listener = lldb.SBListener()
144        process = target.AttachToProcessWithID(
145            empty_listener, popen.pid, error)
146        self.assertTrue(error.Success(), "Attached to process.")
147
148        self.expect("image list -A -b", substrs=["x86_64h testit"])
149
150        # It may seem odd to check the number of frames, but the bug
151        # that motivated this test was that we eventually fixed the
152        # architecture, but we left the ABI set to the original value.
153        # In that case, if you asked the process for its architecture,
154        # it would look right, but since the ABI was wrong,
155        # backtracing failed.
156
157        threads = lldbutil.continue_to_breakpoint(process, bkpt)
158        self.assertEquals(len(threads), 1)
159        thread = threads[0]
160        self.assertTrue(
161            thread.GetNumFrames() > 1,
162            "We were able to backtrace.")
163