1"""
2Use lldb Python API to disassemble raw machine code bytes
3"""
4
5from __future__ import print_function
6
7from io import StringIO
8import sys
9
10import lldb
11from lldbsuite.test.decorators import *
12from lldbsuite.test.lldbtest import *
13from lldbsuite.test import lldbutil
14
15
16class Disassemble_VST1_64(TestBase):
17
18    mydir = TestBase.compute_mydir(__file__)
19
20    @add_test_categories(['pyapi'])
21    @no_debug_info_test
22    @skipIfLLVMTargetMissing("ARM")
23    @skipIfReproducer # lldb::FileSP used in typemap cannot be instrumented.
24    def test_disassemble_invalid_vst_1_64_raw_data(self):
25        """Test disassembling invalid vst1.64 raw bytes with the API."""
26        # Create a target from the debugger.
27        target = self.dbg.CreateTargetWithFileAndTargetTriple("", "thumbv7-apple-macosx")
28        self.assertTrue(target, VALID_TARGET)
29
30        raw_bytes = bytearray([0xf0, 0xb5, 0x03, 0xaf,
31                               0x2d, 0xe9, 0x00, 0x0d,
32                               0xad, 0xf1, 0x40, 0x04,
33                               0x24, 0xf0, 0x0f, 0x04,
34                               0xa5, 0x46])
35
36        assembly = """
37        push   {r4, r5, r6, r7, lr}
38        add    r7, sp, #0xc
39        push.w {r8, r10, r11}
40        sub.w  r4, sp, #0x40
41        bic    r4, r4, #0xf
42        mov    sp, r4
43        """
44        def split(s):
45            return [x.strip() for x in s.strip().splitlines()]
46
47        insts = target.GetInstructions(lldb.SBAddress(), raw_bytes)
48
49        if self.TraceOn():
50            print()
51            for i in insts:
52                print("Disassembled %s" % str(i))
53
54        if sys.version_info.major >= 3:
55            sio = StringIO()
56            insts.Print(sio)
57            self.assertEqual(split(assembly), split(sio.getvalue()))
58
59        self.assertEqual(insts.GetSize(), len(split(assembly)))
60
61        if sys.version_info.major >= 3:
62            for i,asm in enumerate(split(assembly)):
63                inst = insts.GetInstructionAtIndex(i)
64                sio = StringIO()
65                inst.Print(sio)
66                self.assertEqual(asm, sio.getvalue().strip())
67
68        raw_bytes = bytearray([0x04, 0xf9, 0xed, 0x82])
69
70        insts = target.GetInstructions(lldb.SBAddress(), raw_bytes)
71
72        inst = insts.GetInstructionAtIndex(0)
73
74        if self.TraceOn():
75            print()
76            print("Raw bytes:    ", [hex(x) for x in raw_bytes])
77            print("Disassembled%s" % str(inst))
78
79        self.assertTrue(inst.GetMnemonic(target) == "vst1.64")
80