def recursive_prefix(addr): """ Recursively prefix a function tree with a user defined string. """ func_addr = idaapi.get_name_ea(idaapi.BADADDR, idaapi.get_func_name(addr)) if func_addr == idaapi.BADADDR: idaapi.msg("Prefix: 0x%08X does not belong to a defined function\n" % addr) return # NOTE / COMPAT: # prompt the user for a prefix to apply to the selected functions if using_ida7api: tag = idaapi.ask_str(PREFIX_DEFAULT, 0, "Function Tag") else: tag = idaapi.askstr(0, PREFIX_DEFAULT, "Function Tag") # the user closed the window... ignore if tag == None: return # the user put a blank string and hit 'okay'... notify & ignore elif tag == '': idaapi.warning("[ERROR] Tag cannot be empty [ERROR]") return # recursively collect all the functions called by this function nodes_xref_down = graph_down(func_addr, path=set([])) # graph_down returns the int address needs to be converted tmp = [] tmp1 = '' for func_addr in nodes_xref_down: tmp1 = idaapi.get_func_name(func_addr) if tmp1: tmp.append(tmp1) nodes_xref_down = tmp # prefix the tree of functions for rename in nodes_xref_down: func_addr = idaapi.get_name_ea(idaapi.BADADDR, rename) if tag not in rename: idaapi.set_name(func_addr, '%s%s%s' % (str(tag), PREFIX_SEPARATOR, rename), idaapi.SN_NOWARN) # refresh the IDA views refresh_views()
def Label_Dynamically_Resolved_Iat_Addresses(iatList, labeledIatDumpFileName): with open(labeledIatDumpFileName, 'r') as fp: labeledIatList = fp.read().splitlines() imageBase = idaapi.get_imagebase() labeledIatDict = dict() for i in labeledIatList: curRva, curIatLabel = i.split('\t') labeledIatDict[imageBase + int(curRva, 16)] = curIatLabel labeledCount = 0 unresolvedList = [] for entry in iatList: ea = idaapi.get_name_ea(0, entry) curIatLabel = labeledIatDict.get(ea, None) if curIatLabel != None: idc.set_name(ea, curIatLabel, 0) labeledCount += 1 else: unresolvedList.append( 'could not resolve address 0x{:x}'.format(ea)) print('labeled {:x} dynamically resolved IAT entries'.format(labeledCount)) if len(unresolvedList) != 0: print('[*] ERROR, was not able to resolve {:x} entries'.format( len(unresolvedList))) print('\n'.join(unresolvedList))
def clear_prefix(): """ Clear user defined prefixes from the selected functions in the Functions window. """ # # loop through all the functions selected in the 'Functions window' and # clear any user defined prefixes applied to them. # for func_name in get_selected_funcs(): # # locate the last (rfind) prefix separator in the function name as # we will want to keep everything that comes after it # i = func_name.rfind(PREFIX_SEPARATOR) # if there is no prefix (separator), there is nothing to trim if i == -1: continue # trim the prefix off the original function name and discard it new_name = func_name[i + 1:] func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name) idaapi.set_name(func_addr, new_name, idaapi.SN_NOWARN) # refresh the IDA views refresh_views()
def bulk_prefix(): """ Prefix the Functions window selection with a user defined string. """ # prompt the user for a prefix to apply to the selected functions tag = idaapi.ask_str(PREFIX_DEFAULT, 0, "Function Tag") # the user closed the window... ignore if tag == None: return # the user put a blank string and hit 'okay'... notify & ignore elif tag == '': idaapi.warning("[ERROR] Tag cannot be empty [ERROR]") return # # loop through all the functions selected in the 'Functions window' and # apply the user defined prefix tag to each one. # for func_name in get_selected_funcs(): # ignore functions that already have the specified prefix applied if func_name.startswith(tag): continue # apply the user defined prefix to the function (rename it) new_name = '%s%s%s' % (str(tag), PREFIX_SEPARATOR, func_name) func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name) idaapi.set_name(func_addr, new_name, idaapi.SN_NOWARN) # refresh the IDA views refresh_views()
def updateIIDs(self, **kwargs): h = GuidHelper() inst = self.struct.instances() inst.update(self.struct2.instances()) busy = [] for x in inst: n = h.guidOfVals((inst[x]['Data1'], inst[x]['Data2'], inst[x]['Data3'], inst[x]['Data4'])) found = h.findGuid(n) if found: nm = found['name'] for c in " ,.:;-+<>/*": nm = nm.replace(c, '_') for c in nm: if ord(c) > 0x7F: nm = nm.replace(c, '_') if found['prefix'] and not nm.startswith(found['prefix']): nm = found['prefix'] + "_" + nm else: nm = "iid_" + str(n).replace('-', '_') rnm = nm if nm: if idc.Name(x).startswith(nm): busy += [nm] continue i = 2 while nm in busy and i < 10: nm = rnm + "__" + str(i) i += 1 while (idaapi.get_name_ea(idc.BADADDR, nm) != idc.BADADDR or not idc.MakeName(x, nm)) and i < 10: nm = rnm + "__" + str(i) i += 1 busy += [nm]
def open_sync_menu(self): """ Opens sync menu and gives the optinal actions """ # create a dynamic menu table for the users menu_table = self._build_menu_table() # open a dialog to make sync actions dialog = MenuDialog(menu_table) result = dialog.exec_() # only parse the action if the user accepted the result if result != QDialog.Accepted: return # parse action action, user = dialog.getActionSelection() # for every selected function perform the action! for func_name in self._get_selected_funcs(): func_addr = idaapi.get_name_ea(idaapi.BADADDR, func_name) ida_func = idaapi.get_func(func_addr) ret = self._do_action(action, user, ida_func) if ret == False: return
def dump_ke_task_create(): retsult = {} logger = CustomLogger() m = CodeEmulator() at = ArgumentTracker() ke_task_create_addr = idaapi.get_name_ea(idaapi.BADADDR, "ke_task_create") # print "ke_task_create_addr: 0x{:X}".format(ke_task_create_addr) for xref in XrefsTo(ke_task_create_addr, 0): frm_func = idc.get_func_name(xref.frm) ret = at.track_register(xref.frm, "r1") if ret.has_key("target_ea"): # print "target_ea: 0x{:X}".format(ret['target_ea']) if m.emulate(ret['target_ea'], xref.frm): reg = m.mu.reg_read(UC_ARM_REG_R1) logger.log( "call ke_task_create on {} 0x{:X}, task_struct: 0x{:X}". format(frm_func, xref.frm, reg)) retsult[xref.frm] = reg # logger.log("[decompile_tracer] addr: 0x{:X}, task_struct: 0x{:X}".format(xref.frm, at.decompile_tracer(xref.frm, extract_ke_task_create)[0])) for k, v in retsult.items(): frm_func = idc.get_func_name(k) task_desc_ea = v task_desc_name = "{}_task_desc".format(frm_func.split("_init")[0]) define_ke_task_desc(task_desc_ea, task_desc_name) handler = idaapi.get_dword(task_desc_ea + 4) define_ke_state_handler(handler) return retsult
def print_func_args(symname, narg, OS="win", MAXDEPTH=50): args = list() sym_ea = idaapi.get_name_ea(idaapi.NT_NONE, symname) str_type = idaapi.ASCSTR_TERMCHR if OS == "win": if symname[-1] == "W": str_type = idaapi.ASCSTR_UNICODE refs = idautils.CodeRefsTo(sym_ea, 0) for r in refs: sys.stdout.write('0x%08X %s (' % (r, symname)) for m in range(0, narg): current_ea = get_func_arg_ea(r, m) if current_ea == 0xFFFFFFFF: break op_type = idc.GetOpType(current_ea, 0) if op_type == idc.o_imm: str_arg = idc.GetString(idc.GetOperandValue(current_ea, 0), strtype=str_type) if str_arg != None: sys.stdout.write( '(char*)(0x%08X)\"%s\"' % (idc.GetOperandValue(current_ea, 0), str_arg)) else: sys.stdout.write('0x%08X' % idc.GetOperandValue(current_ea, 0)) else: sys.stdout.write('%s' % idc.GetOpnd(current_ea, 0)) if (m + 1) != narg: sys.stdout.write(', ') sys.stdout.write(');\n')
def print_func_args (symname, narg, OS="win", MAXDEPTH=50): args = list() sym_ea = idaapi.get_name_ea (idaapi.NT_NONE, symname) str_type = idaapi.ASCSTR_TERMCHR if OS == "win": if symname[-1] == "W": str_type = idaapi.ASCSTR_UNICODE refs = idautils.CodeRefsTo (sym_ea, 0) for r in refs: sys.stdout.write ('0x%08X %s (' % (r, symname)) for m in range(0, narg): current_ea = get_func_arg_ea (r, m) if current_ea == 0xFFFFFFFF: break op_type = idc.GetOpType (current_ea, 0) if op_type == idc.o_imm: str_arg = idc.GetString (idc.GetOperandValue (current_ea, 0), strtype = str_type) if str_arg != None: sys.stdout.write ('(char*)(0x%08X)\"%s\"' % (idc.GetOperandValue (current_ea, 0), str_arg)) else: sys.stdout.write ('0x%08X' % idc.GetOperandValue (current_ea, 0)) else: sys.stdout.write ('%s' % idc.GetOpnd (current_ea, 0)) if (m+1) != narg: sys.stdout.write (', ') sys.stdout.write (');\n')
def rename (self): for row in range(self.numrows): if str(self.table.model().index(row, self.numcols).data()) == '.': print "Function \"{}\" not renamed".format(str(self.table.model().index(row, 1).data())) else: func_adress = idaapi.get_name_ea(idaapi.BADADDR, str(self.table.model().index(row, 1).data())) idc.MakeName(func_adress, str(self.table.model().index(row, self.numcols).data())) print "Function \"{}\" renamed to \"{}\" successfully".format(str(self.table.model().index(row, 1).data()), str(self.table.model().index(row, self.numcols).data()))
def track_ke_event_callback_set(): logger = CustomLogger() m = CodeEmulator() at = ArgumentTracker() event_dict = {} target_addr = idaapi.get_name_ea(idaapi.BADADDR, "ke_event_callback_set") print "ke_event_callback_set: 0x{:X}".format(target_addr) for xref in XrefsTo(target_addr, 0): frm_func = idc.get_func_name(xref.frm) r1_ret = at.track_register(xref.frm, "r1") r0_ret = at.track_register(xref.frm, "r0") if r0_ret.has_key("target_ea") and r1_ret.has_key("target_ea"): start_ea = min(r0_ret['target_ea'], r1_ret['target_ea']) if m.emulate(start_ea, xref.frm): r1 = m.mu.reg_read(UC_ARM_REG_R1) r0 = m.mu.reg_read(UC_ARM_REG_R0) callback_func_name = idc.get_func_name(r1) if callback_func_name == "": define_func(r1, "event_{}_callback_func".format(r0)) callback_func_name = idc.get_func_name(r1) if r1 & 1: r1 -= 1 event_dict[r0] = r1 logger.log( "addr: 0x{:X}, event: 0x{:X}, callback: {} @ 0x{:X}". format(xref.frm, r0, callback_func_name, r1)) target_addr = idaapi.get_name_ea(idaapi.BADADDR, "ke_event_set") print "ke_event_set: 0x{:X}".format(target_addr) for xref in XrefsTo(target_addr, 0): r0_ret = at.track_register(xref.frm, "r0") if r0_ret.has_key("target_ea"): start_ea = r0_ret['target_ea'] if m.emulate(start_ea, xref.frm): r0 = m.mu.reg_read(UC_ARM_REG_R0) logger.log("addr: 0x{:X}, use event: {}".format(xref.frm, r0)) add_ref(xref.frm, event_dict[r0])
def jump(self, data): j = data['address'].split(" : ") ea = idaapi.get_name_ea(idc.BADADDR, j[0]) ln = int(j[1]) print "JUMPTO", j, ea, ln ui = idaapi.open_pseudocode(ea, False) (pl, x, y) = idaapi.get_custom_viewer_place(ui.ct, False) pl2 = idaapi.place_t_as_simpleline_place_t(pl.clone()) pl2.n = ln idaapi.jumpto(ui.ct, pl2, 0, y)
def click_tree(self): i = self._switch_tree.currentItem() addr = i.text(0).strip() if not addr.startswith("0x"): addr = idaapi.get_name_ea(idc.BADADDR, str(addr)) else: addr = addr[2:10] addr = int(addr, 16) idc.Jump(addr) return
def set_global_data(name, TypeString): ea = idaapi.get_name_ea(-1, str(name)) if ea == idaapi.BADADDR: return ok = idc.SetType(ea, str(TypeString)) if not ok: print("Could not add global type {name} at {ea:#x} : {TypeString}". format(name=name, ea=ea, TypeString=TypeString))
def set_function_type(name, TypeString, print_ERROR=False): ea = idaapi.get_name_ea(-1, str(name)) if ea == idaapi.BADADDR: return ok = idc.SetType(ea, str(TypeString)) if not ok and print_ERROR: print( "Could not add function type {name} at {ea:#x} : {TypeString}". format(name=name, ea=ea, TypeString=TypeString))
def click_row(self): i = self._bytestring_table.item(self._bytestring_table.currentRow(), 0) bstr = self._bytestring_table.item(self._bytestring_table.currentRow(), 2) addr = i.text().strip() bstr = bstr.text() if not addr.startswith("0x"): addr = idaapi.get_name_ea(idc.BADADDR, str(addr)) else: addr = addr[2:10] addr = int(addr, 16) idc.Jump(addr) self._clipboard.setText(bstr)
def subclass(self, sup=None, **kwargs): tp = self.currentType(self.CHECK_VTBL, **kwargs) tp = self.checkVtblStruct(tp) cnm = tp['name'] if not sup: sup = idc.AskStr('', "Subclass " + cnm + " from:") if not sup or sup == cnm: Logger.debug("Subclasssing cancelled") return idc.Til2Idb(-1, sup + 'Vtbl') s = MODS.struct.Struct(sup + 'Vtbl') Logger.debug("Subclassing class %s from %s", str(tp), sup) ea = tp['vtblea'] nm = None funcs = [] while (not nm): ofs = idc.Qword(ea) if not ofs or ofs == idc.BADADDR: break try: func = FuncDescr.fromEA(ofs) except FuncDescr.NotFunctionError as e: func = None if not kwargs.get('force'): raise funcs += [func] ea += 8 nm = idc.Name(ea) flds = s.fields() if len(funcs) != len(flds) and (not kwargs.get('force')): raise self.WrongTypeError("Functions count doesn't match", s.name) for i, fofs in enumerate(sorted(flds.keys())): fld = flds[fofs] f = funcs[i] if f is None: continue refcnt = len(MODS.util.refsFromSeg(f.ea, ".rdata")) if self.untouchedFunc(f.name): nm = cnm if refcnt == 1 else sup was = str(f) f.clearType() f.parseType(fld['type'][0]) f.name = nm + "::" + fld['name'] ni = 1 while idaapi.get_name_ea(idc.BADADDR, f.name) != idc.BADADDR: ni += 1 f.name = nm + "::" + fld['name'] + "_" + str(ni) f.changeParam(0, 'this', nm + '*') f.update(True) Logger.debug("Converted func %s to type %s", was, str(f)) self.update()
def OnDblClick(self, shift): word = self.GetCurrentWord() if not word: return True addr = None try: addr = int(word, 16) except: sym = word.split(':')[1] if ':' in word else word addr = idaapi.get_name_ea(idaapi.BADADDR, sym) if addr: idaapi.jumpto(addr) return True
def analyze_loops(): import idc import idaapi import idautils for fn in idautils.Functions(): fg = FunctionGraph(fn) ds = algorithms.dominate_sets(fg, fn) dt = algorithms.domtree(ds) hs = list(algorithms.loop_headers(fg, ds, fn)) hs.sort() # first remove loop names so we don't have conflicts for i in range(len(hs)): lexits = set() # remove the existing name if it is their name = '_loop_%x' % (i+1) old = idaapi.get_name_ea(fn, name) if old in fg.nodes: idc.MakeNameEx(old, '', idc.SN_LOCAL) # name it idc.MakeNameEx(hs[i], name, idc.SN_LOCAL) lns = set(algorithms.loop_nodes(fg, hs[i], ds)) for j in lns: for k in fg.nodes[j].outgoing: if k not in lns: lexits.add(k) lexits = list(lexits) for j in range(len(lexits)): name = '_loop_%x_exit_%x' % (i+1, j+1) old = idaapi.get_name_ea(fn, name) if old in fg.nodes: idc.MakeNameEx(old, '', idc.SN_LOCAL) idc.MakeNameEx(lexits[j], name, idc.SN_LOCAL)
def origFun(self, ip): print('look for fun having ip 0x%x' % ip) fun = self.getFun(ip) if fun is None: simicsString = gdbProt.Evalx( 'SendGDBMonitor("@cgc.getSO(0x%x)");' % ip) print('No function found. Check load for: %s' % simicsString) if ':' in simicsString: sofile, start_end = str(simicsString).rsplit(':', 1) print('sofile is %s start_end is %s' % (sofile, start_end)) if '-' not in start_end: print('Bad response from getSO: %s' % simicsString) return root_prefix = self.getRootPrefix(sofile) full = os.path.join(root_prefix, sofile[1:]) sopath = self.getFunPath(full) start, end = start_end.split('-') start = int(start, 16) end = int(end, 16) self.add(sopath, start) fun = self.getFun(ip) print('start 0x%x end 0x%x' % (start, end)) #idaapi.analyze_area(start, end) idc.plan_and_wait(start, end) for fun in sorted(self.funs): if fun >= start and fun <= end: name = str(self.funs[fun]['name']) nea = idaapi.get_name_ea(idaapi.BADADDR, name) if nea != idaapi.BADADDR: name = name + '_so' idc.set_name(int(fun), name, idc.SN_CHECK) print('made name for 0x%x %s' % (int(fun), name)) for fun in self.funs: if fun >= start and fun <= end: #print('fun 0x%x name <%s>' % (fun, name)) idaversion.add_func(fun, idaapi.BADADDR) elif fun is not None: print('Do one fun 0x%x' % fun) for i in range(self.funs[fun]['start'], self.funs[fun]['end']): idaversion.del_items(i, 1) idaapi.auto_mark_range(self.funs[fun]['start'], self.funs[fun]['end'], 25) idaapi.autoWait() return fun return None
def dump_msg_id_usage(): logger = CustomLogger() m = CodeEmulator() a = ArgumentTracker() ke_msg_alloc_addr = idaapi.get_name_ea(idaapi.BADADDR, "ke_msg_alloc") result = {} for xref in XrefsTo(ke_msg_alloc_addr, 0): frm_func = idc.get_func_name(xref.frm) # print "frm:0x{:X}, frm_func:{}".format(xref.frm, frm_func) # print " task_desc: 0x{:X}".format(idaapi.get_arg_addrs(xref.frm)[1]) ret = a.track_register(xref.frm, "r0") if ret.has_key("target_ea"): # print "target_ea: 0x{:X}".format(ret['target_ea']) if m.emulate(ret['target_ea'], xref.frm): if not result.has_key(xref.frm): result[xref.frm] = set() r0 = m.mu.reg_read(UC_ARM_REG_R0) logger.log("addr: 0x{:X}, msg id: 0x{:X}".format(xref.frm, r0)) result[xref.frm].add(r0) else: if not result.has_key(frm_func): result[frm_func] = set() # print "emulate 0x{:X}----0x{:X} failed!".format(ret['target_ea'], xref.frm) for msg_id in a.decompile_tracer(xref.frm, extract_ke_msg_alloc_msgid): logger.log( "[ decompile_tracer ] addr: 0x{:X}, msg id: 0x{:X}". format(xref.frm, msg_id)) result[frm_func].add(msg_id) else: logger.log("0x{:X} failed!".format(xref.frm)) for k, v in result.items(): logger.log("{}: {}".format(k, ','.join(["0x{:X}".format(i) for i in v]))) result[k] = list(result[k]) import json with open("msg_id_usage.json", "w") as fp: fp.write(json.dumps(result))
def rename_derived_classes(category, base_ctor_name): # type: (str, str) -> None base_ctor_ea = idaapi.get_name_ea(-1, base_ctor_name) if not idaapi.get_func(base_ctor_ea): return derived_classes = [] for derived_ctor_ea in idautils.CodeRefsTo(base_ctor_ea, 1): derived_ctor_name = idaapi.get_func_name(derived_ctor_ea) if not derived_ctor_name.startswith( "AI_") or not derived_ctor_name.endswith("::ctor"): continue class_name = derived_ctor_name.replace("::ctor", "") print("rename: %s %s 0x%x" % (category, class_name, derived_ctor_ea)) do_rename(category, derived_ctor_ea, class_name) derived_classes.append(derived_ctor_name) for derived_class in derived_classes: rename_derived_classes(category, derived_class)
def calc_expr(self, expr): rd = {} for c in expr.split(" "): if c in ["+", "-", "*"]: continue if c.startswith("0x"): continue if len(re.findall("^\d+$", c)) > 0: continue addr = idaapi.get_name_ea(idaapi.BADADDR, c) if addr != idaapi.BADADDR: value = idaapi.get_dword(addr) rd[c] = "0x{:X}".format(value) for k, v in rd.items(): expr = expr.replace(k, v) return expr.strip()
def find(self, **kwargs): res = [] if kwargs.get('func'): f = kwargs.get('func') if isinstance(f, basestring): f = idaapi.get_name_ea(idc.BADADDR, f) res = self.checkFunc(f, **kwargs) or [] else: for funcea in idautils.Functions(): tp = idc.GetType(funcea) if tp is None or self.stname not in tp: continue r = self.checkFunc(funcea, **kwargs) if r: res += r if kwargs.get("silent"): return res if len(res): dictchooser.DictChooser('.'.join(self.name) + " usage", res, jumpProc=self.jump).Show() else: Logger.info("Nothing found")
def _run(self): try: askd = TrashJumpDialog(self.get_config()['custom_base']) if askd.exec_() != askd.Accepted: return s = askd.cbb_addr.currentText().encode('ascii').strip() diff = 0 if askd.custom_base: diff = idaapi.get_imagebase() - askd.custom_base self.save_config({'custom_base': askd.custom_base}) eas = self.parse(s) for ea in eas: ea += diff if idaapi.isEnabled(ea) and idaapi.jumpto( ea, idaapi.UIJMP_ACTIVATE | idaapi.UIJMP_IDAVIEW): return ea = idaapi.get_name_ea(idaapi.BADADDR, s) if idaapi.BADADDR != ea: if idaapi.isEnabled(ea) and idaapi.jumpto( ea, idaapi.UIJMP_ACTIVATE | idaapi.UIJMP_IDAVIEW): return # last try without custom base for ea in eas: if idaapi.isEnabled(ea) and idaapi.jumpto( ea, idaapi.UIJMP_ACTIVATE | idaapi.UIJMP_IDAVIEW): return idaapi.msg('TrashJump: address not found. Parsed: %r\n' % [hex(ea) for ea in eas]) except: idaapi.msg('TrashJump: address not found\nerror: %s\n' % traceback.format_exc())
def decompile_tracer(self, ea, extract_func): c = idaapi.decompile(ea) # decompilation_text = c.get_pseudocode() # line2citem = map_line2citem(decompilation_text) # line2node = map_line2node(c, line2citem) # for line_number, line_nodes in line2node.iteritems(): # for i in line_nodes: # if ea == i: # break # print line_number sink_list = [] lines = str(c).split("\n") idx = 0 for l in lines: arg = extract_func(l) if arg != "": sink_list.append((idx, arg)) idx += 1 # print sink_list result_expr = [] for sink in sink_list: idx = sink[0] expr = sink[1] expr_queue = [] expr_queue.append(expr) cur_expr = "" while len(expr_queue) > 0: cur_expr = expr_queue.pop() # print expr_queue, cur_expr rd = {} for c in cur_expr.split(" "): c = c.strip() if c in ["+", "-", "*", ">>", "<<", "^", "&", "|"]: continue if c.startswith("0x"): continue if len(re.findall("^\d+$", c)) > 0: continue addr = idaapi.get_name_ea(idaapi.BADADDR, c) if addr == idaapi.BADADDR: value = self.trace_decompile_var(lines, idx, c) else: value = idaapi.get_dword(addr) value = ["0x{:X}".format(value)] rd[c] = value # print rd if len(rd) > 0: for k, vs in rd.items(): for v in vs: cur_expr = cur_expr.replace(k, v) expr_queue.append(cur_expr) else: result_expr.append(cur_expr) ret = [] for i in result_expr: rv = ida_expr.idc_value_t() idaapi.eval_expr(rv, ea, i) if rv.num != 0 and rv.num not in ret: ret.append(rv.num) return ret
def byName(name): return idaapi.get_name_ea(-1, name)
if not logger.handlers: handler = logging.StreamHandler(stream=sys.stdout) logger.addHandler(handler) try: import idautils import idaapi import sark data_vectors = { 'r27': 'XH', 'r26': 'XL', 'r29': 'YH', 'r28': 'YL', 'r31': 'ZH', 'r30': 'ZL' } for vector_register in data_vectors.keys(): register_line = sark.Line(idaapi.get_name_ea(0, vector_register)) register_line.name = data_vectors.get(vector_register) register_line.comments.repeat = "alias:%s" % vector_register except: exc_type, exc_value, exc_traceback = sys.exc_info() logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) idascript.exit()
def get_callers(name): for xr in idautils.CodeRefsTo(idaapi.get_name_ea(idaapi.BADADDR, name), True): fn = idaapi.get_func(xr) if fn: yield fn.startEA
def tev_call(state, call): "stores call events to the IDA Trace Window" caller = state['pc'] callee = idaapi.get_name_ea(0, call[0]) idaapi.dbg_add_call_tev(state['machine-id'], caller, callee)
def byName(name): ea = idaapi.get_name_ea(-1, name) if ea == idaapi.BADADDR: raise Exception, "function.byName(%r):unable to locate function"% name return idaapi.get_func(ea)
base_dir = os.path.dirname( __file__ ) #nice, but only works in idascript command-line, not in runscript() calls xmega128a4u_def = os.path.join(base_dir, '..', 'resources', 'ATxmega128A4U.atdf') try: import idautils import idaapi import sark import xml.etree.ElementTree as et tree = et.parse(xmega128a4u_def) root = tree.getroot() r0_address = idaapi.get_name_ea(0, 'r0') all_bases = dict() for register_group in root.findall( ".//peripherals/module/instance/register-group[@address-space='data']" ): base = int(register_group.attrib['offset'], 0) if all_bases.get("%04x" % base) is None: all_bases.update({"%04x" % base: register_group}) for key in sorted(all_bases.keys()): register_group = all_bases.get(key) base_name = register_group.attrib['name'] name_in_module = register_group.attrib['name-in-module'] base = int(register_group.attrib['offset'], 0) for register in root.findall(
def byName(name): ea = idaapi.get_name_ea(-1, name) if ea == idaapi.BADADDR: raise Exception, "function.byName(%r):unable to locate function" % name return idaapi.get_func(ea)