我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用idc.GetFunctionName()。
def enumerate_function_names(): func_name = dict() for seg_ea in idautils.Segments(): # For each of the functions function_ea = seg_ea while function_ea != 0xffffffffL: function_name = idc.GetFunctionName(function_ea) # if already analyzed if func_name.get(function_name, None) != None: function_ea = idc.NextFunction(function_ea) continue image_base = idaapi.get_imagebase(function_ea) addr = function_ea - image_base addr = str(hex(addr)) addr = addr.replace("L", "") addr = addr.replace("0x", "") func_name[function_name] = get_list_of_function_instr(function_ea) function_ea = idc.NextFunction(function_ea) return func_name
def enumerate_function_names(): ''' The function enumerates all functions in a dll. @return - dictionary {function_name : list of corresponded instructions} ''' func_name = dict() for seg_ea in idautils.Segments(): # For each of the functions function_ea = seg_ea while function_ea != 0xffffffffL: function_name = idc.GetFunctionName(function_ea) # if already analyzed if func_name.get(function_name, None) != None: function_ea = idc.NextFunction(function_ea) continue image_base = idaapi.get_imagebase(function_ea) addr = function_ea - image_base addr = str(hex(addr)) addr = addr.replace("L", "") addr = addr.replace("0x", "") func_name[function_name] = get_list_of_function_instr(function_ea) function_ea = idc.NextFunction(function_ea) return func_name
def revise_syscall(rename=False): if not rename: print('Change the function name with `CGCHeler.revise_syscall(True)`.') # visit all instructions start_ea, end_ea = utils.get_seg_range('.text') eax = -1 ip = start_ea while ip < end_ea and ip != idaapi.BADADDR: if 'int' in idc.GetMnem(ip) and '80h' == idc.GetOpnd(ip, 0): if eax != -1: # fix comment and function name print('{}: {}'.format(hex(ip), syscall_table[eax])) idc.MakeComm(ip, 'CGC syscall: {}'.format(syscall_table[eax])) if rename: print('Change {} to {}'.format(idc.GetFunctionName(ip), syscall_table[eax])) idc.MakeName(idc.GetFunctionAttr(ip, idc.FUNCATTR_START), syscall_table[eax]) elif 'mov' in idc.GetMnem(ip) and 'eax' == idc.GetOpnd(ip, 0) and 5 == idc.GetOpType(ip, 1): value = idc.GetOpnd(ip, 1) if re.search('^[0-9]+$', value) != None: eax = int(value) if eax > 7 or eax < 1: eax = -1 ip = idc.NextHead(ip)
def post_analysis_stuff(self, results): if results.has_formula(): self.action_selector.addItem(self.parent.HIGHLIGHT_CODE) self.action_selector.addItem(self.parent.GRAPH_DEPENDENCY) self.formula_area.setText(self.parent.results.formula) if results.has_values(): self.action_selector.addItem(self.parent.DISASS_UNKNOWN_TARGET) self.action_selector.setEnabled(True) self.action_button.setEnabled(True) report = HTMLReport() report.add_title("Results", size=3) report.add_table_header(["address", "assertion", "status", "values"]) addr = make_cell("%x" % results.target) status = make_cell(results.get_status(), color=results.color, bold=True) vals = "" for value in results.values: flag = idc.GetFlags(value) typ = self.type_to_string(flag) vals += "%x type:%s seg:%s fun:%s<br/>" % (value, typ, idc.SegName(value), idc.GetFunctionName(value)) report.add_table_line([addr, make_cell(cgi.escape(results.query)), status, make_cell(vals)]) report.end_table() data = report.generate() self.result_area.setHtml(data)
def log_stack_chains(chains): f = open("%s/%s" % (LOG_PATH, "stack_chains"), "wb") long_chains = 0 for c in chains: if len(c) > 3: long_chains += 1 for a in c: if type(a) == type("x"): s = a else: s = "[0x%08x] %s+0x%x" % (a, str(idc.GetFunctionName(Dword(a))), Dword(a) - idaapi.get_func(Dword(a)).startEA) #print s f.write(s) f.write("\n") f.write("\n") print "%d chains found" % len(chains) print "%d long chains" % long_chains f.close()
def get_current_function_xrefs_from( self ): addr_in_func = idc.ScreenEA() curr_func = idc.GetFunctionName( addr_in_func ) refs = self.find_xrefs_from( addr_in_func ) return [ ref.get_row( XrefsFromFinder.XREF_TYPE2STR ) for ref in refs ] # ------------------------------------------------------------------------------
def functions_iter(): functions = set() exports = get_export_list() for func_ea in idautils.Functions(): if func_ea in functions: continue # functions with chunks appear once for each of them.. functions.add(func_ea) code, blocks = get_code_and_blocks(func_ea) crefs_to = get_func_code_refs_to(func_ea) crefs_from = get_func_code_refs_from(func_ea, code.iterkeys()) f = func.Function(func_ea, code, blocks, crefs_to, crefs_from) f.ftype = idc.GetType(func_ea) f.name = idc.GetFunctionName(func_ea) if func_ea in exports: f.exported = True yield f typed_imports = get_typed_imports() for imp_ea, ftype in typed_imports: crefs_to = get_func_code_refs_to(imp_ea) f = func.Function(imp_ea, None, None, crefs_to, None) f.ftype = ftype f.level = -1 # special level for imported functions yield f
def sample_source(): global full_hash full_hash = "" c = 0 for addr in idautils.Functions(idc.MinEA(),idc.MaxEA()): fname = idc.GetFunctionName(addr) full_hash += normalize_fname(fname)+":"+calc_hash(addr)+":"+shexst(addr)+"|" c = c+1 if c > 1000: print "Too many subs. Plz run:" print "SRC SAMPLE : open('lame_ipc.txt','wb').write(full_hash)" print "DST SAMPLE : src_data = open('lame_ipc.txt','rb').read(full_hash)" else: print 'src_data = "' + full_hash + '"' return
def sample_dest(): global src_data if src_data is None: print "run the src_data = ... first" return src_hashes = {} for i in src_data.split("|"): z = i.split(":") if len(z) < 2: continue if src_hashes.has_key(z[1]): src_hashes[z[1]] = "baadf00d" else: src_hashes[z[1]] = z[0] dst_hashes = {} for addr in idautils.Functions(idc.MinEA(),idc.MaxEA()): fname = idc.GetFunctionName(addr) z = calc_hash(addr) if dst_hashes.has_key(z): dst_hashes[z] = "baadf00d" else: dst_hashes[z] = addr c = 0 for tmp in dst_hashes: if dst_hashes[tmp] == "baadf00d": continue if src_hashes.has_key(tmp): if src_hashes[tmp] != "baadf00d": idc.MakeNameEx(dst_hashes[tmp],"SHARED_"+src_hashes[tmp], SN_NOWARN) c = c+1 print "%d subs have been renamed" % (c) return
def get_list_of_functions(self): '''Get all functions list.''' seg_ea = idc.BeginEA() functions_list = {} for func_ea in idautils.Functions(idc.SegStart(seg_ea), idc.SegEnd(seg_ea)): function_name = self.maybe_demangle(idc.GetFunctionName(func_ea)) functions_list[function_name] = func_ea return functions_list
def update_mapping(self): pass self.fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1) for x in idautils.Functions()} self.seg_mapping = {idc.SegName(x): (idc.SegStart(x), idc.SegEnd(x)) for x in idautils.Segments()}
def target_button_clicked(self): if self.radio_addr.isChecked(): self.target_field.setText(hex(idc.here())) else: self.target_field.setText(idc.GetFunctionName(idc.here())) # ================================================================================ # ================================================================================ # ==================== Data structures ==================
def process_routine(self, rtn_addr, pred_addr=None, rtn_i=1, total_rtn=1): if rtn_addr not in self.functions_cfg: self.functions_cfg[rtn_addr] = MyFlowGraph(rtn_addr) cfg = self.functions_cfg[rtn_addr] path_to = self.config_to_path_function(cfg) if pred_addr is None: candidates = {x for x in idautils.FuncItems(rtn_addr) if idc.GetMnem(x) in cond_jump} else: candidates = {pred_addr} nb_candidates = len(candidates) self.functions_candidates[rtn_addr] = set() self.functions_spurious_instrs[rtn_addr] = set() self.progressbar_loading.reset() self.progressbar_loading.setMaximum(len(candidates)) name = idc.GetFunctionName(rtn_addr) self.result_widget.webview.append("\n=> Function:%s\n" % name) self.log("[result]", "Start processing function: 0x%x" % rtn_addr) for i, addr in zip(xrange(len(candidates)), candidates): path = path_to(addr) res = self.process_addr(rtn_addr, addr, path) if self.STOP: return elif res is None: continue dead_br = "/" if res.dead_branch is None else "%x" % res.dead_branch self.result_widget.webview.append("%x:\t%s\t\tK:%d\tDead:%s" % (addr, to_status_name(res.status), res.k, dead_br)) self.result_widget.webview.verticalScrollBar().setValue(self.result_widget.webview.verticalScrollBar().maximum()) self.loading_stat.setText("Fun: %d/%d Addr: %d/%d" % (rtn_i, total_rtn, i+1, nb_candidates)) self.progressbar_loading.setValue(self.progressbar_loading.value()+1) self.functions_candidates[rtn_addr].add(addr)
def generate_opaqueness_details_report(self): for rtn_addr, candidates in self.functions_candidates.items(): self.report.add_title('%s' % idc.GetFunctionName(rtn_addr), size=3) self.report.add_table_header(['address', "status", "K", "predicate", "distance", "dead branch"]) for addr in sorted(candidates): res = self.results[addr] status, color = to_status_name(res.status), status_to_color(res.status) status = make_cell(status, bold=True, color=color) dead_br_cell = make_cell("/" if res.dead_branch is None else "%x" % res.dead_branch) self.report.add_table_line([make_cell("%x" % addr), status, make_cell(str(res.k)), make_cell(res.predicate), make_cell(str(res.distance)), dead_br_cell]) self.report.end_table()
def refresh_trace_view(self): index = self.traces_tab.currentIndex() try: table = self.index_map[index] for i in xrange(table.rowCount()): addr_item = table.item(i, 1) addr = int(addr_item.text(), 0) routine_item = table.item(i, 3) routine_item.setText(idc.GetFunctionName(addr)) print "Refresh done" except KeyError: print "Trace not found"
def __init__(self, fun_addr): super(MyFlowGraph, self).__init__() self.fun = idaapi.get_func(fun_addr) self.startEA = self.fun.startEA self.endEA = self.fun.endEA for bb in idaapi.FlowChart(self.fun): self.__setitem__(bb.id, MyBasicBlock(bb)) self._compute_links() self.edge_map = self.make_graph() self.shortest_path_map = self.dijkstra(self.edge_map) self.size = sum([x.size() for x in self.values()]) self.viewer = MyFlowGraphViewer(self, "Extract(%s)" % idc.GetFunctionName(self.startEA))
def _feature_syscalls(self,f_ea): ''' get how many system calls are made within current function, which include (may not limited) 1.direct sys call 2.indirect call from callee recursively prior feature: null ''' calleetree = {} syscallcount = [] calleetree[f_ea] = get_callees(f_ea) for ea in calleetree[f_ea]: fname = idc.GetFunctionName(ea) if fname in self.syscalls:# syscallcount.append(fname) #better record the syscalls name of address return len(syscallcount), syscallcount # for ea in function_eas: # xrefs = idautils.CodeRefsFrom(ea, False) # for xref in xrefs: # if not (xref in function_eas): # callees.append(xref) ''' the above commented is one level, below is recursively '''
def _showFunctions(self): DEBUG_PRINT('IN _showFunctions') try: ea = idc.ScreenEA() deflt_ea = idaapi.get_func(ea).startEA except: deflt_ea = int(self._tablelist[0][0],16) deflt_id = 1 views = ['0','1','2','3'] for view in views: if [hex(deflt_ea),idc.GetFunctionName(deflt_ea),view] in self._tablelist: deflt_id = self._tablelist.index([hex(deflt_ea),idc.GetFunctionName(deflt_ea),view]) + 1 # if [hex(deflt_ea),idc.GetFunctionName(deflt_ea),'0'] in self._tablelist: # deflt_id = self._tablelist.index([hex(deflt_ea),idc.GetFunctionName(deflt_ea),'0']) + 1 # if [hex(deflt_ea),idc.GetFunctionName(deflt_ea),'1'] in self._tablelist: # deflt_id = self._tablelist.index([hex(deflt_ea),idc.GetFunctionName(deflt_ea),'1']) + 1 title = "Functions with Comments" cols = [['Address',10],['Function Name',15],['Show',4]] chooser = IdxChoose2(title, cols, self._tablelist, deflt = deflt_id) id = chooser.show() if -1==id: return 0 else: ea = int(self._tablelist[id][0],16) return ea #hex(int(self._tablelist[id][0],16))
def log_stack_addrs(stack_addrs): print len(stack_addrs) f = open("%s/%s" % (LOG_PATH, "stack_all"), "wb") for a in stack_addrs: #s = "[0x%08x] ret address 0x%08x to function %s" % (a, Dword(a), str(idc.GetFunctionName(Dword(a)))) s = "[0x%08x] %s+0x%x" % (a, str(idc.GetFunctionName(Dword(a))), Dword(a) - idaapi.get_func(Dword(a)).startEA) f.write(s) f.write("\n") f.close()
def name_handlers(ea_from, ea_to): global COUNT addr = ea_from print "from: 0x%08x to: 0x%08x" % (addr, ea_to) while (addr < ea_to): func_to_name_ea = idc.Dword(addr) & 0xFFFFFFFE log_msg_ptr = idc.Dword(addr + 12) log_msg = idc.GetString(log_msg_ptr) #is that a function already? #There were 0 cases of this for our case if not idaapi.get_func(func_to_name_ea): print "There is no function at 0x%08x!" % func_to_name_ea idc.MakeFunction(func_to_name_ea) if "sms_Decode" in idc.GetFunctionName(func_to_name_ea) or "mm_Decode" in idc.GetFunctionName(func_to_name_ea) or "cc_Decode" in idc.GetFunctionName(func_to_name_ea) or "gmm_Decode" in idc.GetFunctionName(func_to_name_ea): print "Already named appropriately, don't overwrite" else: print "Naming %s based on %s as %s" % (idc.GetFunctionName(func_to_name_ea), log_msg, create_name(log_msg)) COUNT += 1 name = create_name(log_msg) # TODO: enable below naming ret = idc.LocByName(name) count = 1 while (ret != 0xffffffff): count += 1 ret = idc.LocByName(name + "__" + "%d" % count) idc.MakeName(func_to_name_ea, name + ("__%d" % count)*(count > 1)) addr += 16
def print_call_trace(stack_top, stack_base): addr = stack_top print '0x%08x - 0x%08x' % (stack_top, stack_base) while (addr >= stack_base): if ret_addr(Dword(addr)): s = "[0x%08x] %s+0x%x" % (addr, str(idc.GetFunctionName(Dword(addr))), Dword(addr) - idaapi.get_func(Dword(addr)).startEA) print s addr -= 4 pass