def react_operator(idx, ctx): print '%x' % (idx.ea) fcn_object = ctx.get_obj("function") """next line was working on ELF""" demangled = ida_name.demangle_name( ida_name.get_name(fcn_object.addr)[1:], 0) """next line was working on MACH-O""" #demangled = ida_name.demangle_name(ida_name.get_name(fcn_object.addr), 0) print demangled if "operator<<" in demangled: arg2 = ctx.get_expr('arg2')[0] arg1 = ctx.get_expr('arg1')[0] arg1_repr = get_string_repr(arg1, ctx) arg2_repr = get_string_repr(arg2, ctx) var = ctx.get_var("res") #varname = ctx.get_var_name(var.idx) varexp = make_var_expr(var.idx, var.typ, var.mba) #varexp = make_var_expr(var2.idx, var2.typ, var2.mba, arg=True) arglist = ida_hexrays.carglist_t() arglist.push_back(arg2) helper = ida_hexrays.call_helper(ida_hexrays.dummy_ptrtype(4, False), arglist, "{} << ".format(arg1_repr)) insn = make_cexpr_insn(idx.ea, make_asgn_expr(varexp, helper)) idx.cleanup() idaapi.qswap(idx, insn) # del original inst because we swapped them on previous line del insn
def main(): is_selected, sel_start, sel_end = ida_kernwin.read_selection() if not is_selected: logger.error('range must be selected') return -1 sel_end = ida_bytes.next_head(sel_end) buf = ida_bytes.get_bytes(sel_start, sel_end - sel_start) if buf is None: logger.error('failed to fetch instruction bytes') return -1 f = ida_funcs.get_func(sel_start) if f != ida_funcs.get_func(sel_end): logger.error('range must be within a single function') return -1 # find mappings from "$localN" to "custom_name" regvars = {} for i in range(0x1000): regvar = ida_frame.find_regvar(f, sel_start, '$local%d' % i) if regvar is None: continue regvars[regvar.canon] = regvar.user if len(regvars) >= f.regvarqty: break globals_ = {} for i, offset in netnode.Netnode('$ wasm.offsets').get('globals', {}).items(): globals_['$global' + i] = ida_name.get_name(offset) frame = {} if f.frame != ida_idaapi.BADADDR: names = set([]) for i in range(ida_struct.get_struc_size(f.frame)): s = ida_struct.get_struc(f.frame) if not s: continue m = ida_struct.get_member(s, i) if not m: continue name = ida_struct.get_member_name(m.id) if name in names: continue frame[i] = name names.add(name) emu = Emulator(buf) emu.run() print( emu.render(ctx={ 'regvars': regvars, 'frame': frame, 'globals': globals_, }))
def addr_to_name(ea): """ 返回任意地址的名称 """ name = ida_name.get_name(ea, ida_name.GN_VISIBLE) if name == "": print("[Error] addr_to_name: Failed to find '0x%x' address" % ea) return "" return name
def get_tooltip(self, addr, mouse_offs): tooltip = '%X: ' % (addr + mouse_offs) if self.switch == 0: tooltip += '%s' % get_name(get_item_head(addr + mouse_offs)) else: f = get_func(addr + mouse_offs) if f: tooltip += '%s' % get_func_name(f.startEA) return tooltip
def set_name_prototype_tl_dr_function(api_number): """Set the name and the prototype of the TL/DR API function associated with the given function number :param api_number: API function number :type api_number: int """ global MAX_TL_API global MAX_DR_API tl_api_name, tl_api_type, dr_api_name, dr_api_type = get_apis_name_type(api_number) index = api_number * 4 if api_number < MAX_TL_API: if not tl_api_name: pass else: dword = ida_bytes.get_dword(tl_table + index) func = ida_funcs.get_func(dword) if func is None: MAX_TL_API = dword else: func_name = ida_name.get_name(func.start_ea) print("[*] Renaming function %s to %s" % (func_name, tl_api_name)) ida_name.set_name(func.start_ea, encode(tl_api_name), ida_name.SN_FORCE) if tl_api_type: set_function_prototype(func, encode(tl_api_type)) if api_number < MAX_DR_API: if not dr_api_name: pass else: dword = ida_bytes.get_dword(dr_table + index) func = ida_funcs.get_func(dword) if func is None: MAX_DR_API = dword else: func_name = ida_name.get_name(func.start_ea) print("[*] Renaming function %s to %s" % (func_name, tl_api_name)) ida_name.set_name(func.start_ea, encode(dr_api_name), ida_name.SN_FORCE) if dr_api_type: set_function_prototype(func, encode(dr_api_type))
def activate(self, ctx): screen_ea = ida_kernwin.get_screen_ea() finder = SignatureFinder() sig = finder.get_signature(screen_ea) print('FakePDB/signatures_find:') print(' * address : %s' % hex(screen_ea)) print(' * name : %s' % ida_name.get_name(screen_ea)) print(' * signature: %s' % sig) print('') return 0
def _apply_tdinfo_symbol(image_base, name_pool, symbol): if symbol.bitfield.symbol_class != tdinfo_structs.SymbolClass.STATIC.name: raise TdinfoParserUnsupportedSymbolClassException() symbol_ea = image_base + symbol.segment * 0x10 + symbol.offset symbol_name = str(name_pool[symbol.index - 1]) if ida_name.get_name(symbol_ea) == symbol_name: raise TdinfoParserSymbolAlreadyAppliedException() if (ida_name.set_name(symbol_ea, symbol_name)): print('Applied name {} to address {:04X}:{:04X}'.format( symbol_name, image_base // 0x10 + symbol.segment, symbol.offset)) else: raise TdinfoParserIdaSetNameFailedException()
def iter_dynamic_functions() -> Iterable[Tuple[int, str]]: """ Iterates the dynamically resolved function signatures. :yield: (ea, name) """ # Look for data elements in the .data segment in which IDA has placed # a function signature element on. data_segment = ida_segment.get_segm_by_name(".data") for ea in idautils.Heads(start=data_segment.start_ea, end=data_segment.end_ea): flags = ida_bytes.get_flags(ea) if idc.is_data(flags) and not idc.is_strlit(flags) and _is_func_type( ea): yield ea, ida_name.get_name(ea)
def api_calls(self) -> collections.Counter: """ Returns counter containing API calls and the number of times they were called. """ if self._api_calls: return self._api_calls api_calls = collections.Counter() for ea, func_ea in self.calls_from: func_name = ida_name.get_name(func_ea) if func_name: api_calls.update([func_name]) self._api_calls = api_calls return self._api_calls
def _f1(idx, ctx): import idc import ida_bytes obj = ctx.get_memref('stroff') print "%x" % obj.ea ti = idaapi.opinfo_t() f = idc.GetFlags(obj.ea) if idaapi.get_opinfo(obj.ea, 0, f, ti): print("tid=%08x - %s" % (ti.tid, idaapi.get_struc_name(ti.tid))) print "Offset: {}".format(obj.offset) import ida_struct obj2 = ctx.get_obj('fcn') print "%x" % obj2.addr name_str = ida_name.get_name(obj2.addr) print "Name {}".format(name_str) ida_struct.set_member_name(ida_struct.get_struc(ti.tid), obj.offset, name_str)
def activate(self, ctx): # get active filename if not ida_nalt.get_root_filename(): print('FakePDB/import offsets: file not loaded') return 1 screen_ea = ida_kernwin.get_screen_ea() finder = SignatureFinder() sig = finder.get_signature(screen_ea) print('FakePDB/signatures_find:') print(' * address : %s' % hex(screen_ea)) print(' * name : %s' % ida_name.get_name(screen_ea)) print(' * signature: %s' % sig) print('') return 0
def api_calls(self): """ Returns counter containing API calls and the number of times they were called. """ if self._api_calls: return self._api_calls api_calls = collections.Counter() for ea in self.heads(): if idc.print_insn_mnem(ea) == "call": for xref in idautils.XrefsFrom(ea, idaapi.XREF_FAR): if xref.to: func_name = ida_name.get_name(xref.to) if func_name: api_calls.update([func_name]) self._api_calls = api_calls return self._api_calls
def find_function_dirtree_path(va: int) -> Optional[str]: """ given the address of a function find its absolute path within the function dirtree. """ func_dir: dirtree_t = ida_dirtree.get_std_dirtree( ida_dirtree.DIRTREE_FUNCS) name = ida_name.get_name(va) if not name: return None for root, _, files in dirtree_walk(func_dir, "/"): for file in files: if file == name: return dirtree_join(root, file) return None
def dump(): ret = [] for addr in idautils.Functions(): name = ida_name.get_name(addr) if name.startswith('sub_') or name.startswith('nullsub_'): continue # For some reason, this get_type function doesn't include the name, # but the SetType function expects it. typ = ida_typeinf.idc_get_type(addr) if typ: typ = typ.replace('__cdecl', '__cdecl %s' % name) + ';' ret.append(filter_none({ 'start': addr, 'name': name, 'type': typ, })) return ret
def callback(addr, name, ordinal): if name: # Name will include a "__imp_" prefix if the import is accessed through # a thunk function. # Pull the address of the thunk function instead. raw_name = ida_name.get_name(addr) if raw_name.startswith("__imp_"): for xref in idautils.XrefsTo(addr): func = ida_funcs.get_func(xref.frm) if func and func.flags & ida_funcs.FUNC_THUNK: addr = func.start_ea name = ida_funcs.get_func_name(addr) break else: raise RuntimeError(f"Failed to find a thunk for {name} at 0x{addr:08X}") entries.append((addr, name)) return True # continue enumeration
def find_symbol(self) -> str: """ Try to find a symbol associated to the event This is based on the event header signature Most of then are into .rdata segment and some of them have a name """ pattern = struct.pack("<HBBBBHQ", self.event_id, self.version, self.channel, self.level, self.opcode, self.task, self.keyword) for start, end in find_segment(".rdata"): offset = idc.get_bytes(start, end - start).find(pattern) if offset == -1: continue name = ida_name.get_name(start + offset) if name is None: continue return name return None
def update_struct_offsets(data_addr, struct_label, struct_name, pad=0): """ Find xrefs to a struct pointer and change all the offsets to be struct offsets. This is useful for updating references to function pointers in EFI tables. For example: mov rax, cs:qword_whatever call qword ptr [rax+150h] Becomes: mov rax, cs:gBootServices call [rax+EFI_BOOT_SERVICES.UninstallMultipleProtocolInterfaces] Parameters: addr - The address of the struct pointer global struct_name - The name of the structure to use for offsets """ # Find all xrefs to this data in the code xrefs = list(idautils.DataRefsTo(data_addr)) print "{}Found {} xrefs".format(' ' * pad, len(xrefs)) print "{}Struct name : {}".format(' ' * pad, struct_name) # Process xrefs for xref in xrefs: inst = idautils.DecodeInstruction(xref) # We're only interested in xrefs in code where the left operand is a # register, and the right operand is the memory address of our data # structure. if inst.Op1.type == ida_ua.o_reg and \ inst.Op2.type == ida_ua.o_mem and \ ida_name.get_name(inst.Op2.addr) == struct_label: print "{}Processing xref from 0x{:08x}: {}".format( ' ' * pad, xref, disasm(xref) ) update_struct_offsets_for_xref(xref, struct_name, pad) else: print "{}Too hard basket - xref from 0x{:08x}: {}".format( ' ' * pad, xref, disasm(xref) )
def on_get_annotations(self, address, size, mouse_offs): item_ea = get_item_head(address + mouse_offs) cursor_ea = address + mouse_offs name = get_name(item_ea) if len(name): name = "(%s)" % name else: name = "" ann = [ (item_ea, self.red[0], "Item: %X" % (item_ea), self.colormap[-1]), (None, None, " Size: %d %s" % (get_item_size(get_item_head(cursor_ea)), name), self.colormap[-3]), (cursor_ea, self.colormap[-1], "Cursor: %X" % (cursor_ea), self.colormap[-1]), (None, None, " %s" % generate_disasm_line( cursor_ea, GENDSM_FORCE_CODE | GENDSM_REMOVE_TAGS), self.colormap[-3]), (None, None, " Value: %02X" % get_byte(cursor_ea), self.colormap[-3]), ] return ann
def react_operator2(idx, ctx): print '%x' % (idx.ea) fcn_object = ctx.get_obj("function") """next line was working on ELF""" demangled = ida_name.demangle_name( ida_name.get_name(fcn_object.addr)[1:], 0) """next line was working on MACH-O""" #demangled = ida_name.demangle_name(ida_name.get_name(fcn_object.addr), 0) print demangled if "operator<<" in demangled: arg1 = ctx.get_expr('arg1')[0] arg1_repr = get_string_repr(arg1, ctx) arg2 = ctx.get_expr('arg2')[0] #varexp = make_var_expr(var2.idx, var2.typ, var2.mba, arg=True) arglist = ida_hexrays.carglist_t() arglist.push_back(arg2) val = ida_hexrays.call_helper(ida_hexrays.dummy_ptrtype(4, False), arglist, "{} << ".format(arg1_repr)) insn = make_cexpr_insn(idx.ea, val) idx.cleanup() idaapi.qswap(idx, insn) del insn
def get_string_repr(obj, ctx): if obj.opname == "cast": obj = obj.x else: pass if obj.opname == "obj": if obj.type.dstr() == "char *": return repr(ida_bytes.get_strlit_contents(obj.obj_ea, 256, -1)) else: name = ida_name.get_name(obj.obj_ea).split("@@")[0] print name if name[0] == ".": name = name[1:] if "endl" in name: return "std::endl" return ida_name.demangle_name(name, 0) elif obj.opname == "ref": return "&" + get_string_repr(obj.x, ctx) elif obj.opname == "var": return ctx.get_var_name(obj.v.idx) # elif else: print obj.opname return ""
def _get_item_info(self, ea): head = get_item_head(ea) name = get_name(head) size = get_item_size(head) return (head, name, size)
for ea in xrefs_to_lib_entry(): chunk_start, chunk_end = find_chunk_boundaries(ea) if chunk_start == ida_idaapi.BADADDR or chunk_end == ida_idaapi.BADADDR: print("[!] %#x - Couldn't find chunk boudaries" % ea) continue api_number = determine_api_number(ea, chunk_start, chunk_end) if api_number == -1: print("[!] %#x - Couldn't determine the api number" % ea) continue api_name, api_type = get_api_name_type(api_number) if api_name is None: print("[!] %#x - Couldn't get the api name" % ea) continue func = ida_funcs.get_func(ea) if not has_only_one_basic_block(func): print("[!] %#x - Function has more than one basic block" % ea) continue func_name = ida_name.get_name(func.start_ea) print("[*] Renaming function %s to %s" % (func_name, api_name)) ida_name.set_name(func.start_ea, encode(api_name), ida_name.SN_FORCE) if not api_type: continue print("[*] Changing function type of %s to '%s'" % (api_name, api_type)) set_function_prototype(func, encode(api_type))
def data(self): name = ida_name.get_name(self.offset) if ida_name.is_uname(name): # TODO: get flags here return {'name': name, 'flags': 0} return None
def data(self): name = ida_name.get_name(self.offset) if ida_name.is_uname(name): return hashlib.md5(name).hexdigest() return None
def _data(cls, offset): name = ida_name.get_name(offset) if ida_name.is_uname(name): # TODO: get flags here return {'name': name} return None
def get_function_raw_name_at(self, function_address): return ida_name.get_name(function_address)
def make_ptr(ea): # TODO: arch ida_bytes.del_items(ea, 0, psize) return ida_bytes.create_dword(ea, psize) def enum_ptrs(start, end): for ea in range(start, end, psize): yield (ea, get_ptr(ea)) def enum_segment_ptrs(ea): seg = ida_segment.getseg(ea) for (ea, ptr) in enum_ptrs(seg.start_ea, seg.end_ea): yield (ea, ptr) for ea, ptr in enum_segment_ptrs(idc.ScreenEA()): name = ida_name.get_name(ptr) if not name: continue if name.startswith('loc_'): continue print(hex(ea) + ': ' + name) make_ptr(ea) ida_name.set_name(ea, name)