Initial SVN commit of version 0.9.54 sources.

This commit is contained in:
gergely.erdelyi 2007-10-20 07:03:51 +00:00
commit 9b85915a48
49 changed files with 9980 additions and 0 deletions

63
BUILDING.txt Normal file
View File

@ -0,0 +1,63 @@
----------------------------------------------------------
IDAPython - Python plugin for Interactive Disassembler Pro
----------------------------------------------------------
Building From Source
--------------------
REQUIREMENTS
[Tested versions are in brackets]
- IDA and IDA SDK [5.1]
http://www.datarescue.com/idabase/
- Python [2.4.4, 2.5]
http://www.python.org/
- Simplified Wrapper Interface Generator (SWIG) [1.3.31]
SWIG is not needed for regular building, only if you want to tweak the wrappers.
http://www.swig.org/
- Unix utilities (GNU patch on Windows):
http://www.research.att.com/sw/tools/uwin/ or
http://unxutils.sourceforge.net/ or
http://www.cygwin.com/
- GCC on Linux and Mac OS X [4.0]
Comes with your distribution
- Microsoft Visual C on Windows [Microsoft Visual C++ 2005 Express Edition]
http://msdn.microsoft.com/vstudio/express/visualc/
BUILDING
Make sure all the needed tools (compiler, make, swig, etc) are on the
PATH.
1, Unpack the IDAPython source and IDA Pro SDK into the following
directory structure:
swigsdk-versions/5.1/ - version 5.0 of the IDA Pro SDK
idapython/ - IDAPython source code
2, Patch the SDK using GNU Patch with one of patches from patches/ directory.
You will have to use the -P option depending on which directory you
patch from.
2, Build the plugin
python build.py
It is possible to build the plugin for different Python versions by
running build.py with the corresponding Python binary.
3, Install the components as described in README.txt
See build.py for build details and tweak opportunities.
-------------------------------------------------------------------------------
Copyright (c) 2004-2007 Gergely Erdelyi <dyce@d-dome.net>. All rights reserved.
-------------------------------------------------------------------------------

72
CHANGES.txt Normal file
View File

@ -0,0 +1,72 @@
Changes from version 0.9.0 to 0.9.53
------------------------------------
- Upgraded IDA Pro base version to 5.1
- Experimental Mac OS X support
- Improved IDC coverage
- Cleanups and fixes
Changes from version 0.8.0 to 0.9.0
-----------------------------------
- Upgraded base version to IDA Pro 5.0
- Works with IDA Pro 5.1
- Python 2.4 and 2.5 supported
- Close to complete IDC compatbility layer (in sync with 4.9)
- Significatnly improved IDA SDK API covergage (see STATUS.txt for details)
- IDA SDK patch size reduced to less than half
- Simplified installation (plugins.cfg modification not needed)
- Evaluation window content is saved over IDA restarts (in the database)
- Windows version is built with Microsoft Visual C++ Express Edition
- Build makefile replaced with a Python script
- Cleanups and small fixes
Changes from version 0.7.0 to 0.8.0
-----------------------------------
- Added support for IDA Pro 4.9
- Dropped support for IDA Pro 4.7
- NOTE: Windows version is linked against Python 2.4.
- New wrappers: search.hpp, dbg.hpp, loader.hpp, diskio.hpp, nalt.hpp
- idc.py synced up to IDA 4.8
- Added 38 IDC functions
- Fixed asklong(), askseg() and askaddr()
- Automatically generated cross reference documentation (epydoc)
- User-specific init file support (see README,txt)
- Deprecated some functions that have direct Python equivalents (see idc.py)
- Fixed exception in ScriptBox when invoked empty.
- Lots of cleanups and small fixes
Changes from version 0.6.0 to 0.7.0
-----------------------------------
- Batch execution support (use the option -OIDAPython:yourscript.py)
- Added ScriptBox - lists previously run scripts (Hotkey:Alt-7)
- Added support for IDA Pro 4.8 (both Linux and Windows)
- Dropped support for IDA Pro 4.6 and 4.6SP1 versions
- Wrapped the list chooser (see examples/choose.py)
- A dozen or so IDC functions added
- Lots of char * API calls wrapped
- Added Python error handling in the plugin C layer
- Bunch of misc small cleanups and fixes
- For more details see CHANGES-SWIG.txt and CHANGES-Plugin.txt
- API CHANGE: {Next|Prev}Function() return BADADDR instead of -1
Changes from version 0.5.0 to 0.6.0
-----------------------------------
- Added support for IDA Pro 4.7 (both Linux and Windows)
- Dropped support for IDA Pro 4.6SP1 beta on Linux
- Lots of IDC wrapper additions and fixes:
- Added 30+ new wrappers to idc.py
- Most Find*, Ask* and Seg* are now wrapped
- Fixed broken NextAddr(), PrevAddr(), MakeFunction() and MakeName()
- Fixes to the makefile
- Cleanups for the idaapi wrapper
- Bunch of misc small cleanups and fixes
- For more details see CHANGES-SWIG.txt and CHANGES-Plugin.txt

27
COPYING.txt Normal file
View File

@ -0,0 +1,27 @@
Copyright (c) 2004-2007 Gergely Erdelyi <dyce@d-dome.net>. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.

70
README.txt Normal file
View File

@ -0,0 +1,70 @@
----------------------------------------------------------
IDAPython - Python plugin for Interactive Disassembler Pro
----------------------------------------------------------
WHAT IS IDAPTYHON?
IDAPython is an IDA plugin which makes it possible to write scripts
for IDA in the Python programming language. IDAPython provides full
access to both the IDA API and any installed Python module.
Check the scripts in the examples directory to get an quick glimpse.
AVAILABILITY
Latest versions of IDAPython are available from
http://www.d-dome.net/idapython/
INSTALLATION FROM BINARIES
1, Install Python 2.4 or 2.5 from http://www.python.org/
2, Copy the directory python\ to the IDA install directory
3. Copy the plugin to the %IDADIR%\plugins\
USAGE
The plugin has three hotkeys:
- Run script (Alt-9)
- Execute Python statement(s) (Alt-8)
- Run previously executed script again (Alt-7)
Batch mode execution:
Start IDA with the following command line options:
-A -OIDAPython:yourscript.py file_to_work_on
If you want fully unattended execution mode, make sure your script
exits with a qexit() call.
User init file:
You can place your custom settings to a file called 'idapythonrc.py'
that should be placed to
${HOME}/.idapro/
or
C:\Documents and Settings\%USER%\Application Data\Datarescue\IDA Pro
The user init file is read and executed at the end of the init process.
THANKS
This project is sponsored by F-Secure Corporation by allowing me to
use some company time and resources for development. Please note that
F-Secure is only sponsoring the project, the company does not provide
any formal support for this software. Questions, comments, bug reports
should be directed to the author.
F-Secure Corporation's website is located at
http://www.F-Secure.com/

72
STATUS.txt Normal file
View File

@ -0,0 +1,72 @@
Status of the IDC wrapper
-------------------------
6 function unimplemented out of 434 (98% coverage):
rotate_left
XRefType
SetMemberType
GetType
GuessType
SetType
Status of IDA API wrappers
--------------------------
COMPLETE: all possible functions wrapped, no SWIG ifdefs
INCOMPLETE: some wrapping or SWIG ifdefs still left
EXCLUDED: will not be wrapped
allins.hpp - COMPLETE
area.hpp - INCOMPLETE (SWIGdefs left)
auto.hpp - COMPLETE
bytes.hpp - INCOMPLETE (no SWIGs, some unwrapped)
compress.hpp - EXCLUDED
dbg.hpp - INCOMPLETE (SWIGs and lot of fixing to do)
demangle.hpp - EXCLUDED
diskio.hpp - INCOMPLETE (no SWIGs, some unwrapped)
entry.hpp - COMPLETE
enum.hpp - INCOMPLETE (no SWIGs, one FIXME)
err.h - EXCLUDED
exehdr.h - EXCLUDED
expr.hpp - INCOMPLETE (wrapped, needs testing)
fixup.hpp - COMPLETE
fpro.h - EXCLUDED
frame.hpp - COMPLETE
funcs.hpp - INCOMPLETE (some SWIGs, few FIXMEs)
gdl.hpp - EXCLUDED
graph.hpp - EXCLUDED
help.h - EXCLUDED
ida.hpp - INCOMPLETE (SWIGs)
idd.hpp - INCOMPLETE (SWIGs)
idp.hpp - INCOMPLETE (SWIGs)
ieee.h - EXCLUDED
intel.hpp - EXCLUDED
ints.hpp - INCOMPLETE (SWIGs)
kernwin.hpp - INCOMPLETE (SWIGs and lot of fixing to do)
lex.hpp - EXCLUDED
lines.hpp - INCOMPLETE (few FIXMEs)
llong.hpp - EXCLUDED
loader.hpp - INCOMPLETE (few FIXMEs)
md5.h - EXCLUDED
moves.hpp - COMPLETE (some needed SWIGs)
nalt.hpp - INCOMPLETE (SWIGs and lot of fixing to do)
name.hpp - INCOMPLETE (few FIXMEs)
netnode.hpp - INCOMPLETE (not wrapped at all)
offset.hpp - COMPLETE
prodir.h - EXCLUDED
pro.h - COMPLETE (some needed SWIGs)
queue.hpp - INCOMPLETE (one FIXME)
regex.h - EXCLUDED
search.hpp - INCOMPLETE (one FIXME)
segment.hpp - INCOMPLETE (no SWIGs, few FIXMEs)
sistack.hpp - EXCLUDED
srarea.hpp - INCOMPLETE (not wrapped at all)
strlist.hpp - COMPLETE
struct.hpp - COMPLETE
typeinf.hpp - INCOMPLETE (no SWIGs, lot of fixing to do)
ua.hpp - INCOMPLETE (SWIGs and lot of fixing to do)
va.hpp - EXCLUDED
vm.hpp - EXCLUDED
xref.hpp - COMPLETE

4
basetsd.h Normal file
View File

@ -0,0 +1,4 @@
#ifndef _BASETSD_H
#define _BASETSD_H
/* Microsoft free compilers seem to lack this file and Python needs it */
#endif

408
build.py Normal file
View File

