# Disassemble binary & return disassembled instructions in CsInsn objects
def disasm(self, code, offset, count=0):
all_insn = ctypes.POINTER(_cs_insn)()#_cs_insn缩写自_capstone_instruction, 是一个c的结构体;这句创建all_insn指针,指向_cs_insn类型
'''if not _python2:
print(code)
code = code.encode()
print(code)'''
# Hack, unicorn's memory accessors give you back bytearrays, but they
# cause TypeErrors when you hand them into Capstone.
if isinstance(code, bytearray):
code = bytes(code)
res = _cs.cs_disasm(self.csh, code, len(code), offset, count, ctypes.byref(all_insn))#通过c函数cs_disasm解析code,获得一个all_insn引用(byref类似于pointer,返回一个引用)
if res > 0:
try:
for i in range(res):
yield CsInsn(self, all_insn[i])#看下构造函数def __init__(self, cs, all_info)可以看出self._raw=all_info=all_insn[i],把all_insn这个_cs_insn结构传递给了_raw,所以_raw储存了address,mnemonic,op_str等关键信息
finally:
_cs.cs_free(all_insn, res)#通过yield输出完CsInsn实例后释放
else:
status = _cs.cs_errno(self.csh)
if status != CS_ERR_OK:
raise CsError(status)
return
yield
# Common instruction operand types - to be consistent across all architectures.
CS_OP_INVALID = 0
CS_OP_REG = 1
CS_OP_IMM = 2
CS_OP_MEM = 3
CS_OP_FP = 4
简单食用一下
[Asm] 纯文本查看复制代码
#创建输入
bin= open('/src/main/lib/armeabi/libshell-super.2019.so','rb').read()
start=0x0000307C
end=0x00004df4
#导入capstone新建Cs实例,安卓一般都是arm的
import capstone
cs = capstone.Cs(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB)
cs.detail = True#打开了detail 才有detail的功能
#打印地址,操作码,操作数
for i in cs.disasm(bin[start:end],start):
print("0x%x:\t%s\t%s\n" %(i.address, i.mnemonic, i.op_str))
#打印groups
# print("\t%s\n" %( i.groups))
# for a in i.groups:
# print(i.group_name(a))
#打印regs_read与regs_write
print("0x%x:\t%s\t%s\n" %(i.address, i.regs_read, i.regs_write))
for a in i.regs_read:
print("regs_read:"+i.reg_name(a))
for a in i.regs_write:
print("regs_write:"+i.reg_name(a))
def __init__(self, arch, mode):
# verify version compatibility with the core before doing anything
(major, minor, _combined) = ks_version()
if major != KS_API_MAJOR or minor != KS_API_MINOR:#先判断下当前版本和核心api是否匹配
self._ksh = None
# our binding version is different from the core's API version
raise KsError(KS_ERR_VERSION)
self._arch, self._mode = arch, mode
self._ksh = c_void_p()
status = _ks.ks_open(arch, mode, byref(self._ksh))#根据参数arch和mode通过c函数ks_open打开ks_engine,获得_ksh的引用
if status != KS_ERR_OK:
self._ksh = None
raise KsError(status)
if arch == KS_ARCH_X86:
# Intel syntax is default for X86
self._syntax = KS_OPT_SYNTAX_INTEL
else:
self._syntax = None