1"""
2Use lldb Python API to disassemble raw machine code bytes
3"""
4
5from __future__ import print_function
6
7
8import re
9import lldb
10from lldbsuite.test.decorators import *
11from lldbsuite.test.lldbtest import *
12from lldbsuite.test import lldbutil
13
14
15class DisassembleRawDataTestCase(TestBase):
16
17    mydir = TestBase.compute_mydir(__file__)
18
19    @no_debug_info_test
20    @skipIfRemote
21    @skipIfReproducer # GetInstructions is not instrumented.
22    def test_disassemble_raw_data(self):
23        """Test disassembling raw bytes with the API."""
24        # Create a target from the debugger.
25        arch = self.getArchitecture()
26        if re.match("mips*el", arch):
27            target = self.dbg.CreateTargetWithFileAndTargetTriple("", "mipsel")
28            raw_bytes = bytearray([0x21, 0xf0, 0xa0, 0x03])
29        elif re.match("mips", arch):
30            target = self.dbg.CreateTargetWithFileAndTargetTriple("", "mips")
31            raw_bytes = bytearray([0x03, 0xa0, 0xf0, 0x21])
32        elif re.match("powerpc64le", arch):
33            target = self.dbg.CreateTargetWithFileAndTargetTriple("", "powerpc64le")
34            raw_bytes = bytearray([0x00, 0x00, 0x80, 0x38])
35        else:
36            target = self.dbg.CreateTargetWithFileAndTargetTriple("", "x86_64")
37            raw_bytes = bytearray([0x48, 0x89, 0xe5])
38
39        self.assertTrue(target, VALID_TARGET)
40        insts = target.GetInstructions(lldb.SBAddress(0, target), raw_bytes)
41
42        inst = insts.GetInstructionAtIndex(0)
43
44        if self.TraceOn():
45            print()
46            print("Raw bytes:    ", [hex(x) for x in raw_bytes])
47            print("Disassembled%s" % str(inst))
48        if re.match("mips", arch):
49            self.assertEqual(inst.GetMnemonic(target), "move")
50            self.assertEqual(inst.GetOperands(target),
51                            '$' + "fp, " + '$' + "sp")
52        elif re.match("powerpc64le", arch):
53            self.assertEqual(inst.GetMnemonic(target), "li")
54            self.assertEqual(inst.GetOperands(target), "4, 0")
55        else:
56            self.assertEqual(inst.GetMnemonic(target), "movq")
57            self.assertEqual(inst.GetOperands(target),
58                            '%' + "rsp, " + '%' + "rbp")
59