@ -0,0 +1,408 @@
#!/usr/bin/env python
#------------------------------------------------------------
# IDAPython - Python plugin for Interactive Disassembler Pro
#
# Copyright (c) 2004-2007 Gergely Erdelyi <dyce@d-dome.net>
#
# All rights reserved.
#
# For detailed copyright information see the file COPYING in
# the root of the distribution archive.
#------------------------------------------------------------
# build.py - Custom build script
#------------------------------------------------------------
import os, sys, platform, types, shutil
from distutils import sysconfig
# Start of user configurable options
VERBOSE = True
IDA_MAJOR_VERSION = 5
IDA_MINOR_VERSION = 1
IDA_SDK = ".." + os.sep + "swigsdk-versions" + os.sep + "%d.%d" % (IDA_MAJOR_VERSION, IDA_MINOR_VERSION)
# End of user configurable options
# IDAPython version
VERSION_MAJOR = 0
VERSION_MINOR = 9
VERSION_PATCH = 53
# Determine Python version
PYTHON_MAJOR_VERSION = int(platform.python_version()[0])
PYTHON_MINOR_VERSION = int(platform.python_version()[2])
# Find Python headers
PYTHON_INCLUDE_DIRECTORY = sysconfig.get_config_var('INCLUDEPY')
# Swig command-line parameters
SWIG_OPTIONS = '-modern -python -c++ -shadow -D__GNUC__'
# Common macros for all compilations
COMMON_MACROS = [
("VER_MAJOR", "%d" % VERSION_MAJOR),
("VER_MINOR", "%d" % VERSION_MINOR),
("VER_PATCH", "%d" % VERSION_PATCH),
"__IDP__",
("MAXSTR", "1024"),
"USE_DANGEROUS_FUNCTIONS",
"USE_STANDARD_FILE_FUNCTIONS" ]
# Common includes for all compilations
COMMON_INCLUDES = [ ".", "swig" ]
# List files for the binary distribution
BINDIST_MANIFEST = [
"README.txt",
"COPYING.txt",
"CHANGES.txt",
"STATUS.txt",
"python/init.py",
"python/idc.py",
"python/idautils.py",
("idaapi.py", "python"),
"docs/notes.txt",
"examples/chooser.py",
"examples/ex1.idc",
"examples/ex1_idaapi.py",
"examples/ex1_idautils.py" ]
# List files for the source distribution (appended to binary list)
SRCDIST_MANIFEST = [
"BUILDING.txt",
"python.cpp",
"basetsd.h",
"build.py",
"swig/auto.i",
"swig/bytes.i",
"swig/dbg.i",
"swig/diskio.i",
"swig/entry.i",
"swig/enum.i",
"swig/expr.i",
"swig/fixup.i",
"swig/frame.i",
"swig/funcs.i",
"swig/ida.i",
"swig/idaapi.i",
"swig/idp.i",
"swig/ints.i",
"swig/kernwin.i",
"swig/lines.i",
"swig/loader.i",
"swig/moves.i",
"swig/nalt.i",
"swig/name.i",
"swig/offset.i",
"swig/pro.i",
"swig/queue.i",
"swig/search.i",
"swig/segment.i",
"swig/srarea.i",
"swig/strlist.i",
"swig/struct.i",
"swig/typeconv.i",
"swig/typeinf.i",
"swig/ua.i",
"swig/xref.i",
"patches/ida51.patch"
]
# Temporaty build files to remove
BUILD_TEMPFILES = [
"idaapi.cpp",
"idaapi.obj",
"idaapi.o",
"idaapi.py",
"idapython.sln",
"idapython.ncb",
"python.exp",
"python.lib",
"python.obj"
]
class BuilderBase:
""" Base class for builders """
def __init__(self):
pass
def compile(self, source, objectname=None, includes=[], macros=[]):
"""
Compile the source file
"""
allmacros = []
allmacros.extend(COMMON_MACROS)
allmacros.extend(self.basemacros)
allmacros.extend(macros)
macrostring = self._build_command_string(allmacros, self.macro_delimiter)
allincludes = []
allincludes.extend(COMMON_INCLUDES)
allincludes.extend(includes)
includestring = self._build_command_string(allincludes, self.include_delimiter)
if not objectname:
objectname = source + self.object_extension
cmdstring = "%s %s %s %s %s %s" % (self.compiler,
self.compiler_parameters,
self.compiler_out_string(objectname),
self.compiler_in_string(source + self.source_extension),
includestring,
macrostring)
if VERBOSE: print cmdstring
return os.system(cmdstring)
def link(self, objects, outfile, libpaths=[], libraries=[], extra_parameters=None):
""" Link the binary from objects and libraries """
cmdstring = "%s %s %s" % (self.linker,
self.linker_parameters,
self.linker_out_string(outfile))
for objectfile in objects:
cmdstring = "%s %s" % (cmdstring, objectfile + self.object_extension)
for libpath in libpaths:
cmdstring = "%s %s%s" % (cmdstring, self.libpath_delimiter, libpath)
for library in libraries:
cmdstring = "%s %s" % (cmdstring, library)
if extra_parameters:
cmdstring = "%s %s" % (cmdstring, extra_parameters)
if VERBOSE: print cmdstring
return os.system(cmdstring)
def _build_command_string(self, macros, argument_delimiter):
macrostring = ""
for item in macros:
if type(item) == types.TupleType:
macrostring += '%s%s="%s" ' % (argument_delimiter, item[0], item[1])
else:
macrostring += '%s%s ' % (argument_delimiter, item)
return macrostring
class GCCBuilder(BuilderBase):
""" Generic GCC compiler class """
def __init__(self):
self.include_delimiter = "-I"
self.macro_delimiter = "-D"
self.libpath_delimiter = "-L"
self.compiler_parameters = ""
self.linker_parameters = "-shared"
self.basemacros = [ ]
self.compiler = "g++"
self.linker = "g++"
self.source_extension = ".cpp"
self.object_extension = ".o"
def compiler_in_string(self, filename):
return "-c %s" % filename
def compiler_out_string(self, filename):
return "-o %s" % filename
def linker_out_string(self, filename):
return "-o %s" % filename
class MSVCBuilder(BuilderBase):
""" Generic GCC compiler class """
def __init__(self):
self.include_delimiter = "/I"
self.macro_delimiter = "/D"
self.libpath_delimiter = "/LIBPATH:"
self.compiler_parameters = "/nologo /EHsc"
self.linker_parameters = "/nologo /dll /export:PLUGIN"
self.basemacros = [ "WIN32",
"_USRDLL",
"__NT__" ]
self.compiler = "cl"
self.linker = "link"
self.source_extension = ".cpp"
self.object_extension = ".obj"
def compiler_in_string(self, filename):
return "/c %s" % filename
def compiler_out_string(self, filename):
return "/Fo%s" % filename
def linker_out_string(self, filename):
return "/out:%s" % filename
def build_distribution(manifest, distrootdir):
""" Create dist tree and copy files to it """
# Remove the previous distibution if exits
if os.path.exists(distrootdir):
shutil.rmtree(distrootdir)
# Create output directory
os.makedirs(distrootdir)
# Copy files, one by one
for f in manifest:
if type(f) == types.TupleType:
srcfilepath = f[0]
srcfilename = os.path.basename(srcfilepath)
dstdir = distrootdir + os.sep + f[1]
dstfilepath = dstdir + os.sep + srcfilename
else:
srcfilepath = f
srcfilename = os.path.basename(f)
srcdir = os.path.dirname(f)
if srcdir == "":
dstdir = distrootdir
else:
dstdir = distrootdir + os.sep + srcdir
if not os.path.exists(dstdir):
os.makedirs(dstdir)
dstfilepath = dstdir + os.sep + srcfilename
shutil.copyfile(srcfilepath, dstfilepath)
def build_plugin(system, idasdkdir):
""" Build the plugin from the SWIG wrapper and plugin main source """
# Find IDA SDK headers
ida_include_directory = idasdkdir + os.sep + "include"
# Platform-specific settings for the Linux build
if system == "Linux":
builder = GCCBuilder()
plugin_name = "python.plx"
platform_macros = [ "__LINUX__" ]
python_libpath = sysconfig.EXEC_PREFIX + os.sep + "lib"
python_library = "-lpython%d.%d" % (PYTHON_MAJOR_VERSION, PYTHON_MINOR_VERSION)
ida_libpath = idasdkdir + os.sep + "libgcc32.lnx"
ida_lib = ""
extra_link_parameters = "/usr/lib/python%s.%s/lib-dynload/*.so" % (PYTHON_MAJOR_VERSION, PYTHON_MINOR_VERSION)
# Platform-specific settings for the Windows build
if system == "Windows":
builder = MSVCBuilder()
plugin_name = "python.plw"
platform_macros = [ "__NT__" ]
python_libpath = sysconfig.EXEC_PREFIX + os.sep + "libs"
python_library = "python%d%d.lib" % (PYTHON_MAJOR_VERSION, PYTHON_MINOR_VERSION)
ida_libpath = idasdkdir + os.sep + "libvc.w32"
ida_lib = "ida.lib"
extra_link_parameters = None
# Platform-specific settings for the Linux build
if system == "Darwin":
builder = GCCBuilder()
builder.linker_parameters = "-dynamiclib"
plugin_name = "python.pmc"
platform_macros = [ "__MAC__" ]
python_libpath = "."
python_library = "-framework Python"
ida_libpath = idasdkdir + os.sep + "libgcc32.mac"
ida_lib = "-lida"
extra_link_parameters = ""
# Build the wrapper from the interface files
swigcmd = "swig %s -Iswig -o idaapi.cpp -I%s idaapi.i" % (SWIG_OPTIONS, ida_include_directory)
if VERBOSE: print swigcmd
res = os.system(swigcmd)
if res != 0: return False
# Compile the wrapper
res = builder.compile("idaapi",
includes=[ PYTHON_INCLUDE_DIRECTORY, ida_include_directory ],
macros=platform_macros)
if res != 0: return False
# Compile the main plugin source
res = builder.compile("python",
includes=[ PYTHON_INCLUDE_DIRECTORY, ida_include_directory ],
macros=platform_macros)
if res != 0: return False
# Link the final binary
res = builder.link( ["idaapi", "python"],
plugin_name,
[ python_libpath, ida_libpath ],
[ python_library, ida_lib ],
extra_link_parameters)
if res != 0: return False
return True
def clean(manifest):
""" Clean the temporary files """
for i in manifest:
try:
os.unlink(i)
except:
pass
if __name__ == "__main__":
# Detect the platform
system = platform.system()
if system == "Windows":
platform_string = "win32"
plugin_name = "python.plw"
if system == "Linux":
platform_string = "linux"
plugin_name = "python.plx"
if system == "Darwin":
platform_string = "macosx"
plugin_name = "python.pmc"
BINDISTDIR = "idapython-%d.%d.%d_ida%d.%d_py%d.%d_%s" % ( VERSION_MAJOR,
VERSION_MINOR,
VERSION_PATCH,
IDA_MAJOR_VERSION,
IDA_MINOR_VERSION,
PYTHON_MAJOR_VERSION,
PYTHON_MINOR_VERSION,
platform_string)
SRCDISTDIR = "idapython-%d.%d.%d" % ( VERSION_MAJOR,
VERSION_MINOR,
VERSION_PATCH )
# Build the plugin
res = build_plugin(system, IDA_SDK)
if not res: sys.exit(1)
# Build the binary distribution
binmanifest = []
binmanifest.extend(BINDIST_MANIFEST)
binmanifest.append((plugin_name, "plugins"))
build_distribution(binmanifest, BINDISTDIR)
# Build the binary distribution
srcmanifest = []
srcmanifest.extend(BINDIST_MANIFEST)
srcmanifest.extend(SRCDIST_MANIFEST)
build_distribution(srcmanifest, SRCDISTDIR)
# Clean the temp files
cleanlist = []
cleanlist.extend(BUILD_TEMPFILES)
cleanlist.append(plugin_name)
clean(cleanlist)

53
docs/notes.txt Normal file
View File

@ -0,0 +1,53 @@
Assorted notes
--------------
Wrapped functions and constants:
All the symbols from the idaapi module are listed in symbollist.txt.
Documentation for the plugin API functions functions is in the IDA
SDK header files. All function and symbol names directly translate
to the C++ counterparts. If you try to use a function that is not
wrapped yet you will get an exception like this:
Traceback (most recent call last):
File "<string>", line 1, in ?
NameError: name 'foobar' is not defined
If this happens you can check the function in symbollist.txt. If it
is not included and it should be please report it to the author.
Data types:
All the C++ data types are mapped to corresponding Python data types.
For example ea_t maps to a Python integer. Complex data types (like
structures and classes) are mapped to Python classes that have the
same attributes as the original type.
Arguments and return values:
Generally all function arguments should be the same type as specified
by the original headers. Pointers to complex types (structures, classes)
are checked and must match the original declarations.
For example comment = get_func_comment("aa", 0) will raise an exception:
Traceback (most recent call last):
File "<string>", line 1, in ?
TypeError: Type error. Got aa, expected _p_func_t
When calling functions that return a string in a buffer (usually with
maximum size) the buffer and size parameter is omitted. These functions
return either the result in a string or None if the call fails and returns
NULL. The output buffers are maximized at MAXSTR.
Example:
C++: get_func_name(0x1234, buf, sizeof(buf));
Python: name = get_func_name(0x1234)
Any function that should return a char * is going to return either a
Python string (up to MAXSTR) or None.

46
examples/chooser.py Normal file
View File

@ -0,0 +1,46 @@
#
# Demonstration of the new chooser usage
#
#
# Modal chooser
#
# Get a modal Choose instance
chooser = Choose([], "MyChooser", 1)
# List to choose from
chooser.list = [ "First", "Second", "Third" ]
# Set the width
chooser.width = 50
# Run the chooser
ch = chooser.choose()
# Print the results
if ch > 0:
print "You chose %d which is %s" % (ch, chooser.list[ch-1])
else:
print "Escape from chooser"
#
# Normal chooser
#
class MyChoose(Choose):
"""
You have to subclass Chooser to override the enter() method
"""
def __init__(self, list=[], name="Choose"):
Choose.__init__(self, list, name)
# Set the width
self.width = 50
def enter(self, n):
print "Enter called. Do some stuff here."
print "The chosen item is %d = %s" % (n, self.list[n-1])
print "Now press ESC to leave."
# Get a Choose instance
chooser = MyChoose([ "First", "Second", "Third" ], "MyChoose")
# Run the chooser
ch = chooser.choose()

35
examples/ex1.idc Normal file
View File

@ -0,0 +1,35 @@
//
// Reference Lister
//
// List all functions and all references to them in the current section.
//
// Implemented in IDC
//
#include <idc.idc>
static main()
{
auto ea, func, ref;
// Get current ea
ea = ScreenEA();
// Loop from start to end in the current segment
for (func=SegStart(ea);
func != BADADDR && func < SegEnd(ea);
func=NextFunction(func))
{
// If the current address is function process it
if (GetFunctionFlags(func) != -1)
{
Message("Function %s at 0x%x\n", GetFunctionName(func), func);
// Find all code references to func
for (ref=RfirstB(func); ref != BADADDR; ref=RnextB(func, ref))
{
Message(" called from %s(0x%x)\n", GetFunctionName(ref), ref);
}
}
}
}

29
examples/ex1_idaapi.py Normal file
View File

@ -0,0 +1,29 @@
#
# Reference Lister
#
# List all functions and all references to them in the current section.
#
# Implemented using direct IDA Plugin API calls
#
from idaapi import *
# Get current ea
ea = get_screen_ea()
# Get segment class
seg = getseg(ea)
# Loop from segment start to end
func = get_func(seg.startEA)
while func != None and func.startEA < seg.endEA:
funcea = func.startEA
print "Function %s at 0x%x" % (GetFunctionName(funcea), funcea)
ref = get_first_cref_to(funcea)
while ref != BADADDR:
print " called from %s(0x%x)" % (get_func_name(ref), ref)
ref = get_next_cref_to(funcea, ref)
func = get_next_func(funcea)

20
examples/ex1_idautils.py Normal file
View File

@ -0,0 +1,20 @@
#
# Reference Lister
#
# List all functions and all references to them in the current section.
#
# Implemented with the idautils module
#
from idautils import *
# Get current ea
ea = ScreenEA()
# Loop from start to end in the current segment
for funcea in Functions(SegStart(ea), SegEnd(ea)):
print "Function %s at 0x%x" % (GetFunctionName(funcea), funcea)
# Find all code references to funcea
for ref in CodeRefsTo(funcea, 1):
print " called from %s(0x%x)" % (GetFunctionName(ref), ref)

