from elftools.elf.elffile import ELFFile import re,os hdr_str=["#include \"opensdk.h\"\n"] symbol_table_org=[] symbol_table = [] gen_table=[] def get_export_func(f): file = open(f, 'r') try: while True: line = file.readline() if line: # print ("line=",line) tmp = re.findall(r"EXPORT_FUNC\((.+)\)",line) if tmp: print(tmp[0]) symbol_table_org.append(line) symbol_table.append(tmp[0]) print("#define app_"+tmp[0]+"_addr ") else: break finally: file.close() print(symbol_table) print("get_export_func") def get_info_from_elf(e_file): # e_file为需要读取的elf文件 tmp_dict = {} # 这个字典用于存放变量名和变量地址的对应关系 file = open(e_file, 'rb') elf_file_obj = ELFFile(file) data_section = elf_file_obj.get_section_by_name('.data') data_address = data_section.header["sh_addr"] print(data_section.data()) print("data addr:0x%X"%data_address) dfile = open("test.data.bin", 'wb') dfile.write(data_section.data()); dfile.close() text_section = elf_file_obj.get_section_by_name(".text") base_address = text_section.header["sh_addr"] print(text_section.data()) print("text addr:0x%X"%base_address) tfile = open("test.text.bin", 'wb') tfile.write(text_section.data()); tfile.close() # got_section = elf_file_obj.get_section_by_name('.got') # got_address = got_section.header["sh_addr"] # print(got_section.data()) # print("got addr:0x%X"%got_address) # gfile = open("test.got.bin", 'wb') # gfile.write(got_section.data()); # gfile.close() # plt_section = elf_file_obj.get_section_by_name('.got.plt') # plt_address = plt_section.header["sh_addr"] # print(plt_section.data()) # print("plt addr:0x%X"%plt_address) # pfile = open("test.plt.bin", 'wb') # pfile.write(plt_section.data()); # pfile.close() for section in elf_file_obj.iter_sections(): # 此处把地址以16进制的字符串形式存入字典,可选择自己需要的格式。 print(section) # tmp_dict[s.name] = str(hex(s.entry["st_value"]))section file.close() return tmp_dict def gen_hdr(e_file): print("gen header file") tmp_dict = {} file = open(e_file, 'rb') elf_file_obj = ELFFile(file) symbol_table_name = elf_file_obj.get_section_by_name(".symtab") for sym in symbol_table_name.iter_symbols(): print(sym.name) print(sym['st_value']) if sym.name in symbol_table: gen_table.append("#define app_"+sym.name+"_addr "+str(hex(sym['st_value']))+"\n") print("insert one sym") print(gen_table) f = open("export_new.h", 'w') for line in hdr_str: f.writelines(line) f.writelines("\n") for line in symbol_table_org: f.writelines(line) f.writelines("\n") for line in gen_table: f.writelines(line) f.close() try: os.remove("inc/export.h") except: print("no inc/export.h") os.rename("export_new.h","inc/export.h") get_info_from_elf("test.elf") get_export_func("inc/export.h") gen_hdr("test.elf")