import os from idaapi import * from idautils import * from idc import * def export_func_asm(file_name,func_addr): try: with open(file_name,"w+") as f: func_ea=get_func(func_addr)#获取有效函数地址对象 func_name=get_func_name(func_addr)#获取函数名称 f.write(f"Assembly for function {func_name} start:0x{func_ea.start_ea:x} end:0x{func_ea.end_ea:x}\n") for ea in Heads(func_ea.start_ea,func_ea.end_ea):#遍历 asm_line=generate_disasm_line(ea,GENDSM_REMOVE_TAGS)#提取汇编,去除标签 f.write(f"0x{ea:x}: {asm_line}\n") except Exception as msg: with open("my.log","a+") as f:#报错日志写入 f.write(f"export_func_asm {func_name} -> {msg}") def export_func(extractfile): if(extractfile is None):exit(-1) save_dir="result" asm_file=save_dir+"/"+extractfile func_file=save_dir+"/"+extractfile+"_extract.c" try: with open(func_file,"w") as file: for func_addr in Functions():#迭代器编译所有函数 func_name=get_func_name(func_addr)#获取函数名称 if(func_name in BLACK_LIST):continue#黑名单处理 func_seg=getseg(func_addr)#获取函数段 if(func_seg.name!=7 or func_seg.perm !=5):continue #去除其他段函数 tmp_filename=asm_file+"_"+func_name+".asm" export_func_asm(tmp_filename,func_addr) #提取函数汇编 code=decompile(func_addr) #反编译,提取c if code : file.write(f"//Function: {func_name} ->0x{func_addr} {func_seg.name} perm->{func_seg.perm}\n") file.write(str(code)+"\n\n") #写入文件 except Exception as msg: with open("my.log","a+") as f: f.write(f"export_func {func_file} -> {msg}") #函数黑名单 BLACK_LIST={ "_start","_dl_relocate_static_pie", "deregister_tm_clones","register_tm_clones", "__do_global_dtors_aux","frame_dummy", } def main(): extractfile="extract.c" filepath="tmp.txt" if (os.path.exists(filepath) and os.path.isfile(filepath) ): with open(filepath,"r") as f: extractfile=f.read() export_func(extractfile) if __name__ == "__main__": main() idaapi.qexit(0)