826
patches/ida51.patch Normal file
View File

@ -0,0 +1,826 @@
diff -ur idasdk-versions/5.1/include/area.hpp swigsdk-versions/5.1/include/area.hpp
--- idasdk-versions/5.1/include/area.hpp 2006-09-20 17:37:08.000000000 +0300
+++ swigsdk-versions/5.1/include/area.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -57,6 +57,7 @@
};
+#ifndef SWIG
// Internal classes
class sarray; // sorted array - keeps information in Btree.
@@ -603,6 +604,7 @@
{ return areacb_t_for_all_areas(this, ea1, ea2, av, ud); }
};
+#endif // SWIG
// Last request information -- for internal use
diff -ur idasdk-versions/5.1/include/bytes.hpp swigsdk-versions/5.1/include/bytes.hpp
--- idasdk-versions/5.1/include/bytes.hpp 2007-01-22 04:07:12.000000000 +0200
+++ swigsdk-versions/5.1/include/bytes.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -1644,9 +1644,9 @@
const uchar *mask, // comparision mask
size_t len, // length of string to search
int step, // direction:
+ int flags);
#define BIN_SEARCH_FORWARD 1
#define BIN_SEARCH_BACKWARD (-1)
- int flags);
#define BIN_SEARCH_CASE 0x01
#define BIN_SEARCH_NOCASE 0x00
#define BIN_SEARCH_NOBREAK 0x02
diff -ur idasdk-versions/5.1/include/dbg.hpp swigsdk-versions/5.1/include/dbg.hpp
--- idasdk-versions/5.1/include/dbg.hpp 2006-11-20 13:18:02.000000000 +0200
+++ swigsdk-versions/5.1/include/dbg.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -31,6 +31,7 @@
idaman debugger_t ida_export_data *dbg; // Current debugger - NULL if no debugger
+#ifndef SWIG
//--------------------------------------------------------------------
// D E B U G G E R C A L L B A C K S
//--------------------------------------------------------------------
@@ -519,6 +520,7 @@
// Notification: none (synchronous function)
bool idaapi is_reg_integer(const char *regname);
+#endif // SWIG
//--------------------------------------------------------------------
// B R E A K P O I N T S
@@ -543,6 +545,7 @@
};
+#ifndef SWIG
// Get number of breakpoints.
// Type: Synchronous function
// Notification: none (synchronous function)
@@ -779,6 +782,7 @@
//--------------------------------------------------------------------
// T R A C I N G E V E N T S
//--------------------------------------------------------------------
+#endif // SWIG
// Trace event types:
enum tev_type_t
@@ -799,6 +803,7 @@
};
+#ifndef SWIG
// Get number of trace events available in trace buffer.
// Type: Synchronous function
// Notification: none (synchronous function)
@@ -877,6 +882,7 @@
// corresponds to a valid breakpoint.
ea_t idaapi get_bpt_tev_ea(int n);
+#endif // SWIG
//--------------------------------------------------------------------
// Utility functions
diff -ur idasdk-versions/5.1/include/expr.hpp swigsdk-versions/5.1/include/expr.hpp
--- idasdk-versions/5.1/include/expr.hpp 2006-04-12 16:29:34.000000000 +0300
+++ swigsdk-versions/5.1/include/expr.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -37,12 +37,16 @@
number of arguments. The actual number of
arguments will be passed in res->num */
+#ifndef SWIG
union
{
+#endif // SWIG
char *str; /* T_str */
sval_t num; /* T_long */
ushort e[6]; /* T_flt */
+#ifndef SWIG
};
+#endif // SWIG
};
diff -ur idasdk-versions/5.1/include/funcs.hpp swigsdk-versions/5.1/include/funcs.hpp
--- idasdk-versions/5.1/include/funcs.hpp 2007-02-17 21:04:02.000000000 +0200
+++ swigsdk-versions/5.1/include/funcs.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -88,10 +88,12 @@
bool is_far(void) const { return (flags & FUNC_FAR) != 0; }
bool does_return(void) const { return (flags & FUNC_NORET) == 0; }
bool analyzed_sp(void) const { return (flags & FUNC_SP_READY) != 0; }
+#ifndef SWIG
union
{
struct // attributes of a function entry chunk
{
+#endif // SWIG
//
// Stack frame of the function. It is represented as a structure:
//
@@ -147,15 +149,19 @@
int tailqty; // number of function tails
area_t *tails; // array of tails, sorted by ea
// use func_tail_iterator_t to access function tails
+#ifndef SWIG
};
struct // attributes of a function tail chunk
{
+#endif // SWIG
ea_t owner; // the address of the main function possessing this tail
int refqty; // number of referers
ea_t *referers; // array of referers (function start addresses)
// use func_parent_iterator_t to access the referers
+#ifndef SWIG
};
};
+#endif // SWIG
};
inline bool is_func_entry(const func_t *pfn) { return pfn != NULL && (pfn->flags & FUNC_TAIL) == 0; }
diff -ur idasdk-versions/5.1/include/ida.hpp swigsdk-versions/5.1/include/ida.hpp
--- idasdk-versions/5.1/include/ida.hpp 2007-01-31 16:35:16.000000000 +0200
+++ swigsdk-versions/5.1/include/ida.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -369,6 +369,7 @@
inline bool idaapi should_create_stkvars(void) { return (inf.af & AF_LVAR) != 0; }
+#ifndef SWIG
// set a 'bit' in 'where' if 'value' if not zero
inline void idaapi setflag(uchar &where,uchar bit,int value)
@@ -390,10 +391,13 @@
else where &= ~bit;
}
+#endif // SWIG
//------------------------------------------------------------------------//
+#ifndef SWIG
#define BADADDR ea_t(-1) // this value is used for 'bad address'
#define BADSEL sel_t(-1) // 'bad selector' value
+#endif // SWIG
// Maximum address allowed to use in the program being disassebled.
// This is obsolete, don't use it!
diff -ur idasdk-versions/5.1/include/idd.hpp swigsdk-versions/5.1/include/idd.hpp
--- idasdk-versions/5.1/include/idd.hpp 2006-12-08 16:52:40.000000000 +0200
+++ swigsdk-versions/5.1/include/idd.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -53,6 +53,7 @@
char name[MAXSTR];
};
+#ifndef SWIG
//====================================================================
//
// Registers
@@ -173,6 +174,7 @@
e_exception_t exc; // EXCEPTION
};
};
+#endif // SWIG
// Hardware breakpoint types
typedef int bpttype_t;
@@ -183,6 +185,7 @@
BPT_SOFT = 4; // Software breakpoint
+#ifndef SWIG
// Exception information
struct exception_info_t
{
@@ -441,6 +444,7 @@
#error "Size of debugger_t is incorrect"
#endif
#endif
+#endif // SWIG
#pragma pack(pop)
#endif // _IDD_HPP
diff -ur idasdk-versions/5.1/include/idp.hpp swigsdk-versions/5.1/include/idp.hpp
--- idasdk-versions/5.1/include/idp.hpp 2007-02-09 12:54:06.000000000 +0200
+++ swigsdk-versions/5.1/include/idp.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -31,6 +31,7 @@
#define IDP_INTERFACE_VERSION 76
+#ifndef SWIG
//-----------------------------------------------------------------------
// AbstractRegister and WorkReg are deprecated!
class WorkReg;
@@ -110,6 +111,7 @@
#define CF_HLL 0x10000 // Instruction may be present in a high level
// language function.
};
+#endif // SWIG
idaman bool ida_export InstrIsSet(int icode,int bit); // does the specified instruction
// have the specified feature?
@@ -119,6 +121,7 @@
idaman bool ida_export is_indirect_jump_insn(ea_t ea);
idaman bool ida_export is_basic_block_end(bool call_insn_stops_block); // in:cmd
+#ifndef SWIG
//-----------------------------------------------------------------------
// Structures related to checkarg_dispatch()
@@ -1384,6 +1387,7 @@
int high_fixup_bits;
};
+#endif // SWIG
#ifdef __BORLANDC__
#if sizeof(processor_t) % 4
@@ -1394,8 +1398,10 @@
// The following two structures contain information about the current
// processor and assembler.
+#ifndef SWIG
idaman processor_t ida_export_data ph; // Current processor
idaman asm_t ida_export_data ash; // Current assembler
+#endif // SWIG
idaman int ida_export str2regf(const char *p); // -1 - error. Returns word reg number
idaman int ida_export str2reg(const char *p); // -1 - error. Returns any reg number
@@ -1500,10 +1506,12 @@
idaman char *ida_export get_idp_name(char *buf, size_t bufsize);
+#ifndef SWIG
// Unload the processor module.
// This function is for the kernel only.
void free_processor_module(void);
+#endif // SWIG
// Set target assembler
@@ -1512,11 +1520,13 @@
idaman void ida_export set_target_assembler(int asmnum);
+#ifndef SWIG
// Read IDA.CFG file and configure IDA for the current processor
// This is an internal kernel function.
// It should not be used in modules.
void read_config_file(int npass);
+#endif // SWIG
// get number of bits in a byte at the given address
diff -ur idasdk-versions/5.1/include/kernwin.hpp swigsdk-versions/5.1/include/kernwin.hpp
--- idasdk-versions/5.1/include/kernwin.hpp 2007-01-29 05:44:54.000000000 +0200
+++ swigsdk-versions/5.1/include/kernwin.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -28,8 +28,10 @@
#include <help.h>
#include <llong.hpp>
+#ifndef SWIG
typedef int atype_t; // autoanalysis types
typedef int idastate_t; // ida state indicator (ready, thinking, waiting)
+#endif // SWIG
typedef uchar color_t; // see <lines.hpp>
typedef uval_t bmask_t; // see <enum.hpp>
typedef tid_t enum_t; // see <enum.hpp>
@@ -95,6 +97,7 @@
class value_t;
class linput_t;
+#ifndef SWIG
union callui_t // Return codes (size of this type should be 4 bytes at most)
{ // (otherwise different compilers return it differently)
bool cnd;
@@ -877,6 +880,8 @@
idaman void ida_export vshow_hex_file(linput_t *li, long pos, size_t count, const char *format, va_list va);
+#endif // SWIG
+#ifndef SWIG
//--------------------------------------------------------------------------
// K E R N E L S E R V I C E S F O R U I
//--------------------------------------------------------------------------
@@ -1218,8 +1223,10 @@
{ return linearray_t_up(this); }
};
+#endif // SWIG
+#ifndef SWIG
//---------------------------------------------------------------------------
// D E B U G G I N G F U N C T I O N S
//---------------------------------------------------------------------------
@@ -1303,11 +1310,13 @@
vshow_hex_file(li, pos, count, fmt, va);
va_end(va);
}
+#endif // SWIG
//-------------------------------------------------------------------------
// U I S E R V I C E F U N C T I O N S
//-------------------------------------------------------------------------
+#ifndef SWIG
// Common function prototypes
// These functions are inlined for the kernel
// They are not inlined for the user-interfaces
@@ -1466,6 +1475,7 @@
sizer, getl, title, icon, deflt, del,
ins, update, edit, enter, destroy, popup_names, get_icon);
}
+#endif // SWIG
// Navigation band colorizer function
// ea - address to calculate the color of
@@ -1570,6 +1580,7 @@
// Get VCL global variables
+#ifndef SWIG
#if defined(__BORLANDC__)
namespace Forms
{
@@ -1590,6 +1601,7 @@
}
#endif // __BORLANDC__
+#endif // SWIG
#ifdef _WINDOWS_
namespace Forms
@@ -1807,6 +1819,7 @@
}
+#ifndef SWIG
// Pointer to idaview marker function.
// This pointer is initialized by callui(ui_get_marker)
@@ -1839,6 +1852,7 @@
if ( idaview_marker != NULL )
idaview_marker(get_screen_ea());
}
+#endif // SWIG
inline char *choose_idasgn(void)
@@ -1914,6 +1928,7 @@
return callui(ui_choose, chtype_struc, title).strptr;
}
+#ifndef SWIG
inline int choose_struc_path(const char *title, tid_t strid,
uval_t offset, adiff_t delta, bool appzero, tid_t *path)
{
@@ -1978,6 +1993,7 @@
widths, sizer, getl, title, icon, deflt, del, ins,
update, edit, enter, destroy, popup_names, get_icon).i32;
}
+#endif // SWIG
// Display a dialog box with "Please wait..."
@@ -2309,6 +2325,7 @@
return nbytes;
}
+#ifndef SWIG
inline int Message(help_t format,...)
{
va_list va;
@@ -2317,8 +2334,10 @@
va_end(va);
return nbytes;
}
+#endif // SWIG
+#ifndef SWIG
//----------------------------------------------------------------------
// F O R M S - C O M P L E X D I A L O G B O X E S
//----------------------------------------------------------------------
@@ -2534,6 +2553,7 @@
<Names pre~f~ix :A:15:15::>
*/
+#endif // SWIG
//---------------------------------------------------------------------------
// Y E S / N O D I A L O G B O X
@@ -2695,6 +2715,7 @@
#define HIST_TYPE 8 // type declarations
+#ifndef SWIG
// Display a dialog box and wait for the user to input multiline text
// size - maximum size of text in bytes
// answer - output buffer. if you specify NULL then the answer
@@ -2719,6 +2740,7 @@
va_end(va);
return result;
}
+#endif // SWIG
//---------------------------------------------------------------------------
@@ -2794,6 +2816,7 @@
idaman const char *ida_export strarray(const strarray_t *array, size_t array_size, int code);
+#ifndef SWIG
// Convert whitespace to tabulations
// This functin will stop the conversion as soon as a string or character constant
// is encountered
@@ -2986,6 +3009,7 @@
// match a string with a regular expression
// returns: 0-no match, 1-match, -1-error
idaman int ida_export regex_match(const char *str, const char *pattern, bool sense_case);
+#endif // SWIG
#pragma pack(pop)
diff -ur idasdk-versions/5.1/include/lines.hpp swigsdk-versions/5.1/include/lines.hpp
--- idasdk-versions/5.1/include/lines.hpp 2006-03-17 17:41:22.000000000 +0200
+++ swigsdk-versions/5.1/include/lines.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -614,12 +614,11 @@
ml_getnam_t *getnam,
ml_genxrf_t *genxrf,
ml_saver_t *saver,
- int flags
+ int flags);
#define MAKELINE_NONE 0x00
#define MAKELINE_BINPREF 0x01
#define MAKELINE_VOID 0x02
#define MAKELINE_STACK 0x04
- );
idaman bool ida_export save_line_in_array(const char *line); // a standard line saver()
idaman void ida_export init_lines_array(char *lnar[],int maxsize);// initialization function for it
diff -ur idasdk-versions/5.1/include/moves.hpp swigsdk-versions/5.1/include/moves.hpp
--- idasdk-versions/5.1/include/moves.hpp 2006-03-17 17:41:22.000000000 +0200
+++ swigsdk-versions/5.1/include/moves.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -26,6 +26,8 @@
{ return !(*this == r); }
};
+
+#ifndef SWIG
// Helper functions. Should not be called directly!
class curloc;
class location_t;
@@ -49,13 +51,16 @@
DEFINE_CURLOC_HELPERS(idaman)
DEFINE_LOCATION_HELPERS(idaman)
+#endif // SWIG
#define CURLOC_SISTACK_ITEMS 4
class curloc : public sistack_t
{
void push(void);
+#ifndef SWIG
DEFINE_CURLOC_HELPERS(friend)
+#endif // SWIG
void unhide_if_necessary(ea_t ea);
void hide_if_necessary(void);
protected:
@@ -120,7 +125,9 @@
class location_t : public curloc
{
typedef curloc inherited;
+#ifndef SWIG
DEFINE_LOCATION_HELPERS(friend)
+#endif // SWIG
public:
graph_location_info_t gli;
location_t(void) {}
diff -ur idasdk-versions/5.1/include/nalt.hpp swigsdk-versions/5.1/include/nalt.hpp
--- idasdk-versions/5.1/include/nalt.hpp 2007-01-29 22:06:46.000000000 +0200
+++ swigsdk-versions/5.1/include/nalt.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -29,6 +29,7 @@
// in them. Look at netnode.hpp for the definition of netnodes.
//
+#ifndef SWIG
#include <netnode.hpp>
//--------------------------------------------------------------------------
@@ -324,6 +325,7 @@
IMPL__IS_AFLAG_FUNCS(AFL_FIXEDSPD, fixed_spd)
IMPL__IS_AFLAG_FUNCS(AFL_ALIGNFLOW,align_flow)
IMPL__IS_AFLAG_FUNCS(AFL_USERTI, userti)
+#endif // SWIG
inline void set_visible_item(ea_t ea, bool visible)
{
@@ -341,11 +343,14 @@
// source line numbers (they are sometimes present in object files)
// Thes functions may be used if necessary.
+#ifndef SWIG
NALT_EA(get_linnum0,set_linnum0, del_linnum0, NALT_LINNUM)
+#endif // SWIG
idaman void ida_export set_source_linnum(ea_t ea, uval_t lnnum);
idaman uval_t ida_export get_source_linnum(ea_t ea); // returns BADADDR if no lnnum
idaman void ida_export del_source_linnum(ea_t ea);
+#ifndef SWIG
// absolute segment base address
// These functions may be used if necessary.
NALT_EA(get_absbase,set_absbase, del_absbase, NALT_ABSBASE)
@@ -366,6 +371,7 @@
// type of string
// Don't use, see: get_typeinfo()
NALT_ULONG(get_str_type,set_str_type,del_str_type,NALT_STRTYPE)
+#endif // SWIG
inline char idaapi get_str_type_code(uval_t strtype) { return char(strtype); }
@@ -402,16 +408,19 @@
}
+#ifndef SWIG
// alignment value (should be power of 2)
// These functions may be used if necessary.
NALT_ULONG(get_alignment,set_alignment,del_alignment,NALT_ALIGN)
// instruction/data background color
NALT_ULONG(_get_item_color,_set_item_color,_del_item_color,NALT_COLOR)
+#endif // SWIG
idaman void ida_export set_item_color(ea_t ea, bgcolor_t color);
idaman bgcolor_t ida_export get_item_color(ea_t ea); // returns DEFCOLOR if no color
idaman void ida_export del_item_color(ea_t ea);
+#ifndef SWIG
//----------------------------------------------------------------------
NSUP_STRING(nalt_cmt,NSUP_CMT) // regular comment (low level, don't use)
NSUP_STRING(nalt_rptcmt,NSUP_REPCMT) // repeatable comment (low level, don't use)
@@ -559,6 +568,7 @@
// Address which holds the switch info. Used at the jump targets.
NALT_EA(get_switch_parent,set_switch_parent,del_switch_parent, NALT_SWITCH)
+#endif // SWIG
//--------------------------------------------------------------------------
@@ -671,6 +681,7 @@
idaman void ida_export write_struc_path(netnode node, int idx, const tid_t *path, int plen, adiff_t delta);
idaman int ida_export read_struc_path(netnode node, int idx, tid_t *path, adiff_t *delta); // returns plen
+#ifndef SWIG
#define DEFINE_PATH_FUNCS(name, code) \
inline int N_PASTE(get_,name)(ea_t ea, tid_t *path, adiff_t *delta) \
{ return read_struc_path(netnode(ea), code, path, delta); } \
@@ -738,6 +749,7 @@
#define RIDX_ALT_CRC32 uval_t(-5) // input file crc32
#define RIDX_ALT_IMAGEBASE uval_t(-6) // image base
#define RIDX_ALT_IDSNODE uval_t(-7) // ids modnode id (for import_module)
+#endif // SWIG
//--------------------------------------------------------------------------
// Get full path of the input file
@@ -784,11 +796,13 @@
return get_input_file_path(buf, bufsize);
}
+#ifndef SWIG
#ifndef NO_OBSOLETE_FUNCS
#define SWI_SHIFT1 0x80 // use formula (element*2 + elbase)
// to find jump targets (obsolete)
NSUP_STRUCT(switch_info,NSUP_SWITCH)
#endif
+#endif // SWIG
#ifndef BYTES_SOURCE // undefined bit masks so no one can use them directly
#undef AFL_LINNUM
diff -ur idasdk-versions/5.1/include/pro.h swigsdk-versions/5.1/include/pro.h
--- idasdk-versions/5.1/include/pro.h 2007-02-17 21:04:34.000000000 +0200
+++ swigsdk-versions/5.1/include/pro.h 2007-09-30 06:56:51.000000000 +0300
@@ -63,6 +63,7 @@
#define __EA64__
#endif
+#ifndef SWIG
#ifdef __VC__
#define ENUM_SIZE(t) : t
#else
@@ -138,6 +139,7 @@
#define __KYLIX__
#endif
+#endif // SWIG
/*==================================================*/
#ifndef MAXSTR
#define MAXSTR 1024
@@ -178,7 +180,12 @@
/*==================================================*/
-#if defined(__IDP__) && defined(__NT__) // for modules
+#if defined(SWIG) // for SWIG
+#define idaapi
+#define idaman
+#define ida_export
+#define ida_export_data
+#elif defined(__IDP__) && defined(__NT__) // for modules
#define idaapi __stdcall
#define idaman EXTERNC
#define ida_export idaapi
@@ -237,7 +244,9 @@
typedef unsigned long ulong;
#endif
+#ifndef SWIG
#include <llong.hpp>
+#endif // SWIG
typedef char int8;
typedef signed char sint8;
@@ -295,6 +304,7 @@
typedef adiff_t sval_t; // signed value used by the processor
// for 32-bit ea_t, long
// for 64-bit ea_t, longlong
+#ifndef SWIG
#define BADADDR ea_t(-1) // this value is used for 'bad address'
// Windows64 declarations
@@ -618,7 +628,9 @@
idaman bool ida_export qisdir(const char *file);
/*==================================================*/
+#endif // SWIG
idaman void ida_export qexit(int code);
+#ifndef SWIG
idaman void ida_export qatexit(void (idaapi *func)(void));
/*==================================================*/
@@ -1286,6 +1298,7 @@
#define cwstr(dst, src, dstsize) qstrncpy(dst, src, dstsize)
#define wcstr(dst, src, dstsize) qstrncpy(dst, src, dstsize)
#endif
+#endif // SWIG
// Old Visual C++ compilers were not defining the following:
#ifdef __NT__
diff -ur idasdk-versions/5.1/include/ua.hpp swigsdk-versions/5.1/include/ua.hpp
--- idasdk-versions/5.1/include/ua.hpp 2006-10-24 23:19:54.000000000 +0300
+++ swigsdk-versions/5.1/include/ua.hpp 2007-09-30 06:56:51.000000000 +0300
@@ -42,10 +42,12 @@
// in 'cmd' structure. They should not access to bytes of instruction
// and decode it again - this should be done in the analysis step.
+#ifndef SWIG
#include <kernwin.hpp> // for btoa()
#include <lines.hpp> // for color_t
#include <xref.hpp> // add_cref()
#include <llong.hpp> // longlong
+#endif // SWIG
//--------------------------------------------------------------------------
// T Y P E O F O P E R A N D
@@ -223,13 +225,17 @@
// The following unions keep other information about the operand
+#ifndef SWIG
union
{
+#endif // SWIG
ushort reg; // number of register (o_reg)
ushort phrase; // number of register phrase (o_phrase,o_displ)
// you yourself define numbers of phrases
// as you like
+#ifndef SWIG
};
+#endif // SWIG
bool is_reg(int r) const { return type == o_reg && reg == r; }
@@ -238,7 +244,9 @@
// VALUE
+#ifndef SWIG
union {
+#endif // SWIG
uval_t value; // value of operand (o_imm)
// outer displacement (o_displ+OF_OUTER_DISP)
@@ -246,14 +254,18 @@
ushort low; // your convenience only
ushort high;
} value_shorts;
+#ifndef SWIG
};
+#endif // SWIG
bool is_imm(uval_t v) const { return type == o_imm && value == v; }
// VIRTUAL ADDRESS (OFFSET WITHIN THE SEGMENT)
+#ifndef SWIG
union {
+#endif // SWIG
ea_t addr; // virtual address pointed or used by the operand
// (o_mem,o_displ,o_far,o_near)
@@ -261,18 +273,25 @@
ushort low; // your convenience only
ushort high;
} addr_shorts;
+
+#ifndef SWIG
};
+#endif // SWIG
// IDP SPECIFIC INFORMATION
+#ifndef SWIG
union {
+#endif // SWIG
ea_t specval; // This field may be used as you want.
struct { // this structure is defined for your convenience only
ushort low; // IBM PC: segment register number (o_mem,o_far,o_near)
ushort high; // IBM PC: segment selector value (o_mem,o_far,o_near)
} specval_shorts;
+#ifndef SWIG
};
+#endif // SWIG
// The following fields are used only in idp modules
// You may use them as you want to store additional information about
@@ -336,15 +355,19 @@
// Additinal information about the instruction.
// You may use these field as you want.
+#ifndef SWIG
union
{
+#endif // SWIG
ushort auxpref; // processor dependent field
struct
{
uchar low;
uchar high;
} auxpref_chars;
+#ifndef SWIG
};
+#endif // SWIG
char segpref; // processor dependent field
char insnpref; // processor dependent field
@@ -374,6 +397,7 @@
// This structure is used to pass values of bytes to helper functions.
+#ifndef SWIG
union value_u
{
uchar v_char;
@@ -393,6 +417,7 @@
// returns: number of immediate values (0..2*UA_MAXOP)
idaman size_t ida_export get_operand_immvals(ea_t ea, int n, uval_t *v);
+#endif // SWIG
//--------------------------------------------------------------------------
@@ -405,6 +430,7 @@
idaman insn_t ida_export_data cmd; // current instruction
+#ifndef SWIG
// Undocumented variable. It is not used by the kernel.
// Its value may be specified in IDA.CFG:
// LOOKBACK = <number>
@@ -810,6 +836,7 @@
// Returns: the reference target address (the same as calc_reference_target)
idaman ea_t ida_export ua_add_off_drefs(const op_t &x, dref_t type);
+#endif // SWIG
// Get size and flags for op_t.dtyp field.
@@ -871,6 +898,7 @@
idaman const char *ida_export ua_mnem(ea_t ea, char *buf, size_t bufsize);
+#ifndef SWIG
//--------------------------------------------------------------------------
// Helper functions for the processor emulator/analyzer
//--------------------------------------------------------------------------
@@ -942,6 +970,7 @@
// Also converts to code, uses fixups, increases segments etc
// This function is only for the kernel
// Use ua_code() instead
+#endif // SWIG
#ifndef NO_OBSOLETE_FUNCS
idaman void ida_export ua_dodata(ea_t ea, int dtype);

461
python.cpp Normal file
View File

@ -0,0 +1,461 @@
//------------------------------------------------------------
// IDAPython - Python plugin for Interactive Disassembler Pro
//
// Copyright (c) 2004-2007 Gergely Erdelyi <dyce@d-dome.net>
//
// All rights reserved.
//
// For detailed copyright information see the file COPYING in
// the root of the distribution archive.
//------------------------------------------------------------
// python.cpp - Main plugin code
//------------------------------------------------------------
#include <Python.h>
/* This define fixes the redefinition of ssize_t */
#ifdef HAVE_SSIZE_T
#define _SSIZE_T_DEFINED 1
#endif
#include <stdio.h>
#include <string.h>
#include <ida.hpp>
#include <idp.hpp>
#include <bytes.hpp>
#include <diskio.hpp>
#include <loader.hpp>
#include <kernwin.hpp>
#include <netnode.hpp>
#ifdef __cplusplus
extern "C"
#endif
/* Python-style version tuple comes from the makefile */
/* Only the serial and status is set here */
#define VER_SERIAL 0
#define VER_STATUS "final"
#define IDAPYTHON_RUNFILE 0
#define IDAPYTHON_RUNSTATEMENT 1
#define IDAPYTHON_SCRIPTBOX 2
#define IDAPYTHON_DATA_STATEMENT 0
void init_idaapi(void);
void idaapi run(int arg);
static int initialized = 0;
/* This is a simple tracing code for debugging purposes. */
/* It might evolve into a tracing facility for user scripts. */
/* #define ENABLE_PYTHON_PROFILING */
#ifdef ENABLE_PYTHON_PROFILING
#include "compile.h"
#include "frameobject.h"
int tracefunc(PyObject *obj, _frame *frame, int what, PyObject *arg)
{
PyObject *str;
/* Catch line change events. */
/* Print the filename and line number */
if (what == PyTrace_LINE)
{
str = PyObject_Str(frame->f_code->co_filename);
if (str)
{
msg("PROFILING: %s:%d\n", PyString_AsString(str), frame->f_lineno);
Py_DECREF(str);
}
}
return 0;
}
#endif
/* QuickFix for the FILE* incompatibility problem */
int ExecFile(char *FileName)
{
PyObject* PyFileObject = PyFile_FromString(FileName, "r");
if (!PyFileObject)
{
return 0;
}
if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), FileName) == 0)
{
Py_DECREF(PyFileObject);
return 1;
}
else
{
Py_DECREF(PyFileObject);
return 0;
}
}
/* Check for the presence of a file in IDADIR/python */
bool CheckFile(char *filename)
{
char filepath[MAXSTR+1];
#if IDP_INTERFACE_VERSION >= 75
qmakepath(filepath, MAXSTR, idadir(NULL), "python", filename, NULL);
#elif IDP_INTERFACE_VERSION >= 69
qmakepath(filepath, idadir(NULL), "python", filename, NULL);
#else
qmakepath(filepath, idadir(), "python", filename, NULL);
#endif
if (!qfileexist(filepath))
{
warning("IDAPython: Missing required file %s", filename);
return false;
}
return true;
}
/* Execute the Python script from the plugin */
/* Default hotkey: Alt-9 */
void IDAPython_RunScript(char *script)
{
char statement[MAXSTR+32];
char slashpath[MAXSTR+1];
char *scriptpath;
int i;
if (script)
{
scriptpath = script;
}
else
{
scriptpath = askfile_c(0, "*.py", "Python file to run");
if (!scriptpath)
{
return;
}
}
/* Make a copy of the path with '\\' => '/' */
for (i=0; scriptpath[i]; i++)
{
if (scriptpath[i] == '\\')
{
slashpath[i] = '/';
}
else
{
slashpath[i] = scriptpath[i];
}
}
slashpath[i] = '\0';
/* Add the script't path to sys.path */
snprintf(statement, sizeof(statement), "runscript(\"%s\")", slashpath);
PyRun_SimpleString(statement);
/* Error handling */
if (PyErr_Occurred())
{
PyErr_Print();
}
}
/* Execute Python statement(s) from an editor window */
/* Default hotkey: Alt-8 */
void IDAPython_RunStatement(void)
{
char statement[4096];
netnode history;
/* Get the existing or create a new netnode in the database */
history.create("IDAPython_Data");
/* Fetch the previous statement */
if (history.supval(IDAPYTHON_DATA_STATEMENT, statement, sizeof(statement)) == -1)
{
statement[0] = '\0';
}
if (asktext(sizeof(statement), statement, statement, "Enter Python expressions"))
{
PyRun_SimpleString(statement);
/* Store the statement to the database */
history.supset(IDAPYTHON_DATA_STATEMENT, statement);
}
}
/* History of previously executed scripts */
/* Default hotkey: Alt-7 */
void IDAPython_ScriptBox(void)
{
PyObject *module;
PyObject *dict;
PyObject *scriptbox;
PyObject *pystr;
/* Get globals() */
/* These two should never fail */
module = PyImport_AddModule("__main__");
dict = PyModule_GetDict(module);
scriptbox = PyDict_GetItemString(dict, "ScriptBox_instance");
if (!scriptbox)
{
warning("INTERNAL ERROR: ScriptBox_instance missing! Broken init.py?");
return;
}
pystr = PyObject_CallMethod(scriptbox, "run", "");
if (pystr)
{
/* If the return value is string use it as path */
if (PyObject_TypeCheck(pystr, &PyString_Type))
{
ExecFile(PyString_AsString(pystr));
}
Py_DECREF(pystr);
}
else
{
/* Print the exception info */
if (PyErr_Occurred())
{
PyErr_Print();
}
}
}
bool idaapi IDAPython_Menu_Callback(void *ud)
{
run((int)ud);
return true;
}
/* Initialize the Python environment */
bool IDAPython_Init(void)
{
char *options;
char tmp[MAXSTR+64];
char *initpath;
bool result = 1;
/* Already initialized? */
if (initialized == 1)
{
return true;
}
/* Check for the presence of essential files */
initialized = 0;
result &= CheckFile("idc.py");
result &= CheckFile("init.py");
result &= CheckFile("idaapi.py");
result &= CheckFile("idautils.py");
if (!result)
{
return false;
}
/* Start the interpreter */
Py_Initialize();
if (!Py_IsInitialized())
{
warning("IDAPython: Py_Initialize() failed");
return false;
}
/* Init the SWIG wrapper */
init_idaapi();
sprintf(tmp, "IDAPYTHON_VERSION=(%d, %d, %d, '%s', %d)", \
VER_MAJOR,
VER_MINOR,
VER_PATCH,
VER_STATUS,
VER_SERIAL);
PyRun_SimpleString(tmp);
#if IDP_INTERFACE_VERSION >= 75
qmakepath(tmp, MAXSTR, idadir("python"), "init.py", NULL);
#elif IDP_INTERFACE_VERSION >= 69
qmakepath(tmp, idadir("python"), "init.py", NULL);
#else
qmakepath(tmp, idadir(), "python", "init.py", NULL);
#endif
/* Pull in the Python side of init */
if (!ExecFile(tmp))
{
warning("IDAPython: error executing init.py");
return false;
}
#ifdef ENABLE_PYTHON_PROFILING
PyEval_SetTrace(tracefunc, NULL);
#endif
/* Batch-mode operation: */
/* A script specified on the command line is run */
options = (char *)get_plugin_options("IDAPython");
if (options)
{
IDAPython_RunScript(options);
}
/* Add menu items for all the functions */
/* Different paths are used for the GUI version */
result = add_menu_item("File/IDC command...", "P~y~thon command...",
"Alt-8", SETMENU_APP,
(menu_item_callback_t *)IDAPython_Menu_Callback,
(void *)IDAPYTHON_RUNSTATEMENT);
result = add_menu_item("File/Load file/IDC file...", "P~y~thon file...",
"Alt-9", SETMENU_APP,
(menu_item_callback_t *)IDAPython_Menu_Callback,
(void *)IDAPYTHON_RUNFILE);
if (!result)
{
add_menu_item("File/IDC command...", "P~y~thon file...",
"Alt-9", SETMENU_APP,
(menu_item_callback_t *)IDAPython_Menu_Callback,
(void *)IDAPYTHON_RUNFILE);
}
result = add_menu_item("View/Open subviews/Show strings", "Python S~c~ripts",
"Alt-7", SETMENU_APP,
(menu_item_callback_t *)IDAPython_Menu_Callback,
(void *)IDAPYTHON_SCRIPTBOX);
if (!result)
{
add_menu_item("View/Open subviews/Problems", "Python S~c~ripts",
"Alt-7", SETMENU_APP,
(menu_item_callback_t *)IDAPython_Menu_Callback,
(void *)IDAPYTHON_SCRIPTBOX);
}
initialized = 1;
return true;
}
/* Cleaning up Python */
void IDAPython_Term(void)
{
/* Remove the menu items before termination */
#if 0
// FIXME: This segfaults the Linux version. The non-existent items might cause this?
del_menu_item("File/Load file/Python file...");
del_menu_item("File/Python file...");
del_menu_item("File/Python command...");
del_menu_item("View/Open subviews/Python Scripts");
#endif
/* Shut the interpreter down */
Py_Finalize();
initialized = 0;
}
/* Plugin init routine */
int idaapi init(void)
{
if (IDAPython_Init())
{
return PLUGIN_KEEP;
}
else
{
return PLUGIN_SKIP;
}
}
/* Plugin term routine */
void idaapi term(void)
{
IDAPython_Term();
}
/* Plugin hotkey entry point */
void idaapi run(int arg)
{
try
{
switch (arg)
{
case 0:
IDAPython_RunScript(NULL);
break;
;;
case 1:
IDAPython_RunStatement();
break;
;;
case 2:
IDAPython_ScriptBox();
break;
;;
default:
warning("IDAPython: unknown plugin argument %d", arg);
break;
;;
}
}
catch(...)
{
warning("Exception in Python interpreter. Reloading...");
IDAPython_Term();
IDAPython_Init();
}
}
//--------------------------------------------------------------------------
// PLUGIN DESCRIPTION BLOCK
//--------------------------------------------------------------------------
char comment[] = "IDAPython";
char help[] = "IDA Python Plugin\n";
char wanted_name[] = "IDAPython";
char wanted_hotkey[] = "Alt-9";
extern "C"
{
plugin_t PLUGIN = {
IDP_INTERFACE_VERSION,
0, // plugin flags
init, // initialize
term, // terminate. this pointer may be NULL.
run, // invoke plugin
comment, // long comment about the plugin
// it could appear in the status line
// or as a hint
help, // multiline help about the plugin
wanted_name, // the preferred short name of the plugin
wanted_hotkey // the preferred hotkey to run the plugin
};
}

