Python capstone.CS_MODE_ARM Examples

The following are 30 code examples of capstone.CS_MODE_ARM(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module capstone , or try the search function .
Example #1
Source File: DisasmViewMode.py    From qiew with GNU General Public License v2.0 6 votes vote down vote up
def init_disassembler_engine(self):
        # init state for disasambler
        # set capstone, lexer, asmline

        arch, mode = self.plugin.hintDisasm()

        self.disasm_engine = capstone.Cs(arch, mode)
        self.disasm_engine.detail = True

        if arch == capstone.CS_ARCH_X86:
            Lexer = X86_Lexer()

        if arch == capstone.CS_ARCH_ARM and mode in [capstone.CS_MODE_ARM, capstone.CS_MODE_THUMB]:
            Lexer = ARM_Lexer()

        if arch == capstone.CS_ARCH_ARM64:
            Lexer = ARM64_Lexer()

        # todo: ASM_ARM_Line?
        self.ASMLine = ASMx86Line
        Lexer.build()
        self.lexer = Lexer.lexer() 
Example #2
Source File: test_armv7cpu.py    From manticore with GNU Affero General Public License v3.0 6 votes vote down vote up
def _setupCpu(self, asm, mode=CS_MODE_ARM, multiple_insts=False):
        self.code = self.mem.mmap(0x1000, 0x1000, "rwx")
        self.data = self.mem.mmap(0xD000, 0x1000, "rw")
        self.stack = self.mem.mmap(0xF000, 0x1000, "rw")

        # it doesn't really matter what's the starting address of code
        # as long as it's known and constant for all the tests;
        # we start it at +4 as it is convenient for some tests to use pc-4 reference
        # (see e.g. test_bl_neg test)
        start = self.code + 4
        if multiple_insts:
            offset = 0
            for asm_single in asm:
                asm_inst = assemble(asm_single, mode)
                self.mem.write(start + offset, asm_inst)
                offset += len(asm_inst)
        else:
            self.mem.write(start, assemble(asm, mode))
        self.rf.write("PC", start)
        self.rf.write("SP", self.stack + 0x1000)
        self.cpu.mode = mode 
Example #3
Source File: test_armv7cpu.py    From manticore with GNU Affero General Public License v3.0 6 votes vote down vote up
def _ks_assemble(asm: str, mode=CS_MODE_ARM) -> bytes:
    """Assemble the given string using Keystone using the specified CPU mode."""
    # Explicitly uses late importing so that Keystone will only be imported if this is called.
    # This lets us avoid requiring installation of Keystone for running tests.
    global ks, ks_thumb
    from keystone import Ks, KS_ARCH_ARM, KS_MODE_ARM, KS_MODE_THUMB

    if ks is None:
        ks = Ks(KS_ARCH_ARM, KS_MODE_ARM)
    if ks_thumb is None:
        ks_thumb = Ks(KS_ARCH_ARM, KS_MODE_THUMB)

    if CS_MODE_ARM == mode:
        ords = ks.asm(asm)[0]

    elif CS_MODE_THUMB == mode:
        ords = ks_thumb.asm(asm)[0]
    else:
        raise Exception(f"bad processor mode for assembly: {mode}")
    if not ords:
        raise Exception(f"bad assembly: {asm}")
    return binascii.hexlify(bytearray(ords)) 
Example #4
Source File: test_armv7unicorn.py    From manticore with GNU Affero General Public License v3.0 6 votes vote down vote up
def _ks_assemble(asm: str, mode=CS_MODE_ARM) -> bytes:
    """Assemble the given string using Keystone using the specified CPU mode."""
    # Explicitly uses late importing so that Keystone will only be imported if this is called.
    # This lets us avoid requiring installation of Keystone for running tests.
    global ks, ks_thumb
    from keystone import Ks, KS_ARCH_ARM, KS_MODE_ARM, KS_MODE_THUMB

    if ks is None:
        ks = Ks(KS_ARCH_ARM, KS_MODE_ARM)
    if ks_thumb is None:
        ks_thumb = Ks(KS_ARCH_ARM, KS_MODE_THUMB)

    if CS_MODE_ARM == mode:
        ords = ks.asm(asm)[0]
    elif CS_MODE_THUMB == mode:
        ords = ks_thumb.asm(asm)[0]
    else:
        raise Exception(f"bad processor mode for assembly: {mode}")
    if not ords:
        raise Exception(f"bad assembly: {asm}")
    return binascii.hexlify(bytearray(ords)) 
Example #5
Source File: arm.py    From manticore with GNU Affero General Public License v3.0 6 votes vote down vote up
def _set_mode_by_val(self, val):
        new_mode = Operators.ITEBV(
            self.address_bit_size, (val & 0x1) == 0x1, cs.CS_MODE_THUMB, cs.CS_MODE_ARM
        )

        if issymbolic(new_mode):
            from ..state import Concretize

            def set_concrete_mode(state, value):
                state.cpu.mode = value

            raise Concretize(
                "Concretizing ARMv7 mode", expression=new_mode, setstate=set_concrete_mode
            )

        self.mode = new_mode 
Example #6
Source File: aarch64.py    From rainbow with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, trace=True, sca_mode=False, local_vars=[]):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_ARM64, uc.UC_MODE_ARM)
        self.disasm = cs.Cs(cs.CS_ARCH_ARM64, cs.CS_MODE_ARM)
        self.disasm.detail = True
        self.word_size = 8
        self.endianness = "little"
        self.page_size = self.emu.query(uc.UC_QUERY_PAGE_SIZE)
        self.page_shift = self.page_size.bit_length() - 1
        self.pc = uc.arm64_const.UC_ARM64_REG_PC

        known_regs = [i[len('UC_ARM64_REG_'):] for i in dir(uc.arm64_const) if '_REG' in i]
        self.reg_map = {r.lower(): getattr(uc.arm64_const, 'UC_ARM64_REG_'+r) for r in known_regs}

        self.stubbed_functions = local_vars
        self.setup(sca_mode)
        
        self.reset_stack() 
