def get_list_of_function_instr(addr):
f_start = addr
f_end = idc.FindFuncEnd(addr)
chunks = enumerate_function_chunks(f_start)
list_of_addr = list()
list_of_calls = list()
image_base = idaapi.get_imagebase(addr)
for chunk in chunks:
for head in idautils.Heads(chunk[0], chunk[1]):
# If the element is an instruction
if head == hex(0xffffffffL):
raise Exception("Invalid head for parsing")
if idc.isCode(idc.GetFlags(head)):
call_name = get_call_name(head)
if call_name != None:
list_of_calls.append(call_name)
head = head - image_base
head = str(hex(head))
head = head.replace("L", "")
head = head.replace("0x", "")
list_of_addr.append(head)
return list_of_addr, list_of_calls
python类isCode()的实例源码
def get_list_of_function_instr(addr):
'''
The function returns a list of instructions from a function
@addr - is function entry point
@return - list of instruction's addresses
'''
f_start = addr
f_end = idc.FindFuncEnd(addr)
chunks = enumerate_function_chunks(f_start)
list_of_addr = list()
image_base = idaapi.get_imagebase(addr)
for chunk in chunks:
for head in idautils.Heads(chunk[0], chunk[1]):
# If the element is an instruction
if head == hex(0xffffffffL):
raise Exception("Invalid head for parsing")
if idc.isCode(idc.GetFlags(head)):
head = head - image_base
head = str(hex(head))
head = head.replace("L", "")
head = head.replace("0x", "")
list_of_addr.append(head)
return list_of_addr
def color_head(ea):
flags = idc.GetFlags(ea)
if not idc.isCode(flags):
return
mnem = idc.GetMnem(ea)
if mnem == 'call':
logger.debug('call: 0x%x', ea)
idc.SetColor(ea, idc.CIC_ITEM, CALL_COLOR)
elif mnem == 'xor':
if idc.GetOpnd(ea, 0) != idc.GetOpnd(ea, 1):
logger.debug('non-zero xor: 0x%x', ea)
idc.SetColor(ea, idc.CIC_ITEM, ENCRYPT_COLOR)
elif mnem in ('sdit', 'sgdt', 'sldt', 'smsw', 'str', 'in', 'cpuid'):
logger.debug('anti-vm: 0x%x', ea)
idc.SetColor(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
elif mnem == 'in':
if idc.GetOpnd(ea, 0) in ("3", "2D"):
logger.debug('anti-debug: 0x%x', ea)
idc.SetColor(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
elif mnem in ('rdtsc', 'icebp'):
logger.debug('anti-debug: 0x%x', ea)
idc.SetColor(ea, idc.CIC_ITEM, ANTIANALYSIS_COLOR)
def heatmap_trace(self):
try:
index = self.traces_tab.currentIndex()
trace = self.core.traces[self.id_map[index]]
if self.heatmaped:
self.heatmap_button.setText("Heatmap")
color = lambda x: 0xffffff
else:
self.heatmap_button.setText("Heatmap undo")
self.heatmap_button.setFlat(True)
hit_map = trace.address_hit_count
color_map = self.compute_step_map(set(hit_map.values()))
print color_map
color = lambda x: color_map[hit_map[x]]
for inst in trace.instrs.values():
if idc.isCode(idc.GetFlags(inst.address)):
c = color(inst.address)
idc.SetColor(inst.address, idc.CIC_ITEM, c)
if not self.heatmaped:
self.heatmap_button.setFlat(False)
self.heatmaped = True
else:
self.heatmaped = False
except KeyError:
print "No trace found"
def get_custom_viewer_hint(self, view, place):
try:
tform = idaapi.get_current_tform()
if idaapi.get_tform_type(tform) != idaapi.BWN_DISASM:
return None
curline = idaapi.get_custom_viewer_curline(view, True)
# sometimes get_custom_viewer_place() returns [x, y] and sometimes [place_t, x, y].
# we want the place_t.
viewer_place = idaapi.get_custom_viewer_place(view, True)
if len(viewer_place) != 3:
return None
_, x, y = viewer_place
ea = place.toea()
# "color" is a bit of misnomer: its the type of the symbol currently hinted
color = get_color_at_char(curline, x)
if color != idaapi.COLOR_ADDR:
return None
# grab the FAR references to code (not necessarilty a branch/call/jump by itself)
far_code_references = [xref.to for xref in idautils.XrefsFrom(ea, ida_xref.XREF_FAR)
if idc.isCode(idc.GetFlags(xref.to))]
if len(far_code_references) != 1:
return None
fva = far_code_references[0]
# ensure its actually a function
if not idaapi.get_func(fva):
return None
# this magic constant is the number of "important lines" to display by default.
# the remaining lines get shown if you scroll down while the hint is displayed, revealing more lines.
return render_function_hint(fva), DEFAULT_IMPORTANT_LINES_NUM
except Exception as e:
logger.warning('unexpected exception: %s. Get in touch with @williballenthin.', e, exc_info=True)
return None
def compute_nb_instr(self):
return 0 # FIXME: by iterating all segments
count = 0
start, stop = self.seg_mapping[".text"] # TODO: Iterate all executable segs
current = start
while current <= stop:
if idc.isCode(idc.GetFlags(current)):
count += 1
current = idc.NextHead(current, stop)
return count
def disassemble_new_targets(self, _):
for value in self.results.values:
flag = idc.GetFlags(value)
if not idc.isCode(flag) and idc.isUnknown(flag):
res = idc.MakeCode(value)
if res == 0:
print "Try disassemble at:"+hex(value)+" KO"
# TODO: Rollback ?
else:
print "Try disassemble at:"+hex(value)+" Success !"
# ============================= RESULT WIDGET ===============================
# ===========================================================================
def type_to_string(t):
if idc.isCode(t):
return "C"
elif idc.isData(t):
return "D"
elif idc.isTail(t):
return "T"
elif idc.isUnknown(t):
return "Ukn"
else:
return "Err"
def set_start_stop(self, ftype):
assert_ida_available()
import idc
import idaapi
import idautils
fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1)
for x in idautils.Functions()}
start = idc.BeginEA()
stop = 0
if ftype == PE:
start, stop = fun_mapping["start"]
else:
if not idc.isCode(idc.GetFlags(start)):
if idc.MakeCode(start) == 0:
print "Fail to decode instr !"
idaapi.autoWait()
if idc.GetFunctionName(start) == "":
if idc.MakeFunction(start) == 0:
print "Fail to create function !"
idaapi.autoWait()
fun_mapping = {idc.GetFunctionName(x): (idaapi.get_func(x).startEA, idaapi.get_func(x).endEA-1)
for x in idautils.Functions()}
if "main" in fun_mapping:
start, stop = fun_mapping["main"]
elif "start" in fun_mapping:
if "__libc_start_main" in fun_mapping:
instrs = list(idautils.FuncItems(fun_mapping["start"][0]))
instrs.reverse()
for inst in instrs:
arg1 = idc.GetOperandValue(inst, 0)
if idc.GetMnem(inst) == "push":
start, stop = arg1, fun_mapping["start"][1]
break
else:
start, stop = fun_mapping["start"]
self.config.start, self.config.stop = start, stop
def disassemble_from_trace(self):
try:
index = self.traces_tab.currentIndex()
trace = self.core.traces[self.id_map[index]]
self.disassemble_button.setFlat(True)
found_match = False
for k, inst in trace.instrs.items():
if k in trace.metas:
for name, arg1, arg2 in trace.metas[k]:
if name == "wave":
self.parent.log("LOG", "Wave n°%d encountered at (%s,%x) stop.." % (arg1, k, inst.address))
prev_inst = trace.instrs[k-1]
idc.MakeComm(prev_inst.address, "Jump into Wave %d" % arg1)
self.disassemble_button.setFlat(False)
return
# TODO: Check that the address is in the address space of the program
if not idc.isCode(idc.GetFlags(inst.address)):
found_match = True
# TODO: Add an xref with the previous instruction
self.parent.log("LOG", "Addr:%x not decoded as an instruction" % inst.address)
if idc.MakeCode(inst.address) == 0:
self.parent.log("ERROR", "Fail to decode at:%x" % inst.address)
else:
idaapi.autoWait()
self.parent.log("SUCCESS", "Instruction decoded at:%x" % inst.address)
if not found_match:
self.parent.log("LOG", "All instruction are already decoded")
self.disassemble_button.setFlat(False)
except KeyError:
print "No trace found to use"
def decode_here_clicked(self):
inst = idc.here()
if not idc.isCode(idc.GetFlags(inst)):
print "Not code instruction"
else:
raw = idc.GetManyBytes(inst, idc.NextHead(inst)-inst)
s = to_hex(raw)
self.decode_ir(s)
def handleDebugStepOver(self):
if self.clientSocket is None:
return
if self.debugBreakId is None:
return
cur_ea = self.debugBreakId
decode_insn(cur_ea)
next_ea = cur_ea + idaapi.cmd.size
if isCode(getFlags(next_ea)) == False:
return
entry = None
# remove current
if self.debugBreakId in self.idbHookMap:
entry = self.idbHookMap[self.debugBreakId]
outJSON = json.dumps({
"req_id": kFridaLink_DelHookRequest,
"data": entry.genDelRequest()
})
del self.idbHookMap[self.debugBreakId]
self.clientSocket.sendto(outJSON, self.clientAddress)
SetColor(self.debugBreakId, CIC_ITEM, kIDAViewColor_Reset)
refresh_idaview_anyway()
offset, moduleName = self.getAddressDetails(next_ea)
# install next
if entry == None:
hook = InstHook()
hook.id = next_ea
hook.once = once
hook.breakpoint = True
entry = HookEntry(hook)
entry.hook.id = next_ea
entry.hook.mnemonic = GetDisasm(next_ea)
entry.hook.address = offset
entry.hook.module = moduleName
outJSON = json.dumps({
"req_id": kFridaLink_SetHookRequest,
"data": entry.genSetRequest()
})
self.clientSocket.sendto(outJSON, self.clientAddress)
self.idbHookMap[next_ea] = entry
self.idbHooksView.setContent(self.idbHookMap)
self.handleDebugContinue()