268
python/idautils.py Normal file
View File

@ -0,0 +1,268 @@
#------------------------------------------------------------
# IDAPython - Python plugin for Interactive Disassembler Pro
#
# Copyright (c) 2004-2007 Gergely Erdelyi <dyce@d-dome.net>
#
# All rights reserved.
#
# For detailed copyright information see the file COPYING in
# the root of the distribution archive.
#------------------------------------------------------------
"""
idautils.py - High level utility functions for IDA
"""
from idaapi import *
def refs(ea, funcfirst, funcnext):
"""
Generic reference collector - INTERNAL USE ONLY.
"""
reflist = []
ref = funcfirst(ea)
if ref != BADADDR:
reflist.append(ref)
while 1:
ref = funcnext(ea, ref)
if ref == BADADDR:
break
else:
reflist.append(ref)
return reflist
def CodeRefsTo(ea, flow):
"""
Get a list of code references to 'ea'
@param ea: Target address
@param flow: Follow normal code flow or not
@type flow: Boolean (0/1, False/True)
@return: list of references (may be empty list)
Example::
for ref in CodeRefsTo(ScreenEA(), 1):
print ref
"""
if flow == 1:
return refs(ea, get_first_cref_to, get_next_cref_to)
else:
return refs(ea, get_first_fcref_to, get_next_fcref_to)
def CodeRefsFrom(ea, flow):
"""
Get a list of code references from 'ea'
@param ea: Target address
@param flow: Follow normal code flow or not
@type flow: Boolean (0/1, False/True)
@return: list of references (may be empty list)
Example::
for ref in CodeRefsFrom(ScreenEA(), 1):
print ref
"""
if flow == 1:
return refs(ea, get_first_cref_from, get_next_cref_from)
else:
return refs(ea, get_first_fcref_from, get_next_fcref_from)
def DataRefsTo(ea):
"""
Get a list of data references to 'ea'
@param ea: Target address
@return: list of references (may be empty list)
Example::
for ref in DataRefsTo(ScreenEA(), 1):
print ref
"""
return refs(ea, get_first_dref_to, get_next_dref_to)
def DataRefsFrom(ea):
"""
Get a list of data references from 'ea'
@param ea: Target address
@return: list of references (may be empty list)
Example::
for ref in DataRefsFrom(ScreenEA(), 1):
print ref
"""
return refs(ea, get_first_dref_from, get_next_dref_from)
def Heads(start, end):
"""
Get a list of heads (instructions or data)
@param start: start address (this one is always included)
@param end: end address
@return: list of heads between start and end
"""
headlist = []
headlist.append(start)
ea = start
while 1:
ea = next_head(ea, end)
if ea == BADADDR:
break
else:
headlist.append(ea)
return headlist
def Functions(start, end):
"""
Get a list of functions
@param start: start address
@param end: end address
@return: list of heads between start and end
@note: The last function that starts before 'end' is included even
if it extends beyond 'end'.
"""
startaddr = start
endaddr = end
funclist = []
func = get_func(start)
if func:
funclist.append(func.startEA)
ea = start
while 1:
func = get_next_func(ea)
if not func: break
if func.startEA < end:
funclist.append(func.startEA)
ea = func.startEA
else:
break
return funclist
def Segments():
"""
Get list of segments (sections) in the binary image
@return: List of segment start addresses.
"""
seglist = []
for n in range(get_segm_qty()):
seg = getnseg(n)
if not seg:
break
else:
seglist.append(seg.startEA)
return seglist
def GetDataList(ea, count, itemsize=1):
"""
Get data list - INTERNAL USE ONLY
"""
getdata = None
if itemsize == 1:
getdata = get_byte
if itemsize == 2:
getdata = get_word
if itemsize == 4:
getdata = get_dword
if getdata == None:
raise ValueError, "Invalid data size! Must be 1, 2 or 4"
list = []
for offs in range(count):
list.append(getdata(ea))
ea = ea + itemsize
return list
def PutDataList(ea, list, itemsize=1):
"""
Put data list - INTERNAL USE ONLY
"""
putdata = None
if itemsize == 1:
putdata = patch_byte
if itemsize == 2:
putdata = patch_word
if itemsize == 4:
putdata = patch_dword
if putdata == None:
raise ValueError, "Invalid data size! Must be 1, 2 or 4"
for val in list:
putdata(ea, val)
ea = ea + itemsize
def MapDataList(ea, length, func, wordsize=1):
"""
Map through a list of data words in the database
@param ea: start address
@param length: number of words to map
@param func: mapping function
@param wordsize: size of words to map [default: 1 byte]
@return: None
"""
PutDataList(ea, map(func, GetDataList(ea, length, wordsize)), wordsize)
def GetInputFileMD5():
"""
Return the MD5 hash of the input binary file
@return: MD5 string or None on error
"""
ua=ucharArray(16)
if retrieve_input_file_md5(ua.cast()):
md5str=""
for i in range(16):
md5str += "%02x" % ua[i]
return md5str
else:
return None