Example #7
Source File: arm.py    From rainbow with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, trace=True, sca_mode=False, local_vars={}):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_ARM, uc.UC_MODE_ARM)
        self.disasm = cs.Cs(cs.CS_ARCH_ARM, cs.CS_MODE_ARM | cs.CS_MODE_THUMB)
        self.disasm.detail = True
        self.word_size = 4
        self.endianness = "little"
        self.page_size = self.emu.query(uc.UC_QUERY_PAGE_SIZE)
        self.page_shift = self.page_size.bit_length() - 1
        self.pc = uc.arm_const.UC_ARM_REG_PC

        known_regs = [i[len('UC_ARM_REG_'):] for i in dir(uc.arm_const) if '_REG' in i]
        self.reg_map = {r.lower(): getattr(uc.arm_const, 'UC_ARM_REG_'+r) for r in known_regs}

        self.stubbed_functions = local_vars
        self.setup(sca_mode)
    
        self.reset_stack() 
Example #8
Source File: disassembler.py    From barf-project with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _cs_disassemble_one(self, data, address):
        """Disassemble the data into an instruction in string form.
        """
        disasm = list(self._disassembler.disasm(bytes(data), address))

        # TODO: Improve this check.
        if len(disasm) > 0:
            return disasm[0]
        else:
            cs_arm = Cs(CS_ARCH_ARM, CS_MODE_ARM)
            cs_arm.detail = True
            disasm = list(cs_arm.disasm(bytes(data), address))

            if len(disasm) > 0:
                return disasm[0]
            else:
                raise InvalidDisassemblerData("CAPSTONE: Unknown instruction (Addr: {:s}).".format(hex(address))) 
Example #9
Source File: disassembler.py    From barf-project with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __setup_available_disassemblers(self):
        arch_map = {
            ARCH_ARM_MODE_ARM:   CS_MODE_ARM,
            ARCH_ARM_MODE_THUMB: CS_MODE_THUMB,
        }

        self._available_disassemblers = {
            ARCH_ARM_MODE_ARM:   Cs(CS_ARCH_ARM, arch_map[ARCH_ARM_MODE_ARM]),
            ARCH_ARM_MODE_THUMB: Cs(CS_ARCH_ARM, arch_map[ARCH_ARM_MODE_THUMB]),
        }

        self._available_disassemblers[ARCH_ARM_MODE_ARM].detail = True
        self._available_disassemblers[ARCH_ARM_MODE_THUMB].detail = True

    # Casptone to BARF translation
    # ======================================================================== # 
