def PrevFchunk(ea):
"""
Get previous function chunk
@param ea: any address
@return: the starting address of the function chunk or BADADDR
@note: This function enumerates all chunks of all functions in the database
"""
func = idaapi.get_prev_fchunk(ea)
if func:
return func.startEA
else:
return BADADDR
python类BADADDR的实例源码
def GetConstEx(enum_id, value, serial, bmask):
"""
Get id of constant
@param enum_id: id of enum
@param value: value of constant
@param serial: serial number of the constant in the
enumeration. See OpEnumEx() for details.
@param bmask: bitmask of the constant
ordinary enums accept only -1 as a bitmask
@return: id of constant or -1 if error
"""
if bmask < 0:
bmask &= BADADDR
return idaapi.get_enum_member(enum_id, value, serial, bmask)
def GetPrevConst(enum_id, value, bmask):
"""
Get prev constant in the enum
@param enum_id: id of enum
@param bmask : bitmask of the constant
ordinary enums accept only -1 as a bitmask
@param value: value of the current constant
@return: value of a constant with value lower than the specified
value. -1 no such constants exist.
All constants are sorted by their values as unsigned longs.
"""
if bmask < 0:
bmask &= BADADDR
return idaapi.get_prev_enum_member(enum_id, value, bmask)
def AddEnum(idx, name, flag):
"""
Add a new enum type
@param idx: serial number of the new enum.
If another enum with the same serial number
exists, then all enums with serial
numbers >= the specified idx get their
serial numbers incremented (in other words,
the new enum is put in the middle of the list of enums).
If idx >= GetEnumQty() or idx == -1
then the new enum is created at the end of
the list of enums.
@param name: name of the enum.
@param flag: flags for representation of numeric constants
in the definition of enum.
@return: id of new enum or BADADDR
"""
if idx < 0:
idx = idx & SIZE_MAX
return idaapi.add_enum(idx, name, flag)
def DelConstEx(enum_id, value, serial, bmask):
"""
Delete a member of enum - a symbolic constant
@param enum_id: id of enum
@param value: value of symbolic constant.
@param serial: serial number of the constant in the
enumeration. See OpEnumEx() for for details.
@param bmask: bitmask of the constant ordinary enums accept
only -1 as a bitmask
@return: 1-ok, 0-failed
"""
if bmask < 0:
bmask &= BADADDR
return idaapi.del_enum_member(enum_id, value, serial, bmask)
def SetRegValue(value, name):
"""
Set register value
@param name: the register name
@param value: new register value
@note: The debugger should be running
It is not necessary to use this function to set register values.
A register name in the left side of an assignment will do too.
"""
rv = idaapi.regval_t()
if type(value) == types.StringType:
value = int(value, 16)
elif type(value) != types.IntType and type(value) != types.LongType:
print "SetRegValue: value must be integer!"
return BADADDR
if value < 0:
#ival_set cannot handle negative numbers
value &= 0xFFFFFFFF
rv.ival = value
return idaapi.set_reg_val(name, rv)
def finish_populating_tform_popup(self, form, popup):
# disassembly window
if idaapi.get_tform_type(form) == idaapi.BWN_DISASMS:
if get_cursor_func_ref() == idaapi.BADADDR:
return
idaapi.attach_action_to_popup(
form,
popup,
funcref_t.ACTION_COPY
)
# functions window
elif idaapi.get_tform_type(form) == idaapi.BWN_FUNCS:
idaapi.attach_action_to_popup(form, popup, funcref_t.ACTION_BULK, "Copy All", idaapi.SETMENU_INS)
return 0
def hxe_callback(self, event, *args):
if event == idaapi.hxe_populating_popup:
form, popup, vu = args
if get_cursor_func_ref() == idaapi.BADADDR:
return 0
idaapi.attach_action_to_popup(
form,
popup,
funcref_t.ACTION_COPY,
"Rename global item",
idaapi.SETMENU_APP
)
return 0
def createenum(self, symbols):
"""
Given full symbols and addresses create an enum name with the library name (the string before !)
Some constants will fail due to weird characters in symbols used by MS. eg( `$)
symbols: (dict) A set of symbols and addresses that have been cleaned.
"""
enum_name = symbols.keys()[0].split('!')[0]
enum = idc.AddEnum(0, enum_name, idaapi.hexflag())
if enum == idaapi.BADADDR:
print "[!] Failed to create enum: %s\n" % enum_name
return
for symbol, address in symbols.iteritems():
# "ADVAPI32!RegCreateKeyExWStub": "0xffff8007be2f89f0"
org_symb = symbol
symbol = str(symbol.split('!')[1].encode('utf-8'))
symbol = symbol.strip()
symbol = 's_'+symbol
address = int(address,16)
ret = idc.AddConstEx(enum, symbol, address, -1)
if ret !=0:
print "[!] Failed to create constant for symbol %s - (%s). %s" % (org_symb,symbol,ENUM_ERRORS[ret])
continue
self.enums[address] = enum
print "[+] Finished adding enum %s\n" % enum_name
def output_symbols(out):
"""Dump symbols."""
try:
from idaapi import get_func_name2 as get_func_name
# Since get_func_name is deprecated (at least from IDA 6.9)
except ImportError:
from idaapi import get_func_name
# Older versions of IDA don't have get_func_name2
# so we just use the older name get_func_name
def func_name_propagate_thunk(ea):
current_name = get_func_name(ea)
if current_name[0].isalpha():
return current_name
func = idaapi.get_func(ea)
temp_ptr = idaapi.ea_pointer()
ea_new = idaapi.BADADDR
if func.flags & idaapi.FUNC_THUNK == idaapi.FUNC_THUNK:
ea_new = idaapi.calc_thunk_func_target(func, temp_ptr.cast())
if ea_new != idaapi.BADADDR:
ea = ea_new
propagated_name = get_func_name(ea) or '' # Ensure it is not `None`
if len(current_name) > len(propagated_name) > 0:
return propagated_name
else:
return current_name
# Fallback to non-propagated name for weird times that IDA gives
# a 0 length name, or finds a longer import name
for ea in idautils.Segments():
fs = idautils.Functions(idc.SegStart(ea), idc.SegEnd(ea))
for f in fs:
out.write('("%s" 0x%x 0x%x)\n' % (
func_name_propagate_thunk(f),
idc.GetFunctionAttr(f, idc.FUNCATTR_START),
idc.GetFunctionAttr(f, idc.FUNCATTR_END)))
def add_starts(self, bap):
syms = []
for line in bap.syms:
heappush(syms, int(line, 16))
for i in range(len(syms)):
idaapi.add_func(heappop(syms), idaapi.BADADDR)
idc.Refresh()
idaapi.refresh_idaview_anyway()
def _del_action_recursive(self):
"""
Delete the recursive rename action from IDA.
"""
idaapi.unregister_action(self.ACTION_RECURSIVE)
idaapi.free_custom_icon(self._recursive_icon_id)
self._recursive_icon_id = idaapi.BADADDR
#------------------------------------------------------------------------------
# Plugin Hooks
#------------------------------------------------------------------------------
def recursive_prefix_cursor():
"""
Recursive prefix under the user cursor.
"""
# get the function reference under the user cursor (if there is one)
target = get_cursor_func_ref()
if target == idaapi.BADADDR:
return
# execute the recursive prefix
recursive_prefix(target)
def bulk_prefix():
"""
Prefix the Functions window selection with a user defined string.
"""
# 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
#
# 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 notify_calc_step_over(self, ip):
"""
Calculate the address of the instruction which will be
executed after "step over". The kernel will put a breakpoint there.
If the step over is equal to step into or we can not calculate
the address, return BADADDR.
args:
ip - instruction address
returns: target or BADADDR
"""
return idaapi.BADADDR
def highlight_instructions(highlighters):
ea = idc.NextHead(0)
while ea != idaapi.BADADDR:
for h in highlighters:
h.highlight(ea)
ea = idc.NextHead(ea)
def code_search(ea, val):
"""Search forward for the next occurance of val. Return None if no match."""
res = idc.FindBinary(ea, idc.SEARCH_DOWN, val)
if res == idaapi.BADADDR:
return None
else:
return res
def _uninstall_open_coverage_overview(self):
"""
Remove the 'View->Open subviews->Coverage Overview' menu entry.
"""
# remove the entry from the View-> menu
result = idaapi.detach_action_from_menu(
"View/Open subviews/Hex dump",
self.ACTION_COVERAGE_OVERVIEW
)
if not result:
return False
# unregister the action
result = idaapi.unregister_action(self.ACTION_COVERAGE_OVERVIEW)
if not result:
return False
# delete the entry's icon
idaapi.free_custom_icon(self._icon_id_overview)
self._icon_id_overview = idaapi.BADADDR
logger.info("Uninstalled the 'Coverage Overview' menu entry")
#--------------------------------------------------------------------------
# UI - Actions
#--------------------------------------------------------------------------
def by_name(name):
'''Return the function with the name ``name``.'''
ea = idaapi.get_name_ea(-1, name)
if ea == idaapi.BADADDR:
raise LookupError("{:s}.by_name({!r}) : Unable to locate function".format(__name__, name))
return idaapi.get_func(ea)
def add(start, **end):
"""Make a function at the address ``start``.
If the address ``end`` is specified, then stop processing the function at it's address.
"""
start = interface.address.inside(start)
end = end.get('end', idaapi.BADADDR)
ok = idaapi.add_func(start, end)
idaapi.autoWait()
return ok