6123
python/idc.py Normal file

File diff suppressed because it is too large Load Diff

135
python/init.py Normal file
View File

@ -0,0 +1,135 @@
#!/usr/bin/env python
#------------------------------------------------------------
# IDAPython - Python plugin for Interactive Disassembler Pro
#
# Copyright (c) 2004-2007 Gergely Erdelyi <dyce@d-dome.net>
#
# All rights reserved.
#
# For detailed copyright information see the file COPYING in
# the root of the distribution archive.
#------------------------------------------------------------
# init.py - Essential init routines
#------------------------------------------------------------
import sys, os, os.path, traceback, warnings
import _idaapi
# FIXME: Should fix the offending constant instead
warnings.filterwarnings('ignore', category=FutureWarning)
def addscriptpath(script):
"""
Add the path part of the scriptfile to the system path to
allow modules to be loaded from the same place.
Each path is added only once.
"""
pathfound = 0
scriptpath = os.path.dirname(script)
for pathitem in sys.path:
if pathitem == scriptpath:
pathfound = 1
break
if pathfound == 0:
sys.path.append(scriptpath)
# Add the script to ScriptBox if it's not there yet
if not script in ScriptBox_instance.list:
ScriptBox_instance.list.insert(0, script)
def runscript(script):
"""
Run the specified script after adding its directory path to
system path.
This function is used by the low-level plugin code.
"""
addscriptpath(script)
argv = sys.argv
sys.argv = [ script ]
execfile(script, globals())
sys.argv = argv
def print_banner():
version1 = "IDAPython version %d.%d.%d %s (serial %d) initialized" % IDAPYTHON_VERSION
version2 = "Python interpreter version %d.%d.%d %s (serial %d)" % sys.version_info
linelen = max(len(version1), len(version2))
print '-' * linelen
print version1
print version2
print '-' * linelen
#-----------------------------------------------------------
# Take over the standard text outputs
#-----------------------------------------------------------
class MyStdOut:
"""
Dummy file-like class that receives stout and stderr
"""
def write(self, text):
_idaapi.msg(text.replace("%", "%%"))
def flush(self):
pass
# Redirect stderr and stdout to the IDA message window
sys.stdout = sys.stderr = MyStdOut()
# Assign a default sys.argv
sys.argv = [ "" ]
# Have to make sure Python finds our modules
sys.path.append(_idaapi.idadir("python"))
print_banner()
#-----------------------------------------------------------
# Import all the required modules
#-----------------------------------------------------------
from idc import *
from idautils import *
#-----------------------------------------------------------
# Build up the ScriptBox tool
#-----------------------------------------------------------
class ScriptBox(Choose):
def __init__(self, list=[]):
Choose.__init__(self, list, "ScriptBox", 1)
self.width = 50
def run(self):
if len(self.list) == 0:
Warning("ScriptBox history is empty.\nRun some script with Alt-9 and try again.")
return None
n = self.choose()
if n > 0:
return self.list[n-1]
else:
return None
def addscript(self, scriptpath):
self.list.append(scriptpath)
ScriptBox_instance = ScriptBox([])
# Load the users personal init file
userrc = get_user_idadir() + os.sep + "idapythonrc.py"
if os.path.exists(userrc):
runscript(userrc)
# Remove the user script from the history
del ScriptBox_instance.list[0]
# All done, ready to rock.