Example #10
Source File: disassembler.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, mode, **kwargs):
        super(Capstone, self).__init__(mode, **kwargs)

        if self.mode == "I386":
            self.cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
        elif self.mode == "AMD64":
            self.cs = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
        elif self.mode == "MIPS":
            self.cs = capstone.Cs(capstone.CS_ARCH_MIPS, capstone.CS_MODE_32 +
                                  capstone.CS_MODE_BIG_ENDIAN)
        # This is not really supported yet.
        elif self.mode == "ARM":
            self.cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM)
        else:
            raise NotImplementedError(
                "No disassembler available for this arch.")

        self.cs.detail = True
        self.cs.skipdata_setup = ("db", None, None)
        self.cs.skipdata = True 
Example #11
Source File: disasm.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def _import_dependencies(self):

        # Load the Capstone bindings.
        global capstone
        if capstone is None:
            import capstone

        # Load the constants for the requested architecture.
        self.__constants = {
            win32.ARCH_I386:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_32),
            win32.ARCH_AMD64:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_64),
            win32.ARCH_THUMB:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_THUMB),
            win32.ARCH_ARM:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_ARM),
            win32.ARCH_ARM64:
                (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
        }

        # Test for the bug in early versions of Capstone.
        # If found, warn the user about it.
        try:
            self.__bug = not isinstance(
                capstone.cs_disasm_quick(
                    capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1)[0],
                capstone.capstone.CsInsn)
        except AttributeError:
            self.__bug = False
        if self.__bug:
            warnings.warn(
                "This version of the Capstone bindings is unstable,"
                " please upgrade to a newer one!",
                RuntimeWarning, stacklevel=4) 
Example #12
Source File: database.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def mdarm(self):
        if self._mdarm is None:
            self._mdarm = capstone.Cs(capstone.CS_ARCH_ARM,
                                      capstone.CS_MODE_ARM + capstone.CS_MODE_V8)
            self._mdarm.detail = True
        return self._mdarm 
Example #13
Source File: database.py    From bootloader_instrumentation_suite with MIT License 5 votes vote down vote up
def uboot_mux_init(self):
        self._mux_name = "set_muxconf_regs"
        (self._mux_start, self._mux_end) = utils.get_symbol_location_start_end(self._mux_name,
                                                                               self.stage)
        self._mux_start += 2
        self._mux_end -= 2
        if self.thumbranges.overlaps_point(self._mux_start):
            self.cs = capstone.Cs(CS_ARCH_ARM, CS_MODE_THUMB)
            self.cs.detail = True
            self._thumb = True
            self.emu = Uc(UC_ARCH_ARM, UC_MODE_THUMB)
        else:
            self.cs = capstone.Cs(CS_ARCH_ARM, CS_MODE_ARM)
            self.cs.detail = True
            self._thumb = False
            self.emu = Uc(UC_ARCH_ARM, UC_MODE_ARM)
        entrypoint = self._mux_start
        headers = pure_utils.get_section_headers(elf)
        for h in headers:
            if h['size'] > 0:
                codeaddr = h['virtaddr']
                break
        alignedstart = self._mux_start & 0xFFFFF0000
        size = 2*1024*1024
        fileoffset = alignedstart
        elf = stage.elf
        code = open(elf, "rb").read()[self._mux_start-fileoffset:self._mux_end-fileoffset]
        hw = Main.get_hardwareclass_config()
        for i in hw.addr_range:
            if i.begin == 0:
                size = i.end
            else:
                size = i.begin - i.end
            self.emu.mem_map(i.begin, size, UC_PROT_ALL)

        self.emu.mem_write(self._mux_start, code)
        self.emu.reg_write(self.stage.elf.entrypoint, ARM_REG_SP) 
Example #14
Source File: disasm.py    From OpenXMolar with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, arch = None):
        super(CapstoneEngine, self).__init__(arch)

        # Load the constants for the requested architecture.
        self.__constants = {
            win32.ARCH_I386:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_32),
            win32.ARCH_AMD64:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_64),
            win32.ARCH_THUMB:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_THUMB),
            win32.ARCH_ARM:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_ARM),
            win32.ARCH_ARM64:
                (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
        }

        # Test for the bug in early versions of Capstone.
        # If found, warn the user about it.
        try:
            self.__bug = not isinstance(
                list(capstone.cs_disasm_quick(
                    capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1
                ))[0],
                capstone.capstone.CsInsn
            )
        except AttributeError:
            self.__bug = False
        if self.__bug:
            warnings.warn(
                "This version of the Capstone bindings is unstable,"
                " please upgrade to a newer one!",
                RuntimeWarning, stacklevel=4) 
