How to use the capstone.Cs function in capstone

To help you get started, we’ve selected a few capstone examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cslarsen / minijit / compiler-tests.py View on Github external
def test(function):
    print("")
    print("=== Function %s ===" % function.__name__)
    print("")

    native, asm = compiler.compile_function(function)

    try:
        print("Native code:")
        md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
        for i in md.disasm(asm.raw, asm.address):
            print("  0x%x:\t%s\t%s" % (i.address, i.mnemonic, i.op_str))
            if i.mnemonic == "ret":
                break
        print("")

    except NameError:
        pass

    test_function(function, native)
github PS3Xploit / PS3HEN / server.py View on Github external
def disassemble(addr, data):
	none = 0
	md = Cs(CS_ARCH_PPC, CS_MODE_BIG_ENDIAN)
	disassed = md.disasm(data, addr)
	for i in disassed:
		none = 1
		print("0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))
	if none != 1:
		print("Couldn't disassemble at 0x%x"%(addr))
github teemu-l / execution-trace-viewer / core / trace_files.py View on Github external
pointer_size = 8  # qword
        else:
            regs = prefs.X32_REGS
            ip_reg = "eip"
            capstone_mode = CS_MODE_32
            pointer_size = 4  # dword

        for i, reg in enumerate(regs):
            reg_indexes[reg] = i

        trace_data.arch = arch
        trace_data.ip_reg = ip_reg
        trace_data.regs = reg_indexes
        trace_data.pointer_size = pointer_size

        md = Cs(CS_ARCH_X86, capstone_mode)
        reg_values = [None] * len(reg_indexes)
        trace = []
        row_id = 0
        while f.read(1) == b"\x00":
            register_changes = int.from_bytes(f.read(1), "little")
            memory_accesses = int.from_bytes(f.read(1), "little")
            flags_and_opcode_size = int.from_bytes(f.read(1), "little")  # Bitfield
            thread_id_bit = (flags_and_opcode_size >> 7) & 1  # msb
            opcode_size = flags_and_opcode_size & 15  # 4 lsbs

            if thread_id_bit > 0:
                thread_id = int.from_bytes(f.read(4), "little")

            opcodes = f.read(opcode_size)

            register_change_position = []
github Ledger-Donjon / rainbow / rainbow / generics / x64.py View on Github external
def __init__(self, trace=True, sca_mode=False, local_vars={}):
        super().__init__(trace, sca_mode)
        self.emu = uc.Uc(uc.UC_ARCH_X86, uc.UC_MODE_64)
        self.disasm = cs.Cs(cs.CS_ARCH_X86, cs.CS_MODE_64)
        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.x86_const.UC_X86_REG_RIP

        # workaround for capstone 4
        uc.x86_const.UC_X86_REG_RFLAGS = uc.x86_const.UC_X86_REG_EFLAGS

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

        self.stubbed_functions = local_vars
        self.setup(sca_mode)
github lucamassarelli / yarasafe / ida-pro-plugin / SAFE_plugin.py View on Github external
def filter_asm_and_return_instruction_list(address, asm, symbols, arch, mode, API):
    binary = binascii.unhexlify(asm)
    md = capstone.Cs(arch, mode)
    md.detail = True
    insns = []
    cap_insns = []
    cnt = 0;
    for i in md.disasm(binary, address):
        cnt += 1
        insns.append(filter_memory_references(i, symbols, API))
        cap_insns.append(i)
    print("Found {} instructions".format(cnt))
    return (constantIndependt_hash(cap_insns), insns)
github AirbusCyber / grap / src / tools / grap_disassembler / disassembler.py View on Github external
def __init__(self, arch, mode):
        self.arch = arch
        self.mode = mode
        self.capstone = Cs(self.arch, self.mode)

        self.prologues = {
            # Triple backslash (\\\) are needed to escape bytes in the compiled regex
            CS_MODE_32: [
                b"\x55\x89\xE5",  # push ebp & mov ebp, esp
                b"\x55\x8B\xEC",  # push ebp & mov ebp, esp
                b"\x55\x8b\x6c\x24",  # push ebp & mov ebp, [esp+?]
            ],
            CS_MODE_64: [
                b"\x55\x48\x89\xE5",  # push rbp & mov rbp, rsp
            ]
        }[mode]

        self.conditional_jmp_mnemonics = {'jz', 'je', 'jcxz', 'jecxz', 'jrcxz', 'jnz', 'jp', 'jpe', 'jnp', 'ja', 'jae', 'jb', 'jbe', 'jg', 'jge', 'jl', 'jle', 'js', 'jns', 'jo', 'jno', 'jecxz', 'loop', 'loopne', 'loope', 'jne'}
        self.x86_32_registers = {'eax', 'ebx', 'ecx', 'edx', 'esi', 'edi', 'esp', 'ebp'}
        self.max_instruction_size = 16
github volatilityfoundation / volatility3 / volatility / cli / text_renderer.py View on Github external
def display_disassembly(disasm: interfaces.renderers.Disassembly) -> str:
    """Renders a disassembly renderer type into string format.

    Args:
        disasm: Input disassembly objects

    Returns:
        A string as rendererd by capstone where available, otherwise output as if it were just bytes
    """

    if CAPSTONE_PRESENT:
        disasm_types = {
            'intel': capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32),
            'intel64': capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64),
            'arm': capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM),
            'arm64': capstone.Cs(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM)
        }
        output = ""
        if disasm.architecture is not None:
            for i in disasm_types[disasm.architecture].disasm(disasm.data, disasm.offset):
                output += "\n0x%x:\t%s\t%s" % (i.address, i.mnemonic, i.op_str)
        return output
    return QuickTextRenderer._type_renderers[bytes](disasm.data)
github google / rekall / rekall-core / rekall / plugins / tools / disassembler.py View on Github external
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