13
swig/auto.i Normal file
View File

@ -0,0 +1,13 @@
%ignore auto_process_all;
%ignore autoPlanned;
%ignore nextPlanned;
%ignore autoDelCode;
%ignore autoPeek;
%ignore autoProcess;
%ignore auto_init;
%ignore auto_save;
%ignore auto_term;
%ignore ea_without_xrefs;
%include "auto.hpp"

72
swig/bytes.i Normal file
View File

@ -0,0 +1,72 @@
// This makes put_many_bytes and patch_many_bytes work nicely
%apply (char *STRING, int LENGTH) { (const void *buf, size_t size) };
// Make get_any_cmt() work
%apply unsigned char *OUTPUT { color_t *cmttype };
// For get_enum_id()
%apply unsigned char *OUTPUT { uchar *serial };
// Unexported and kernel-only declarations
%ignore FlagsEnable;
%ignore FlagsDisable;
%ignore testf_t;
%ignore nextthat;
%ignore prevthat;
%ignore adjust_visea;
%ignore prev_visea;
%ignore next_visea;
%ignore is_first_visea;
%ignore is_last_visea;
%ignore is_visible_finally;
%ignore invalidate_visea_cache;
%ignore fluFlags;
%ignore setFlbits;
%ignore clrFlbits;
%ignore get_8bit;
%ignore get_ascii_char;
%ignore del_typeinfo;
%ignore del_operand_typeinfo;
%ignore doCode;
%ignore get_repeatable_cmt;
%ignore get_any_indented_cmt;
%ignore del_code_comments;
%ignore doFlow;
%ignore noFlow;
%ignore doRef;
%ignore noRef;
%ignore doExtra;
%ignore noExtra;
%ignore coagulate;
%ignore coagulate_dref;
%ignore get_item_head;
%ignore init_hidden_areas;
%ignore save_hidden_areas;
%ignore term_hidden_areas;
%ignore check_move_args;
%ignore movechunk;
%ignore lock_dbgmem_config;
%ignore unlock_dbgmem_config;
%ignore set_op_type_no_event;
%ignore ida_vpagesize;
%ignore ida_vpages;
%ignore ida_npagesize;
%ignore ida_npages;
%ignore FlagsInit;
%ignore FlagsTerm;
%ignore FlagsReset;
// TODO: These could be fixed if someone needs them.
%ignore get_many_bytes;
%ignore put_many_bytes;
%ignore patch_many_bytes;
%ignore set_dbgmem_source;
%ignore invalidate_dbgmem_config;
%ignore invalidate_dbgmem_contents;
%ignore is_debugger_on;
%include "bytes.hpp"
%clear(const void *buf, size_t size);
%clear(void *buf, ssize_t size);
%clear(typeinfo_t *);

10
swig/dbg.i Normal file
View File

@ -0,0 +1,10 @@
// SWIG chokes on the original declaration so it is replicated here
typedef struct
{
ulonglong ival; // 8: integer value
ushort fval[6]; // 12: floating point value in the internal representation (see ieee.h)
} regval_t;
%immutable dbg;
%include "dbg.hpp"

43
swig/diskio.i Normal file
View File

@ -0,0 +1,43 @@
// TODO: These could be wrapped
%ignore enumerate_files;
%ignore enumerate_system_files;
%ignore ioport_bit_t;
%ignore ioport_bits_t;
%ignore ioport_t;
%ignore read_ioports;
%ignore choose_ioport_device;
%ignore find_ioport;
%ignore find_ioport_bit;
%ignore free_ioports;
%ignore lread;
%ignore qlread;
%ignore qlgets;
%ignore qlgetc;
%ignore lreadbytes;
%ignore lread2bytes;
%ignore lread2bytes;
%ignore lread4bytes;
%ignore lread4bytes;
%ignore lread8bytes;
%ignore lread8bytes;
%ignore qlsize;
%ignore qlseek;
%ignore qltell;
%ignore qlfile;
%ignore make_linput;
%ignore unmake_linput;
// FIXME: These should be wrapped for completeness
%ignore eread;
%ignore ewrite;
// Ignore kernel-only & unexported symbols
%ignore get_thread_priority;
%ignore set_thread_priority;
%ignore checkdspace;
%ignore lowdiskgo;
%ignore ida_argv;
%ignore exename;
%include "diskio.hpp"

7
swig/entry.i Normal file
View File

@ -0,0 +1,7 @@
%ignore init_entries;
%ignore term_entries;
%ignore move_entries;
%ignore set_entry_name;
%include "entry.hpp"

28
swig/enum.i Normal file
View File

@ -0,0 +1,28 @@
// Kernel only & unexported symbols
%ignore enums;
%ignore init_enums;
%ignore save_enums;
%ignore term_enums;
%ignore get_selected_enum;
%ignore add_selected_enum;
%ignore unmark_selected_enums;
%ignore is_good_bmask;
%ignore get_bmask_enum;
%ignore ENUM_REVERSE;
%ignore ENUM_SELMEMS;
%ignore ENUM_QTY_IDX;
%ignore ENUM_FLG_IDX;
%ignore ENUM_FLAGS;
%ignore ENUM_FLAGS_IS_BF;
%ignore ENUM_FLAGS_HIDDEN;
%ignore ENUM_MASKS;
%ignore ENUM_MEMBERS;
%ignore CONST_ENUM;
%ignore CONST_VALUE;
%ignore CONST_BMASK;
%ignore CONST_SERIAL;
%ignore CONST_SERIALS;
// FIXME: Check uval_t declarations
%include "enum.hpp"

32
swig/expr.i Normal file
View File

@ -0,0 +1,32 @@
%ignore extfun_t;
%ignore funcset_t;
%ignore IDCFuncs;
%ignore set_idc_func;
%ignore VarLong;
%ignore VarNum;
%ignore VarString;
%ignore VarFloat;
%ignore VarFree;
%ignore calcexpr_long;
%ignore CompileEx;
%ignore Compile;
%ignore CompileLine;
%ignore Run;
%ignore ExecuteLine;
%ignore ExecuteFile;
%ignore set_idc_func_body;
%ignore get_idc_func_body;
%ignore idc_stacksize;
%ignore idc_calldepth;
%ignore expr_printf;
%ignore expr_sprintf;
%ignore expr_printfer;
%ignore idaapi init_idc;
%ignore idaapi term_idc;
%ignore del_idc_userfuncs;
%ignore find_builtin_idc_func;
%ignore idc_lx;
%include "expr.hpp"

6
swig/fixup.i Normal file
View File

@ -0,0 +1,6 @@
%ignore apply_fixup;
%ignore convert_fixups;
%ignore move_fixups;
%include "fixup.hpp"

20
swig/frame.i Normal file
View File

@ -0,0 +1,20 @@
%ignore add_frame_spec_member;
%ignore del_stkvars;
%ignore calc_frame_offset;
%ignore read_regvars;
%ignore write_regvars;
%ignore del_regvars;
%ignore free_regvar;
%ignore gen_regvar_defs;
%ignore set_llabel;
%ignore get_llabel_ea;
%ignore get_llabel;
%ignore read_llabels;
%ignore write_llabels;
%ignore del_llabels;
%ignore free_llabel;
%ignore read_stkpnts;
%ignore write_stkpnts;
%ignore del_stkpnts;
%include "frame.hpp"

36
swig/funcs.i Normal file
View File

@ -0,0 +1,36 @@
%cstring_bounded_output_none(char *buf, MAXSTR);
%cstring_bounded_output_none(char *optlibs, MAXSTR);
// FIXME: These should probably be fixed
%ignore iterate_func_chunks;
%ignore get_idasgn_desc;
%ignore get_sig_filename;
%ignore get_idasgn_header_by_short_name;
%ignore get_idasgn_title;
// Kernel-only & unexported symbols
%ignore del_regargs;
%ignore write_regargs;
%ignore find_regarg;
%ignore free_regarg;
%ignore determine_rtl;
%ignore init_signatures;
%ignore save_signatures;
%ignore term_signatures;
%ignore init_funcs;
%ignore save_funcs;
%ignore term_funcs;
%ignore move_funcs;
%ignore copy_noret_info;
%ignore recalc_func_noret_flag;
%ignore plan_for_noret_analysis;
%ignore invalidate_sp_analysis;
%ignore create_func_eas_array;
%ignore auto_add_func_tails;
%include "funcs.hpp"
%clear(char *buf);
%clear(char *optlibs);