Example #15
Source File: test_armv7cpu.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_blx_reg(self):
        self.assertEqual(self.rf.read("PC"), 0x1008)
        self.assertEqual(self.rf.read("LR"), 0x1008)
        self.assertEqual(self.cpu.mode, CS_MODE_ARM) 
Example #16
Source File: test_armv7cpu.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_bx_basic(self):
        self.cpu.execute()
        self.assertEqual(self.rf.read("PC"), 0x1008)
        self.assertEqual(self.cpu.mode, CS_MODE_ARM) 
Example #17
Source File: test_armv7cpu.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_ldr_imm_off_none(self):
        self.cpu.stack_push(42)
        self.cpu.execute()
        self.assertEqual(self.rf.read("R1"), 42)
        self.assertEqual(self.cpu.mode, CS_MODE_ARM) 
Example #18
Source File: test_armv7cpu.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def itest_multiple(asms):
    def instr_dec(assertions_func):
        @wraps(assertions_func)
        def wrapper(self):
            self._setupCpu(asms, mode=CS_MODE_ARM, multiple_insts=True)
            for i in range(len(asms)):
                self.cpu.execute()
            assertions_func(self)

        return wrapper

    return instr_dec 
Example #19
Source File: test_armv7cpu.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def assemble(asm: str, mode=CS_MODE_ARM) -> bytes:
    """
    Assemble the given string.
    
    An assembly cache is first checked, and if there is no entry there, then Keystone is used.
    """
    if asm in assembly_cache[mode]:
        return binascii.unhexlify(assembly_cache[mode][asm])
    return binascii.unhexlify(_ks_assemble(asm, mode=mode)) 
Example #20
Source File: disasm.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def _import_dependencies(self):

        # Load the Capstone bindings.
        global capstone
        if capstone is None:
            import capstone

        # Load the constants for the requested architecture.
        self.__constants = {
            win32.ARCH_I386:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_32),
            win32.ARCH_AMD64:
                (capstone.CS_ARCH_X86,   capstone.CS_MODE_64),
            win32.ARCH_THUMB:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_THUMB),
            win32.ARCH_ARM:
                (capstone.CS_ARCH_ARM,   capstone.CS_MODE_ARM),
            win32.ARCH_ARM64:
                (capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
        }

        # Test for the bug in early versions of Capstone.
        # If found, warn the user about it.
        try:
            self.__bug = not isinstance(
                capstone.cs_disasm_quick(
                    capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1)[0],
                capstone.capstone.CsInsn)
        except AttributeError:
            self.__bug = False
        if self.__bug:
            warnings.warn(
                "This version of the Capstone bindings is unstable,"
                " please upgrade to a newer one!",
                RuntimeWarning, stacklevel=4) 
Example #21
Source File: test_armv7unicorn.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def _setupCpu(self, asm, mode=CS_MODE_ARM):
        self.code = self.mem.mmap(0x1000, 0x1000, "rwx")
        self.data = self.mem.mmap(0xD000, 0x1000, "rw")
        self.stack = self.mem.mmap(0xF000, 0x1000, "rw")
        start = self.code + 4
        self.mem.write(start, assemble(asm, mode))
        self.rf.write("PC", start)
        self.rf.write("SP", self.stack + 0x1000)
        self.cpu.mode = mode 
Example #22
Source File: test_armv7unicorn.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def assemble(asm: str, mode=CS_MODE_ARM) -> bytes:
    """
    Assemble the given string.
    
    An assembly cache is first checked, and if there is no entry there, then Keystone is used.
    """
    if asm in assembly_cache[mode]:
        return binascii.unhexlify(assembly_cache[mode][asm])
    return binascii.unhexlify(_ks_assemble(asm, mode=mode)) 
Example #23
Source File: translator.py    From reil with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        TranslationContext.__init__(self)

        self.registers = {
            capstone.arm.ARM_REG_R0:    r('r0', 32),
            capstone.arm.ARM_REG_R1:    r('r1', 32),
            capstone.arm.ARM_REG_R2:    r('r2', 32),
            capstone.arm.ARM_REG_R3:    r('r3', 32),
            capstone.arm.ARM_REG_R4:    r('r4', 32),
            capstone.arm.ARM_REG_R5:    r('r5', 32),
            capstone.arm.ARM_REG_R6:    r('r6', 32),
            capstone.arm.ARM_REG_R7:    r('r7', 32),
            capstone.arm.ARM_REG_R8:    r('r8', 32),
            capstone.arm.ARM_REG_R9:    r('r9', 32),
            capstone.arm.ARM_REG_R10:   r('r10', 32),
            capstone.arm.ARM_REG_R11:   r('r11', 32),
            capstone.arm.ARM_REG_R13:   r('sp', 32),
            capstone.arm.ARM_REG_R14:   r('lr', 32),
            capstone.arm.ARM_REG_R15:   r('pc', 32),
        }

        self.word_size = 32
        self.thumb = False
        self.stack_ptr = self.registers[capstone.arm.ARM_REG_R13]
        self.link_reg = self.registers[capstone.arm.ARM_REG_R14]
        self.program_ctr = self.registers[capstone.arm.ARM_REG_R15]
        self.disassembler = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM)
        self.disassembler.detail = True 
Example #24
Source File: arm.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def _swap_mode(self):
        """Toggle between ARM and Thumb mode"""
        assert self.mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB)
        if self.mode == cs.CS_MODE_ARM:
            self.mode = cs.CS_MODE_THUMB
        else:
            self.mode = cs.CS_MODE_ARM

    # Flags that are the result of arithmetic instructions. Unconditionally
    # set, but conditionally committed.
    #
    # Register file has the actual CPU flags 
Example #25
Source File: arm.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def mode(self, new_mode):
        assert new_mode in (cs.CS_MODE_ARM, cs.CS_MODE_THUMB)

        if self._mode != new_mode:
            logger.debug(f'swapping into {"ARM" if new_mode == cs.CS_MODE_ARM else "THUMB"} mode')

        self._mode = new_mode
        self.disasm.disasm.mode = new_mode 
Example #26
Source File: arm.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, memory):
        self._it_conditional = list()
        self._last_flags = {"C": 0, "V": 0, "N": 0, "Z": 0, "GE": 0}
        self._at_symbolic_conditional = None
        self._mode = cs.CS_MODE_ARM
        super().__init__(Armv7RegisterFile(), memory) 
Example #27
Source File: arm.py    From manticore with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_mem_base_addr(self):
        assert self.__type == "memory"

        base = self.cpu.regfile.read(self.mem.base)

        # PC relative addressing is fun in ARM:
        # In ARM mode, the spec defines the base value as current insn + 8
        # In thumb mode, the spec defines the base value as ALIGN(current insn address) + 4,
        # where ALIGN(current insn address) => <current insn address> & 0xFFFFFFFC
        #
        # Regardless of mode, our implementation of read(PC) will return the address
        # of the instruction following the next instruction.
        if self.mem.base in ("PC", "R15"):
            if self.cpu.mode == cs.CS_MODE_ARM:
                logger.debug(f"ARM mode PC relative addressing: PC + offset: 0x{base:x} + 0x{4:x}")
                return base + 4
            else:
                # base currently has the value PC + len(current_instruction)
                # we need (PC & 0xFFFFFFFC) + 4
                # thus:
                new_base = (base - self.cpu.instruction.size) & 0xFFFFFFFC
                logger.debug(
                    f"THUMB mode PC relative addressing: ALIGN(PC) + offset => 0x{new_base:x} + 0x{4:x}"
                )
                return new_base + 4
        else:
            return base 
Example #28
Source File: assembly_repository.py    From Il2cppSpy with MIT License 5 votes vote down vote up
def disassemble(self, code: bytes, address: int) -> List[DumpAssembly]:
        dump_assemblies = []
        md = Cs(CS_ARCH_ARM, CS_MODE_ARM)
        for i in md.disasm(code, address):
            dump_assemblies.append(DumpAssembly(i.address, f'{i.mnemonic}\t{i.op_str}'))
        return dump_assemblies 