13
swig/ida.i Normal file
View File

@ -0,0 +1,13 @@
// Ignore kernel-only symbols
%ignore dual_text_options_t;
%ignore init;
%ignore retrieve;
%ignore read;
%ignore write;
// Make idainfo::get_proc_name() work
%cstring_bounded_output(char *buf, 8);
%include "ida.hpp"
%clear(char *buf);

112
swig/idaapi.i Normal file
View File

@ -0,0 +1,112 @@
%module(docstring="IDA Pro Plugin SDK API wrapper") idaapi
// Suppress 'previous definition of XX' warnings
#pragma SWIG nowarn=302
// Enable automatic docstring generation
%feature(autodoc);
%{
#include <Python.h>
#define USE_DANGEROUS_FUNCTIONS 1
#ifdef HAVE_SSIZE_T
#define _SSIZE_T_DEFINED 1
#endif
#include "ida.hpp"
#include "auto.hpp"
#include "bytes.hpp"
#include "dbg.hpp"
#include "diskio.hpp"
#include "entry.hpp"
#include "enum.hpp"
#include "expr.hpp"
#include "frame.hpp"
#include "fixup.hpp"
#include "funcs.hpp"
#include "idd.hpp"
#include "idp.hpp"
#include "ints.hpp"
#include "kernwin.hpp"
#include "lines.hpp"
#include "loader.hpp"
#include "moves.hpp"
#include "nalt.hpp"
#include "name.hpp"
#include "offset.hpp"
#include "queue.hpp"
#include "search.hpp"
#include "srarea.hpp"
#include "strlist.hpp"
#include "struct.hpp"
#include "typeinf.hpp"
#include "ua.hpp"
#include "xref.hpp"
%}
%constant ea_t BADADDR = 0xFFFFFFFF;
%constant sel_t BADSEL = 0xFFFFFFFF;
// Help SWIG to figure out the ulonglong type
#ifdef SWIGWIN
typedef unsigned __int64 ulonglong;
typedef __int64 longlong;
#else
typedef unsigned long long ulonglong;
typedef long long longlong;
#endif
%include "typemaps.i"
%include "cstring.i"
%include "carrays.i"
%include "cpointer.i"
%include "typeconv.i"
%include "pro.h"
// Convert all of these
%cstring_output_maxstr_none(char *buf, size_t bufsize);
%array_class(uchar, ucharArray);
%array_class(tid_t, tidArray);
%pointer_class(int, int_pointer);
%include "ida.i"
%include "idd.hpp"
%include "idp.i"
%include "area.hpp"
%include "auto.i"
%include "bytes.i"
%include "dbg.i"
%include "diskio.i"
%include "entry.i"
%include "enum.i"
%include "expr.i"
%include "fixup.i"
%include "frame.i"
%include "funcs.i"
%inline {
/* Small wrapper to get the inf structure */
idainfo *get_inf_structure(void)
{
return &inf;
}
}
%include "ints.i"
%include "kernwin.i"
%include "lines.i"
%include "loader.i"
%include "moves.i"
%include "nalt.i"
%include "name.i"
%include "offset.i"
%include "queue.i"
%include "search.i"
%include "segment.i"
%include "srarea.i"
%include "strlist.i"
%include "struct.i"
%include "typeinf.i"
%include "ua.i"
%include "xref.i"

3
swig/idp.i Normal file
View File

@ -0,0 +1,3 @@
%ignore gen_idb_event;
%include "idp.hpp"

6
swig/ints.i Normal file
View File

@ -0,0 +1,6 @@
// Kernel-only symbols
%ignore init_predefs;
%ignore term_predefs;
%include "ints.i"

217
swig/kernwin.i Normal file
View File

@ -0,0 +1,217 @@
%include "typemaps.i"
// Make askaddr(), askseg(), and asklong() return a
// tuple: (result, value)
%apply unsigned long *INOUT { sval_t *value };
%rename (_asklong) asklong;
%apply unsigned long *INOUT { ea_t *addr };
%rename (_askaddr) askaddr;
%apply unsigned long *INOUT { sel_t *sel };
%rename (_askseg) askseg;
%pythoncode %{
def asklong(defval, format):
res, val = _idaapi._asklong(defval, format)
if res == 1:
return val
else:
return None
def askaddr(defval, format):
res, ea = _idaapi._askaddr(defval, format)
if res == 1:
return ea
else:
return None
def askseg(defval, format):
res, sel = _idaapi._askseg(defval, format)
if res == 1:
return sel
else:
return None
%}
# This is for get_cursor()
%apply int *OUTPUT {int *x, int *y};
# This is for read_selection()
%apply unsigned long *OUTPUT { ea_t *ea1, ea_t *ea2 };
// Ignore the va_list functions
%ignore AskUsingForm_cv;
%ignore close_form;
%ignore vaskstr;
%ignore vasktext;
%ignore vwarning;
%ignore vinfo;
%ignore vnomem;
%ignore vmsg;
%ignore show_wait_box_v;
%ignore askbuttons_cv;
%ignore askfile_cv;
%ignore askyn_cv;
%ignore askyn_v;
// Ignore these string functions. There are trivial replacements in Python.
%ignore addblanks;
%ignore trim;
%ignore skipSpaces;
%ignore stristr;
%include "kernwin.hpp"
ulong choose_choose(PyObject *self,
int flags,
int x0,int y0,
int x1,int y1,
int width);
%{
ulong idaapi choose_sizer(void *self)
{
PyObject *pyres;
ulong res;
pyres = PyObject_CallMethod((PyObject *)self, "sizer", "");
res = PyInt_AsLong(pyres);
Py_DECREF(pyres);
return res;
}
char * idaapi choose_getl(void *self, ulong n, char *buf)
{
PyObject *pyres;
char *res;
char tmp[1024];
pyres = PyObject_CallMethod((PyObject *)self, "getl", "l", n);
if (!pyres)
{
strcpy(buf, "<Empty>");
return buf;
}
res = PyString_AsString(pyres);
if (res)
{
strcpy(buf, res);
res = buf;
}
else
{
strcpy(buf, "<Empty>");
res = buf;
}
Py_DECREF(pyres);
return res;
}
void idaapi choose_enter(void *self, ulong n)
{
PyObject_CallMethod((PyObject *)self, "enter", "l", n);
return;
}
ulong choose_choose(void *self,
int flags,
int x0,int y0,
int x1,int y1,
int width)
{
PyObject *pytitle;
char deftitle[] = "Choose";
char *title = NULL;
if ((pytitle = PyObject_GetAttrString((PyObject *)self, "title")))
{
title = PyString_AsString(pytitle);
}
return choose(
flags, // various flags: see above for description
x0, y0, // x0=-1 for autoposition
x1, y1,
self, // object to show
width, // Max width of lines
&choose_sizer, // Number of items
&choose_getl, // Description of n-th item (1..n)
// 0-th item if header line
title ? title : deftitle,
1,
1,
NULL,
NULL,
NULL,
NULL,
&choose_enter
); // number of the default icon to display
}
%}
%pythoncode %{
class Choose:
"""
Choose - class for choose() with callbacks
"""
def __init__(self, list, title, flags=0):
self.list = list
self.title = title
self.flags = flags
self.x0 = -1
self.x1 = -1
self.y0 = -1
self.y1 = -1
self.width = -1
def sizer(self):
"""
Callback: sizer - returns the length of the list
"""
return len(self.list)
def getl(self, n):
"""
Callback: getl - get one item from the list
"""
if n <= len(self.list):
return self.list[n-1]
else:
return "<Empty>"
def ins(self):
pass
def update(self, n):
pass
def edit(self, n):
pass
def enter(self, n):
print "enter(%d) called" % n
def destroy(self):
pass
def get_icon(self, n):
pass
def choose(self):
"""
choose - Display the choose dialogue
"""
return _idaapi.choose_choose(self, self.flags, self.x0, self.y0, self.x1, self.y1, self.width)
%}

63
swig/lines.i Normal file
View File

@ -0,0 +1,63 @@
// Convert this for ver 4.8 tag_remove()
%cstring_output_maxstr_none(char *buf, int bufsize);
// FIXME: These should be fixed
%ignore tag_on;
%ignore tag_off;
%ignore tag_addchr;
%ignore tag_addstr;
%ignore tag_addr;
%ignore tag_advance;
%ignore tag_skipcodes;
%ignore tag_skipcode;
%ignore set_user_defined_prefix;
%ignore get_user_defined_prefix;
// Ignore va_list versions
%ignore printf_line_v;
%ignore gen_colored_cmt_line_v;
%ignore gen_cmt_line_v;
%ignore add_long_cmt_v;
%ignore describex;
// Kernel-only and unexported symbols
%ignore init_sourcefiles;
%ignore save_sourcefiles;
%ignore term_sourcefiles;
%ignore move_sourcefiles;
%ignore gen_xref_lines;
%ignore ml_getcmt_t;
%ignore ml_getnam_t;
%ignore ml_genxrf_t;
%ignore ml_saver_t;
%ignore setup_makeline;
%ignore MAKELINE_NONE;
%ignore MAKELINE_BINPREF;
%ignore MAKELINE_VOID;
%ignore MAKELINE_STACK;
%ignore save_line_in_array;
%ignore init_lines_array;
%ignore finish_makeline;
%ignore generate_disassembly;
%ignore gen_labeled_line;
%ignore gen_lname_line;
%ignore makeline_producer_t;
%ignore set_makeline_producer;
%ignore closing_comment;
%ignore close_comment;
%ignore copy_extra_lines;
%ignore ExtraLines;
%ignore ExtraKill;
%ignore ExtraFree;
%ignore Dumper;
%ignore init_lines;
%ignore save_lines;
%ignore term_lines;
%ignore gl_namedone;
%ignore data_as_stack;
%ignore calc_stack_alignment;
%ignore align_down_to_stack;
%ignore align_up_to_stack;
%ignore remove_spaces;
%include "lines.hpp"
%clear(char *buf, int bufsize);

123
swig/loader.i Normal file
View File

@ -0,0 +1,123 @@
// Ignore callback members
%ignore loader_t::accept_file;
%ignore loader_t::load_file;
%ignore loader_t::save_file;
%ignore loader_t::move_segm;
%ignore loader_t::init_loader_options;
%ignore plugin_t::init;
%ignore plugin_t::term;
%ignore plugin_t::run;
%ignore vloader_failure;
%ignore loader_failure;
// TODO: These could be wrapped if needed
%ignore load_info_t;
%ignore build_loaders_list;
%ignore free_loaders_list;
%ignore get_loader_name_from_dll;
%ignore get_loader_name;
%ignore init_loader_options;
%ignore load_nonbinary_file;
%ignore impinfo_t;
%ignore import_module;
%ignore plugin_info_t;
%ignore get_plugins;
%ignore invoke_plugin;
%ignore dbg_info_t;
%ignore get_debugger_plugins;
%ignore init_plugins;
%ignore term_plugins;
// Callback and loader-only symbols are ignored (for now)
%ignore html_header_cb_t;
%ignore html_footer_cb_t;
%ignore html_line_cb_t;
%ignore gen_outline_t;
%ignore create_filename_cmt;
%ignore hook_cb_t;
%ignore hook_type_t;
%ignore hook_to_notification_point;
%ignore unhook_from_notification_point;
%ignore invoke_callbacks;
// Ignore kernel-only & unexported symbols
%ignore LDSC;
%ignore PLUGIN;
%ignore LNE_MAXSEG;
%ignore dlldata;
%ignore DLLDATASTART;
%ignore ldrdata;
%ignore LDRDATASTART;
%ignore idadll_t;
%ignore load_dll;
%ignore RE_NOFILE;
%ignore RE_NOTIDP;
%ignore RE_NOPAGE;
%ignore RE_NOLINK;
%ignore RE_BADRTP;
%ignore RE_BADORD;
%ignore RE_BADATP;
%ignore RE_BADMAP;
%ignore load_dll_or_die;
%ignore load_dll_or_say;
%ignore free_dll;
%ignore IDP_DESC_START;
%ignore IDP_DESC_END;
%ignore get_idp_desc;
%ignore init_fileregions;
%ignore term_fileregions;
%ignore save_fileregions;
%ignore add_fileregion;
%ignore move_fileregions;
%ignore local_gen_idc_file;
%ignore print_all_places;
%ignore save_text_line;
%ignore print_all_structs;
%ignore print_all_enums;
%ignore database_id0;
%ignore is_database_ext;
%ignore ida_database_memory;
%ignore database_flags;
%ignore DBFL_KILL;
%ignore DBFL_COMP;
%ignore DBFL_BAK;
%ignore DBFL_TEMP;
%ignore is_temp_database;
%ignore pe_create_idata;
%ignore pe_load_resources;
%ignore pe_create_flat_group;
%ignore dbcheck_t;
%ignore DBCHK_NONE;
%ignore DBCHK_OK;
%ignore DBCHK_BAD;
%ignore DBCHK_NEW;
%ignore check_database;
%ignore open_database;
%ignore flush_buffers;
%ignore save_database;
%ignore close_database;
%ignore compress_btree;
%ignore get_input_file_from_archive;
%ignore loader_move_segm;
%ignore generate_ida_copyright;
%ignore is_in_loader;
%ignore get_ids_filename;
// mem2base() has a custom wrapper
%ignore mem2base;
%include "loader.hpp"
// Custom wrapper for mem2base()
%rename (mem2base) mem2base_wrap;
%apply (char *STRING, int LENGTH) { (char *buf, int len) };
%inline %{
int mem2base_wrap(char *buf, int len, ea_t ea, long fpos)
{
return mem2base((void *)buf, ea, ea+len, fpos);
}
%}

11
swig/moves.i Normal file
View File

@ -0,0 +1,11 @@
// Ignore kernel only symbols
%ignore init_marks;
%ignore term_marks;
%ignore change_jumps_stack_format;
%ignore move_marks;
%ignore loc_gtag;
%ignore DEFINE_CURLOC_HELPERS;
%ignore DEFINE_LOCATION_HELPERS;
%include "moves.hpp"

6
swig/nalt.i Normal file
View File

@ -0,0 +1,6 @@
%ignore NALT_EA;
%ignore NALT_ULONG;
#define NALT_EA()
%include "nalt.hpp"

35
swig/name.i Normal file
View File

@ -0,0 +1,35 @@
%cstring_output_maxstr_none(char *buf, int bufsize);
%cstring_bounded_output(char *dstname, MAXSTR);
%cstring_bounded_output(char *buf, MAXSTR);
// FIXME: These should be fixed
%ignore get_name_value;
%ignore append_struct_fields;
%ignore get_struct_operand;
%ignore debug_name_how_t;
%ignore set_debug_names;
%ignore set_debug_name;
%ignore get_debug_name;
%ignore del_debug_names;
%ignore get_debug_name_ea;
%ignore nameVa;
// Unexported & kernel-only
%ignore get_short_name;
%ignore get_long_name;
%ignore get_colored_short_name;
%ignore get_colored_long_name;
%ignore addDummyName;
%ignore convert_debug_names_to_normal;
%ignore convert_name_formats;
%ignore showhide_name;
%ignore clear_lname_bit;
%ignore fix_new_name;
%ignore rename;
%ignore move_names;
%ignore is_exit_name;
%ignore dummy_name_ea;
%include "name.hpp"

3
swig/offset.i Normal file
View File

@ -0,0 +1,3 @@
%ignore calc_probable_base;
%include "offset.hpp"

3
swig/pro.i Normal file
View File

@ -0,0 +1,3 @@
%ignore print_all_counters;
%include "pro.h"

12
swig/queue.i Normal file
View File

@ -0,0 +1,12 @@
// TODO: This could be wrapped.
%ignore QueueGet;
// Kernel-only & unexported symbols
%ignore QueueDel;
%ignore init_queue;
%ignore save_queue;
%ignore term_queue;
%ignore move_problems;
%ignore queue_del;
%include "queue.hpp"

14
swig/search.i Normal file
View File

@ -0,0 +1,14 @@
%apply int * OUTPUT { int *opnum };
// Do not generate overloaded versions for default arguments
%feature("compactdefaultargs") find_error;
%feature("compactdefaultargs") find_notype;
%feature("compactdefaultargs") find_void;
%feature("compactdefaultargs") find_imm;
// FIXME: search() should be checked and enabled
%ignore search;
%ignore user2bin;
%include "search.hpp"
%clear int *opnum;

29
swig/segment.i Normal file
View File

@ -0,0 +1,29 @@
// FIXME: These could be fixed
%ignore getn_selector;
%ignore set_segment_translations;
%ignore del_segment_translations;
%ignore get_segment_translations;
// Ignore functions with callbacks
%ignore enumerate_selectors;
%ignore enumerate_segments_with_selector;
// Kernel-only
%ignore init_groups;
%ignore save_groups;
%ignore term_groups;
%ignore vset_segm_name;
%ignore get_segm_expr;
%ignore get_based_segm_expr;
%ignore createSegmentation;
%ignore initSegment;
%ignore save_segments;
%ignore termSegment;
%ignore DeleteAllSegments;
%ignore delete_debug_segments;
%ignore is_debugger_segm;
%ignore is_ephemeral_segm;
%ignore correct_address;
%include "segment.hpp"

21
swig/srarea.i Normal file
View File

@ -0,0 +1,21 @@
// Ignore kernel-only symbols
%ignore createSRarea;
%ignore killSRareas;
%ignore delSRarea;
%ignore SRareaStart;
%ignore SRareaEnd;
%ignore repairSRarea;
%ignore SRinit;
%ignore SRterm;
%ignore SRsave;
#define R_es 29
#define R_cs 30
#define R_ss 31
#define R_ds 32
#define R_fs 33
#define R_gs 34
%feature("compactdefaultargs") splitSRarea1;
%include "srarea.hpp"

11
swig/strlist.i Normal file
View File

@ -0,0 +1,11 @@
// Ignore kernel-only symbol
%ignore strwinsetup_t::setup_strings_window;
%ignore strwinsetup_t::save_config;
%ignore strwinsetup_t::restore_config;
%ignore move_strings;
%include "strlist.hpp"

14
swig/struct.i Normal file
View File

@ -0,0 +1,14 @@
// Kernel-only symbols
%ignore init_struc;
%ignore save_struc;
%ignore term_struc;
%feature("compactdefaultargs") add_struc;
%include "struct.hpp"
// Add a get_member() member function to struc_t.
// This helps to access the members array in the class.
%extend struc_t {
member_t * get_member(int index) { return &(self->members[index]); }
}

82
swig/typeconv.i Normal file
View File

@ -0,0 +1,82 @@
// Convert an incoming Python list to a tid_t[] array
%typemap(in) tid_t[ANY](tid_t temp[$1_dim0]) {
int i, len;
if (!PySequence_Check($input))
{
PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
return NULL;
}
/* Cap the number of elements to copy */
len = PySequence_Length($input) < $1_dim0 ? PySequence_Length($input) : $1_dim0;
for (i =0; i < len; i++)
{
PyObject *o = PySequence_GetItem($input,i);
if (!PyLong_Check(o))
{
Py_XDECREF(o);
PyErr_SetString(PyExc_ValueError,"Expecting a sequence of long integers");
return NULL;
}
temp[i] = PyLong_AsUnsignedLong(o);
Py_DECREF(o);
}
$1 = &temp[0];
}
%define %cstring_output_maxstr_none(TYPEMAP, SIZE)
%typemap (default) SIZE {
$1 = MAXSTR;
}
%typemap(in,numinputs=0) (TYPEMAP, SIZE) {
#ifdef __cplusplus
$1 = ($1_ltype) new char[MAXSTR+1];
#else
$1 = ($1_ltype) malloc(MAXSTR+1);
#endif
}
%typemap(out) ssize_t {
/* REMOVING ssize_t return value in $symname */
}
%typemap(argout) (TYPEMAP,SIZE) {
if (result > 0)
{
resultobj = PyString_FromString($1);
}
else
{
Py_INCREF(Py_None);
resultobj = Py_None;
}
#ifdef __cplusplus
delete [] $1;
#else
free($1);
#endif
}
%enddef
%define %cstring_bounded_output_none(TYPEMAP,MAX)
%typemap(in, numinputs=0) TYPEMAP(char temp[MAX+1]) {
$1 = ($1_ltype) temp;
}
%typemap(argout,fragment="t_output_helper") TYPEMAP {
PyObject *o;
$1[MAX] = 0;
if ($1 > 0)
{
o = PyString_FromString($1);
}
else
{
o = Py_None;
Py_INCREF(Py_None);
}
$result = t_output_helper($result,o);
}
%enddef

174
swig/typeinf.i Normal file
View File

@ -0,0 +1,174 @@
// Most of these could be wrapped if needed
%ignore get_cc;
%ignore get_cc_type_size;
%ignore set_argloc;
%ignore set_dt;
%ignore set_da;
%ignore set_de;
%ignore get_dt;
%ignore get_da;
%ignore get_de;
%ignore skip_ptr_type_header;
%ignore skip_array_type_header;
%ignore typend;
%ignore typlen;
%ignore typncpy;
%ignore tppncpy;
%ignore typcmp;
%ignore typdup;
%ignore equal_types;
%ignore resolve_typedef;
%ignore is_resolved_type_const;
%ignore is_resolved_type_void;
%ignore is_resolved_type_ptr;
%ignore is_resolved_type_func;
%ignore is_resolved_type_array;
%ignore is_resolved_type_complex;
%ignore is_resolved_type_struct;
%ignore is_resolved_type_union;
%ignore is_resolved_type_enum;
%ignore is_resolved_type_bitfld;
%ignore is_castable;
%ignore remove_constness;
%ignore remove_pointerness;
%ignore get_int_type_bit;
%ignore get_unk_type_bit;
%ignore tns;
%ignore til_t::base;
%ignore til_t::syms;
%ignore til_t::types;
%ignore til_t::macros;
%ignore add_base_tils;
%ignore sort_til;
%ignore til_add_macro;
%ignore til_next_macro;
%ignore get_type_size;
%ignore get_type_size0;
%ignore skip_type;
%ignore get_pointer_object_size;
%ignore descr_t;
%ignore unpack_type;
%ignore print_type_to_one_line;
%ignore print_type_to_many_lines;
%ignore print_type;
%ignore show_type;
%ignore show_plist;
%ignore extract_pstr;
%ignore extract_name;
%ignore skipName;
%ignore extract_comment;
%ignore skipComment;
%ignore extract_fargcmt;
%ignore skip_argloc;
%ignore extract_argloc;
%ignore h2ti;
%ignore h2ti_warning;
%ignore parse_type;
%ignore parse_types;
%ignore get_named_type;
%ignore set_named_type;
%ignore get_named_type_size;
%ignore decorate_name;
%ignore gen_decorate_name;
%ignore calc_bare_name;
%ignore predicate_t;
%ignore choose_named_type;
%ignore get_default_align;
%ignore align_size;
%ignore align_size;
%ignore get_default_enum_size;
%ignore max_ptr_size;
%ignore based_ptr_name_and_size;
%ignore calc_arglocs;
%ignore apply_type;
%ignore apply_callee_type;
%ignore guess_func_type;
%ignore guess_type;
%ignore build_funcarg_arrays;
%ignore free_funcarg_arrays;
%ignore extract_func_ret_type;
%ignore calc_names_cmts;
%ignore resolve_complex_type;
%ignore foreach_strmem;
%ignore is_type_scalar;
%ignore get_type_signness;
%ignore is_type_signed;
%ignore is_type_unsigned;
%ignore get_struct_member;
%ignore idb_type_to_til;
%ignore get_idb_type;
%ignore apply_type_to_stkarg;
%ignore use_regarg_type_cb;
%ignore set_op_type_t;
%ignore is_stkarg_load_t;
%ignore has_delay_slot_t;
%ignore gen_use_arg_types;
// Kernel-only symbols
%ignore init_til;
%ignore save_til;
%ignore term_til;
%ignore determine_til;
%ignore get_tilpath;
%ignore autoload_til;
%ignore get_idainfo_by_type;
%ignore apply_callee_type;
%ignore propagate_stkargs;
%ignore build_anon_type_name;
%ignore type_names;
%ignore get_compiler_id;
%include "typeinf.hpp"
// Custom wrappers
%rename (load_til) load_til_wrap;
%inline %{
til_t * load_til(const char *tildir, const char *name)
{
char errbuf[4096];
til_t *res;
res = load_til(tildir, name, errbuf, sizeof(errbuf));
if (!res)
{
PyErr_SetString(PyExc_RuntimeError, errbuf);
return NULL;
}
return res;
}
%}
%rename (load_til_header_wrap) load_til_header_wrap;
%inline %{
til_t * load_til_header_wrap(const char *tildir, const char *name)
{
char errbuf[4096];
til_t *res;
res = load_til_header(tildir, name, errbuf, sizeof(errbuf));;
if (!res)
{
PyErr_SetString(PyExc_RuntimeError, errbuf);
return NULL;
}
return res;
}
%}

27
swig/ua.i Normal file
View File

@ -0,0 +1,27 @@
// Include the patched header
// All the unchecked declarations are between
// #ifndef SWIG
%include "ua.hpp"
// Small function to get the global cmd pointer
// In Python it returns an insn_t class instance
%inline {
insn_t * get_current_instruction()
{
return &cmd;
}
}
// Get the nth operand from the insn_t class
%inline {
op_t *get_instruction_operand(insn_t *ins, int n)
{
if (!ins)
{
return NULL;
}
return &(ins->Operands[n]);
}
}

22
swig/xref.i Normal file
View File

@ -0,0 +1,22 @@
// Ignore kernel-only functions and variables
%ignore create_xrefs_from;
%ignore create_xrefs_from_data;
%ignore delete_all_xrefs_from;
%ignore delete_data_xrefs_from;
%ignore delete_code_xrefs_from;
%ignore destroy_if_align;
%ignore lastXR;
%ignore has_jump_or_flow_xref;
%ignore has_call_xref;
%ignore destroy_switch_info;
// These functions should not be called directly (according to docs)
%ignore xrefblk_t_first_from;
%ignore xrefblk_t_next_from;
%ignore xrefblk_t_first_to;
%ignore xrefblk_t_next_to;
// 'from' is a reserved Python keyword
%rename (frm) from;
%include "xref.hpp"