Example #29
Source File: translator.py    From reil with Apache License 2.0 4 votes vote down vote up
def __init__(self):
        TranslationContext.__init__(self)

        self.registers = {
            capstone.arm64.ARM64_REG_X0:  r('x0',  64),
            capstone.arm64.ARM64_REG_X1:  r('x1',  64),
            capstone.arm64.ARM64_REG_X2:  r('x2',  64),
            capstone.arm64.ARM64_REG_X3:  r('x3',  64),
            capstone.arm64.ARM64_REG_X4:  r('x4',  64),
            capstone.arm64.ARM64_REG_X5:  r('x5',  64),
            capstone.arm64.ARM64_REG_X6:  r('x6',  64),
            capstone.arm64.ARM64_REG_X7:  r('x7',  64),
            capstone.arm64.ARM64_REG_X8:  r('x8',  64),
            capstone.arm64.ARM64_REG_X9:  r('x9',  64),
            capstone.arm64.ARM64_REG_X10: r('x10', 64),
            capstone.arm64.ARM64_REG_X11: r('x11', 64),
            capstone.arm64.ARM64_REG_X12: r('x12', 64),
            capstone.arm64.ARM64_REG_X13: r('x13', 64),
            capstone.arm64.ARM64_REG_X14: r('x14', 64),
            capstone.arm64.ARM64_REG_X15: r('x15', 64),
            capstone.arm64.ARM64_REG_X16: r('x16', 64),
            capstone.arm64.ARM64_REG_X17: r('x17', 64),
            capstone.arm64.ARM64_REG_X18: r('x18', 64),
            capstone.arm64.ARM64_REG_X19: r('x19', 64),
            capstone.arm64.ARM64_REG_X20: r('x20', 64),
            capstone.arm64.ARM64_REG_X21: r('x21', 64),
            capstone.arm64.ARM64_REG_X22: r('x22', 64),
            capstone.arm64.ARM64_REG_X23: r('x23', 64),
            capstone.arm64.ARM64_REG_X24: r('x24', 64),
            capstone.arm64.ARM64_REG_X25: r('x25', 64),
            capstone.arm64.ARM64_REG_X26: r('x26', 64),
            capstone.arm64.ARM64_REG_X27: r('x27', 64),
            capstone.arm64.ARM64_REG_X28: r('x28', 64),
            capstone.arm64.ARM64_REG_X29: r('x29', 64),
            capstone.arm64.ARM64_REG_X30: r('x30', 64),
            capstone.arm64.ARM64_REG_SP:  r('sp',  64),
            capstone.arm64.ARM64_REG_LR:  r('lr',  64),
        }

        self.word_size = 64
        self.stack_ptr = self.registers[capstone.arm64.ARM64_REG_SP]
        self.link_reg = self.registers[capstone.arm64.ARM64_REG_LR]
        self.program_ctr = r('pc', 64)
        self.disassembler = capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
        self.disassembler.detail = True 
Example #30
Source File: gdb_tools.py    From bootloader_instrumentation_suite with MIT License 4 votes vote down vote up
def __init__(self, controller, r, stage):
        # controller.gdb_print("creating longwrite break\n")
        self.emptywrite = {'start': None,
                           'end': None,
                           'pc': None}
        self.writeinfo = self.emptywrite
        self.breakaddr = r['breakaddr']
        self.contaddr = r['contaddr']
        self.writeaddr = r['writeaddr']
        self.thumb = r['thumb']
        r2.gets(stage.elf, "s 0x%x" % self.writeaddr)
        if self.thumb:
            self.emu = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_THUMB)
            r2.gets(stage.elf, "ahb 16")
            r2.gets(stage.elf, "e asm.bits=16")
            self.cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
        else:
            self.emu = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_ARM)
            r2.gets(stage.elf, "ahb 32")
            r2.gets(stage.elf, "e asm.bits=32")
            self.cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM)
        r2.get(stage.elf, "pdj 1")

        self.cs.detail = True
        self.info = staticanalysis.LongWriteInfo(stage.elf, r['start'],
                                                 r['end'], self.thumb)
        self.inss = []
        self.regs = set()
        self.bytes = b""
        self.dst_addrs = []
        self.write_size = r['writesize']
        for i in self.info.bbs:
            self.inss.append(i)
            bs = i["bytes"].decode("hex")
            self.bytes += b"%s" % bs
            ci = next(self.cs.disasm(bs, i["offset"], 1))
            if i["offset"] == self.writeaddr:
                self.write_ins = ci
            (read, write) = ci.regs_access()
            for rs in (read, write):
                self.regs.update([ci.reg_name(rn).encode('ascii') for rn in rs])
        self.emu.mem_map(0, 0xFFFFFFFF + 1, unicorn.UC_PROT_ALL)
        self.emu.mem_write(self.inss[0]["offset"], self.bytes)
        self.emu.hook_add(unicorn.UC_HOOK_MEM_WRITE, self.write_hook)
        self.spec = "*(0x%x)" % r['breakaddr']
        TargetBreak.__init__(self, self.spec, controller, True, stage, r=r)