· 8 years ago · Dec 09, 2017, 09:12 PM
1#!/usr/bin/env python
2#---------------------------------------------------------------------
3# IDAPython - Python plugin for Interactive Disassembler
4#
5# Original IDC.IDC:
6# Copyright (c) 1990-2010 Ilfak Guilfanov
7#
8# Python conversion:
9# Copyright (c) 2004-2010 Gergely Erdelyi <gergely.erdelyi@d-dome.net>
10#
11# All rights reserved.
12#
13# For detailed copyright information see the file COPYING in
14# the root of the distribution archive.
15#---------------------------------------------------------------------
16# idc.py - IDC compatibility module
17#---------------------------------------------------------------------
18"""
19IDC compatibility module
20
21This file contains IDA built-in function declarations and internal bit
22definitions. Each byte of the program has 32-bit flags (low 8 bits keep
23the byte value). These 32 bits are used in GetFlags/SetFlags functions.
24You may freely examine these bits using GetFlags() but the use of the
25SetFlags() function is strongly discouraged.
26
27This file is subject to change without any notice.
28Future versions of IDA may use other definitions.
29"""
30try:
31 import idaapi
32except ImportError:
33 print "Could not import idaapi. Running in 'pydoc mode'."
34
35import os
36import re
37import struct
38import time
39import types
40
41__EA64__ = idaapi.BADADDR == 0xFFFFFFFFFFFFFFFFL
42WORDMASK = 0xFFFFFFFFFFFFFFFF if __EA64__ else 0xFFFFFFFF
43class DeprecatedIDCError(Exception):
44 """
45 Exception for deprecated function calls
46 """
47 pass
48
49
50def _IDC_GetAttr(obj, attrmap, attroffs):
51 """
52 Internal function to generically get object attributes
53 Do not use unless you know what you are doing
54 """
55 if attroffs in attrmap and hasattr(obj, attrmap[attroffs][1]):
56 return getattr(obj, attrmap[attroffs][1])
57 else:
58 errormsg = "attribute with offset %d not found, check the offset and report the problem" % attroffs
59 raise KeyError, errormsg
60
61
62def _IDC_SetAttr(obj, attrmap, attroffs, value):
63 """
64 Internal function to generically set object attributes
65 Do not use unless you know what you are doing
66 """
67 # check for read-only atributes
68 if attroffs in attrmap:
69 if attrmap[attroffs][0]:
70 raise KeyError, "attribute with offset %d is read-only" % attroffs
71 elif hasattr(obj, attrmap[attroffs][1]):
72 return setattr(obj, attrmap[attroffs][1], value)
73 errormsg = "attribute with offset %d not found, check the offset and report the problem" % attroffs
74 raise KeyError, errormsg
75
76
77BADADDR = idaapi.BADADDR # Not allowed address value
78BADSEL = idaapi.BADSEL # Not allowed selector value/number
79MAXADDR = idaapi.MAXADDR & WORDMASK
80SIZE_MAX = idaapi.SIZE_MAX
81#
82# Flag bit definitions (for GetFlags())
83#
84MS_VAL = idaapi.MS_VAL # Mask for byte value
85FF_IVL = idaapi.FF_IVL # Byte has value ?
86
87# Do flags contain byte value? (i.e. has the byte a value?)
88# if not, the byte is uninitialized.
89
90def hasValue(F): return ((F & FF_IVL) != 0) # any defined value?
91
92def byteValue(F):
93 """
94 Get byte value from flags
95 Get value of byte provided that the byte is initialized.
96 This macro works ok only for 8-bit byte machines.
97 """
98 return (F & MS_VAL)
99
100
101def isLoaded(ea):
102 """Is the byte initialized?"""
103 return hasValue(GetFlags(ea)) # any defined value?
104
105MS_CLS = idaapi.MS_CLS # Mask for typing
106FF_CODE = idaapi.FF_CODE # Code ?
107FF_DATA = idaapi.FF_DATA # Data ?
108FF_TAIL = idaapi.FF_TAIL # Tail ?
109FF_UNK = idaapi.FF_UNK # Unknown ?
110
111def isCode(F): return ((F & MS_CLS) == FF_CODE) # is code byte?
112def isData(F): return ((F & MS_CLS) == FF_DATA) # is data byte?
113def isTail(F): return ((F & MS_CLS) == FF_TAIL) # is tail byte?
114def isUnknown(F): return ((F & MS_CLS) == FF_UNK) # is unexplored byte?
115def isHead(F): return ((F & FF_DATA) != 0) # is start of code/data?
116
117#
118# Common bits
119#
120MS_COMM = idaapi.MS_COMM # Mask of common bits
121FF_COMM = idaapi.FF_COMM # Has comment?
122FF_REF = idaapi.FF_REF # has references?
123FF_LINE = idaapi.FF_LINE # Has next or prev cmt lines ?
124FF_NAME = idaapi.FF_NAME # Has user-defined name ?
125FF_LABL = idaapi.FF_LABL # Has dummy name?
126FF_FLOW = idaapi.FF_FLOW # Exec flow from prev instruction?
127FF_VAR = idaapi.FF_VAR # Is byte variable ?
128FF_ANYNAME = FF_LABL | FF_NAME
129
130def isFlow(F): return ((F & FF_FLOW) != 0)
131def isVar(F): return ((F & FF_VAR ) != 0)
132def isExtra(F): return ((F & FF_LINE) != 0)
133def isRef(F): return ((F & FF_REF) != 0)
134def hasName(F): return ((F & FF_NAME) != 0)
135def hasUserName(F): return ((F & FF_ANYNAME) == FF_NAME)
136
137MS_0TYPE = idaapi.MS_0TYPE # Mask for 1st arg typing
138FF_0VOID = idaapi.FF_0VOID # Void (unknown)?
139FF_0NUMH = idaapi.FF_0NUMH # Hexadecimal number?
140FF_0NUMD = idaapi.FF_0NUMD # Decimal number?
141FF_0CHAR = idaapi.FF_0CHAR # Char ('x')?
142FF_0SEG = idaapi.FF_0SEG # Segment?
143FF_0OFF = idaapi.FF_0OFF # Offset?
144FF_0NUMB = idaapi.FF_0NUMB # Binary number?
145FF_0NUMO = idaapi.FF_0NUMO # Octal number?
146FF_0ENUM = idaapi.FF_0ENUM # Enumeration?
147FF_0FOP = idaapi.FF_0FOP # Forced operand?
148FF_0STRO = idaapi.FF_0STRO # Struct offset?
149FF_0STK = idaapi.FF_0STK # Stack variable?
150
151MS_1TYPE = idaapi.MS_1TYPE # Mask for 2nd arg typing
152FF_1VOID = idaapi.FF_1VOID # Void (unknown)?
153FF_1NUMH = idaapi.FF_1NUMH # Hexadecimal number?
154FF_1NUMD = idaapi.FF_1NUMD # Decimal number?
155FF_1CHAR = idaapi.FF_1CHAR # Char ('x')?
156FF_1SEG = idaapi.FF_1SEG # Segment?
157FF_1OFF = idaapi.FF_1OFF # Offset?
158FF_1NUMB = idaapi.FF_1NUMB # Binary number?
159FF_1NUMO = idaapi.FF_1NUMO # Octal number?
160FF_1ENUM = idaapi.FF_1ENUM # Enumeration?
161FF_1FOP = idaapi.FF_1FOP # Forced operand?
162FF_1STRO = idaapi.FF_1STRO # Struct offset?
163FF_1STK = idaapi.FF_1STK # Stack variable?
164
165# The following macros answer questions like
166# 'is the 1st (or 2nd) operand of instruction or data of the given type'?
167# Please note that data items use only the 1st operand type (is...0)
168
169def isDefArg0(F): return ((F & MS_0TYPE) != FF_0VOID)
170def isDefArg1(F): return ((F & MS_1TYPE) != FF_1VOID)
171def isDec0(F): return ((F & MS_0TYPE) == FF_0NUMD)
172def isDec1(F): return ((F & MS_1TYPE) == FF_1NUMD)
173def isHex0(F): return ((F & MS_0TYPE) == FF_0NUMH)
174def isHex1(F): return ((F & MS_1TYPE) == FF_1NUMH)
175def isOct0(F): return ((F & MS_0TYPE) == FF_0NUMO)
176def isOct1(F): return ((F & MS_1TYPE) == FF_1NUMO)
177def isBin0(F): return ((F & MS_0TYPE) == FF_0NUMB)
178def isBin1(F): return ((F & MS_1TYPE) == FF_1NUMB)
179def isOff0(F): return ((F & MS_0TYPE) == FF_0OFF)
180def isOff1(F): return ((F & MS_1TYPE) == FF_1OFF)
181def isChar0(F): return ((F & MS_0TYPE) == FF_0CHAR)
182def isChar1(F): return ((F & MS_1TYPE) == FF_1CHAR)
183def isSeg0(F): return ((F & MS_0TYPE) == FF_0SEG)
184def isSeg1(F): return ((F & MS_1TYPE) == FF_1SEG)
185def isEnum0(F): return ((F & MS_0TYPE) == FF_0ENUM)
186def isEnum1(F): return ((F & MS_1TYPE) == FF_1ENUM)
187def isFop0(F): return ((F & MS_0TYPE) == FF_0FOP)
188def isFop1(F): return ((F & MS_1TYPE) == FF_1FOP)
189def isStroff0(F): return ((F & MS_0TYPE) == FF_0STRO)
190def isStroff1(F): return ((F & MS_1TYPE) == FF_1STRO)
191def isStkvar0(F): return ((F & MS_0TYPE) == FF_0STK)
192def isStkvar1(F): return ((F & MS_1TYPE) == FF_1STK)
193
194#
195# Bits for DATA bytes
196#
197DT_TYPE = idaapi.DT_TYPE & 0xFFFFFFFF # Mask for DATA typing
198
199FF_BYTE = idaapi.FF_BYTE & 0xFFFFFFFF # byte
200FF_WORD = idaapi.FF_WORD & 0xFFFFFFFF # word
201FF_DWRD = idaapi.FF_DWRD & 0xFFFFFFFF # dword
202FF_QWRD = idaapi.FF_QWRD & 0xFFFFFFFF # qword
203FF_TBYT = idaapi.FF_TBYT & 0xFFFFFFFF # tbyte
204FF_ASCI = idaapi.FF_ASCI & 0xFFFFFFFF # ASCII ?
205FF_STRU = idaapi.FF_STRU & 0xFFFFFFFF # Struct ?
206FF_OWRD = idaapi.FF_OWRD & 0xFFFFFFFF # octaword (16 bytes)
207FF_FLOAT = idaapi.FF_FLOAT & 0xFFFFFFFF # float
208FF_DOUBLE = idaapi.FF_DOUBLE & 0xFFFFFFFF # double
209FF_PACKREAL = idaapi.FF_PACKREAL & 0xFFFFFFFF # packed decimal real
210FF_ALIGN = idaapi.FF_ALIGN & 0xFFFFFFFF # alignment directive
211
212def isByte(F): return (isData(F) and (F & DT_TYPE) == FF_BYTE)
213def isWord(F): return (isData(F) and (F & DT_TYPE) == FF_WORD)
214def isDwrd(F): return (isData(F) and (F & DT_TYPE) == FF_DWRD)
215def isQwrd(F): return (isData(F) and (F & DT_TYPE) == FF_QWRD)
216def isOwrd(F): return (isData(F) and (F & DT_TYPE) == FF_OWRD)
217def isTbyt(F): return (isData(F) and (F & DT_TYPE) == FF_TBYT)
218def isFloat(F): return (isData(F) and (F & DT_TYPE) == FF_FLOAT)
219def isDouble(F): return (isData(F) and (F & DT_TYPE) == FF_DOUBLE)
220def isPackReal(F): return (isData(F) and (F & DT_TYPE) == FF_PACKREAL)
221def isASCII(F): return (isData(F) and (F & DT_TYPE) == FF_ASCI)
222def isStruct(F): return (isData(F) and (F & DT_TYPE) == FF_STRU)
223def isAlign(F): return (isData(F) and (F & DT_TYPE) == FF_ALIGN)
224
225#
226# Bits for CODE bytes
227#
228MS_CODE = idaapi.MS_CODE & 0xFFFFFFFF
229FF_FUNC = idaapi.FF_FUNC & 0xFFFFFFFF # function start?
230FF_IMMD = idaapi.FF_IMMD & 0xFFFFFFFF # Has Immediate value ?
231FF_JUMP = idaapi.FF_JUMP & 0xFFFFFFFF # Has jump table
232
233#
234# Loader flags
235#
236NEF_SEGS = idaapi.NEF_SEGS # Create segments
237NEF_RSCS = idaapi.NEF_RSCS # Load resources
238NEF_NAME = idaapi.NEF_NAME # Rename entries
239NEF_MAN = idaapi.NEF_MAN # Manual load
240NEF_FILL = idaapi.NEF_FILL # Fill segment gaps
241NEF_IMPS = idaapi.NEF_IMPS # Create imports section
242NEF_FIRST = idaapi.NEF_FIRST # This is the first file loaded
243NEF_CODE = idaapi.NEF_CODE # for load_binary_file:
244NEF_RELOAD = idaapi.NEF_RELOAD # reload the file at the same place:
245NEF_FLAT = idaapi.NEF_FLAT # Autocreated FLAT group (PE)
246
247# List of built-in functions
248# --------------------------
249#
250# The following conventions are used in this list:
251# 'ea' is a linear address
252# 'success' is 0 if a function failed, 1 otherwise
253# 'void' means that function returns no meaningful value (always 0)
254#
255# All function parameter conversions are made automatically.
256#
257# ----------------------------------------------------------------------------
258# M I S C E L L A N E O U S
259# ----------------------------------------------------------------------------
260def IsString(var): raise NotImplementedError, "this function is not needed in Python"
261def IsLong(var): raise NotImplementedError, "this function is not needed in Python"
262def IsFloat(var): raise NotImplementedError, "this function is not needed in Python"
263def IsFunc(var): raise NotImplementedError, "this function is not needed in Python"
264def IsPvoid(var): raise NotImplementedError, "this function is not needed in Python"
265def IsInt64(var): raise NotImplementedError, "this function is not needed in Python"
266
267def MK_FP(seg, off):
268 """
269 Return value of expression: ((seg<<4) + off)
270 """
271 return (seg << 4) + off
272
273def form(format, *args):
274 raise DeprecatedIDCError, "form() is deprecated. Use python string operations instead."
275
276def substr(s, x1, x2):
277 raise DeprecatedIDCError, "substr() is deprecated. Use python string operations instead."
278
279def strstr(s1, s2):
280 raise DeprecatedIDCError, "strstr() is deprecated. Use python string operations instead."
281
282def strlen(s):
283 raise DeprecatedIDCError, "strlen() is deprecated. Use python string operations instead."
284
285def xtol(s):
286 raise DeprecatedIDCError, "xtol() is deprecated. Use python long() instead."
287
288
289def atoa(ea):
290 """
291 Convert address value to a string
292 Return address in the form 'seg000:1234'
293 (the same as in line prefixes)
294
295 @param ea: address to format
296 """
297 segname = SegName(ea)
298
299 if segname == "":
300 segname = "0"
301
302 return "%s:%X" % (segname, ea)
303
304
305def ltoa(n, radix):
306 raise DeprecatedIDCError, "ltoa() is deprecated. Use python string operations instead."
307
308def atol(s):
309 raise DeprecatedIDCError, "atol() is deprecated. Use python long() instead."
310
311
312def rotate_left(value, count, nbits, offset):
313 """
314 Rotate a value to the left (or right)
315
316 @param value: value to rotate
317 @param count: number of times to rotate. negative counter means
318 rotate to the right
319 @param nbits: number of bits to rotate
320 @param offset: offset of the first bit to rotate
321
322 @return: the value with the specified field rotated
323 all other bits are not modified
324 """
325 assert offset >= 0, "offset must be >= 0"
326 assert nbits > 0, "nbits must be > 0"
327
328 mask = 2**(offset+nbits) - 2**offset
329 tmp = value & mask
330
331 if count > 0:
332 for x in xrange(count):
333 if (tmp >> (offset+nbits-1)) & 1:
334 tmp = (tmp << 1) | (1 << offset)
335 else:
336 tmp = (tmp << 1)
337 else:
338 for x in xrange(-count):
339 if (tmp >> offset) & 1:
340 tmp = (tmp >> 1) | (1 << (offset+nbits-1))
341 else:
342 tmp = (tmp >> 1)
343
344 value = (value-(value&mask)) | (tmp & mask)
345
346 return value
347
348
349def rotate_dword(x, count): return rotate_left(x, count, 32, 0)
350def rotate_word(x, count): return rotate_left(x, count, 16, 0)
351def rotate_byte(x, count): return rotate_left(x, count, 8, 0)
352
353
354# AddHotkey return codes
355IDCHK_OK = 0 # ok
356IDCHK_ARG = -1 # bad argument(s)
357IDCHK_KEY = -2 # bad hotkey name
358IDCHK_MAX = -3 # too many IDC hotkeys
359
360def AddHotkey(hotkey, idcfunc):
361 """
362 Add hotkey for IDC function
363
364 @param hotkey: hotkey name ('a', "Alt-A", etc)
365 @param idcfunc: IDC function name
366
367 @return: None
368 """
369 return idaapi.add_idc_hotkey(hotkey, idcfunc)
370
371
372def DelHotkey(hotkey):
373 """
374 Delete IDC function hotkey
375
376 @param hotkey: hotkey code to delete
377 """
378 return idaapi.del_idc_hotkey(hotkey)
379
380
381def Jump(ea):
382 """
383 Move cursor to the specifed linear address
384
385 @param ea: linear address
386 """
387 return idaapi.jumpto(ea)
388
389
390def Wait():
391 """
392 Process all entries in the autoanalysis queue
393 Wait for the end of autoanalysis
394
395 @note: This function will suspend execution of the calling script
396 till the autoanalysis queue is empty.
397 """
398 return idaapi.autoWait()
399
400
401def CompileEx(input, isfile):
402 """
403 Compile an IDC script
404
405 The input should not contain functions that are
406 currently executing - otherwise the behaviour of the replaced
407 functions is undefined.
408
409 @param input: if isfile != 0, then this is the name of file to compile
410 otherwise it holds the text to compile
411 @param isfile: specify if 'input' holds a filename or the expression itself
412
413 @return: 0 - ok, otherwise it returns an error message
414 """
415 if isfile:
416 res = idaapi.Compile(input)
417 else:
418 res = idaapi.CompileLine(input)
419
420 if res:
421 return res
422 else:
423 return 0
424
425
426def Eval(expr):
427 """
428 Evaluate an IDC expression
429
430 @param expr: an expression
431
432 @return: the expression value. If there are problems, the returned value will be "IDC_FAILURE: xxx"
433 where xxx is the error description
434
435 @note: Python implementation evaluates IDC only, while IDC can call other registered languages
436 """
437 rv = idaapi.idc_value_t()
438
439 err = idaapi.calc_idc_expr(BADADDR, expr, rv)
440 if err:
441 return "IDC_FAILURE: "+err
442 else:
443 if rv.vtype == '\x01': # VT_STR
444 return rv.str
445 elif rv.vtype == '\x02': # long
446 return rv.num
447 elif rv.vtype == '\x07': # VT_STR2
448 return rv.c_str()
449 else:
450 raise NotImplementedError, "Eval() supports only expressions returning strings or longs"
451
452
453def EVAL_FAILURE(code):
454 """
455 Check the result of Eval() for evaluation failures
456
457 @param code: result of Eval()
458
459 @return: True if there was an evaluation error
460 """
461 return type(code) == types.StringType and code.startswith("IDC_FAILURE: ")
462
463
464def SaveBase(idbname, flags=0):
465 """
466 Save current database to the specified idb file
467
468 @param idbname: name of the idb file. if empty, the current idb
469 file will be used.
470 @param flags: combination of idaapi.DBFL_... bits or 0
471 """
472 if len(idbname) == 0:
473 idbname = GetIdbPath()
474 saveflags = idaapi.cvar.database_flags
475 mask = idaapi.DBFL_KILL | idaapi.DBFL_COMP | idaapi.DBFL_BAK
476 idaapi.cvar.database_flags &= ~mask
477 idaapi.cvar.database_flags |= flags & mask
478 res = idaapi.save_database(idbname, 0)
479 idaapi.cvar.database_flags = saveflags
480 return res
481
482DBFL_BAK = idaapi.DBFL_BAK # for compatiblity with older versions, eventually delete this
483
484def ValidateNames():
485 """
486 check consistency of IDB name records
487 @return: number of inconsistent name records
488 """
489 return idaapi.validate_idb_names()
490
491def Exit(code):
492 """
493 Stop execution of IDC program, close the database and exit to OS
494
495 @param code: code to exit with.
496
497 @return: -
498 """
499 idaapi.qexit(code)
500
501
502def Exec(command):
503 """
504 Execute an OS command.
505
506 @param command: command line to execute
507
508 @return: error code from OS
509
510 @note:
511 IDA will wait for the started program to finish.
512 In order to start the command in parallel, use OS methods.
513 For example, you may start another program in parallel using
514 "start" command.
515 """
516 return os.system(command)
517
518
519def Sleep(milliseconds):
520 """
521 Sleep the specified number of milliseconds
522 This function suspends IDA for the specified amount of time
523
524 @param milliseconds: time to sleep
525 """
526 time.sleep(float(milliseconds)/1000)
527
528
529def RunPlugin(name, arg):
530 """
531 Load and run a plugin
532
533 @param name: The plugin name is a short plugin name without an extension
534 @param arg: integer argument
535
536 @return: 0 if could not load the plugin, 1 if ok
537 """
538 return idaapi.load_and_run_plugin(name, arg)
539
540
541def ApplySig(name):
542 """
543 Load (plan to apply) a FLIRT signature file
544
545 @param name: signature name without path and extension
546
547 @return: 0 if could not load the signature file, !=0 otherwise
548 """
549 return idaapi.plan_to_apply_idasgn(name)
550
551
552#----------------------------------------------------------------------------
553# C H A N G E P R O G R A M R E P R E S E N T A T I O N
554#----------------------------------------------------------------------------
555
556
557def DeleteAll():
558 """
559 Delete all segments, instructions, comments, i.e. everything
560 except values of bytes.
561 """
562 ea = idaapi.cvar.inf.minEA
563
564 # Brute-force nuke all info from all the heads
565 while ea != BADADDR and ea <= idaapi.cvar.inf.maxEA:
566 idaapi.del_local_name(ea)
567 idaapi.del_global_name(ea)
568 func = idaapi.get_func(ea)
569 if func:
570 idaapi.del_func_cmt(func, False)
571 idaapi.del_func_cmt(func, True)
572 idaapi.del_func(ea)
573 idaapi.del_hidden_area(ea)
574 seg = idaapi.getseg(ea)
575 if seg:
576 idaapi.del_segment_cmt(seg, False)
577 idaapi.del_segment_cmt(seg, True)
578 idaapi.del_segm(ea, idaapi.SEGDEL_KEEP | idaapi.SEGDEL_SILENT)
579
580 ea = idaapi.next_head(ea, idaapi.cvar.inf.maxEA)
581
582
583def MakeCode(ea):
584 """
585 Create an instruction at the specified address
586
587 @param ea: linear address
588
589 @return: 0 - can not create an instruction (no such opcode, the instruction
590 would overlap with existing items, etc) otherwise returns length of the
591 instruction in bytes
592 """
593 return idaapi.create_insn(ea)
594
595
596def AnalyzeArea(sEA, eEA):
597 """
598 Perform full analysis of the area
599
600 @param sEA: starting linear address
601 @param eEA: ending linear address (excluded)
602
603 @return: 1-ok, 0-Ctrl-Break was pressed.
604 """
605 return idaapi.analyze_area(sEA, eEA)
606
607
608def MakeNameEx(ea, name, flags):
609 """
610 Rename an address
611
612 @param ea: linear address
613 @param name: new name of address. If name == "", then delete old name
614 @param flags: combination of SN_... constants
615
616 @return: 1-ok, 0-failure
617 """
618 return idaapi.set_name(ea, name, flags)
619
620SN_CHECK = idaapi.SN_CHECK # Fail if the name contains invalid
621 # characters
622 # If this bit is clear, all invalid chars
623 # (those !is_ident_char()) will be replaced
624 # by SubstChar (usually '_')
625 # List of valid characters is defined in
626 # ida.cfg
627SN_NOCHECK = idaapi.SN_NOCHECK # Replace invalid chars with SubstChar
628SN_PUBLIC = idaapi.SN_PUBLIC # if set, make name public
629SN_NON_PUBLIC = idaapi.SN_NON_PUBLIC # if set, make name non-public
630SN_WEAK = idaapi.SN_WEAK # if set, make name weak
631SN_NON_WEAK = idaapi.SN_NON_WEAK # if set, make name non-weak
632SN_AUTO = idaapi.SN_AUTO # if set, make name autogenerated
633SN_NON_AUTO = idaapi.SN_NON_AUTO # if set, make name non-autogenerated
634SN_NOLIST = idaapi.SN_NOLIST # if set, exclude name from the list
635 # if not set, then include the name into
636 # the list (however, if other bits are set,
637 # the name might be immediately excluded
638 # from the list)
639SN_NOWARN = idaapi.SN_NOWARN # don't display a warning if failed
640SN_LOCAL = idaapi.SN_LOCAL # create local name. a function should exist.
641 # local names can't be public or weak.
642 # also they are not included into the list
643 # of names they can't have dummy prefixes
644
645def MakeComm(ea, comment):
646 """
647 Set an indented regular comment of an item
648
649 @param ea: linear address
650 @param comment: comment string
651
652 @return: None
653 """
654 return idaapi.set_cmt(ea, comment, 0)
655
656
657def MakeRptCmt(ea, comment):
658 """
659 Set an indented repeatable comment of an item
660
661 @param ea: linear address
662 @param comment: comment string
663
664 @return: None
665 """
666 return idaapi.set_cmt(ea, comment, 1)
667
668
669def MakeArray(ea, nitems):
670 """
671 Create an array.
672
673 @param ea: linear address
674 @param nitems: size of array in items
675
676 @note: This function will create an array of the items with the same type as
677 the type of the item at 'ea'. If the byte at 'ea' is undefined, then
678 this function will create an array of bytes.
679 """
680 flags = idaapi.getFlags(ea)
681
682 if idaapi.isCode(flags) or idaapi.isTail(flags) or idaapi.isAlign(flags):
683 return False
684
685 if idaapi.isUnknown(flags):
686 flags = idaapi.FF_BYTE
687
688 if idaapi.isStruct(flags):
689 ti = idaapi.opinfo_t()
690 assert idaapi.get_opinfo(ea, 0, flags, ti), "get_opinfo() failed"
691 itemsize = idaapi.get_data_elsize(ea, flags, ti)
692 tid = ti.tid
693 else:
694 itemsize = idaapi.get_item_size(ea)
695 tid = BADADDR
696
697 return idaapi.do_data_ex(ea, flags, itemsize*nitems, tid)
698
699
700def MakeStr(ea, endea):
701 """
702 Create a string.
703
704 This function creates a string (the string type is determined by the
705 value of GetLongPrm(INF_STRTYPE))
706
707 @param ea: linear address
708 @param endea: ending address of the string (excluded)
709 if endea == BADADDR, then length of string will be calculated
710 by the kernel
711
712 @return: 1-ok, 0-failure
713
714 @note: The type of an existing string is returned by GetStringType()
715 """
716 return idaapi.make_ascii_string(ea, 0 if endea == BADADDR else endea - ea, GetLongPrm(INF_STRTYPE))
717
718
719def MakeData(ea, flags, size, tid):
720 """
721 Create a data item at the specified address
722
723 @param ea: linear address
724 @param flags: FF_BYTE..FF_PACKREAL
725 @param size: size of item in bytes
726 @param tid: for FF_STRU the structure id
727
728 @return: 1-ok, 0-failure
729 """
730 return idaapi.do_data_ex(ea, flags, size, tid)
731
732
733def MakeByte(ea):
734 """
735 Convert the current item to a byte
736
737 @param ea: linear address
738
739 @return: 1-ok, 0-failure
740 """
741 return idaapi.doByte(ea, 1)
742
743
744def MakeWord(ea):
745 """
746 Convert the current item to a word (2 bytes)
747
748 @param ea: linear address
749
750 @return: 1-ok, 0-failure
751 """
752 return idaapi.doWord(ea, 2)
753
754
755def MakeDword(ea):
756 """
757 Convert the current item to a double word (4 bytes)
758
759 @param ea: linear address
760
761 @return: 1-ok, 0-failure
762 """
763 return idaapi.doDwrd(ea, 4)
764
765
766def MakeQword(ea):
767 """
768 Convert the current item to a quadro word (8 bytes)
769
770 @param ea: linear address
771
772 @return: 1-ok, 0-failure
773 """
774 return idaapi.doQwrd(ea, 8)
775
776
777def MakeOword(ea):
778 """
779 Convert the current item to an octa word (16 bytes/128 bits)
780
781 @param ea: linear address
782
783 @return: 1-ok, 0-failure
784 """
785 return idaapi.doOwrd(ea, 16)
786
787
788def MakeYword(ea):
789 """
790 Convert the current item to a ymm word (32 bytes/256 bits)
791
792 @param ea: linear address
793
794 @return: 1-ok, 0-failure
795 """
796 return idaapi.doYwrd(ea, 32)
797
798
799def MakeFloat(ea):
800 """
801 Convert the current item to a floating point (4 bytes)
802
803 @param ea: linear address
804
805 @return: 1-ok, 0-failure
806 """
807 return idaapi.doFloat(ea, 4)
808
809
810def MakeDouble(ea):
811 """
812 Convert the current item to a double floating point (8 bytes)
813
814 @param ea: linear address
815
816 @return: 1-ok, 0-failure
817 """
818 return idaapi.doDouble(ea, 8)
819
820
821def MakePackReal(ea):
822 """
823 Convert the current item to a packed real (10 or 12 bytes)
824
825 @param ea: linear address
826
827 @return: 1-ok, 0-failure
828 """
829 return idaapi.doPackReal(ea, idaapi.ph_get_tbyte_size())
830
831
832def MakeTbyte(ea):
833 """
834 Convert the current item to a tbyte (10 or 12 bytes)
835
836 @param ea: linear address
837
838 @return: 1-ok, 0-failure
839 """
840 return idaapi.doTbyt(ea, idaapi.ph_get_tbyte_size())
841
842
843def MakeStructEx(ea, size, strname):
844 """
845 Convert the current item to a structure instance
846
847 @param ea: linear address
848 @param size: structure size in bytes. -1 means that the size
849 will be calculated automatically
850 @param strname: name of a structure type
851
852 @return: 1-ok, 0-failure
853 """
854 strid = idaapi.get_struc_id(strname)
855
856 if size == -1:
857 size = idaapi.get_struc_size(strid)
858
859 return idaapi.doStruct(ea, size, strid)
860
861
862def MakeCustomDataEx(ea, size, dtid, fid):
863 """
864 Convert the item at address to custom data.
865
866 @param ea: linear address.
867 @param size: custom data size in bytes.
868 @param dtid: data type ID.
869 @param fid: data format ID.
870
871 @return: 1-ok, 0-failure
872 """
873 return idaapi.doCustomData(ea, size, dtid, fid)
874
875
876
877def MakeAlign(ea, count, align):
878 """
879 Convert the current item to an alignment directive
880
881 @param ea: linear address
882 @param count: number of bytes to convert
883 @param align: 0 or 1..32
884 if it is 0, the correct alignment will be calculated
885 by the kernel
886
887 @return: 1-ok, 0-failure
888 """
889 return idaapi.doAlign(ea, count, align)
890
891
892def MakeLocal(start, end, location, name):
893 """
894 Create a local variable
895
896 @param start: start of address range for the local variable
897 @param end: end of address range for the local variable
898 @param location: the variable location in the "[bp+xx]" form where xx is
899 a number. The location can also be specified as a
900 register name.
901 @param name: name of the local variable
902
903 @return: 1-ok, 0-failure
904
905 @note: For the stack variables the end address is ignored.
906 If there is no function at 'start' then this function.
907 will fail.
908 """
909 func = idaapi.get_func(start)
910
911 if not func:
912 return 0
913
914 # Find out if location is in the [bp+xx] form
915 r = re.compile("\[([a-z]+)([-+][0-9a-fx]+)", re.IGNORECASE)
916 m = r.match(location)
917
918 if m:
919 # Location in the form of [bp+xx]
920 register = idaapi.str2reg(m.group(1))
921 offset = int(m.group(2), 0)
922 frame = idaapi.get_frame(func)
923
924 if register == -1 or not frame:
925 return 0
926
927 offset += func.frsize
928 member = idaapi.get_member(frame, offset)
929
930 if member:
931 # Member already exists, rename it
932 if idaapi.set_member_name(frame, offset, name):
933 return 1
934 else:
935 return 0
936 else:
937 # No member at the offset, create a new one
938 if idaapi.add_struc_member(frame,
939 name,
940 offset,
941 idaapi.byteflag(),
942 None, 1) == 0:
943 return 1
944 else:
945 return 0
946 else:
947 # Location as simple register name
948 return idaapi.add_regvar(func, start, end, location, name, None)
949
950
951def MakeUnkn(ea, flags):
952 """
953 Convert the current item to an explored item
954
955 @param ea: linear address
956 @param flags: combination of DOUNK_* constants
957
958 @return: None
959 """
960 return idaapi.do_unknown(ea, flags)
961
962
963def MakeUnknown(ea, size, flags):
964 """
965 Convert the current item to an explored item
966
967 @param ea: linear address
968 @param size: size of the range to undefine (for MakeUnknown)
969 @param flags: combination of DOUNK_* constants
970
971 @return: None
972 """
973 return idaapi.do_unknown_range(ea, size, flags)
974
975
976DOUNK_SIMPLE = idaapi.DOUNK_SIMPLE # simply undefine the specified item
977DOUNK_EXPAND = idaapi.DOUNK_EXPAND # propogate undefined items, for example
978 # if removing an instruction removes all
979 # references to the next instruction, then
980 # plan to convert to unexplored the next
981 # instruction too.
982DOUNK_DELNAMES = idaapi.DOUNK_DELNAMES # delete any names at the specified address(es)
983
984
985def SetArrayFormat(ea, flags, litems, align):
986 """
987 Set array representation format
988
989 @param ea: linear address
990 @param flags: combination of AP_... constants or 0
991 @param litems: number of items per line. 0 means auto
992 @param align: element alignment
993 - -1: do not align
994 - 0: automatic alignment
995 - other values: element width
996
997 @return: 1-ok, 0-failure
998 """
999 return Eval("SetArrayFormat(0x%X, 0x%X, %d, %d)"%(ea, flags, litems, align))
1000
1001AP_ALLOWDUPS = 0x00000001L # use 'dup' construct
1002AP_SIGNED = 0x00000002L # treats numbers as signed
1003AP_INDEX = 0x00000004L # display array element indexes as comments
1004AP_ARRAY = 0x00000008L # reserved (this flag is not stored in database)
1005AP_IDXBASEMASK = 0x000000F0L # mask for number base of the indexes
1006AP_IDXDEC = 0x00000000L # display indexes in decimal
1007AP_IDXHEX = 0x00000010L # display indexes in hex
1008AP_IDXOCT = 0x00000020L # display indexes in octal
1009AP_IDXBIN = 0x00000030L # display indexes in binary
1010
1011def OpBinary(ea, n):
1012 """
1013 Convert an operand of the item (instruction or data) to a binary number
1014
1015 @param ea: linear address
1016 @param n: number of operand
1017 - 0 - the first operand
1018 - 1 - the second, third and all other operands
1019 - -1 - all operands
1020
1021 @return: 1-ok, 0-failure
1022
1023 @note: the data items use only the type of the first operand
1024 """
1025 return idaapi.op_bin(ea, n)
1026
1027
1028def OpOctal(ea, n):
1029 """
1030 Convert an operand of the item (instruction or data) to an octal number
1031
1032 @param ea: linear address
1033 @param n: number of operand
1034 - 0 - the first operand
1035 - 1 - the second, third and all other operands
1036 - -1 - all operands
1037 """
1038 return idaapi.op_oct(ea, n)
1039
1040
1041def OpDecimal(ea, n):
1042 """
1043 Convert an operand of the item (instruction or data) to a decimal number
1044
1045 @param ea: linear address
1046 @param n: number of operand
1047 - 0 - the first operand
1048 - 1 - the second, third and all other operands
1049 - -1 - all operands
1050 """
1051 return idaapi.op_dec(ea, n)
1052
1053
1054def OpHex(ea, n):
1055 """
1056 Convert an operand of the item (instruction or data) to a hexadecimal number
1057
1058 @param ea: linear address
1059 @param n: number of operand
1060 - 0 - the first operand
1061 - 1 - the second, third and all other operands
1062 - -1 - all operands
1063 """
1064 return idaapi.op_hex(ea, n)
1065
1066
1067def OpChr(ea, n):
1068 """
1069 @param ea: linear address
1070 @param n: number of operand
1071 - 0 - the first operand
1072 - 1 - the second, third and all other operands
1073 - -1 - all operands
1074 """
1075 return idaapi.op_chr(ea, n)
1076
1077
1078def OpOff(ea, n, base):
1079 """
1080 Convert operand to an offset
1081 (for the explanations of 'ea' and 'n' please see OpBinary())
1082
1083 Example:
1084 ========
1085
1086 seg000:2000 dw 1234h
1087
1088 and there is a segment at paragraph 0x1000 and there is a data item
1089 within the segment at 0x1234:
1090
1091 seg000:1234 MyString db 'Hello, world!',0
1092
1093 Then you need to specify a linear address of the segment base to
1094 create a proper offset:
1095
1096 OpOff(["seg000",0x2000],0,0x10000);
1097
1098 and you will have:
1099
1100 seg000:2000 dw offset MyString
1101
1102 Motorola 680x0 processor have a concept of "outer offsets".
1103 If you want to create an outer offset, you need to combine number
1104 of the operand with the following bit:
1105
1106 Please note that the outer offsets are meaningful only for
1107 Motorola 680x0.
1108
1109 @param ea: linear address
1110 @param n: number of operand
1111 - 0 - the first operand
1112 - 1 - the second, third and all other operands
1113 - -1 - all operands
1114 @param base: base of the offset as a linear address
1115 If base == BADADDR then the current operand becomes non-offset
1116 """
1117 return idaapi.set_offset(ea, n, base)
1118
1119
1120OPND_OUTER = idaapi.OPND_OUTER # outer offset base
1121
1122
1123def OpOffEx(ea, n, reftype, target, base, tdelta):
1124 """
1125 Convert operand to a complex offset expression
1126 This is a more powerful version of OpOff() function.
1127 It allows to explicitly specify the reference type (off8,off16, etc)
1128 and the expression target with a possible target delta.
1129 The complex expressions are represented by IDA in the following form:
1130
1131 target + tdelta - base
1132
1133 If the target is not present, then it will be calculated using
1134
1135 target = operand_value - tdelta + base
1136
1137 The target must be present for LOW.. and HIGH.. reference types
1138
1139 @param ea: linear address of the instruction/data
1140 @param n: number of operand to convert (the same as in OpOff)
1141 @param reftype: one of REF_... constants
1142 @param target: an explicitly specified expression target. if you don't
1143 want to specify it, use -1. Please note that LOW... and
1144 HIGH... reference type requre the target.
1145 @param base: the offset base (a linear address)
1146 @param tdelta: a displacement from the target which will be displayed
1147 in the expression.
1148
1149 @return: success (boolean)
1150 """
1151 return idaapi.op_offset(ea, n, reftype, target, base, tdelta)
1152
1153
1154REF_OFF8 = idaapi.REF_OFF8 # 8bit full offset
1155REF_OFF16 = idaapi.REF_OFF16 # 16bit full offset
1156REF_OFF32 = idaapi.REF_OFF32 # 32bit full offset
1157REF_LOW8 = idaapi.REF_LOW8 # low 8bits of 16bit offset
1158REF_LOW16 = idaapi.REF_LOW16 # low 16bits of 32bit offset
1159REF_HIGH8 = idaapi.REF_HIGH8 # high 8bits of 16bit offset
1160REF_HIGH16 = idaapi.REF_HIGH16 # high 16bits of 32bit offset
1161REF_VHIGH = idaapi.REF_VHIGH # high ph.high_fixup_bits of 32bit offset (processor dependent)
1162REF_VLOW = idaapi.REF_VLOW # low (32-ph.high_fixup_bits) of 32bit offset (processor dependent)
1163REF_OFF64 = idaapi.REF_OFF64 # 64bit full offset
1164REFINFO_RVA = 0x10 # based reference (rva)
1165REFINFO_PASTEND = 0x20 # reference past an item it may point to an nonexistitng
1166 # do not destroy alignment dirs
1167REFINFO_NOBASE = 0x80 # offset base is a number
1168 # that base have be any value
1169 # nb: base xrefs are created only if base
1170 # points to the middle of a segment
1171REFINFO_SUBTRACT = 0x0100 # the reference value is subtracted from
1172 # the base value instead of (as usual)
1173 # being added to it
1174REFINFO_SIGNEDOP = 0x0200 # the operand value is sign-extended (only
1175 # supported for REF_OFF8/16/32/64)
1176
1177def OpSeg(ea, n):
1178 """
1179 Convert operand to a segment expression
1180
1181 @param ea: linear address
1182 @param n: number of operand
1183 - 0 - the first operand
1184 - 1 - the second, third and all other operands
1185 - -1 - all operands
1186 """
1187 return idaapi.op_seg(ea, n)
1188
1189
1190def OpNumber(ea, n):
1191 """
1192 Convert operand to a number (with default number base, radix)
1193
1194 @param ea: linear address
1195 @param n: number of operand
1196 - 0 - the first operand
1197 - 1 - the second, third and all other operands
1198 - -1 - all operands
1199 """
1200 return idaapi.op_num(ea, n)
1201
1202
1203def OpFloat(ea, n):
1204 """
1205 Convert operand to a floating-point number
1206
1207 @param ea: linear address
1208 @param n: number of operand
1209 - 0 - the first operand
1210 - 1 - the second, third and all other operands
1211 - -1 - all operands
1212
1213 @return: 1-ok, 0-failure
1214 """
1215 return idaapi.op_flt(ea, n)
1216
1217
1218def OpAlt(ea, n, opstr):
1219 """
1220 Specify operand represenation manually.
1221
1222 @param ea: linear address
1223 @param n: number of operand
1224 - 0 - the first operand
1225 - 1 - the second, third and all other operands
1226 - -1 - all operands
1227 @param opstr: a string represenation of the operand
1228
1229 @note: IDA will not check the specified operand, it will simply display
1230 it instead of the orginal representation of the operand.
1231 """
1232 return idaapi.set_forced_operand(ea, n, opstr)
1233
1234
1235def OpSign(ea, n):
1236 """
1237 Change sign of the operand
1238
1239 @param ea: linear address
1240 @param n: number of operand
1241 - 0 - the first operand
1242 - 1 - the second, third and all other operands
1243 - -1 - all operands
1244 """
1245 return idaapi.toggle_sign(ea, n)
1246
1247
1248def OpNot(ea, n):
1249 """
1250 Toggle the bitwise not operator for the operand
1251
1252 @param ea: linear address
1253 @param n: number of operand
1254 - 0 - the first operand
1255 - 1 - the second, third and all other operands
1256 - -1 - all operands
1257 """
1258 idaapi.toggle_bnot(ea, n)
1259 return True
1260
1261
1262def OpEnumEx(ea, n, enumid, serial):
1263 """
1264 Convert operand to a symbolic constant
1265
1266 @param ea: linear address
1267 @param n: number of operand
1268 - 0 - the first operand
1269 - 1 - the second, third and all other operands
1270 - -1 - all operands
1271 @param enumid: id of enumeration type
1272 @param serial: serial number of the constant in the enumeration
1273 The serial numbers are used if there are more than
1274 one symbolic constant with the same value in the
1275 enumeration. In this case the first defined constant
1276 get the serial number 0, then second 1, etc.
1277 There could be 256 symbolic constants with the same
1278 value in the enumeration.
1279 """
1280 return idaapi.op_enum(ea, n, enumid, serial)
1281
1282
1283def OpStroffEx(ea, n, strid, delta):
1284 """
1285 Convert operand to an offset in a structure
1286
1287 @param ea: linear address
1288 @param n: number of operand
1289 - 0 - the first operand
1290 - 1 - the second, third and all other operands
1291 - -1 - all operands
1292 @param strid: id of a structure type
1293 @param delta: struct offset delta. usually 0. denotes the difference
1294 between the structure base and the pointer into the structure.
1295
1296 """
1297 path = idaapi.tid_array(1)
1298 path[0] = strid
1299 return idaapi.op_stroff(ea, n, path.cast(), 1, delta)
1300
1301
1302def OpStkvar(ea, n):
1303 """
1304 Convert operand to a stack variable
1305
1306 @param ea: linear address
1307 @param n: number of operand
1308 - 0 - the first operand
1309 - 1 - the second, third and all other operands
1310 - -1 - all operands
1311 """
1312 return idaapi.op_stkvar(ea, n)
1313
1314
1315def OpHigh(ea, n, target):
1316 """
1317 Convert operand to a high offset
1318 High offset is the upper 16bits of an offset.
1319 This type is used by TMS320C6 processors (and probably by other
1320 RISC processors too)
1321
1322 @param ea: linear address
1323 @param n: number of operand
1324 - 0 - the first operand
1325 - 1 - the second, third and all other operands
1326 - -1 - all operands
1327 @param target: the full value (all 32bits) of the offset
1328 """
1329 return idaapi.op_offset(ea, n, idaapi.REF_HIGH16, target)
1330
1331
1332def MakeVar(ea):
1333 """
1334 Mark the location as "variable"
1335
1336 @param ea: address to mark
1337
1338 @return: None
1339
1340 @note: All that IDA does is to mark the location as "variable".
1341 Nothing else, no additional analysis is performed.
1342 This function may disappear in the future.
1343 """
1344 idaapi.doVar(ea, 1)
1345
1346
1347def ExtLinA(ea, n, line):
1348 """
1349 Specify an additional line to display before the generated ones.
1350
1351 @param ea: linear address
1352 @param n: number of anterior additional line (0..MAX_ITEM_LINES)
1353 @param line: the line to display
1354
1355 @return: None
1356
1357 @note: IDA displays additional lines from number 0 up to the first unexisting
1358 additional line. So, if you specify additional line #150 and there is no
1359 additional line #149, your line will not be displayed. MAX_ITEM_LINES is
1360 defined in IDA.CFG
1361 """
1362 idaapi.update_extra_cmt(ea, idaapi.E_PREV + n, line)
1363 idaapi.doExtra(ea)
1364
1365
1366def ExtLinB(ea, n, line):
1367 """
1368 Specify an additional line to display after the generated ones.
1369
1370 @param ea: linear address
1371 @param n: number of posterior additional line (0..MAX_ITEM_LINES)
1372 @param line: the line to display
1373
1374 @return: None
1375
1376 @note: IDA displays additional lines from number 0 up to the first
1377 unexisting additional line. So, if you specify additional line #150
1378 and there is no additional line #149, your line will not be displayed.
1379 MAX_ITEM_LINES is defined in IDA.CFG
1380 """
1381 idaapi.update_extra_cmt(ea, idaapi.E_NEXT + n, line)
1382 idaapi.doExtra(ea)
1383
1384
1385def DelExtLnA(ea, n):
1386 """
1387 Delete an additional anterior line
1388
1389 @param ea: linear address
1390 @param n: number of anterior additional line (0..500)
1391
1392 @return: None
1393 """
1394 idaapi.del_extra_cmt(ea, idaapi.E_PREV + n)
1395
1396
1397def DelExtLnB(ea, n):
1398 """
1399 Delete an additional posterior line
1400
1401 @param ea: linear address
1402 @param n: number of posterior additional line (0..500)
1403
1404 @return: None
1405 """
1406 idaapi.del_extra_cmt(ea, idaapi.E_NEXT + n)
1407
1408
1409def SetManualInsn(ea, insn):
1410 """
1411 Specify instruction represenation manually.
1412
1413 @param ea: linear address
1414 @param insn: a string represenation of the operand
1415
1416 @note: IDA will not check the specified instruction, it will simply
1417 display it instead of the orginal representation.
1418 """
1419 return idaapi.set_manual_insn(ea, insn)
1420
1421
1422def GetManualInsn(ea):
1423 """
1424 Get manual representation of instruction
1425
1426 @param ea: linear address
1427
1428 @note: This function returns value set by SetManualInsn earlier.
1429 """
1430 return idaapi.get_manual_insn(ea)
1431
1432
1433def PatchDbgByte(ea,value):
1434 """
1435 Change a byte in the debugged process memory only
1436
1437 @param ea: address
1438 @param value: new value of the byte
1439
1440 @return: 1 if successful, 0 if not
1441 """
1442 return idaapi.put_dbg_byte(ea, value)
1443
1444
1445def PatchByte(ea, value):
1446 """
1447 Change value of a program byte
1448 If debugger was active then the debugged process memory will be patched too
1449
1450 @param ea: linear address
1451 @param value: new value of the byte
1452
1453 @return: 1 if successful, 0 if not
1454 """
1455 return idaapi.patch_byte(ea, value)
1456
1457
1458def PatchWord(ea, value):
1459 """
1460 Change value of a program word (2 bytes)
1461
1462 @param ea: linear address
1463 @param value: new value of the word
1464
1465 @return: 1 if successful, 0 if not
1466 """
1467 return idaapi.patch_word(ea, value)
1468
1469
1470def PatchDword(ea, value):
1471 """
1472 Change value of a double word
1473
1474 @param ea: linear address
1475 @param value: new value of the double word
1476
1477 @return: 1 if successful, 0 if not
1478 """
1479 return idaapi.patch_long(ea, value)
1480
1481
1482def SetFlags(ea, flags):
1483 """
1484 Set new value of flags
1485 This function should not used be used directly if possible.
1486 It changes properties of a program byte and if misused, may lead to
1487 very-very strange results.
1488
1489 @param ea: adress
1490 @param flags: new flags value
1491 """
1492 return idaapi.setFlags(ea, flags)
1493
1494def SetRegEx(ea, reg, value, tag):
1495 """
1496 Set value of a segment register.
1497
1498 @param ea: linear address
1499 @param reg: name of a register, like "cs", "ds", "es", etc.
1500 @param value: new value of the segment register.
1501 @param tag: of SR_... constants
1502
1503 @note: IDA keeps tracks of all the points where segment register change their
1504 values. This function allows you to specify the correct value of a segment
1505 register if IDA is not able to find the corrent value.
1506
1507 See also SetReg() compatibility macro.
1508 """
1509 reg = idaapi.str2reg(reg);
1510 if reg >= 0:
1511 return idaapi.splitSRarea1(ea, reg, value, tag)
1512 else:
1513 return False
1514
1515SR_inherit = 1 # value is inherited from the previous area
1516SR_user = 2 # value is specified by the user
1517SR_auto = 3 # value is determined by IDA
1518SR_autostart = 4 # as SR_auto for segment starting address
1519
1520
1521def AutoMark2(start, end, queuetype):
1522 """
1523 Plan to perform an action in the future.
1524 This function will put your request to a special autoanalysis queue.
1525 Later IDA will retrieve the request from the queue and process
1526 it. There are several autoanalysis queue types. IDA will process all
1527 queries from the first queue and then switch to the second queue, etc.
1528 """
1529 return idaapi.auto_mark_range(start, end, queuetype)
1530
1531
1532def AutoUnmark(start, end, queuetype):
1533 """
1534 Remove range of addresses from a queue.
1535 """
1536 return idaapi.autoUnmark(start, end, queuetype)
1537
1538
1539def AutoMark(ea,qtype):
1540 """
1541 Plan to analyze an address
1542 """
1543 return AutoMark2(ea,ea+1,qtype)
1544
1545AU_UNK = idaapi.AU_UNK # make unknown
1546AU_CODE = idaapi.AU_CODE # convert to instruction
1547AU_PROC = idaapi.AU_PROC # make function
1548AU_USED = idaapi.AU_USED # reanalyze
1549AU_LIBF = idaapi.AU_LIBF # apply a flirt signature (the current signature!)
1550AU_FINAL = idaapi.AU_FINAL # coagulate unexplored items
1551
1552
1553#----------------------------------------------------------------------------
1554# P R O D U C E O U T P U T F I L E S
1555#----------------------------------------------------------------------------
1556
1557def GenerateFile(filetype, path, ea1, ea2, flags):
1558 """
1559 Generate an output file
1560
1561 @param filetype: type of output file. One of OFILE_... symbols. See below.
1562 @param path: the output file path (will be overwritten!)
1563 @param ea1: start address. For some file types this argument is ignored
1564 @param ea2: end address. For some file types this argument is ignored
1565 @param flags: bit combination of GENFLG_...
1566
1567 @returns: number of the generated lines.
1568 -1 if an error occured
1569 OFILE_EXE: 0-can't generate exe file, 1-ok
1570 """
1571 f = idaapi.fopenWT(path)
1572
1573 if f:
1574 retval = idaapi.gen_file(filetype, f, ea1, ea2, flags)
1575 idaapi.eclose(f)
1576 return retval
1577 else:
1578 return -1
1579
1580
1581# output file types:
1582OFILE_MAP = idaapi.OFILE_MAP
1583OFILE_EXE = idaapi.OFILE_EXE
1584OFILE_IDC = idaapi.OFILE_IDC
1585OFILE_LST = idaapi.OFILE_LST
1586OFILE_ASM = idaapi.OFILE_ASM
1587OFILE_DIF = idaapi.OFILE_DIF
1588
1589# output control flags:
1590GENFLG_MAPSEG = idaapi.GENFLG_MAPSEG # map: generate map of segments
1591GENFLG_MAPNAME = idaapi.GENFLG_MAPNAME # map: include dummy names
1592GENFLG_MAPDMNG = idaapi.GENFLG_MAPDMNG # map: demangle names
1593GENFLG_MAPLOC = idaapi.GENFLG_MAPLOC # map: include local names
1594GENFLG_IDCTYPE = idaapi.GENFLG_IDCTYPE # idc: gen only information about types
1595GENFLG_ASMTYPE = idaapi.GENFLG_ASMTYPE # asm&lst: gen information about types too
1596GENFLG_GENHTML = idaapi.GENFLG_GENHTML # asm&lst: generate html (gui version only)
1597GENFLG_ASMINC = idaapi.GENFLG_ASMINC # asm&lst: gen information only about types
1598
1599def GenFuncGdl(outfile, title, ea1, ea2, flags):
1600 """
1601 Generate a flow chart GDL file
1602
1603 @param outfile: output file name. GDL extension will be used
1604 @param title: graph title
1605 @param ea1: beginning of the area to flow chart
1606 @param ea2: end of the area to flow chart.
1607 @param flags: combination of CHART_... constants
1608
1609 @note: If ea2 == BADADDR then ea1 is treated as an address within a function.
1610 That function will be flow charted.
1611 """
1612 return idaapi.gen_flow_graph(outfile, title, None, ea1, ea2, flags)
1613
1614
1615CHART_PRINT_NAMES = 0x1000 # print labels for each block?
1616CHART_GEN_GDL = 0x4000 # generate .gdl file (file extension is forced to .gdl)
1617CHART_WINGRAPH = 0x8000 # call wingraph32 to display the graph
1618CHART_NOLIBFUNCS = 0x0400 # don't include library functions in the graph
1619
1620
1621def GenCallGdl(outfile, title, flags):
1622 """
1623 Generate a function call graph GDL file
1624
1625 @param outfile: output file name. GDL extension will be used
1626 @param title: graph title
1627 @param flags: combination of CHART_GEN_GDL, CHART_WINGRAPH, CHART_NOLIBFUNCS
1628 """
1629 return idaapi.gen_simple_call_chart(outfile, "Generating chart", title, flags)
1630
1631
1632#----------------------------------------------------------------------------
1633# C O M M O N I N F O R M A T I O N
1634#----------------------------------------------------------------------------
1635def GetIdaDirectory():
1636 """
1637 Get IDA directory
1638
1639 This function returns the directory where IDA.EXE resides
1640 """
1641 return idaapi.idadir("")
1642
1643
1644def GetInputFile():
1645 """
1646 Get input file name
1647
1648 This function returns name of the file being disassembled
1649 """
1650 return idaapi.get_root_filename()
1651
1652
1653def GetInputFilePath():
1654 """
1655 Get input file path
1656
1657 This function returns the full path of the file being disassembled
1658 """
1659 return idaapi.get_input_file_path()
1660
1661
1662def SetInputFilePath(path):
1663 """
1664 Set input file name
1665 This function updates the file name that is stored in the database
1666 It is used by the debugger and other parts of IDA
1667 Use it when the database is moved to another location or when you
1668 use remote debugging.
1669
1670 @param path: new input file path
1671 """
1672 return idaapi.set_root_filename(path)
1673
1674
1675def GetIdbPath():
1676 """
1677 Get IDB full path
1678
1679 This function returns full path of the current IDB database
1680 """
1681 return idaapi.as_cstr(idaapi.cvar.database_idb)
1682
1683
1684def GetInputMD5():
1685 """
1686 Return the MD5 hash of the input binary file
1687
1688 @return: MD5 string or None on error
1689 """
1690 ua = idaapi.uchar_array(16)
1691 if idaapi.retrieve_input_file_md5(ua.cast()):
1692 return "".join(["%02X" % ua[i] for i in xrange(16)])
1693 else:
1694 return None
1695
1696
1697def GetFlags(ea):
1698 """
1699 Get internal flags
1700
1701 @param ea: linear address
1702
1703 @return: 32-bit value of internal flags. See start of IDC.IDC file
1704 for explanations.
1705 """
1706 return idaapi.getFlags(ea)
1707
1708
1709def IdbByte(ea):
1710 """
1711 Get one byte (8-bit) of the program at 'ea' from the database even if the debugger is active
1712
1713 @param ea: linear address
1714
1715 @return: byte value. If the byte has no value then 0xFF is returned.
1716
1717 @note: If the current byte size is different from 8 bits, then the returned value may have more 1's.
1718 To check if a byte has a value, use this expr: hasValue(GetFlags(ea))
1719 """
1720 return idaapi.get_db_byte(ea)
1721
1722
1723def GetManyBytes(ea, size, use_dbg = False):
1724 """
1725 Return the specified number of bytes of the program
1726
1727 @param ea: linear address
1728
1729 @param size: size of buffer in normal 8-bit bytes
1730
1731 @param use_dbg: if True, use debugger memory, otherwise just the database
1732
1733 @return: None on failure
1734 otherwise a string containing the read bytes
1735 """
1736 if use_dbg:
1737 return idaapi.dbg_read_memory(ea, size)
1738 else:
1739 return idaapi.get_many_bytes(ea, size)
1740
1741
1742def Byte(ea):
1743 """
1744 Get value of program byte
1745
1746 @param ea: linear address
1747
1748 @return: value of byte. If byte has no value then returns 0xFF
1749 If the current byte size is different from 8 bits, then the returned value
1750 might have more 1's.
1751 To check if a byte has a value, use functions hasValue(GetFlags(ea))
1752 """
1753 return idaapi.get_full_byte(ea)
1754
1755
1756def __DbgValue(ea, len):
1757 if len not in idaapi.__struct_unpack_table:
1758 return None
1759 r = idaapi.dbg_read_memory(ea, len)
1760 return None if r is None else struct.unpack((">" if idaapi.cvar.inf.mf else "<") + idaapi.__struct_unpack_table[len][1], r)[0]
1761
1762
1763def DbgByte(ea):
1764 """
1765 Get value of program byte using the debugger memory
1766
1767 @param ea: linear address
1768 @return: The value or None on failure.
1769 """
1770 return __DbgValue(ea, 1)
1771
1772
1773def DbgWord(ea):
1774 """
1775 Get value of program word using the debugger memory
1776
1777 @param ea: linear address
1778 @return: The value or None on failure.
1779 """
1780 return __DbgValue(ea, 2)
1781
1782
1783def DbgDword(ea):
1784 """
1785 Get value of program double-word using the debugger memory
1786
1787 @param ea: linear address
1788 @return: The value or None on failure.
1789 """
1790 return __DbgValue(ea, 4)
1791
1792
1793def DbgQword(ea):
1794 """
1795 Get value of program quadro-word using the debugger memory
1796
1797 @param ea: linear address
1798 @return: The value or None on failure.
1799 """
1800 return __DbgValue(ea, 8)
1801
1802
1803def DbgRead(ea, size):
1804 """
1805 Read from debugger memory.
1806
1807 @param ea: linear address
1808 @param size: size of data to read
1809 @return: data as a string. If failed, If failed, throws an exception
1810
1811 Thread-safe function (may be called only from the main thread and debthread)
1812 """
1813 return idaapi.dbg_read_memory(ea, size)
1814
1815
1816def DbgWrite(ea, data):
1817 """
1818 Write to debugger memory.
1819
1820 @param ea: linear address
1821 @param data: string to write
1822 @return: number of written bytes (-1 - network/debugger error)
1823
1824 Thread-safe function (may be called only from the main thread and debthread)
1825 """
1826 if not idaapi.dbg_can_query():
1827 return -1
1828 elif len(data) > 0:
1829 return idaapi.dbg_write_memory(ea, data)
1830
1831
1832def GetOriginalByte(ea):
1833 """
1834 Get original value of program byte
1835
1836 @param ea: linear address
1837
1838 @return: the original value of byte before any patch applied to it
1839 """
1840 return idaapi.get_original_byte(ea)
1841
1842
1843def Word(ea):
1844 """
1845 Get value of program word (2 bytes)
1846
1847 @param ea: linear address
1848
1849 @return: the value of the word. If word has no value then returns 0xFFFF
1850 If the current byte size is different from 8 bits, then the returned value
1851 might have more 1's.
1852 """
1853 return idaapi.get_full_word(ea)
1854
1855
1856def Dword(ea):
1857 """
1858 Get value of program double word (4 bytes)
1859
1860 @param ea: linear address
1861
1862 @return: the value of the double word. If failed returns -1
1863 """
1864 return idaapi.get_full_long(ea)
1865
1866
1867def Qword(ea):
1868 """
1869 Get value of program quadro word (8 bytes)
1870
1871 @param ea: linear address
1872
1873 @return: the value of the quadro word. If failed, returns -1
1874 """
1875 return idaapi.get_qword(ea)
1876
1877
1878def GetFloat(ea):
1879 """
1880 Get value of a floating point number (4 bytes)
1881 This function assumes number stored using IEEE format
1882 and in the same endianness as integers.
1883
1884 @param ea: linear address
1885
1886 @return: float
1887 """
1888 tmp = struct.pack("I", Dword(ea))
1889 return struct.unpack("f", tmp)[0]
1890
1891
1892def GetDouble(ea):
1893 """
1894 Get value of a floating point number (8 bytes)
1895 This function assumes number stored using IEEE format
1896 and in the same endianness as integers.
1897
1898 @param ea: linear address
1899
1900 @return: double
1901 """
1902 tmp = struct.pack("Q", Qword(ea))
1903 return struct.unpack("d", tmp)[0]
1904
1905
1906def LocByName(name):
1907 """
1908 Get linear address of a name
1909
1910 @param name: name of program byte
1911
1912 @return: address of the name
1913 BADADDR - No such name
1914 """
1915 return idaapi.get_name_ea(BADADDR, name)
1916
1917
1918def LocByNameEx(fromaddr, name):
1919 """
1920 Get linear address of a name
1921
1922 @param fromaddr: the referring address. Allows to retrieve local label
1923 addresses in functions. If a local name is not found,
1924 then address of a global name is returned.
1925
1926 @param name: name of program byte
1927
1928 @return: address of the name (BADADDR - no such name)
1929
1930 @note: Dummy names (like byte_xxxx where xxxx are hex digits) are parsed by this
1931 function to obtain the address. The database is not consulted for them.
1932 """
1933 return idaapi.get_name_ea(fromaddr, name)
1934
1935
1936def SegByBase(base):
1937 """
1938 Get segment by segment base
1939
1940 @param base: segment base paragraph or selector
1941
1942 @return: linear address of the start of the segment or BADADDR
1943 if no such segment
1944 """
1945 sel = idaapi.find_selector(base)
1946 seg = idaapi.get_segm_by_sel(sel)
1947
1948 if seg:
1949 return seg.startEA
1950 else:
1951 return BADADDR
1952
1953
1954def ScreenEA():
1955 """
1956 Get linear address of cursor
1957 """
1958 return idaapi.get_screen_ea()
1959
1960
1961def GetCurrentLine():
1962 """
1963 Get the disassembly line at the cursor
1964
1965 @return: string
1966 """
1967 return idaapi.tag_remove(idaapi.get_curline())
1968
1969
1970def SelStart():
1971 """
1972 Get start address of the selected area
1973 returns BADADDR - the user has not selected an area
1974 """
1975 selection, startaddr, endaddr = idaapi.read_selection()
1976
1977 if selection == 1:
1978 return startaddr
1979 else:
1980 return BADADDR
1981
1982
1983def SelEnd():
1984 """
1985 Get end address of the selected area
1986
1987 @return: BADADDR - the user has not selected an area
1988 """
1989 selection, startaddr, endaddr = idaapi.read_selection()
1990
1991 if selection == 1:
1992 return endaddr
1993 else:
1994 return BADADDR
1995
1996
1997def GetReg(ea, reg):
1998 """
1999 Get value of segment register at the specified address
2000
2001 @param ea: linear address
2002 @param reg: name of segment register
2003
2004 @return: the value of the segment register or -1 on error
2005
2006 @note: The segment registers in 32bit program usually contain selectors,
2007 so to get paragraph pointed by the segment register you need to
2008 call AskSelector() function.
2009 """
2010 reg = idaapi.str2reg(reg);
2011 if reg >= 0:
2012 return idaapi.getSR(ea, reg)
2013 else:
2014 return -1
2015
2016def NextAddr(ea):
2017 """
2018 Get next address in the program
2019
2020 @param ea: linear address
2021
2022 @return: BADADDR - the specified address in the last used address
2023 """
2024 return idaapi.nextaddr(ea)
2025
2026
2027def PrevAddr(ea):
2028 """
2029 Get previous address in the program
2030
2031 @param ea: linear address
2032
2033 @return: BADADDR - the specified address in the first address
2034 """
2035 return idaapi.prevaddr(ea)
2036
2037
2038def NextHead(ea, maxea=BADADDR):
2039 """
2040 Get next defined item (instruction or data) in the program
2041
2042 @param ea: linear address to start search from
2043 @param maxea: the search will stop at the address
2044 maxea is not included in the search range
2045
2046 @return: BADADDR - no (more) defined items
2047 """
2048 return idaapi.next_head(ea, maxea)
2049
2050
2051def PrevHead(ea, minea=0):
2052 """
2053 Get previous defined item (instruction or data) in the program
2054
2055 @param ea: linear address to start search from
2056 @param minea: the search will stop at the address
2057 minea is included in the search range
2058
2059 @return: BADADDR - no (more) defined items
2060 """
2061 return idaapi.prev_head(ea, minea)
2062
2063
2064def NextNotTail(ea):
2065 """
2066 Get next not-tail address in the program
2067 This function searches for the next displayable address in the program.
2068 The tail bytes of instructions and data are not displayable.
2069
2070 @param ea: linear address
2071
2072 @return: BADADDR - no (more) not-tail addresses
2073 """
2074 return idaapi.next_not_tail(ea)
2075
2076
2077def PrevNotTail(ea):
2078 """
2079 Get previous not-tail address in the program
2080 This function searches for the previous displayable address in the program.
2081 The tail bytes of instructions and data are not displayable.
2082
2083 @param ea: linear address
2084
2085 @return: BADADDR - no (more) not-tail addresses
2086 """
2087 return idaapi.prev_not_tail(ea)
2088
2089
2090def ItemHead(ea):
2091 """
2092 Get starting address of the item (instruction or data)
2093
2094 @param ea: linear address
2095
2096 @return: the starting address of the item
2097 if the current address is unexplored, returns 'ea'
2098 """
2099 return idaapi.get_item_head(ea)
2100
2101
2102def ItemEnd(ea):
2103 """
2104 Get address of the end of the item (instruction or data)
2105
2106 @param ea: linear address
2107
2108 @return: address past end of the item at 'ea'
2109 """
2110 return idaapi.get_item_end(ea)
2111
2112
2113def ItemSize(ea):
2114 """
2115 Get size of instruction or data item in bytes
2116
2117 @param ea: linear address
2118
2119 @return: 1..n
2120 """
2121 return idaapi.get_item_end(ea) - ea
2122
2123
2124def NameEx(fromaddr, ea):
2125 """
2126 Get visible name of program byte
2127
2128 This function returns name of byte as it is displayed on the screen.
2129 If a name contains illegal characters, IDA replaces them by the
2130 substitution character during displaying. See IDA.CFG for the
2131 definition of the substitution character.
2132
2133 @param fromaddr: the referring address. May be BADADDR.
2134 Allows to retrieve local label addresses in functions.
2135 If a local name is not found, then a global name is
2136 returned.
2137 @param ea: linear address
2138
2139 @return: "" - byte has no name
2140 """
2141 name = idaapi.get_name(fromaddr, ea)
2142
2143 if not name:
2144 return ""
2145 else:
2146 return name
2147
2148
2149def GetTrueNameEx(fromaddr, ea):
2150 """
2151 Get true name of program byte
2152
2153 This function returns name of byte as is without any replacements.
2154
2155 @param fromaddr: the referring address. May be BADADDR.
2156 Allows to retrieve local label addresses in functions.
2157 If a local name is not found, then a global name is returned.
2158 @param ea: linear address
2159
2160 @return: "" - byte has no name
2161 """
2162 name = idaapi.get_true_name(fromaddr, ea)
2163
2164 if not name:
2165 return ""
2166 else:
2167 return name
2168
2169
2170def Demangle(name, disable_mask):
2171 """
2172 Demangle a name
2173
2174 @param name: name to demangle
2175 @param disable_mask: a mask that tells how to demangle the name
2176 it is a good idea to get this mask using
2177 GetLongPrm(INF_SHORT_DN) or GetLongPrm(INF_LONG_DN)
2178
2179 @return: a demangled name
2180 If the input name cannot be demangled, returns None
2181 """
2182 return idaapi.demangle_name(name, disable_mask)
2183
2184
2185def GetDisasmEx(ea, flags):
2186 """
2187 Get disassembly line
2188
2189 @param ea: linear address of instruction
2190
2191 @param flags: combination of the GENDSM_ flags, or 0
2192
2193 @return: "" - could not decode instruction at the specified location
2194
2195 @note: this function may not return exactly the same mnemonics
2196 as you see on the screen.
2197 """
2198 text = idaapi.generate_disasm_line(ea, flags)
2199 if text:
2200 return idaapi.tag_remove(text)
2201 else:
2202 return ""
2203
2204# flags for GetDisasmEx
2205# generate a disassembly line as if
2206# there is an instruction at 'ea'
2207GENDSM_FORCE_CODE = idaapi.GENDSM_FORCE_CODE
2208
2209# if the instruction consists of several lines,
2210# produce all of them (useful for parallel instructions)
2211GENDSM_MULTI_LINE = idaapi.GENDSM_MULTI_LINE
2212
2213def GetDisasm(ea):
2214 """
2215 Get disassembly line
2216
2217 @param ea: linear address of instruction
2218
2219 @return: "" - could not decode instruction at the specified location
2220
2221 @note: this function may not return exactly the same mnemonics
2222 as you see on the screen.
2223 """
2224 return GetDisasmEx(ea, 0)
2225
2226def GetMnem(ea):
2227 """
2228 Get instruction mnemonics
2229
2230 @param ea: linear address of instruction
2231
2232 @return: "" - no instruction at the specified location
2233
2234 @note: this function may not return exactly the same mnemonics
2235 as you see on the screen.
2236 """
2237 res = idaapi.ua_mnem(ea)
2238
2239 if not res:
2240 return ""
2241 else:
2242 return res
2243
2244
2245def GetOpnd(ea, n):
2246 """
2247 Get operand of an instruction
2248
2249 @param ea: linear address of instruction
2250 @param n: number of operand:
2251 0 - the first operand
2252 1 - the second operand
2253
2254 @return: the current text representation of operand or ""
2255 """
2256
2257 if not isCode(idaapi.get_flags_novalue(ea)):
2258 return ""
2259
2260 res = idaapi.ua_outop2(ea, n)
2261
2262 if not res:
2263 return ""
2264 else:
2265 return idaapi.tag_remove(res)
2266
2267
2268def GetOpType(ea, n):
2269 """
2270 Get type of instruction operand
2271
2272 @param ea: linear address of instruction
2273 @param n: number of operand:
2274 0 - the first operand
2275 1 - the second operand
2276
2277 @return: any of o_* constants or -1 on error
2278 """
2279 inslen = idaapi.decode_insn(ea)
2280 return -1 if inslen == 0 else idaapi.cmd.Operands[n].type
2281
2282
2283o_void = idaapi.o_void # No Operand ----------
2284o_reg = idaapi.o_reg # General Register (al,ax,es,ds...) reg
2285o_mem = idaapi.o_mem # Direct Memory Reference (DATA) addr
2286o_phrase = idaapi.o_phrase # Memory Ref [Base Reg + Index Reg] phrase
2287o_displ = idaapi.o_displ # Memory Reg [Base Reg + Index Reg + Displacement] phrase+addr
2288o_imm = idaapi.o_imm # Immediate Value value
2289o_far = idaapi.o_far # Immediate Far Address (CODE) addr
2290o_near = idaapi.o_near # Immediate Near Address (CODE) addr
2291o_idpspec0 = idaapi.o_idpspec0 # IDP specific type
2292o_idpspec1 = idaapi.o_idpspec1 # IDP specific type
2293o_idpspec2 = idaapi.o_idpspec2 # IDP specific type
2294o_idpspec3 = idaapi.o_idpspec3 # IDP specific type
2295o_idpspec4 = idaapi.o_idpspec4 # IDP specific type
2296o_idpspec5 = idaapi.o_idpspec5 # IDP specific type
2297o_last = idaapi.o_last # first unused type
2298
2299# x86
2300o_trreg = idaapi.o_idpspec0 # trace register
2301o_dbreg = idaapi.o_idpspec1 # debug register
2302o_crreg = idaapi.o_idpspec2 # control register
2303o_fpreg = idaapi.o_idpspec3 # floating point register
2304o_mmxreg = idaapi.o_idpspec4 # mmx register
2305o_xmmreg = idaapi.o_idpspec5 # xmm register
2306
2307# arm
2308o_reglist = idaapi.o_idpspec1 # Register list (for LDM/STM)
2309o_creglist = idaapi.o_idpspec2 # Coprocessor register list (for CDP)
2310o_creg = idaapi.o_idpspec3 # Coprocessor register (for LDC/STC)
2311o_fpreg = idaapi.o_idpspec4 # Floating point register
2312o_fpreglist = idaapi.o_idpspec5 # Floating point register list
2313o_text = (idaapi.o_idpspec5+1) # Arbitrary text stored in the operand
2314
2315# ppc
2316o_spr = idaapi.o_idpspec0 # Special purpose register
2317o_twofpr = idaapi.o_idpspec1 # Two FPRs
2318o_shmbme = idaapi.o_idpspec2 # SH & MB & ME
2319o_crf = idaapi.o_idpspec3 # crfield x.reg
2320o_crb = idaapi.o_idpspec4 # crbit x.reg
2321o_dcr = idaapi.o_idpspec5 # Device control register
2322
2323def GetOperandValue(ea, n):
2324 """
2325 Get number used in the operand
2326
2327 This function returns an immediate number used in the operand
2328
2329 @param ea: linear address of instruction
2330 @param n: the operand number
2331
2332 @return: value
2333 operand is an immediate value => immediate value
2334 operand has a displacement => displacement
2335 operand is a direct memory ref => memory address
2336 operand is a register => register number
2337 operand is a register phrase => phrase number
2338 otherwise => -1
2339 """
2340 inslen = idaapi.decode_insn(ea)
2341 if inslen == 0:
2342 return -1
2343 op = idaapi.cmd.Operands[n]
2344 if not op:
2345 return -1
2346
2347 if op.type in [ idaapi.o_mem, idaapi.o_far, idaapi.o_near, idaapi.o_displ ]:
2348 value = op.addr
2349 elif op.type == idaapi.o_reg:
2350 value = op.reg
2351 elif op.type == idaapi.o_imm:
2352 value = op.value
2353 elif op.type == idaapi.o_phrase:
2354 value = op.phrase
2355 else:
2356 value = -1
2357 return value
2358
2359
2360def LineA(ea, num):
2361 """
2362 Get anterior line
2363
2364 @param ea: linear address
2365 @param num: number of anterior line (0..MAX_ITEM_LINES)
2366 MAX_ITEM_LINES is defined in IDA.CFG
2367
2368 @return: anterior line string
2369 """
2370 return idaapi.get_extra_cmt(ea, idaapi.E_PREV + num)
2371
2372
2373def LineB(ea, num):
2374 """
2375 Get posterior line
2376
2377 @param ea: linear address
2378 @param num: number of posterior line (0..MAX_ITEM_LINES)
2379
2380 @return: posterior line string
2381 """
2382 return idaapi.get_extra_cmt(ea, idaapi.E_NEXT + num)
2383
2384
2385def GetCommentEx(ea, repeatable):
2386 """
2387 Get regular indented comment
2388
2389 @param ea: linear address
2390
2391 @param repeatable: 1 to get the repeatable comment, 0 to get the normal comment
2392
2393 @return: string or None if it fails
2394 """
2395 return idaapi.get_cmt(ea, repeatable)
2396
2397
2398def CommentEx(ea, repeatable):
2399 """
2400 Get regular indented comment
2401
2402 @param ea: linear address
2403
2404 @param repeatable: 1 to get the repeatable comment, 0 to get the normal comment
2405
2406 @return: string or None if it fails
2407 """
2408 return GetCommentEx(ea, repeatable)
2409
2410
2411def AltOp(ea, n):
2412 """
2413 Get manually entered operand string
2414
2415 @param ea: linear address
2416 @param n: number of operand:
2417 0 - the first operand
2418 1 - the second operand
2419
2420 @return: string or None if it fails
2421 """
2422 return idaapi.get_forced_operand(ea, n)
2423
2424ASCSTR_C = idaapi.ASCSTR_TERMCHR # C-style ASCII string
2425ASCSTR_PASCAL = idaapi.ASCSTR_PASCAL # Pascal-style ASCII string (length byte)
2426ASCSTR_LEN2 = idaapi.ASCSTR_LEN2 # Pascal-style, length is 2 bytes
2427ASCSTR_UNICODE = idaapi.ASCSTR_UNICODE # Unicode string
2428ASCSTR_LEN4 = idaapi.ASCSTR_LEN4 # Pascal-style, length is 4 bytes
2429ASCSTR_ULEN2 = idaapi.ASCSTR_ULEN2 # Pascal-style Unicode, length is 2 bytes
2430ASCSTR_ULEN4 = idaapi.ASCSTR_ULEN4 # Pascal-style Unicode, length is 4 bytes
2431ASCSTR_LAST = idaapi.ASCSTR_LAST # Last string type
2432
2433def GetString(ea, length = -1, strtype = ASCSTR_C):
2434 """
2435 Get string contents
2436 @param ea: linear address
2437 @param length: string length. -1 means to calculate the max string length
2438 @param strtype: the string type (one of ASCSTR_... constants)
2439
2440 @return: string contents or empty string
2441 """
2442 if length == -1:
2443 length = idaapi.get_max_ascii_length(ea, strtype, idaapi.ALOPT_IGNHEADS)
2444
2445 return idaapi.get_ascii_contents2(ea, length, strtype)
2446
2447
2448def GetStringType(ea):
2449 """
2450 Get string type
2451
2452 @param ea: linear address
2453
2454 @return: One of ASCSTR_... constants
2455 """
2456 ti = idaapi.opinfo_t()
2457
2458 if idaapi.get_opinfo(ea, 0, GetFlags(ea), ti):
2459 return ti.strtype
2460 else:
2461 return None
2462
2463# The following functions search for the specified byte
2464# ea - address to start from
2465# flag is combination of the following bits
2466
2467# returns BADADDR - not found
2468def FindVoid (ea, flag): return idaapi.find_void(ea, flag)
2469def FindCode (ea, flag): return idaapi.find_code(ea, flag)
2470def FindData (ea, flag): return idaapi.find_data(ea, flag)
2471def FindUnexplored (ea, flag): return idaapi.find_unknown(ea, flag)
2472def FindExplored (ea, flag): return idaapi.find_defined(ea, flag)
2473def FindImmediate (ea, flag, value): return idaapi.find_imm(ea, flag, value)
2474
2475SEARCH_UP = idaapi.SEARCH_UP # search backward
2476SEARCH_DOWN = idaapi.SEARCH_DOWN # search forward
2477SEARCH_NEXT = idaapi.SEARCH_NEXT # start the search at the next/prev item
2478 # useful only for FindText() and FindBinary()
2479SEARCH_CASE = idaapi.SEARCH_CASE # search case-sensitive
2480 # (only for bin&txt search)
2481SEARCH_REGEX = idaapi.SEARCH_REGEX # enable regular expressions (only for text)
2482SEARCH_NOBRK = idaapi.SEARCH_NOBRK # don't test ctrl-break
2483SEARCH_NOSHOW = idaapi.SEARCH_NOSHOW # don't display the search progress
2484
2485def FindText(ea, flag, y, x, searchstr):
2486 """
2487 @param ea: start address
2488 @param flag: combination of SEARCH_* flags
2489 @param y: number of text line at ea to start from (0..MAX_ITEM_LINES)
2490 @param x: coordinate in this line
2491 @param searchstr: search string
2492
2493 @return: ea of result or BADADDR if not found
2494 """
2495 return idaapi.find_text(ea, y, x, searchstr, flag)
2496
2497
2498def FindBinary(ea, flag, searchstr, radix=16):
2499 """
2500 @param ea: start address
2501 @param flag: combination of SEARCH_* flags
2502 @param searchstr: a string as a user enters it for Search Text in Core
2503 @param radix: radix of the numbers (default=16)
2504
2505 @return: ea of result or BADADDR if not found
2506
2507 @note: Example: "41 42" - find 2 bytes 41h,42h (radix is 16)
2508 """
2509 endea = flag & 1 and idaapi.cvar.inf.maxEA or idaapi.cvar.inf.minEA
2510 return idaapi.find_binary(ea, endea, searchstr, radix, flag)
2511
2512
2513#----------------------------------------------------------------------------
2514# G L O B A L S E T T I N G S M A N I P U L A T I O N
2515#----------------------------------------------------------------------------
2516def ChangeConfig(directive):
2517 """
2518 Parse one or more ida.cfg config directives
2519 @param directive: directives to process, for example: PACK_DATABASE=2
2520
2521 @note: If the directives are erroneous, a fatal error will be generated.
2522 The settings are permanent: effective for the current session and the next ones
2523 """
2524 return Eval('ChangeConfig("%s")' % idaapi.str2user(directive))
2525
2526
2527# The following functions allow you to set/get common parameters.
2528# Please note that not all parameters can be set directly.
2529
2530def GetLongPrm(offset):
2531 """
2532 """
2533 val = _IDC_GetAttr(idaapi.cvar.inf, _INFMAP, offset)
2534 if offset == INF_PROCNAME:
2535 # procName is a character array
2536 val = idaapi.as_cstr(val)
2537 return val
2538
2539def GetShortPrm(offset):
2540 return GetLongPrm(offset)
2541
2542
2543def GetCharPrm (offset):
2544 return GetLongPrm(offset)
2545
2546
2547def SetLongPrm (offset, value):
2548 """
2549 """
2550 if offset == INF_PROCNAME:
2551 raise NotImplementedError, "Please use idaapi.set_processor_type() to change processor"
2552 return _IDC_SetAttr(idaapi.cvar.inf, _INFMAP, offset, value)
2553
2554
2555def SetShortPrm(offset, value):
2556 SetLongPrm(offset, value)
2557
2558
2559def SetCharPrm (offset, value):
2560 SetLongPrm(offset, value)
2561
2562
2563INF_VERSION = 3 # short; Version of database
2564INF_PROCNAME = 5 # char[8]; Name of current processor
2565INF_LFLAGS = 13 # char; IDP-dependent flags
2566LFLG_PC_FPP = 0x01 # decode floating point processor
2567 # instructions?
2568LFLG_PC_FLAT = 0x02 # Flat model?
2569LFLG_64BIT = 0x04 # 64-bit program?
2570LFLG_DBG_NOPATH = 0x08 # do not store input full path
2571LFLG_SNAPSHOT = 0x10 # is memory snapshot?
2572 # in debugger process options
2573INF_DEMNAMES = 14 # char; display demangled names as:
2574DEMNAM_CMNT = 0 # comments
2575DEMNAM_NAME = 1 # regular names
2576DEMNAM_NONE = 2 # don't display
2577INF_FILETYPE = 15 # short; type of input file (see ida.hpp)
2578FT_EXE_OLD = 0 # MS DOS EXE File (obsolete)
2579FT_COM_OLD = 1 # MS DOS COM File (obsolete)
2580FT_BIN = 2 # Binary File
2581FT_DRV = 3 # MS DOS Driver
2582FT_WIN = 4 # New Executable (NE)
2583FT_HEX = 5 # Intel Hex Object File
2584FT_MEX = 6 # MOS Technology Hex Object File
2585FT_LX = 7 # Linear Executable (LX)
2586FT_LE = 8 # Linear Executable (LE)
2587FT_NLM = 9 # Netware Loadable Module (NLM)
2588FT_COFF = 10 # Common Object File Format (COFF)
2589FT_PE = 11 # Portable Executable (PE)
2590FT_OMF = 12 # Object Module Format
2591FT_SREC = 13 # R-records
2592FT_ZIP = 14 # ZIP file (this file is never loaded to IDA database)
2593FT_OMFLIB = 15 # Library of OMF Modules
2594FT_AR = 16 # ar library
2595FT_LOADER = 17 # file is loaded using LOADER DLL
2596FT_ELF = 18 # Executable and Linkable Format (ELF)
2597FT_W32RUN = 19 # Watcom DOS32 Extender (W32RUN)
2598FT_AOUT = 20 # Linux a.out (AOUT)
2599FT_PRC = 21 # PalmPilot program file
2600FT_EXE = 22 # MS DOS EXE File
2601FT_COM = 23 # MS DOS COM File
2602FT_AIXAR = 24 # AIX ar library
2603INF_FCORESIZ = 17
2604INF_CORESTART = 21
2605INF_OSTYPE = 25 # short; FLIRT: OS type the program is for
2606OSTYPE_MSDOS = 0x0001
2607OSTYPE_WIN = 0x0002
2608OSTYPE_OS2 = 0x0004
2609OSTYPE_NETW = 0x0008
2610INF_APPTYPE = 27 # short; FLIRT: Application type
2611APPT_CONSOLE = 0x0001 # console
2612APPT_GRAPHIC = 0x0002 # graphics
2613APPT_PROGRAM = 0x0004 # EXE
2614APPT_LIBRARY = 0x0008 # DLL
2615APPT_DRIVER = 0x0010 # DRIVER
2616APPT_1THREAD = 0x0020 # Singlethread
2617APPT_MTHREAD = 0x0040 # Multithread
2618APPT_16BIT = 0x0080 # 16 bit application
2619APPT_32BIT = 0x0100 # 32 bit application
2620INF_START_SP = 29 # long; SP register value at the start of
2621 # program execution
2622INF_START_AF = 33 # short; Analysis flags:
2623AF_FIXUP = 0x0001 # Create offsets and segments using fixup info
2624AF_MARKCODE = 0x0002 # Mark typical code sequences as code
2625AF_UNK = 0x0004 # Delete instructions with no xrefs
2626AF_CODE = 0x0008 # Trace execution flow
2627AF_PROC = 0x0010 # Create functions if call is present
2628AF_USED = 0x0020 # Analyze and create all xrefs
2629AF_FLIRT = 0x0040 # Use flirt signatures
2630AF_PROCPTR = 0x0080 # Create function if data xref data->code32 exists
2631AF_JFUNC = 0x0100 # Rename jump functions as j_...
2632AF_NULLSUB = 0x0200 # Rename empty functions as nullsub_...
2633AF_LVAR = 0x0400 # Create stack variables
2634AF_TRACE = 0x0800 # Trace stack pointer
2635AF_ASCII = 0x1000 # Create ascii string if data xref exists
2636AF_IMMOFF = 0x2000 # Convert 32bit instruction operand to offset
2637AF_DREFOFF = 0x4000 # Create offset if data xref to seg32 exists
2638AF_FINAL = 0x8000 # Final pass of analysis
2639INF_START_IP = 35 # long; IP register value at the start of
2640 # program execution
2641INF_BEGIN_EA = 39 # long; Linear address of program entry point
2642INF_MIN_EA = 43 # long; The lowest address used
2643 # in the program
2644INF_MAX_EA = 47 # long; The highest address used
2645 # in the program - = 1
2646INF_OMIN_EA = 51
2647INF_OMAX_EA = 55
2648INF_LOW_OFF = 59 # long; low limit of voids
2649INF_HIGH_OFF = 63 # long; high limit of voids
2650INF_MAXREF = 67 # long; max xref depth
2651INF_ASCII_BREAK = 71 # char; ASCII line break symbol
2652INF_WIDE_HIGH_BYTE_FIRST = 72
2653INF_INDENT = 73 # char; Indention for instructions
2654INF_COMMENT = 74 # char; Indention for comments
2655INF_XREFNUM = 75 # char; Number of references to generate
2656 # = 0 - xrefs wont be generated at all
2657INF_ENTAB = 76 # char; Use '\t' chars in the output file?
2658INF_SPECSEGS = 77
2659INF_VOIDS = 78 # char; Display void marks?
2660INF_SHOWAUTO = 80 # char; Display autoanalysis indicator?
2661INF_AUTO = 81 # char; Autoanalysis is enabled?
2662INF_BORDER = 82 # char; Generate borders?
2663INF_NULL = 83 # char; Generate empty lines?
2664INF_GENFLAGS = 84 # char; General flags:
2665INFFL_LZERO = 0x01 # generate leading zeroes in numbers
2666INFFL_LOADIDC = 0x04 # Loading an idc file t
2667INF_SHOWPREF = 85 # char; Show line prefixes?
2668INF_PREFSEG = 86 # char; line prefixes with segment name?
2669INF_ASMTYPE = 87 # char; target assembler number (0..n)
2670INF_BASEADDR = 88 # long; base paragraph of the program
2671INF_XREFS = 92 # char; xrefs representation:
2672SW_SEGXRF = 0x01 # show segments in xrefs?
2673SW_XRFMRK = 0x02 # show xref type marks?
2674SW_XRFFNC = 0x04 # show function offsets?
2675SW_XRFVAL = 0x08 # show xref values? (otherwise-"...")
2676INF_BINPREF = 93 # short; # of instruction bytes to show
2677 # in line prefix
2678INF_CMTFLAG = 95 # char; comments:
2679SW_RPTCMT = 0x01 # show repeatable comments?
2680SW_ALLCMT = 0x02 # comment all lines?
2681SW_NOCMT = 0x04 # no comments at all
2682SW_LINNUM = 0x08 # show source line numbers
2683SW_MICRO = 0x10 # show microcode (if implemented)
2684INF_NAMETYPE = 96 # char; dummy names represenation type
2685NM_REL_OFF = 0
2686NM_PTR_OFF = 1
2687NM_NAM_OFF = 2
2688NM_REL_EA = 3
2689NM_PTR_EA = 4
2690NM_NAM_EA = 5
2691NM_EA = 6
2692NM_EA4 = 7
2693NM_EA8 = 8
2694NM_SHORT = 9
2695NM_SERIAL = 10
2696INF_SHOWBADS = 97 # char; show bad instructions?
2697 # an instruction is bad if it appears
2698 # in the ash.badworks array
2699
2700INF_PREFFLAG = 98 # char; line prefix type:
2701PREF_SEGADR = 0x01 # show segment addresses?
2702PREF_FNCOFF = 0x02 # show function offsets?
2703PREF_STACK = 0x04 # show stack pointer?
2704
2705INF_PACKBASE = 99 # char; pack database?
2706
2707INF_ASCIIFLAGS = 100 # uchar; ascii flags
2708ASCF_GEN = 0x01 # generate ASCII names?
2709ASCF_AUTO = 0x02 # ASCII names have 'autogenerated' bit?
2710ASCF_SERIAL = 0x04 # generate serial names?
2711ASCF_COMMENT = 0x10 # generate auto comment for ascii references?
2712ASCF_SAVECASE = 0x20 # preserve case of ascii strings for identifiers
2713
2714INF_LISTNAMES = 101 # uchar; What names should be included in the list?
2715LN_NORMAL = 0x01 # normal names
2716LN_PUBLIC = 0x02 # public names
2717LN_AUTO = 0x04 # autogenerated names
2718LN_WEAK = 0x08 # weak names
2719
2720INF_ASCIIPREF = 102 # char[16];ASCII names prefix
2721INF_ASCIISERNUM = 118 # ulong; serial number
2722INF_ASCIIZEROES = 122 # char; leading zeroes
2723INF_MF = 126 # uchar; Byte order: 1==MSB first
2724INF_ORG = 127 # char; Generate 'org' directives?
2725INF_ASSUME = 128 # char; Generate 'assume' directives?
2726INF_CHECKARG = 129 # char; Check manual operands?
2727INF_START_SS = 130 # long; value of SS at the start
2728INF_START_CS = 134 # long; value of CS at the start
2729INF_MAIN = 138 # long; address of main()
2730INF_SHORT_DN = 142 # long; short form of demangled names
2731INF_LONG_DN = 146 # long; long form of demangled names
2732 # see demangle.h for definitions
2733INF_DATATYPES = 150 # long; data types allowed in data carousel
2734INF_STRTYPE = 154 # long; current ascii string type
2735 # is considered as several bytes:
2736 # low byte:
2737ASCSTR_TERMCHR = 0 # Character-terminated ASCII string
2738ASCSTR_C = 0 # C-string, zero terminated
2739ASCSTR_PASCAL = 1 # Pascal-style ASCII string (length byte)
2740ASCSTR_LEN2 = 2 # Pascal-style, length is 2 bytes
2741ASCSTR_UNICODE = 3 # Unicode string
2742ASCSTR_LEN4 = 4 # Delphi string, length is 4 bytes
2743ASCSTR_ULEN2 = 5 # Pascal-style Unicode, length is 2 bytes
2744ASCSTR_ULEN4 = 6 # Pascal-style Unicode, length is 4 bytes
2745
2746# = 2nd byte - termination chracters for ASCSTR_TERMCHR:
2747#STRTERM1(strtype) ((strtype>>8)&0xFF)
2748# = 3d byte:
2749#STRTERM2(strtype) ((strtype>>16)&0xFF)
2750 # The termination characters are kept in
2751 # the = 2nd and 3d bytes of string type
2752 # if the second termination character is
2753 # '\0', then it is ignored.
2754INF_AF2 = 158 # ushort; Analysis flags 2
2755AF2_JUMPTBL = 0x0001 # Locate and create jump tables
2756AF2_DODATA = 0x0002 # Coagulate data segs in final pass
2757AF2_HFLIRT = 0x0004 # Automatically hide library functions
2758AF2_STKARG = 0x0008 # Propagate stack argument information
2759AF2_REGARG = 0x0010 # Propagate register argument information
2760AF2_CHKUNI = 0x0020 # Check for unicode strings
2761AF2_SIGCMT = 0x0040 # Append a signature name comment for recognized anonymous library functions
2762AF2_SIGMLT = 0x0080 # Allow recognition of several copies of the same function
2763AF2_FTAIL = 0x0100 # Create function tails
2764AF2_DATOFF = 0x0200 # Automatically convert data to offsets
2765AF2_ANORET = 0x0400 # Perform 'no-return' analysis
2766AF2_VERSP = 0x0800 # Perform full stack pointer analysis
2767AF2_DOCODE = 0x1000 # Coagulate code segs at the final pass
2768AF2_TRFUNC = 0x2000 # Truncate functions upon code deletion
2769AF2_PURDAT = 0x4000 # Control flow to data segment is ignored
2770INF_NAMELEN = 160 # ushort; max name length (without zero byte)
2771INF_MARGIN = 162 # ushort; max length of data lines
2772INF_LENXREF = 164 # ushort; max length of line with xrefs
2773INF_LPREFIX = 166 # char[16];prefix of local names
2774 # if a new name has this prefix,
2775 # it will be automatically converted to a local name
2776INF_LPREFIXLEN = 182 # uchar; length of the lprefix
2777INF_COMPILER = 183 # uchar; compiler
2778COMP_MASK = 0x0F # mask to apply to get the pure compiler id
2779COMP_UNK = 0x00 # Unknown
2780COMP_MS = 0x01 # Visual C++
2781COMP_BC = 0x02 # Borland C++
2782COMP_WATCOM = 0x03 # Watcom C++
2783COMP_GNU = 0x06 # GNU C++
2784COMP_VISAGE = 0x07 # Visual Age C++
2785COMP_BP = 0x08 # Delphi
2786
2787INF_MODEL = 184 # uchar; memory model & calling convention
2788INF_SIZEOF_INT = 185 # uchar; sizeof(int)
2789INF_SIZEOF_BOOL = 186 # uchar; sizeof(bool)
2790INF_SIZEOF_ENUM = 187 # uchar; sizeof(enum)
2791INF_SIZEOF_ALGN = 188 # uchar; default alignment
2792INF_SIZEOF_SHORT = 189
2793INF_SIZEOF_LONG = 190
2794INF_SIZEOF_LLONG = 191
2795INF_CHANGE_COUNTER = 192 # database change counter; keeps track of byte and segment modifications
2796INF_SIZEOF_LDBL = 196 # uchar; sizeof(long double)
2797
2798# Redefine these offsets for 64-bit version
2799if __EA64__:
2800 INF_CORESTART = 25
2801 INF_OSTYPE = 33
2802 INF_APPTYPE = 35
2803 INF_START_SP = 37
2804 INF_AF = 45
2805 INF_START_IP = 47
2806 INF_BEGIN_EA = 55
2807 INF_MIN_EA = 63
2808 INF_MAX_EA = 71
2809 INF_OMIN_EA = 79
2810 INF_OMAX_EA = 87
2811 INF_LOW_OFF = 95
2812 INF_HIGH_OFF = 103
2813 INF_MAXREF = 111
2814 INF_ASCII_BREAK = 119
2815 INF_WIDE_HIGH_BYTE_FIRST = 120
2816 INF_INDENT = 121
2817 INF_COMMENT = 122
2818 INF_XREFNUM = 123
2819 INF_ENTAB = 124
2820 INF_SPECSEGS = 125
2821 INF_VOIDS = 126
2822 INF_SHOWAUTO = 128
2823 INF_AUTO = 129
2824 INF_BORDER = 130
2825 INF_NULL = 131
2826 INF_GENFLAGS = 132
2827 INF_SHOWPREF = 133
2828 INF_PREFSEG = 134
2829 INF_ASMTYPE = 135
2830 INF_BASEADDR = 136
2831 INF_XREFS = 144
2832 INF_BINPREF = 145
2833 INF_CMTFLAG = 147
2834 INF_NAMETYPE = 148
2835 INF_SHOWBADS = 149
2836 INF_PREFFLAG = 150
2837 INF_PACKBASE = 151
2838 INF_ASCIIFLAGS = 152
2839 INF_LISTNAMES = 153
2840 INF_ASCIIPREF = 154
2841 INF_ASCIISERNUM = 170
2842 INF_ASCIIZEROES = 178
2843 INF_MF = 182
2844 INF_ORG = 183
2845 INF_ASSUME = 184
2846 INF_CHECKARG = 185
2847 INF_START_SS = 186
2848 INF_START_CS = 194
2849 INF_MAIN = 202
2850 INF_SHORT_DN = 210
2851 INF_LONG_DN = 218
2852 INF_DATATYPES = 226
2853 INF_STRTYPE = 234
2854 INF_AF2 = 242
2855 INF_NAMELEN = 244
2856 INF_MARGIN = 246
2857 INF_LENXREF = 248
2858 INF_LPREFIX = 250
2859 INF_LPREFIXLEN = 266
2860 INF_COMPILER = 267
2861 INF_MODEL = 268
2862 INF_SIZEOF_INT = 269
2863 INF_SIZEOF_BOOL = 270
2864 INF_SIZEOF_ENUM = 271
2865 INF_SIZEOF_ALGN = 272
2866 INF_SIZEOF_SHORT = 273
2867 INF_SIZEOF_LONG = 274
2868 INF_SIZEOF_LLONG = 275
2869 INF_CHANGE_COUNTER = 276
2870 INF_SIZEOF_LBDL = 280
2871
2872_INFMAP = {
2873INF_VERSION : (False, 'version'), # short; Version of database
2874INF_PROCNAME : (False, 'procName'), # char[8]; Name of current processor
2875INF_LFLAGS : (False, 'lflags'), # char; IDP-dependent flags
2876INF_DEMNAMES : (False, 'demnames'), # char; display demangled names as:
2877INF_FILETYPE : (False, 'filetype'), # short; type of input file (see ida.hpp)
2878INF_FCORESIZ : (False, 'fcoresize'),
2879INF_CORESTART : (False, 'corestart'),
2880INF_OSTYPE : (False, 'ostype'), # short; FLIRT: OS type the program is for
2881INF_APPTYPE : (False, 'apptype'), # short; FLIRT: Application type
2882INF_START_SP : (False, 'startSP'), # long; SP register value at the start of
2883INF_START_AF : (False, 'af'), # short; Analysis flags:
2884INF_START_IP : (False, 'startIP'), # long; IP register value at the start of
2885INF_BEGIN_EA : (False, 'beginEA'), # long; Linear address of program entry point
2886INF_MIN_EA : (False, 'minEA'), # long; The lowest address used
2887INF_MAX_EA : (False, 'maxEA'), # long; The highest address used
2888INF_OMIN_EA : (False, 'ominEA'),
2889INF_OMAX_EA : (False, 'omaxEA'),
2890INF_LOW_OFF : (False, 'lowoff'), # long; low limit of voids
2891INF_HIGH_OFF : (False, 'highoff'), # long; high limit of voids
2892INF_MAXREF : (False, 'maxref'), # long; max xref depth
2893INF_ASCII_BREAK : (False, 'ASCIIbreak'), # char; ASCII line break symbol
2894INF_WIDE_HIGH_BYTE_FIRST : (False, 'wide_high_byte_first'),
2895INF_INDENT : (False, 'indent'), # char; Indention for instructions
2896INF_COMMENT : (False, 'comment'), # char; Indention for comments
2897INF_XREFNUM : (False, 'xrefnum'), # char; Number of references to generate
2898INF_ENTAB : (False, 's_entab'), # char; Use '\t' chars in the output file?
2899INF_SPECSEGS : (False, 'specsegs'),
2900INF_VOIDS : (False, 's_void'), # char; Display void marks?
2901INF_SHOWAUTO : (False, 's_showauto'), # char; Display autoanalysis indicator?
2902INF_AUTO : (False, 's_auto'), # char; Autoanalysis is enabled?
2903INF_BORDER : (False, 's_limiter'), # char; Generate borders?
2904INF_NULL : (False, 's_null'), # char; Generate empty lines?
2905INF_GENFLAGS : (False, 's_genflags'), # char; General flags:
2906INF_SHOWPREF : (False, 's_showpref'), # char; Show line prefixes?
2907INF_PREFSEG : (False, 's_prefseg'), # char; line prefixes with segment name?
2908INF_ASMTYPE : (False, 'asmtype'), # char; target assembler number (0..n)
2909INF_BASEADDR : (False, 'baseaddr'), # long; base paragraph of the program
2910INF_XREFS : (False, 's_xrefflag'), # char; xrefs representation:
2911INF_BINPREF : (False, 'binSize'), # short; # of instruction bytes to show
2912INF_CMTFLAG : (False, 's_cmtflg'), # char; comments:
2913INF_NAMETYPE : (False, 'nametype'), # char; dummy names represenation type
2914INF_SHOWBADS : (False, 's_showbads'), # char; show bad instructions?
2915INF_PREFFLAG : (False, 's_prefflag'), # char; line prefix type:
2916INF_PACKBASE : (False, 's_packbase'), # char; pack database?
2917INF_ASCIIFLAGS : (False, 'asciiflags'), # uchar; ascii flags
2918INF_LISTNAMES : (False, 'listnames'), # uchar; What names should be included in the list?
2919INF_ASCIIPREF : (False, 'ASCIIpref'), # char[16];ASCII names prefix
2920INF_ASCIISERNUM : (False, 'ASCIIsernum'), # ulong; serial number
2921INF_ASCIIZEROES : (False, 'ASCIIzeroes'), # char; leading zeroes
2922INF_MF : (False, 'mf'), # uchar; Byte order: 1==MSB first
2923INF_ORG : (False, 's_org'), # char; Generate 'org' directives?
2924INF_ASSUME : (False, 's_assume'), # char; Generate 'assume' directives?
2925INF_CHECKARG : (False, 's_checkarg'), # char; Check manual operands?
2926INF_START_SS : (False, 'start_ss'), # long; value of SS at the start
2927INF_START_CS : (False, 'start_cs'), # long; value of CS at the start
2928INF_MAIN : (False, 'main'), # long; address of main()
2929INF_SHORT_DN : (False, 'short_demnames'), # long; short form of demangled names
2930INF_LONG_DN : (False, 'long_demnames'), # long; long form of demangled names
2931INF_DATATYPES : (False, 'datatypes'), # long; data types allowed in data carousel
2932INF_STRTYPE : (False, 'strtype'), # long; current ascii string type
2933INF_AF2 : (False, 'af2'), # ushort; Analysis flags 2
2934INF_NAMELEN : (False, 'namelen'), # ushort; max name length (without zero byte)
2935INF_MARGIN : (False, 'margin'), # ushort; max length of data lines
2936INF_LENXREF : (False, 'lenxref'), # ushort; max length of line with xrefs
2937INF_LPREFIX : (False, 'lprefix'), # char[16];prefix of local names
2938INF_LPREFIXLEN : (False, 'lprefixlen'), # uchar; length of the lprefix
2939INF_COMPILER : (False, 'cc') # uchar; compiler
2940
2941#INF_MODEL = 184 # uchar; memory model & calling convention
2942#INF_SIZEOF_INT = 185 # uchar; sizeof(int)
2943#INF_SIZEOF_BOOL = 186 # uchar; sizeof(bool)
2944#INF_SIZEOF_ENUM = 187 # uchar; sizeof(enum)
2945#INF_SIZEOF_ALGN = 188 # uchar; default alignment
2946#INF_SIZEOF_SHORT = 189
2947#INF_SIZEOF_LONG = 190
2948#INF_SIZEOF_LLONG = 191
2949}
2950
2951
2952def SetProcessorType (processor, level):
2953 """
2954 Change current processor
2955
2956 @param processor: name of processor in short form.
2957 run 'ida ?' to get list of allowed processor types
2958 @param level: the power of request:
2959 - SETPROC_COMPAT - search for the processor type in the current module
2960 - SETPROC_ALL - search for the processor type in all modules
2961 only if there were not calls with SETPROC_USER
2962 - SETPROC_USER - search for the processor type in all modules
2963 and prohibit level SETPROC_USER
2964 - SETPROC_FATAL - can be combined with previous bits.
2965 means that if the processor type can't be
2966 set, IDA should display an error message and exit.
2967 """
2968 return idaapi.set_processor_type(processor, level)
2969
2970def SetTargetAssembler(asmidx):
2971 """
2972 Set target assembler
2973 @param asmidx: index of the target assembler in the array of
2974 assemblers for the current processor.
2975
2976 @return: 1-ok, 0-failed
2977 """
2978 return idaapi.set_target_assembler(asmidx)
2979
2980SETPROC_COMPAT = idaapi.SETPROC_COMPAT
2981SETPROC_ALL = idaapi.SETPROC_ALL
2982SETPROC_USER = idaapi.SETPROC_USER
2983SETPROC_FATAL = idaapi.SETPROC_FATAL
2984
2985def SetPrcsr(processor): return SetProcessorType(processor, SETPROC_COMPAT)
2986
2987
2988def Batch(batch):
2989 """
2990 Enable/disable batch mode of operation
2991
2992 @param batch: Batch mode
2993 0 - ida will display dialog boxes and wait for the user input
2994 1 - ida will not display dialog boxes, warnings, etc.
2995
2996 @return: old balue of batch flag
2997 """
2998 batch_prev = idaapi.cvar.batch
2999 idaapi.cvar.batch = batch
3000 return batch_prev
3001
3002
3003#----------------------------------------------------------------------------
3004# I N T E R A C T I O N W I T H T H E U S E R
3005#----------------------------------------------------------------------------
3006def AskStr(defval, prompt):
3007 """
3008 Ask the user to enter a string
3009
3010 @param defval: the default string value. This value will appear
3011 in the dialog box.
3012 @param prompt: the prompt to display in the dialog box
3013
3014 @return: the entered string or None.
3015 """
3016 return idaapi.askstr(0, defval, prompt)
3017
3018
3019def AskFile(forsave, mask, prompt):
3020 """
3021 Ask the user to choose a file
3022
3023 @param forsave: 0: "Open" dialog box, 1: "Save" dialog box
3024 @param mask: the input file mask as "*.*" or the default file name.
3025 @param prompt: the prompt to display in the dialog box
3026
3027 @return: the selected file or None.
3028 """
3029 return idaapi.askfile_c(forsave, mask, prompt)
3030
3031
3032def AskAddr(defval, prompt):
3033 """
3034 Ask the user to enter an address
3035
3036 @param defval: an ea_t designating the default address value. This value
3037 will appear in the dialog box.
3038 @param prompt: the prompt to display in the dialog box
3039
3040 @return: the entered address or BADADDR.
3041 """
3042 return idaapi.askaddr(defval, prompt)
3043
3044
3045def AskLong(defval, prompt):
3046 """
3047 Ask the user to enter a number
3048
3049 @param defval: a number designating the default value. This value
3050 will appear in the dialog box.
3051 @param prompt: the prompt to display in the dialog box
3052
3053 @return: the entered number or -1.
3054 """
3055 return idaapi.asklong(defval, prompt)
3056
3057
3058def ProcessUiAction(name, flags=0):
3059 """
3060 Invokes an IDA UI action by name
3061
3062 @param name: Command name
3063 @param flags: Reserved. Must be zero
3064 @return: Boolean
3065 """
3066 return idaapi.process_ui_action(name, flags)
3067
3068
3069def AskSeg(defval, prompt):
3070 """
3071 Ask the user to enter a segment value
3072
3073 @param defval: the default value. This value
3074 will appear in the dialog box.
3075 @param prompt: the prompt to display in the dialog box
3076
3077 @return: the entered segment selector or BADSEL.
3078 """
3079 return idaapi.askseg(defval, prompt)
3080
3081
3082def AskIdent(defval, prompt):
3083 """
3084 Ask the user to enter an identifier
3085
3086 @param defval: the default identifier. This value will appear in
3087 the dialog box.
3088 @param prompt: the prompt to display in the dialog box
3089
3090 @return: the entered identifier or None.
3091 """
3092 return idaapi.askident(defval, prompt)
3093
3094
3095def AskYN(defval, prompt):
3096 """
3097 Ask the user a question and let him answer Yes/No/Cancel
3098
3099 @param defval: the default answer. This answer will be selected if the user
3100 presses Enter. -1:cancel,0-no,1-ok
3101 @param prompt: the prompt to display in the dialog box
3102
3103 @return: -1:cancel,0-no,1-ok
3104 """
3105 return idaapi.askyn_c(defval, prompt)
3106
3107
3108def Message(msg):
3109 """
3110 Display a message in the message window
3111
3112 @param msg: message to print (formatting is done in Python)
3113
3114 This function can be used to debug IDC scripts
3115 """
3116 idaapi.msg(msg)
3117
3118
3119def Warning(msg):
3120 """
3121 Display a message in a message box
3122
3123 @param msg: message to print (formatting is done in Python)
3124
3125 This function can be used to debug IDC scripts
3126 The user will be able to hide messages if they appear twice in a row on
3127 the screen
3128 """
3129 idaapi.warning(msg)
3130
3131
3132def Fatal(format):
3133 """
3134 Display a fatal message in a message box and quit IDA
3135
3136 @param format: message to print
3137 """
3138 idaapi.error(format)
3139
3140
3141def SetStatus(status):
3142 """
3143 Change IDA indicator.
3144
3145 @param status: new status
3146
3147 @return: the previous status.
3148 """
3149 return idaapi.setStat(status)
3150
3151
3152IDA_STATUS_READY = 0 # READY IDA is idle
3153IDA_STATUS_THINKING = 1 # THINKING Analyzing but the user may press keys
3154IDA_STATUS_WAITING = 2 # WAITING Waiting for the user input
3155IDA_STATUS_WORK = 3 # BUSY IDA is busy
3156
3157
3158def Refresh():
3159 """
3160 Refresh all disassembly views
3161 """
3162 idaapi.refresh_idaview_anyway()
3163
3164
3165def RefreshLists():
3166 """
3167 Refresh all list views (names, functions, etc)
3168 """
3169 idaapi.refresh_lists()
3170
3171
3172#----------------------------------------------------------------------------
3173# S E G M E N T A T I O N
3174#----------------------------------------------------------------------------
3175def AskSelector(sel):
3176 """
3177 Get a selector value
3178
3179 @param sel: the selector number
3180
3181 @return: selector value if found
3182 otherwise the input value (sel)
3183
3184 @note: selector values are always in paragraphs
3185 """
3186 s = idaapi.sel_pointer()
3187 base = idaapi.ea_pointer()
3188 res,tmp = idaapi.getn_selector(sel, s.cast(), base.cast())
3189
3190 if not res:
3191 return sel
3192 else:
3193 return base.value()
3194
3195
3196def FindSelector(val):
3197 """
3198 Find a selector which has the specifed value
3199
3200 @param val: value to search for
3201
3202 @return: the selector number if found,
3203 otherwise the input value (val & 0xFFFF)
3204
3205 @note: selector values are always in paragraphs
3206 """
3207 return idaapi.find_selector(val) & 0xFFFF
3208
3209
3210def SetSelector(sel, value):
3211 """
3212 Set a selector value
3213
3214 @param sel: the selector number
3215 @param value: value of selector
3216
3217 @return: None
3218
3219 @note: ida supports up to 4096 selectors.
3220 if 'sel' == 'val' then the selector is destroyed because
3221 it has no significance
3222 """
3223 return idaapi.set_selector(sel, value)
3224
3225
3226def DelSelector(sel):
3227 """
3228 Delete a selector
3229
3230 @param sel: the selector number to delete
3231
3232 @return: None
3233
3234 @note: if the selector is found, it will be deleted
3235 """
3236 return idaapi.del_selector(sel)
3237
3238
3239def FirstSeg():
3240 """
3241 Get first segment
3242
3243 @return: address of the start of the first segment
3244 BADADDR - no segments are defined
3245 """
3246 seg = idaapi.get_first_seg()
3247 if not seg:
3248 return BADADDR
3249 else:
3250 return seg.startEA
3251
3252
3253def NextSeg(ea):
3254 """
3255 Get next segment
3256
3257 @param ea: linear address
3258
3259 @return: start of the next segment
3260 BADADDR - no next segment
3261 """
3262 nextseg = idaapi.get_next_seg(ea)
3263 if not nextseg:
3264 return BADADDR
3265 else:
3266 return nextseg.startEA
3267
3268 return BADADDR
3269
3270
3271def SegStart(ea):
3272 """
3273 Get start address of a segment
3274
3275 @param ea: any address in the segment
3276
3277 @return: start of segment
3278 BADADDR - the specified address doesn't belong to any segment
3279 """
3280 seg = idaapi.getseg(ea)
3281
3282 if not seg:
3283 return BADADDR
3284 else:
3285 return seg.startEA
3286
3287
3288def SegEnd(ea):
3289 """
3290 Get end address of a segment
3291
3292 @param ea: any address in the segment
3293
3294 @return: end of segment (an address past end of the segment)
3295 BADADDR - the specified address doesn't belong to any segment
3296 """
3297 seg = idaapi.getseg(ea)
3298
3299 if not seg:
3300 return BADADDR
3301 else:
3302 return seg.endEA
3303
3304
3305def SegName(ea):
3306 """
3307 Get name of a segment
3308
3309 @param ea: any address in the segment
3310
3311 @return: "" - no segment at the specified address
3312 """
3313 seg = idaapi.getseg(ea)
3314
3315 if not seg:
3316 return ""
3317 else:
3318 name = idaapi.get_true_segm_name(seg)
3319
3320 if not name:
3321 return ""
3322 else:
3323 return name
3324
3325
3326def AddSegEx(startea, endea, base, use32, align, comb, flags):
3327 """
3328 Create a new segment
3329
3330 @param startea: linear address of the start of the segment
3331 @param endea: linear address of the end of the segment
3332 this address will not belong to the segment
3333 'endea' should be higher than 'startea'
3334 @param base: base paragraph or selector of the segment.
3335 a paragraph is 16byte memory chunk.
3336 If a selector value is specified, the selector should be
3337 already defined.
3338 @param use32: 0: 16bit segment, 1: 32bit segment, 2: 64bit segment
3339 @param align: segment alignment. see below for alignment values
3340 @param comb: segment combination. see below for combination values.
3341 @param flags: combination of ADDSEG_... bits
3342
3343 @return: 0-failed, 1-ok
3344 """
3345 s = idaapi.segment_t()
3346 s.startEA = startea
3347 s.endEA = endea
3348 s.sel = idaapi.setup_selector(base)
3349 s.bitness = use32
3350 s.align = align
3351 s.comb = comb
3352 return idaapi.add_segm_ex(s, "", "", flags)
3353
3354ADDSEG_NOSREG = idaapi.ADDSEG_NOSREG # set all default segment register values
3355 # to BADSELs
3356 # (undefine all default segment registers)
3357ADDSEG_OR_DIE = idaapi. ADDSEG_OR_DIE # qexit() if can't add a segment
3358ADDSEG_NOTRUNC = idaapi.ADDSEG_NOTRUNC # don't truncate the new segment at the beginning
3359 # of the next segment if they overlap.
3360 # destroy/truncate old segments instead.
3361ADDSEG_QUIET = idaapi.ADDSEG_QUIET # silent mode, no "Adding segment..." in the messages window
3362ADDSEG_FILLGAP = idaapi.ADDSEG_FILLGAP # If there is a gap between the new segment
3363 # and the previous one, and this gap is less
3364 # than 64K, then fill the gap by extending the
3365 # previous segment and adding .align directive
3366 # to it. This way we avoid gaps between segments.
3367 # Too many gaps lead to a virtual array failure.
3368 # It can not hold more than ~1000 gaps.
3369ADDSEG_SPARSE = idaapi.ADDSEG_SPARSE # Use sparse storage method for the new segment
3370
3371def AddSeg(startea, endea, base, use32, align, comb):
3372 return AddSegEx(startea, endea, base, use32, align, comb, ADDSEG_NOSREG)
3373
3374def DelSeg(ea, flags):
3375 """
3376 Delete a segment
3377
3378 @param ea: any address in the segment
3379 @param flags: combination of SEGMOD_* flags
3380
3381 @return: boolean success
3382 """
3383 return idaapi.del_segm(ea, flags)
3384
3385SEGMOD_KILL = idaapi.SEGMOD_KILL # disable addresses if segment gets
3386 # shrinked or deleted
3387SEGMOD_KEEP = idaapi.SEGMOD_KEEP # keep information (code & data, etc)
3388SEGMOD_SILENT = idaapi.SEGMOD_SILENT # be silent
3389
3390
3391def SetSegBounds(ea, startea, endea, flags):
3392 """
3393 Change segment boundaries
3394
3395 @param ea: any address in the segment
3396 @param startea: new start address of the segment
3397 @param endea: new end address of the segment
3398 @param flags: combination of SEGMOD_... flags
3399
3400 @return: boolean success
3401 """
3402 return idaapi.set_segm_start(ea, startea, flags) & \
3403 idaapi.set_segm_end(ea, endea, flags)
3404
3405
3406def RenameSeg(ea, name):
3407 """
3408 Change name of the segment
3409
3410 @param ea: any address in the segment
3411 @param name: new name of the segment
3412
3413 @return: success (boolean)
3414 """
3415 seg = idaapi.getseg(ea)
3416
3417 if not seg:
3418 return False
3419
3420 return idaapi.set_segm_name(seg, name)
3421
3422
3423def SetSegClass(ea, segclass):
3424 """
3425 Change class of the segment
3426
3427 @param ea: any address in the segment
3428 @param segclass: new class of the segment
3429
3430 @return: success (boolean)
3431 """
3432 seg = idaapi.getseg(ea)
3433
3434 if not seg:
3435 return False
3436
3437 return idaapi.set_segm_class(seg, segclass)
3438
3439
3440def SegAlign(ea, alignment):
3441 """
3442 Change alignment of the segment
3443
3444 @param ea: any address in the segment
3445 @param alignment: new alignment of the segment (one of the sa... constants)
3446
3447 @return: success (boolean)
3448 """
3449 return SetSegmentAttr(ea, SEGATTR_ALIGN, alignment)
3450
3451
3452saAbs = idaapi.saAbs # Absolute segment.
3453saRelByte = idaapi.saRelByte # Relocatable, byte aligned.
3454saRelWord = idaapi.saRelWord # Relocatable, word (2-byte, 16-bit) aligned.
3455saRelPara = idaapi.saRelPara # Relocatable, paragraph (16-byte) aligned.
3456saRelPage = idaapi.saRelPage # Relocatable, aligned on 256-byte boundary
3457 # (a "page" in the original Intel specification).
3458saRelDble = idaapi.saRelDble # Relocatable, aligned on a double word
3459 # (4-byte) boundary. This value is used by
3460 # the PharLap OMF for the same alignment.
3461saRel4K = idaapi.saRel4K # This value is used by the PharLap OMF for
3462 # page (4K) alignment. It is not supported
3463 # by LINK.
3464saGroup = idaapi.saGroup # Segment group
3465saRel32Bytes = idaapi.saRel32Bytes # 32 bytes
3466saRel64Bytes = idaapi.saRel64Bytes # 64 bytes
3467saRelQword = idaapi.saRelQword # 8 bytes
3468
3469
3470def SegComb(segea, comb):
3471 """
3472 Change combination of the segment
3473
3474 @param segea: any address in the segment
3475 @param comb: new combination of the segment (one of the sc... constants)
3476
3477 @return: success (boolean)
3478 """
3479 return SetSegmentAttr(segea, SEGATTR_COMB, comb)
3480
3481
3482scPriv = idaapi.scPriv # Private. Do not combine with any other program
3483 # segment.
3484scPub = idaapi.scPub # Public. Combine by appending at an offset that
3485 # meets the alignment requirement.
3486scPub2 = idaapi.scPub2 # As defined by Microsoft, same as C=2 (public).
3487scStack = idaapi.scStack # Stack. Combine as for C=2. This combine type
3488 # forces byte alignment.
3489scCommon = idaapi.scCommon # Common. Combine by overlay using maximum size.
3490scPub3 = idaapi.scPub3 # As defined by Microsoft, same as C=2 (public).
3491
3492
3493def SetSegAddressing(ea, bitness):
3494 """
3495 Change segment addressing
3496
3497 @param ea: any address in the segment
3498 @param bitness: 0: 16bit, 1: 32bit, 2: 64bit
3499
3500 @return: success (boolean)
3501 """
3502 seg = idaapi.getseg(ea)
3503
3504 if not seg:
3505 return False
3506
3507 seg.bitness = bitness
3508
3509 return True
3510
3511
3512def SegByName(segname):
3513 """
3514 Get segment by name
3515
3516 @param segname: name of segment
3517
3518 @return: segment selector or BADADDR
3519 """
3520 seg = idaapi.get_segm_by_name(segname)
3521
3522 if not seg:
3523 return BADADDR
3524
3525 return seg.sel
3526
3527
3528def SetSegDefReg(ea, reg, value):
3529 """
3530 Set default segment register value for a segment
3531
3532 @param ea: any address in the segment
3533 if no segment is present at the specified address
3534 then all segments will be affected
3535 @param reg: name of segment register
3536 @param value: default value of the segment register. -1-undefined.
3537 """
3538 seg = idaapi.getseg(ea)
3539
3540 reg = idaapi.str2reg(reg);
3541 if seg and reg >= 0:
3542 return idaapi.SetDefaultRegisterValue(seg, reg, value)
3543 else:
3544 return False
3545
3546
3547def SetSegmentType(segea, segtype):
3548 """
3549 Set segment type
3550
3551 @param segea: any address within segment
3552 @param segtype: new segment type:
3553
3554 @return: !=0 - ok
3555 """
3556 seg = idaapi.getseg(segea)
3557
3558 if not seg:
3559 return False
3560
3561 seg.type = segtype
3562 return seg.update()
3563
3564
3565SEG_NORM = idaapi.SEG_NORM
3566SEG_XTRN = idaapi.SEG_XTRN # * segment with 'extern' definitions
3567 # no instructions are allowed
3568SEG_CODE = idaapi.SEG_CODE # pure code segment
3569SEG_DATA = idaapi.SEG_DATA # pure data segment
3570SEG_IMP = idaapi.SEG_IMP # implementation segment
3571SEG_GRP = idaapi.SEG_GRP # * group of segments
3572 # no instructions are allowed
3573SEG_NULL = idaapi.SEG_NULL # zero-length segment
3574SEG_UNDF = idaapi.SEG_UNDF # undefined segment type
3575SEG_BSS = idaapi.SEG_BSS # uninitialized segment
3576SEG_ABSSYM = idaapi.SEG_ABSSYM # * segment with definitions of absolute symbols
3577 # no instructions are allowed
3578SEG_COMM = idaapi.SEG_COMM # * segment with communal definitions
3579 # no instructions are allowed
3580SEG_IMEM = idaapi.SEG_IMEM # internal processor memory & sfr (8051)
3581
3582
3583def GetSegmentAttr(segea, attr):
3584 """
3585 Get segment attribute
3586
3587 @param segea: any address within segment
3588 @param attr: one of SEGATTR_... constants
3589 """
3590 seg = idaapi.getseg(segea)
3591 assert seg, "could not find segment at 0x%x" % segea
3592 if attr in [ SEGATTR_ES, SEGATTR_CS, SEGATTR_SS, SEGATTR_DS, SEGATTR_FS, SEGATTR_GS ]:
3593 return idaapi.get_defsr(seg, _SEGATTRMAP[attr])
3594 else:
3595 return _IDC_GetAttr(seg, _SEGATTRMAP, attr)
3596
3597
3598def SetSegmentAttr(segea, attr, value):
3599 """
3600 Set segment attribute
3601
3602 @param segea: any address within segment
3603 @param attr: one of SEGATTR_... constants
3604
3605 @note: Please note that not all segment attributes are modifiable.
3606 Also some of them should be modified using special functions
3607 like SetSegAddressing, etc.
3608 """
3609 seg = idaapi.getseg(segea)
3610 assert seg, "could not find segment at 0x%x" % segea
3611 if attr in [ SEGATTR_ES, SEGATTR_CS, SEGATTR_SS, SEGATTR_DS, SEGATTR_FS, SEGATTR_GS ]:
3612 idaapi.set_defsr(seg, _SEGATTRMAP[attr], value)
3613 else:
3614 _IDC_SetAttr(seg, _SEGATTRMAP, attr, value)
3615 return seg.update()
3616
3617
3618SEGATTR_START = 0 # starting address
3619SEGATTR_END = 4 # ending address
3620SEGATTR_ORGBASE = 16
3621SEGATTR_ALIGN = 20 # alignment
3622SEGATTR_COMB = 21 # combination
3623SEGATTR_PERM = 22 # permissions
3624SEGATTR_BITNESS = 23 # bitness (0: 16, 1: 32, 2: 64 bit segment)
3625 # Note: modifying the attribute directly does
3626 # not lead to the reanalysis of the segment.
3627 # Using SetSegAddressing() is more correct.
3628SEGATTR_FLAGS = 24 # segment flags
3629SEGATTR_SEL = 26 # segment selector
3630SEGATTR_ES = 30 # default ES value
3631SEGATTR_CS = 34 # default CS value
3632SEGATTR_SS = 38 # default SS value
3633SEGATTR_DS = 42 # default DS value
3634SEGATTR_FS = 46 # default FS value
3635SEGATTR_GS = 50 # default GS value
3636SEGATTR_TYPE = 94 # segment type
3637SEGATTR_COLOR = 95 # segment color
3638
3639# Redefining these for 64-bit
3640if __EA64__:
3641 SEGATTR_START = 0
3642 SEGATTR_END = 8
3643 SEGATTR_ORGBASE = 32
3644 SEGATTR_ALIGN = 40
3645 SEGATTR_COMB = 41
3646 SEGATTR_PERM = 42
3647 SEGATTR_BITNESS = 43
3648 SEGATTR_FLAGS = 44
3649 SEGATTR_SEL = 46
3650 SEGATTR_ES = 54
3651 SEGATTR_CS = 62
3652 SEGATTR_SS = 70
3653 SEGATTR_DS = 78
3654 SEGATTR_FS = 86
3655 SEGATTR_GS = 94
3656 SEGATTR_TYPE = 182
3657 SEGATTR_COLOR = 183
3658
3659_SEGATTRMAP = {
3660 SEGATTR_START : (True, 'startEA'),
3661 SEGATTR_END : (True, 'endEA'),
3662 SEGATTR_ORGBASE : (False, 'orgbase'),
3663 SEGATTR_ALIGN : (False, 'align'),
3664 SEGATTR_COMB : (False, 'comb'),
3665 SEGATTR_PERM : (False, 'perm'),
3666 SEGATTR_BITNESS : (False, 'bitness'),
3667 SEGATTR_FLAGS : (False, 'flags'),
3668 SEGATTR_SEL : (False, 'sel'),
3669 SEGATTR_ES : (False, 0),
3670 SEGATTR_CS : (False, 1),
3671 SEGATTR_SS : (False, 2),
3672 SEGATTR_DS : (False, 3),
3673 SEGATTR_FS : (False, 4),
3674 SEGATTR_GS : (False, 5),
3675 SEGATTR_TYPE : (False, 'type'),
3676 SEGATTR_COLOR : (False, 'color'),
3677}
3678
3679# Valid segment flags
3680SFL_COMORG = 0x01 # IDP dependent field (IBM PC: if set, ORG directive is not commented out)
3681SFL_OBOK = 0x02 # orgbase is present? (IDP dependent field)
3682SFL_HIDDEN = 0x04 # is the segment hidden?
3683SFL_DEBUG = 0x08 # is the segment created for the debugger?
3684SFL_LOADER = 0x10 # is the segment created by the loader?
3685SFL_HIDETYPE = 0x20 # hide segment type (do not print it in the listing)
3686
3687
3688def MoveSegm(ea, to, flags):
3689 """
3690 Move a segment to a new address
3691 This function moves all information to the new address
3692 It fixes up address sensitive information in the kernel
3693 The total effect is equal to reloading the segment to the target address
3694
3695 @param ea: any address within the segment to move
3696 @param to: new segment start address
3697 @param flags: combination MFS_... constants
3698
3699 @returns: MOVE_SEGM_... error code
3700 """
3701 seg = idaapi.getseg(ea)
3702 if not seg:
3703 return MOVE_SEGM_PARAM
3704 return idaapi.move_segm(seg, to, flags)
3705
3706
3707MSF_SILENT = 0x0001 # don't display a "please wait" box on the screen
3708MSF_NOFIX = 0x0002 # don't call the loader to fix relocations
3709MSF_LDKEEP = 0x0004 # keep the loader in the memory (optimization)
3710MSF_FIXONCE = 0x0008 # valid for rebase_program(): call loader only once
3711
3712MOVE_SEGM_OK = 0 # all ok
3713MOVE_SEGM_PARAM = -1 # The specified segment does not exist
3714MOVE_SEGM_ROOM = -2 # Not enough free room at the target address
3715MOVE_SEGM_IDP = -3 # IDP module forbids moving the segment
3716MOVE_SEGM_CHUNK = -4 # Too many chunks are defined, can't move
3717MOVE_SEGM_LOADER = -5 # The segment has been moved but the loader complained
3718MOVE_SEGM_ODD = -6 # Can't move segments by an odd number of bytes
3719
3720
3721def rebase_program(delta, flags):
3722 """
3723 Rebase the whole program by 'delta' bytes
3724
3725 @param delta: number of bytes to move the program
3726 @param flags: combination of MFS_... constants
3727 it is recommended to use MSF_FIXONCE so that the loader takes
3728 care of global variables it stored in the database
3729
3730 @returns: error code MOVE_SEGM_...
3731 """
3732 return idaapi.rebase_program(delta, flags)
3733
3734
3735def SetStorageType(startEA, endEA, stt):
3736 """
3737 Set storage type
3738
3739 @param startEA: starting address
3740 @param endEA: ending address
3741 @param stt: new storage type, one of STT_VA and STT_MM
3742
3743 @returns: 0 - ok, otherwise internal error code
3744 """
3745 return idaapi.change_storage_type(startEA, endEA, stt)
3746
3747
3748STT_VA = 0 # regular storage: virtual arrays, an explicit flag for each byte
3749STT_MM = 1 # memory map: sparse storage. useful for huge objects
3750
3751
3752#----------------------------------------------------------------------------
3753# C R O S S R E F E R E N C E S
3754#----------------------------------------------------------------------------
3755# Flow types (combine with XREF_USER!):
3756fl_CF = 16 # Call Far
3757fl_CN = 17 # Call Near
3758fl_JF = 18 # Jump Far
3759fl_JN = 19 # Jump Near
3760fl_F = 21 # Ordinary flow
3761
3762XREF_USER = 32 # All user-specified xref types
3763 # must be combined with this bit
3764
3765
3766# Mark exec flow 'from' 'to'
3767def AddCodeXref(From, To, flowtype):
3768 """
3769 """
3770 return idaapi.add_cref(From, To, flowtype)
3771
3772
3773def DelCodeXref(From, To, undef):
3774 """
3775 Unmark exec flow 'from' 'to'
3776
3777 @param undef: make 'To' undefined if no more references to it
3778
3779 @returns: 1 - planned to be made undefined
3780 """
3781 return idaapi.del_cref(From, To, undef)
3782
3783
3784# The following functions include the ordinary flows:
3785# (the ordinary flow references are returned first)
3786def Rfirst(From):
3787 """
3788 Get first code xref from 'From'
3789 """
3790 return idaapi.get_first_cref_from(From)
3791
3792
3793def Rnext(From, current):
3794 """
3795 Get next code xref from
3796 """
3797 return idaapi.get_next_cref_from(From, current)
3798
3799
3800def RfirstB(To):
3801 """
3802 Get first code xref to 'To'
3803 """
3804 return idaapi.get_first_cref_to(To)
3805
3806
3807def RnextB(To, current):
3808 """
3809 Get next code xref to 'To'
3810 """
3811 return idaapi.get_next_cref_to(To, current)
3812
3813
3814# The following functions don't take into account the ordinary flows:
3815def Rfirst0(From):
3816 """
3817 Get first xref from 'From'
3818 """
3819 return idaapi.get_first_fcref_from(From)
3820
3821
3822def Rnext0(From, current):
3823 """
3824 Get next xref from
3825 """
3826 return idaapi.get_next_fcref_from(From, current)
3827
3828
3829def RfirstB0(To):
3830 """
3831 Get first xref to 'To'
3832 """
3833 return idaapi.get_first_fcref_to(To)
3834
3835
3836def RnextB0(To, current):
3837 """
3838 Get next xref to 'To'
3839 """
3840 return idaapi.get_next_fcref_to(To, current)
3841
3842
3843# Data reference types (combine with XREF_USER!):
3844dr_O = idaapi.dr_O # Offset
3845dr_W = idaapi.dr_W # Write
3846dr_R = idaapi.dr_R # Read
3847dr_T = idaapi.dr_T # Text (names in manual operands)
3848dr_I = idaapi.dr_I # Informational
3849
3850
3851def add_dref(From, To, drefType):
3852 """
3853 Create Data Ref
3854 """
3855 return idaapi.add_dref(From, To, drefType)
3856
3857
3858def del_dref(From, To):
3859 """
3860 Unmark Data Ref
3861 """
3862 return idaapi.del_dref(From, To)
3863
3864
3865def Dfirst(From):
3866 """
3867 Get first data xref from 'From'
3868 """
3869 return idaapi.get_first_dref_from(From)
3870
3871
3872def Dnext(From, current):
3873 """
3874 Get next data xref from 'From'
3875 """
3876 return idaapi.get_next_dref_from(From, current)
3877
3878
3879def DfirstB(To):
3880 """
3881 Get first data xref to 'To'
3882 """
3883 return idaapi.get_first_dref_to(To)
3884
3885
3886def DnextB(To, current):
3887 """
3888 Get next data xref to 'To'
3889 """
3890 return idaapi.get_next_dref_to(To, current)
3891
3892
3893def XrefType():
3894 """
3895 Return type of the last xref obtained by
3896 [RD]first/next[B0] functions.
3897
3898 @return: constants fl_* or dr_*
3899 """
3900 raise DeprecatedIDCError, "use XrefsFrom() XrefsTo() from idautils instead."
3901
3902
3903#----------------------------------------------------------------------------
3904# F I L E I / O
3905#----------------------------------------------------------------------------
3906def fopen(f, mode):
3907 raise DeprecatedIDCError, "fopen() deprecated. Use Python file objects instead."
3908
3909def fclose(handle):
3910 raise DeprecatedIDCError, "fclose() deprecated. Use Python file objects instead."
3911
3912def filelength(handle):
3913 raise DeprecatedIDCError, "filelength() deprecated. Use Python file objects instead."
3914
3915def fseek(handle, offset, origin):
3916 raise DeprecatedIDCError, "fseek() deprecated. Use Python file objects instead."
3917
3918def ftell(handle):
3919 raise DeprecatedIDCError, "ftell() deprecated. Use Python file objects instead."
3920
3921
3922def LoadFile(filepath, pos, ea, size):
3923 """
3924 Load file into IDA database
3925
3926 @param filepath: path to input file
3927 @param pos: position in the file
3928 @param ea: linear address to load
3929 @param size: number of bytes to load
3930
3931 @return: 0 - error, 1 - ok
3932 """
3933 li = idaapi.open_linput(filepath, False)
3934
3935 if li:
3936 retval = idaapi.file2base(li, pos, ea, ea+size, False)
3937 idaapi.close_linput(li)
3938 return retval
3939 else:
3940 return 0
3941
3942def loadfile(filepath, pos, ea, size): return LoadFile(filepath, pos, ea, size)
3943
3944
3945def SaveFile(filepath, pos, ea, size):
3946 """
3947 Save from IDA database to file
3948
3949 @param filepath: path to output file
3950 @param pos: position in the file
3951 @param ea: linear address to save from
3952 @param size: number of bytes to save
3953
3954 @return: 0 - error, 1 - ok
3955 """
3956 of = idaapi.fopenM(filepath)
3957
3958 if of:
3959 retval = idaapi.base2file(of, pos, ea, ea+size)
3960 idaapi.eclose(of)
3961 return retval
3962 else:
3963 return 0
3964
3965def savefile(filepath, pos, ea, size): return SaveFile(filepath, pos, ea, size)
3966
3967
3968def fgetc(handle):
3969 raise DeprecatedIDCError, "fgetc() deprecated. Use Python file objects instead."
3970
3971def fputc(byte, handle):
3972 raise DeprecatedIDCError, "fputc() deprecated. Use Python file objects instead."
3973
3974def fprintf(handle, format, *args):
3975 raise DeprecatedIDCError, "fprintf() deprecated. Use Python file objects instead."
3976
3977def readshort(handle, mostfirst):
3978 raise DeprecatedIDCError, "readshort() deprecated. Use Python file objects instead."
3979
3980def readlong(handle, mostfirst):
3981 raise DeprecatedIDCError, "readlong() deprecated. Use Python file objects instead."
3982
3983def writeshort(handle, word, mostfirst):
3984 raise DeprecatedIDCError, "writeshort() deprecated. Use Python file objects instead."
3985
3986def writelong(handle, dword, mostfirst):
3987 raise DeprecatedIDCError, "writelong() deprecated. Use Python file objects instead."
3988
3989def readstr(handle):
3990 raise DeprecatedIDCError, "readstr() deprecated. Use Python file objects instead."
3991
3992def writestr(handle, s):
3993 raise DeprecatedIDCError, "writestr() deprecated. Use Python file objects instead."
3994
3995# ----------------------------------------------------------------------------
3996# F U N C T I O N S
3997# ----------------------------------------------------------------------------
3998
3999def MakeFunction(start, end = idaapi.BADADDR):
4000 """
4001 Create a function
4002
4003 @param start: function bounds
4004 @param end: function bounds
4005
4006 If the function end address is BADADDR, then
4007 IDA will try to determine the function bounds
4008 automatically. IDA will define all necessary
4009 instructions to determine the function bounds.
4010
4011 @return: !=0 - ok
4012
4013 @note: an instruction should be present at the start address
4014 """
4015 return idaapi.add_func(start, end)
4016
4017
4018def DelFunction(ea):
4019 """
4020 Delete a function
4021
4022 @param ea: any address belonging to the function
4023
4024 @return: !=0 - ok
4025 """
4026 return idaapi.del_func(ea)
4027
4028
4029def SetFunctionEnd(ea, end):
4030 """
4031 Change function end address
4032
4033 @param ea: any address belonging to the function
4034 @param end: new function end address
4035
4036 @return: !=0 - ok
4037 """
4038 return idaapi.func_setend(ea, end)
4039
4040
4041def NextFunction(ea):
4042 """
4043 Find next function
4044
4045 @param ea: any address belonging to the function
4046
4047 @return: BADADDR - no more functions
4048 otherwise returns the next function start address
4049 """
4050 func = idaapi.get_next_func(ea)
4051
4052 if not func:
4053 return BADADDR
4054 else:
4055 return func.startEA
4056
4057
4058def PrevFunction(ea):
4059 """
4060 Find previous function
4061
4062 @param ea: any address belonging to the function
4063
4064 @return: BADADDR - no more functions
4065 otherwise returns the previous function start address
4066 """
4067 func = idaapi.get_prev_func(ea)
4068
4069 if not func:
4070 return BADADDR
4071 else:
4072 return func.startEA
4073
4074
4075def GetFunctionAttr(ea, attr):
4076 """
4077 Get a function attribute
4078
4079 @param ea: any address belonging to the function
4080 @param attr: one of FUNCATTR_... constants
4081
4082 @return: BADADDR - error otherwise returns the attribute value
4083 """
4084 func = idaapi.get_func(ea)
4085
4086 return _IDC_GetAttr(func, _FUNCATTRMAP, attr) if func else BADADDR
4087
4088
4089def SetFunctionAttr(ea, attr, value):
4090 """
4091 Set a function attribute
4092
4093 @param ea: any address belonging to the function
4094 @param attr: one of FUNCATTR_... constants
4095 @param value: new value of the attribute
4096
4097 @return: 1-ok, 0-failed
4098 """
4099 func = idaapi.get_func(ea)
4100
4101 if func:
4102 _IDC_SetAttr(func, _FUNCATTRMAP, attr, value)
4103 return idaapi.update_func(func)
4104 return 0
4105
4106
4107FUNCATTR_START = 0 # function start address
4108FUNCATTR_END = 4 # function end address
4109FUNCATTR_FLAGS = 8 # function flags
4110FUNCATTR_FRAME = 10 # function frame id
4111FUNCATTR_FRSIZE = 14 # size of local variables
4112FUNCATTR_FRREGS = 18 # size of saved registers area
4113FUNCATTR_ARGSIZE = 20 # number of bytes purged from the stack
4114FUNCATTR_FPD = 24 # frame pointer delta
4115FUNCATTR_COLOR = 28 # function color code
4116FUNCATTR_OWNER = 10 # chunk owner (valid only for tail chunks)
4117FUNCATTR_REFQTY = 14 # number of chunk parents (valid only for tail chunks)
4118
4119# Redefining the constants for 64-bit
4120if __EA64__:
4121 FUNCATTR_START = 0
4122 FUNCATTR_END = 8
4123 FUNCATTR_FLAGS = 16
4124 FUNCATTR_FRAME = 18
4125 FUNCATTR_FRSIZE = 26
4126 FUNCATTR_FRREGS = 34
4127 FUNCATTR_ARGSIZE = 36
4128 FUNCATTR_FPD = 44
4129 FUNCATTR_COLOR = 52
4130 FUNCATTR_OWNER = 18
4131 FUNCATTR_REFQTY = 26
4132
4133
4134_FUNCATTRMAP = {
4135 FUNCATTR_START : (True, 'startEA'),
4136 FUNCATTR_END : (True, 'endEA'),
4137 FUNCATTR_FLAGS : (False, 'flags'),
4138 FUNCATTR_FRAME : (True, 'frame'),
4139 FUNCATTR_FRSIZE : (True, 'frsize'),
4140 FUNCATTR_FRREGS : (True, 'frregs'),
4141 FUNCATTR_ARGSIZE : (True, 'argsize'),
4142 FUNCATTR_FPD : (False, 'fpd'),
4143 FUNCATTR_COLOR : (False, 'color'),
4144 FUNCATTR_OWNER : (True, 'owner'),
4145 FUNCATTR_REFQTY : (True, 'refqty')
4146}
4147
4148
4149def GetFunctionFlags(ea):
4150 """
4151 Retrieve function flags
4152
4153 @param ea: any address belonging to the function
4154
4155 @return: -1 - function doesn't exist otherwise returns the flags
4156 """
4157 func = idaapi.get_func(ea)
4158
4159 if not func:
4160 return -1
4161 else:
4162 return func.flags
4163
4164
4165FUNC_NORET = idaapi.FUNC_NORET # function doesn't return
4166FUNC_FAR = idaapi.FUNC_FAR # far function
4167FUNC_LIB = idaapi.FUNC_LIB # library function
4168FUNC_STATIC = idaapi.FUNC_STATICDEF # static function
4169FUNC_FRAME = idaapi.FUNC_FRAME # function uses frame pointer (BP)
4170FUNC_USERFAR = idaapi.FUNC_USERFAR # user has specified far-ness
4171 # of the function
4172FUNC_HIDDEN = idaapi.FUNC_HIDDEN # a hidden function
4173FUNC_THUNK = idaapi.FUNC_THUNK # thunk (jump) function
4174FUNC_BOTTOMBP = idaapi.FUNC_BOTTOMBP # BP points to the bottom of the stack frame
4175FUNC_NORET_PENDING = idaapi.FUNC_NORET_PENDING # Function 'non-return' analysis
4176 # must be performed. This flag is
4177 # verified upon func_does_return()
4178FUNC_SP_READY = idaapi.FUNC_SP_READY # SP-analysis has been performed
4179 # If this flag is on, the stack
4180 # change points should not be not
4181 # modified anymore. Currently this
4182 # analysis is performed only for PC
4183FUNC_PURGED_OK = idaapi.FUNC_PURGED_OK # 'argsize' field has been validated.
4184 # If this bit is clear and 'argsize'
4185 # is 0, then we do not known the real
4186 # number of bytes removed from
4187 # the stack. This bit is handled
4188 # by the processor module.
4189FUNC_TAIL = idaapi.FUNC_TAIL # This is a function tail.
4190 # Other bits must be clear
4191 # (except FUNC_HIDDEN)
4192
4193
4194def SetFunctionFlags(ea, flags):
4195 """
4196 Change function flags
4197
4198 @param ea: any address belonging to the function
4199 @param flags: see GetFunctionFlags() for explanations
4200
4201 @return: !=0 - ok
4202 """
4203 func = idaapi.get_func(ea)
4204
4205 if not func:
4206 return 0
4207 else:
4208 func.flags = flags
4209 idaapi.update_func(func)
4210 return 1
4211
4212
4213def GetFunctionName(ea):
4214 """
4215 Retrieve function name
4216
4217 @param ea: any address belonging to the function
4218
4219 @return: null string - function doesn't exist
4220 otherwise returns function name
4221 """
4222 name = idaapi.get_func_name(ea)
4223
4224 if not name:
4225 return ""
4226 else:
4227 return name
4228
4229
4230def GetFunctionCmt(ea, repeatable):
4231 """
4232 Retrieve function comment
4233
4234 @param ea: any address belonging to the function
4235 @param repeatable: 1: get repeatable comment
4236 0: get regular comment
4237
4238 @return: function comment string
4239 """
4240 func = idaapi.get_func(ea)
4241
4242 if not func:
4243 return ""
4244 else:
4245 comment = idaapi.get_func_cmt(func, repeatable)
4246
4247 if not comment:
4248 return ""
4249 else:
4250 return comment
4251
4252
4253def SetFunctionCmt(ea, cmt, repeatable):
4254 """
4255 Set function comment
4256
4257 @param ea: any address belonging to the function
4258 @param cmt: a function comment line
4259 @param repeatable: 1: get repeatable comment
4260 0: get regular comment
4261 """
4262 func = idaapi.get_func(ea)
4263
4264 if not func:
4265 return None
4266 else:
4267 return idaapi.set_func_cmt(func, cmt, repeatable)
4268
4269
4270def ChooseFunction(title):
4271 """
4272 Ask the user to select a function
4273
4274 Arguments:
4275
4276 @param title: title of the dialog box
4277
4278 @return: -1 - user refused to select a function
4279 otherwise returns the selected function start address
4280 """
4281 f = idaapi.choose_func(title, idaapi.BADADDR)
4282 return BADADDR if f is None else f.startEA
4283
4284
4285def GetFuncOffset(ea):
4286 """
4287 Convert address to 'funcname+offset' string
4288
4289 @param ea: address to convert
4290
4291 @return: if the address belongs to a function then return a string
4292 formed as 'name+offset' where 'name' is a function name
4293 'offset' is offset within the function else return null string
4294 """
4295 return idaapi.a2funcoff(ea)
4296
4297
4298def FindFuncEnd(ea):
4299 """
4300 Determine a new function boundaries
4301
4302 @param ea: starting address of a new function
4303
4304 @return: if a function already exists, then return its end address.
4305 If a function end cannot be determined, the return BADADDR
4306 otherwise return the end address of the new function
4307 """
4308 func = idaapi.func_t()
4309
4310 res = idaapi.find_func_bounds(ea, func, idaapi.FIND_FUNC_DEFINE)
4311
4312 if res == idaapi.FIND_FUNC_UNDEF:
4313 return BADADDR
4314 else:
4315 return func.endEA
4316
4317
4318def GetFrame(ea):
4319 """
4320 Get ID of function frame structure
4321
4322 @param ea: any address belonging to the function
4323
4324 @return: ID of function frame or None In order to access stack variables
4325 you need to use structure member manipulaion functions with the
4326 obtained ID.
4327 """
4328 frame = idaapi.get_frame(ea)
4329
4330 if frame:
4331 return frame.id
4332 else:
4333 return None
4334
4335
4336def GetFrameLvarSize(ea):
4337 """
4338 Get size of local variables in function frame
4339
4340 @param ea: any address belonging to the function
4341
4342 @return: Size of local variables in bytes.
4343 If the function doesn't have a frame, return 0
4344 If the function does't exist, return None
4345 """
4346 return GetFunctionAttr(ea, FUNCATTR_FRSIZE)
4347
4348
4349def GetFrameRegsSize(ea):
4350 """
4351 Get size of saved registers in function frame
4352
4353 @param ea: any address belonging to the function
4354
4355 @return: Size of saved registers in bytes.
4356 If the function doesn't have a frame, return 0
4357 This value is used as offset for BP (if FUNC_FRAME is set)
4358 If the function does't exist, return None
4359 """
4360 return GetFunctionAttr(ea, FUNCATTR_FRREGS)
4361
4362
4363def GetFrameArgsSize(ea):
4364 """
4365 Get size of arguments in function frame which are purged upon return
4366
4367 @param ea: any address belonging to the function
4368
4369 @return: Size of function arguments in bytes.
4370 If the function doesn't have a frame, return 0
4371 If the function does't exist, return -1
4372 """
4373 return GetFunctionAttr(ea, FUNCATTR_ARGSIZE)
4374
4375
4376def GetFrameSize(ea):
4377 """
4378 Get full size of function frame
4379
4380 @param ea: any address belonging to the function
4381 @returns: Size of function frame in bytes.
4382 This function takes into account size of local
4383 variables + size of saved registers + size of
4384 return address + size of function arguments
4385 If the function doesn't have a frame, return size of
4386 function return address in the stack.
4387 If the function does't exist, return 0
4388 """
4389 func = idaapi.get_func(ea)
4390
4391 if not func:
4392 return 0
4393 else:
4394 return idaapi.get_frame_size(func)
4395
4396
4397def MakeFrame(ea, lvsize, frregs, argsize):
4398 """
4399 Make function frame
4400
4401 @param ea: any address belonging to the function
4402 @param lvsize: size of function local variables
4403 @param frregs: size of saved registers
4404 @param argsize: size of function arguments
4405
4406 @return: ID of function frame or -1
4407 If the function did not have a frame, the frame
4408 will be created. Otherwise the frame will be modified
4409 """
4410 func = idaapi.get_func(ea)
4411 if func is None:
4412 return -1
4413
4414 frameid = idaapi.add_frame(func, lvsize, frregs, argsize)
4415
4416 if not frameid:
4417 if not idaapi.set_frame_size(func, lvsize, frregs, argsize):
4418 return -1
4419
4420 return func.frame
4421
4422
4423def GetSpd(ea):
4424 """
4425 Get current delta for the stack pointer
4426
4427 @param ea: end address of the instruction
4428 i.e.the last address of the instruction+1
4429
4430 @return: The difference between the original SP upon
4431 entering the function and SP for the specified address
4432 """
4433 func = idaapi.get_func(ea)
4434
4435 if not func:
4436 return None
4437
4438 return idaapi.get_spd(func, ea)
4439
4440
4441def GetSpDiff(ea):
4442 """
4443 Get modification of SP made by the instruction
4444
4445 @param ea: end address of the instruction
4446 i.e.the last address of the instruction+1
4447
4448 @return: Get modification of SP made at the specified location
4449 If the specified location doesn't contain a SP change point, return 0
4450 Otherwise return delta of SP modification
4451 """
4452 func = idaapi.get_func(ea)
4453
4454 if not func:
4455 return None
4456
4457 return idaapi.get_sp_delta(func, ea)
4458
4459
4460def SetSpDiff(ea, delta):
4461 """
4462 Setup modification of SP made by the instruction
4463
4464 @param ea: end address of the instruction
4465 i.e.the last address of the instruction+1
4466 @param delta: the difference made by the current instruction.
4467
4468 @return: 1-ok, 0-failed
4469 """
4470 return idaapi.add_user_stkpnt(ea, delta)
4471
4472
4473# ----------------------------------------------------------------------------
4474# S T A C K
4475# ----------------------------------------------------------------------------
4476
4477def AddAutoStkPnt2(func_ea, ea, delta):
4478 """
4479 Add automatical SP register change point
4480 @param func_ea: function start
4481 @param ea: linear address where SP changes
4482 usually this is the end of the instruction which
4483 modifies the stack pointer (cmd.ea+cmd.size)
4484 @param delta: difference between old and new values of SP
4485 @return: 1-ok, 0-failed
4486 """
4487 pfn = idaapi.get_func(func_ea)
4488 if not pfn:
4489 return 0
4490 return idaapi.add_auto_stkpnt2(pfn, ea, delta)
4491
4492def AddUserStkPnt(ea, delta):
4493 """
4494 Add user-defined SP register change point.
4495
4496 @param ea: linear address where SP changes
4497 @param delta: difference between old and new values of SP
4498
4499 @return: 1-ok, 0-failed
4500 """
4501 return idaapi.add_user_stkpnt(ea, delta);
4502
4503def DelStkPnt(func_ea, ea):
4504 """
4505 Delete SP register change point
4506
4507 @param func_ea: function start
4508 @param ea: linear address
4509 @return: 1-ok, 0-failed
4510 """
4511 pfn = idaapi.get_func(func_ea)
4512 if not pfn:
4513 return 0
4514 return idaapi.del_stkpnt(pfn, ea)
4515
4516def GetMinSpd(func_ea):
4517 """
4518 Return the address with the minimal spd (stack pointer delta)
4519 If there are no SP change points, then return BADADDR.
4520
4521 @param func_ea: function start
4522 @return: BADDADDR - no such function
4523 """
4524 pfn = idaapi.get_func(func_ea)
4525 if not pfn:
4526 return BADADDR
4527 return idaapi.get_min_spd_ea(pfn)
4528
4529def RecalcSpd(cur_ea):
4530 """
4531 Recalculate SP delta for an instruction that stops execution.
4532
4533 @param cur_ea: linear address of the current instruction
4534 @return: 1 - new stkpnt is added, 0 - nothing is changed
4535 """
4536 return idaapi.recalc_spd(cur_ea)
4537
4538
4539
4540
4541
4542# ----------------------------------------------------------------------------
4543# E N T R Y P O I N T S
4544# ----------------------------------------------------------------------------
4545
4546def GetEntryPointQty():
4547 """
4548 Retrieve number of entry points
4549
4550 @returns: number of entry points
4551 """
4552 return idaapi.get_entry_qty()
4553
4554
4555def AddEntryPoint(ordinal, ea, name, makecode):
4556 """
4557 Add entry point
4558
4559 @param ordinal: entry point number
4560 if entry point doesn't have an ordinal
4561 number, 'ordinal' should be equal to 'ea'
4562 @param ea: address of the entry point
4563 @param name: name of the entry point. If null string,
4564 the entry point won't be renamed.
4565 @param makecode: if 1 then this entry point is a start
4566 of a function. Otherwise it denotes data bytes.
4567
4568 @return: 0 - entry point with the specifed ordinal already exists
4569 1 - ok
4570 """
4571 return idaapi.add_entry(ordinal, ea, name, makecode)
4572
4573
4574def GetEntryOrdinal(index):
4575 """
4576 Retrieve entry point ordinal number
4577
4578 @param index: 0..GetEntryPointQty()-1
4579
4580 @return: 0 if entry point doesn't exist
4581 otherwise entry point ordinal
4582 """
4583 return idaapi.get_entry_ordinal(index)
4584
4585
4586def GetEntryPoint(ordinal):
4587 """
4588 Retrieve entry point address
4589
4590 @param ordinal: entry point number
4591 it is returned by GetEntryPointOrdinal()
4592
4593 @return: BADADDR if entry point doesn't exist
4594 otherwise entry point address.
4595 If entry point address is equal to its ordinal
4596 number, then the entry point has no ordinal.
4597 """
4598 return idaapi.get_entry(ordinal)
4599
4600
4601def GetEntryName(ordinal):
4602 """
4603 Retrieve entry point name
4604
4605 @param ordinal: entry point number, ass returned by GetEntryPointOrdinal()
4606
4607 @return: entry point name or None
4608 """
4609 return idaapi.get_entry_name(ordinal)
4610
4611
4612def RenameEntryPoint(ordinal, name):
4613 """
4614 Rename entry point
4615
4616 @param ordinal: entry point number
4617 @param name: new name
4618
4619 @return: !=0 - ok
4620 """
4621 return idaapi.rename_entry(ordinal, name)
4622
4623
4624# ----------------------------------------------------------------------------
4625# F I X U P S
4626# ----------------------------------------------------------------------------
4627def GetNextFixupEA(ea):
4628 """
4629 Find next address with fixup information
4630
4631 @param ea: current address
4632
4633 @return: BADADDR - no more fixups otherwise returns the next
4634 address with fixup information
4635 """
4636 return idaapi.get_next_fixup_ea(ea)
4637
4638
4639def GetPrevFixupEA(ea):
4640 """
4641 Find previous address with fixup information
4642
4643 @param ea: current address
4644
4645 @return: BADADDR - no more fixups otherwise returns the
4646 previous address with fixup information
4647 """
4648 return idaapi.get_prev_fixup_ea(ea)
4649
4650
4651def GetFixupTgtType(ea):
4652 """
4653 Get fixup target type
4654
4655 @param ea: address to get information about
4656
4657 @return: -1 - no fixup at the specified address
4658 otherwise returns fixup target type:
4659 """
4660 fd = idaapi.fixup_data_t()
4661
4662 if not idaapi.get_fixup(ea, fd):
4663 return -1
4664
4665 return fd.type
4666
4667
4668FIXUP_MASK = 0xF
4669FIXUP_OFF8 = 0 # 8-bit offset.
4670FIXUP_BYTE = FIXUP_OFF8 # 8-bit offset.
4671FIXUP_OFF16 = 1 # 16-bit offset.
4672FIXUP_SEG16 = 2 # 16-bit base--logical segment base (selector).
4673FIXUP_PTR32 = 3 # 32-bit long pointer (16-bit base:16-bit
4674 # offset).
4675FIXUP_OFF32 = 4 # 32-bit offset.
4676FIXUP_PTR48 = 5 # 48-bit pointer (16-bit base:32-bit offset).
4677FIXUP_HI8 = 6 # high 8 bits of 16bit offset
4678FIXUP_HI16 = 7 # high 16 bits of 32bit offset
4679FIXUP_LOW8 = 8 # low 8 bits of 16bit offset
4680FIXUP_LOW16 = 9 # low 16 bits of 32bit offset
4681FIXUP_REL = 0x10 # fixup is relative to the linear address
4682 # specified in the 3d parameter to set_fixup()
4683FIXUP_SELFREL = 0x0 # self-relative?
4684 # - disallows the kernel to convert operands
4685 # in the first pass
4686 # - this fixup is used during output
4687 # This type of fixups is not used anymore.
4688 # Anyway you can use it for commenting purposes
4689 # in the loader modules
4690FIXUP_EXTDEF = 0x20 # target is a location (otherwise - segment)
4691FIXUP_UNUSED = 0x40 # fixup is ignored by IDA
4692 # - disallows the kernel to convert operands
4693 # - this fixup is not used during output
4694FIXUP_CREATED = 0x80 # fixup was not present in the input file
4695
4696
4697def GetFixupTgtSel(ea):
4698 """
4699 Get fixup target selector
4700
4701 @param ea: address to get information about
4702
4703 @return: -1 - no fixup at the specified address
4704 otherwise returns fixup target selector
4705 """
4706 fd = idaapi.fixup_data_t()
4707
4708 if not idaapi.get_fixup(ea, fd):
4709 return -1
4710
4711 return fd.sel
4712
4713
4714def GetFixupTgtOff(ea):
4715 """
4716 Get fixup target offset
4717
4718 @param ea: address to get information about
4719
4720 @return: -1 - no fixup at the specified address
4721 otherwise returns fixup target offset
4722 """
4723 fd = idaapi.fixup_data_t()
4724
4725 if not idaapi.get_fixup(ea, fd):
4726 return -1
4727
4728 return fd.off
4729
4730
4731def GetFixupTgtDispl(ea):
4732 """
4733 Get fixup target displacement
4734
4735 @param ea: address to get information about
4736
4737 @return: -1 - no fixup at the specified address
4738 otherwise returns fixup target displacement
4739 """
4740 fd = idaapi.fixup_data_t()
4741
4742 if not idaapi.get_fixup(ea, fd):
4743 return -1
4744
4745 return fd.displacement
4746
4747
4748def SetFixup(ea, fixuptype, targetsel, targetoff, displ):
4749 """
4750 Set fixup information
4751
4752 @param ea: address to set fixup information about
4753 @param fixuptype: fixup type. see GetFixupTgtType()
4754 for possible fixup types.
4755 @param targetsel: target selector
4756 @param targetoff: target offset
4757 @param displ: displacement
4758
4759 @return: none
4760 """
4761 fd = idaapi.fixup_data_t()
4762 fd.type = fixuptype
4763 fd.sel = targetsel
4764 fd.off = targetoff
4765 fd.displacement = displ
4766
4767 idaapi.set_fixup(ea, fd)
4768
4769
4770def DelFixup(ea):
4771 """
4772 Delete fixup information
4773
4774 @param ea: address to delete fixup information about
4775
4776 @return: None
4777 """
4778 idaapi.del_fixup(ea)
4779
4780
4781#----------------------------------------------------------------------------
4782# M A R K E D P O S I T I O N S
4783#----------------------------------------------------------------------------
4784
4785def MarkPosition(ea, lnnum, x, y, slot, comment):
4786 """
4787 Mark position
4788
4789 @param ea: address to mark
4790 @param lnnum: number of generated line for the 'ea'
4791 @param x: x coordinate of cursor
4792 @param y: y coordinate of cursor
4793 @param slot: slot number: 1..1024
4794 if the specifed value is not within the
4795 range, IDA will ask the user to select slot.
4796 @param comment: description of the mark. Should be not empty.
4797
4798 @return: None
4799 """
4800 curloc = idaapi.curloc()
4801 curloc.ea = ea
4802 curloc.lnnum = lnnum
4803 curloc.x = x
4804 curloc.y = y
4805 curloc.mark(slot, comment, comment)
4806
4807
4808def GetMarkedPos(slot):
4809 """
4810 Get marked position
4811
4812 @param slot: slot number: 1..1024 if the specifed value is <= 0
4813 range, IDA will ask the user to select slot.
4814
4815 @return: BADADDR - the slot doesn't contain a marked address
4816 otherwise returns the marked address
4817 """
4818 curloc = idaapi.curloc()
4819 intp = idaapi.int_pointer()
4820 intp.assign(slot)
4821 return curloc.markedpos(intp)
4822
4823
4824def GetMarkComment(slot):
4825 """
4826 Get marked position comment
4827
4828 @param slot: slot number: 1..1024
4829
4830 @return: None if the slot doesn't contain a marked address
4831 otherwise returns the marked address comment
4832 """
4833 curloc = idaapi.curloc()
4834 return curloc.markdesc(slot)
4835
4836
4837# ----------------------------------------------------------------------------
4838# S T R U C T U R E S
4839# ----------------------------------------------------------------------------
4840
4841def GetStrucQty():
4842 """
4843 Get number of defined structure types
4844
4845 @return: number of structure types
4846 """
4847 return idaapi.get_struc_qty()
4848
4849
4850def GetFirstStrucIdx():
4851 """
4852 Get index of first structure type
4853
4854 @return: BADADDR if no structure type is defined
4855 index of first structure type.
4856 Each structure type has an index and ID.
4857 INDEX determines position of structure definition
4858 in the list of structure definitions. Index 1
4859 is listed first, after index 2 and so on.
4860 The index of a structure type can be changed any
4861 time, leading to movement of the structure definition
4862 in the list of structure definitions.
4863 ID uniquely denotes a structure type. A structure
4864 gets a unique ID at the creation time and this ID
4865 can't be changed. Even when the structure type gets
4866 deleted, its ID won't be resued in the future.
4867 """
4868 return idaapi.get_first_struc_idx()
4869
4870
4871def GetLastStrucIdx():
4872 """
4873 Get index of last structure type
4874
4875 @return: BADADDR if no structure type is defined
4876 index of last structure type.
4877 See GetFirstStrucIdx() for the explanation of
4878 structure indices and IDs.
4879 """
4880 return idaapi.get_last_struc_idx()
4881
4882
4883def GetNextStrucIdx(index):
4884 """
4885 Get index of next structure type
4886
4887 @param index: current structure index
4888
4889 @return: BADADDR if no (more) structure type is defined
4890 index of the next structure type.
4891 See GetFirstStrucIdx() for the explanation of
4892 structure indices and IDs.
4893 """
4894 return idaapi.get_next_struc_idx(index)
4895
4896
4897def GetPrevStrucIdx(index):
4898 """
4899 Get index of previous structure type
4900
4901 @param index: current structure index
4902
4903 @return: BADADDR if no (more) structure type is defined
4904 index of the presiouvs structure type.
4905 See GetFirstStrucIdx() for the explanation of
4906 structure indices and IDs.
4907 """
4908 return idaapi.get_prev_struc_idx(index)
4909
4910
4911def GetStrucIdx(sid):
4912 """
4913 Get structure index by structure ID
4914
4915 @param sid: structure ID
4916
4917 @return: BADADDR if bad structure ID is passed
4918 otherwise returns structure index.
4919 See GetFirstStrucIdx() for the explanation of
4920 structure indices and IDs.
4921 """
4922 return idaapi.get_struc_idx(sid)
4923
4924
4925def GetStrucId(index):
4926 """
4927 Get structure ID by structure index
4928
4929 @param index: structure index
4930
4931 @return: BADADDR if bad structure index is passed otherwise returns structure ID.
4932
4933 @note: See GetFirstStrucIdx() for the explanation of structure indices and IDs.
4934 """
4935 return idaapi.get_struc_by_idx(index)
4936
4937
4938def GetStrucIdByName(name):
4939 """
4940 Get structure ID by structure name
4941
4942 @param name: structure type name
4943
4944 @return: BADADDR if bad structure type name is passed
4945 otherwise returns structure ID.
4946 """
4947 return idaapi.get_struc_id(name)
4948
4949
4950def GetStrucName(sid):
4951 """
4952 Get structure type name
4953
4954 @param sid: structure type ID
4955
4956 @return: None if bad structure type ID is passed
4957 otherwise returns structure type name.
4958 """
4959 return idaapi.get_struc_name(sid)
4960
4961
4962def GetStrucComment(sid, repeatable):
4963 """
4964 Get structure type comment
4965
4966 @param sid: structure type ID
4967 @param repeatable: 1: get repeatable comment
4968 0: get regular comment
4969
4970 @return: None if bad structure type ID is passed
4971 otherwise returns comment.
4972 """
4973 return idaapi.get_struc_cmt(sid, repeatable)
4974
4975
4976def GetStrucSize(sid):
4977 """
4978 Get size of a structure
4979
4980 @param sid: structure type ID
4981
4982 @return: 0 if bad structure type ID is passed
4983 otherwise returns size of structure in bytes.
4984 """
4985 return idaapi.get_struc_size(sid)
4986
4987
4988def GetMemberQty(sid):
4989 """
4990 Get number of members of a structure
4991
4992 @param sid: structure type ID
4993
4994 @return: -1 if bad structure type ID is passed otherwise
4995 returns number of members.
4996
4997 @note: Union members are, in IDA's internals, located
4998 at subsequent byte offsets: member 0 -> offset 0x0,
4999 member 1 -> offset 0x1, etc...
5000 """
5001 s = idaapi.get_struc(sid)
5002 return -1 if not s else s.memqty
5003
5004
5005def GetMemberId(sid, member_offset):
5006 """
5007 @param sid: structure type ID
5008 @param member_offset:. The offset can be
5009 any offset in the member. For example,
5010 is a member is 4 bytes long and starts
5011 at offset 2, then 2,3,4,5 denote
5012 the same structure member.
5013
5014 @return: -1 if bad structure type ID is passed or there is
5015 no member at the specified offset.
5016 otherwise returns the member id.
5017 """
5018 s = idaapi.get_struc(sid)
5019 if not s:
5020 return -1
5021
5022 m = idaapi.get_member(s, member_offset)
5023 if not m:
5024 return -1
5025
5026 return m.id
5027
5028
5029def GetStrucPrevOff(sid, offset):
5030 """
5031 Get previous offset in a structure
5032
5033 @param sid: structure type ID
5034 @param offset: current offset
5035
5036 @return: -1 if bad structure type ID is passed,
5037 idaapi.BADADDR if no (more) offsets in the structure,
5038 otherwise returns previous offset in a structure.
5039
5040 @note: IDA allows 'holes' between members of a
5041 structure. It treats these 'holes'
5042 as unnamed arrays of bytes.
5043 This function returns a member offset or a hole offset.
5044 It will return size of the structure if input
5045 'offset' is bigger than the structure size.
5046
5047 @note: Union members are, in IDA's internals, located
5048 at subsequent byte offsets: member 0 -> offset 0x0,
5049 member 1 -> offset 0x1, etc...
5050 """
5051 s = idaapi.get_struc(sid)
5052 if not s:
5053 return -1
5054
5055 return idaapi.get_struc_prev_offset(s, offset)
5056
5057
5058def GetStrucNextOff(sid, offset):
5059 """
5060 Get next offset in a structure
5061
5062 @param sid: structure type ID
5063 @param offset: current offset
5064
5065 @return: -1 if bad structure type ID is passed,
5066 idaapi.BADADDR if no (more) offsets in the structure,
5067 otherwise returns next offset in a structure.
5068
5069 @note: IDA allows 'holes' between members of a
5070 structure. It treats these 'holes'
5071 as unnamed arrays of bytes.
5072 This function returns a member offset or a hole offset.
5073 It will return size of the structure if input
5074 'offset' belongs to the last member of the structure.
5075
5076 @note: Union members are, in IDA's internals, located
5077 at subsequent byte offsets: member 0 -> offset 0x0,
5078 member 1 -> offset 0x1, etc...
5079 """
5080 s = idaapi.get_struc(sid)
5081 return -1 if not s else idaapi.get_struc_next_offset(s, offset)
5082
5083
5084def GetFirstMember(sid):
5085 """
5086 Get offset of the first member of a structure
5087
5088 @param sid: structure type ID
5089
5090 @return: -1 if bad structure type ID is passed,
5091 idaapi.BADADDR if structure has no members,
5092 otherwise returns offset of the first member.
5093
5094 @note: IDA allows 'holes' between members of a
5095 structure. It treats these 'holes'
5096 as unnamed arrays of bytes.
5097
5098 @note: Union members are, in IDA's internals, located
5099 at subsequent byte offsets: member 0 -> offset 0x0,
5100 member 1 -> offset 0x1, etc...
5101 """
5102 s = idaapi.get_struc(sid)
5103 if not s:
5104 return -1
5105
5106 return idaapi.get_struc_first_offset(s)
5107
5108
5109def GetLastMember(sid):
5110 """
5111 Get offset of the last member of a structure
5112
5113 @param sid: structure type ID
5114
5115 @return: -1 if bad structure type ID is passed,
5116 idaapi.BADADDR if structure has no members,
5117 otherwise returns offset of the last member.
5118
5119 @note: IDA allows 'holes' between members of a
5120 structure. It treats these 'holes'
5121 as unnamed arrays of bytes.
5122
5123 @note: Union members are, in IDA's internals, located
5124 at subsequent byte offsets: member 0 -> offset 0x0,
5125 member 1 -> offset 0x1, etc...
5126 """
5127 s = idaapi.get_struc(sid)
5128 if not s:
5129 return -1
5130
5131 return idaapi.get_struc_last_offset(s)
5132
5133
5134def GetMemberOffset(sid, member_name):
5135 """
5136 Get offset of a member of a structure by the member name
5137
5138 @param sid: structure type ID
5139 @param member_name: name of structure member
5140
5141 @return: -1 if bad structure type ID is passed
5142 or no such member in the structure
5143 otherwise returns offset of the specified member.
5144
5145 @note: Union members are, in IDA's internals, located
5146 at subsequent byte offsets: member 0 -> offset 0x0,
5147 member 1 -> offset 0x1, etc...
5148 """
5149 s = idaapi.get_struc(sid)
5150 if not s:
5151 return -1
5152
5153 m = idaapi.get_member_by_name(s, member_name)
5154 if not m:
5155 return -1
5156
5157 return m.get_soff()
5158
5159
5160def GetMemberName(sid, member_offset):
5161 """
5162 Get name of a member of a structure
5163
5164 @param sid: structure type ID
5165 @param member_offset: member offset. The offset can be
5166 any offset in the member. For example,
5167 is a member is 4 bytes long and starts
5168 at offset 2, then 2,3,4,5 denote
5169 the same structure member.
5170
5171 @return: None if bad structure type ID is passed
5172 or no such member in the structure
5173 otherwise returns name of the specified member.
5174 """
5175 s = idaapi.get_struc(sid)
5176 if not s:
5177 return None
5178
5179 m = idaapi.get_member(s, member_offset)
5180 if not m:
5181 return None
5182
5183 return idaapi.get_member_name(m.id)
5184
5185
5186def GetMemberComment(sid, member_offset, repeatable):
5187 """
5188 Get comment of a member
5189
5190 @param sid: structure type ID
5191 @param member_offset: member offset. The offset can be
5192 any offset in the member. For example,
5193 is a member is 4 bytes long and starts
5194 at offset 2, then 2,3,4,5 denote
5195 the same structure member.
5196 @param repeatable: 1: get repeatable comment
5197 0: get regular comment
5198
5199 @return: None if bad structure type ID is passed
5200 or no such member in the structure
5201 otherwise returns comment of the specified member.
5202 """
5203 s = idaapi.get_struc(sid)
5204 if not s:
5205 return None
5206
5207 m = idaapi.get_member(s, member_offset)
5208 if not m:
5209 return None
5210
5211 return idaapi.get_member_cmt(m.id, repeatable)
5212
5213
5214def GetMemberSize(sid, member_offset):
5215 """
5216 Get size of a member
5217
5218 @param sid: structure type ID
5219 @param member_offset: member offset. The offset can be
5220 any offset in the member. For example,
5221 is a member is 4 bytes long and starts
5222 at offset 2, then 2,3,4,5 denote
5223 the same structure member.
5224
5225 @return: None if bad structure type ID is passed,
5226 or no such member in the structure
5227 otherwise returns size of the specified
5228 member in bytes.
5229 """
5230 s = idaapi.get_struc(sid)
5231 if not s:
5232 return None
5233
5234 m = idaapi.get_member(s, member_offset)
5235 if not m:
5236 return None
5237
5238 return idaapi.get_member_size(m)
5239
5240
5241def GetMemberFlag(sid, member_offset):
5242 """
5243 Get type of a member
5244
5245 @param sid: structure type ID
5246 @param member_offset: member offset. The offset can be
5247 any offset in the member. For example,
5248 is a member is 4 bytes long and starts
5249 at offset 2, then 2,3,4,5 denote
5250 the same structure member.
5251
5252 @return: -1 if bad structure type ID is passed
5253 or no such member in the structure
5254 otherwise returns type of the member, see bit
5255 definitions above. If the member type is a structure
5256 then function GetMemberStrid() should be used to
5257 get the structure type id.
5258 """
5259 s = idaapi.get_struc(sid)
5260 if not s:
5261 return -1
5262
5263 m = idaapi.get_member(s, member_offset)
5264 return -1 if not m else m.flag
5265
5266
5267def GetMemberStrId(sid, member_offset):
5268 """
5269 Get structure id of a member
5270
5271 @param sid: structure type ID
5272 @param member_offset: member offset. The offset can be
5273 any offset in the member. For example,
5274 is a member is 4 bytes long and starts
5275 at offset 2, then 2,3,4,5 denote
5276 the same structure member.
5277 @return: -1 if bad structure type ID is passed
5278 or no such member in the structure
5279 otherwise returns structure id of the member.
5280 If the current member is not a structure, returns -1.
5281 """
5282 s = idaapi.get_struc(sid)
5283 if not s:
5284 return -1
5285
5286 m = idaapi.get_member(s, member_offset)
5287 if not m:
5288 return -1
5289
5290 cs = idaapi.get_sptr(m)
5291 if cs:
5292 return cs.id
5293 else:
5294 return -1
5295
5296
5297def IsUnion(sid):
5298 """
5299 Is a structure a union?
5300
5301 @param sid: structure type ID
5302
5303 @return: 1: yes, this is a union id
5304 0: no
5305
5306 @note: Unions are a special kind of structures
5307 """
5308 s = idaapi.get_struc(sid)
5309 if not s:
5310 return 0
5311
5312 return s.is_union()
5313
5314
5315def AddStrucEx(index, name, is_union):
5316 """
5317 Define a new structure type
5318
5319 @param index: index of new structure type
5320 If another structure has the specified index,
5321 then index of that structure and all other
5322 structures will be incremented, freeing the specifed
5323 index. If index is == -1, then the biggest index
5324 number will be used.
5325 See GetFirstStrucIdx() for the explanation of
5326 structure indices and IDs.
5327 @param name: name of the new structure type.
5328 @param is_union: 0: structure
5329 1: union
5330
5331 @return: -1 if can't define structure type because of
5332 bad structure name: the name is ill-formed or is
5333 already used in the program.
5334 otherwise returns ID of the new structure type
5335 """
5336 if index == -1:
5337 index = BADADDR
5338
5339 return idaapi.add_struc(index, name, is_union)
5340
5341
5342def DelStruc(sid):
5343 """
5344 Delete a structure type
5345
5346 @param sid: structure type ID
5347
5348 @return: 0 if bad structure type ID is passed
5349 1 otherwise the structure type is deleted. All data
5350 and other structure types referencing to the
5351 deleted structure type will be displayed as array
5352 of bytes.
5353 """
5354 s = idaapi.get_struc(sid)
5355 if not s:
5356 return 0
5357
5358 return idaapi.del_struc(s)
5359
5360
5361def SetStrucIdx(sid, index):
5362 """
5363 Change structure index
5364
5365 @param sid: structure type ID
5366 @param index: new index of the structure
5367
5368 @return: != 0 - ok
5369
5370 @note: See GetFirstStrucIdx() for the explanation of
5371 structure indices and IDs.
5372 """
5373 s = idaapi.get_struc(sid)
5374 if not s:
5375 return 0
5376
5377 return idaapi.set_struc_idx(s, index)
5378
5379
5380def SetStrucName(sid, name):
5381 """
5382 Change structure name
5383
5384 @param sid: structure type ID
5385 @param name: new name of the structure
5386
5387 @return: != 0 - ok
5388 """
5389 return idaapi.set_struc_name(sid, name)
5390
5391
5392def SetStrucComment(sid, comment, repeatable):
5393 """
5394 Change structure comment
5395
5396 @param sid: structure type ID
5397 @param comment: new comment of the structure
5398 @param repeatable: 1: change repeatable comment
5399 0: change regular comment
5400 @return: != 0 - ok
5401 """
5402 return idaapi.set_struc_cmt(sid, comment, repeatable)
5403
5404
5405def AddStrucMember(sid, name, offset, flag, typeid, nbytes, target=-1, tdelta=0, reftype=REF_OFF32):
5406 """
5407 Add structure member
5408
5409 @param sid: structure type ID
5410 @param name: name of the new member
5411 @param offset: offset of the new member
5412 -1 means to add at the end of the structure
5413 @param flag: type of the new member. Should be one of
5414 FF_BYTE..FF_PACKREAL (see above) combined with FF_DATA
5415 @param typeid: if isStruc(flag) then typeid specifies the structure id for the member
5416 if isOff0(flag) then typeid specifies the offset base.
5417 if isASCII(flag) then typeid specifies the string type (ASCSTR_...).
5418 if isStroff(flag) then typeid specifies the structure id
5419 if isEnum(flag) then typeid specifies the enum id
5420 if isCustom(flags) then typeid specifies the dtid and fid: dtid|(fid<<16)
5421 Otherwise typeid should be -1.
5422 @param nbytes: number of bytes in the new member
5423
5424 @param target: target address of the offset expr. You may specify it as
5425 -1, ida will calculate it itself
5426 @param tdelta: offset target delta. usually 0
5427 @param reftype: see REF_... definitions
5428
5429 @note: The remaining arguments are allowed only if isOff0(flag) and you want
5430 to specify a complex offset expression
5431
5432 @return: 0 - ok, otherwise error code (one of STRUC_ERROR_*)
5433
5434 """
5435 if isOff0(flag):
5436 return Eval('AddStrucMember(%d, "%s", %d, %d, %d, %d, %d, %d, %d);' % (sid, idaapi.str2user(name), offset, flag, typeid, nbytes,
5437 target, tdelta, reftype))
5438 else:
5439 return Eval('AddStrucMember(%d, "%s", %d, %d, %d, %d);' % (sid, idaapi.str2user(name), offset, flag, typeid, nbytes))
5440
5441
5442STRUC_ERROR_MEMBER_NAME = -1 # already has member with this name (bad name)
5443STRUC_ERROR_MEMBER_OFFSET = -2 # already has member at this offset
5444STRUC_ERROR_MEMBER_SIZE = -3 # bad number of bytes or bad sizeof(type)
5445STRUC_ERROR_MEMBER_TINFO = -4 # bad typeid parameter
5446STRUC_ERROR_MEMBER_STRUCT = -5 # bad struct id (the 1st argument)
5447STRUC_ERROR_MEMBER_UNIVAR = -6 # unions can't have variable sized members
5448STRUC_ERROR_MEMBER_VARLAST = -7 # variable sized member should be the last member in the structure
5449
5450
5451def DelStrucMember(sid, member_offset):
5452 """
5453 Delete structure member
5454
5455 @param sid: structure type ID
5456 @param member_offset: offset of the member
5457
5458 @return: != 0 - ok.
5459
5460 @note: IDA allows 'holes' between members of a
5461 structure. It treats these 'holes'
5462 as unnamed arrays of bytes.
5463 """
5464 s = idaapi.get_struc(sid)
5465 if not s:
5466 return 0
5467
5468 return idaapi.del_struc_member(s, member_offset)
5469
5470
5471def SetMemberName(sid, member_offset, name):
5472 """
5473 Change structure member name
5474
5475 @param sid: structure type ID
5476 @param member_offset: offset of the member
5477 @param name: new name of the member
5478
5479 @return: != 0 - ok.
5480 """
5481 s = idaapi.get_struc(sid)
5482 if not s:
5483 return 0
5484
5485 return idaapi.set_member_name(s, member_offset, name)
5486
5487
5488def SetMemberType(sid, member_offset, flag, typeid, nitems, target=-1, tdelta=0, reftype=REF_OFF32):
5489 """
5490 Change structure member type
5491
5492 @param sid: structure type ID
5493 @param member_offset: offset of the member
5494 @param flag: new type of the member. Should be one of
5495 FF_BYTE..FF_PACKREAL (see above) combined with FF_DATA
5496 @param typeid: if isStruc(flag) then typeid specifies the structure id for the member
5497 if isOff0(flag) then typeid specifies the offset base.
5498 if isASCII(flag) then typeid specifies the string type (ASCSTR_...).
5499 if isStroff(flag) then typeid specifies the structure id
5500 if isEnum(flag) then typeid specifies the enum id
5501 if isCustom(flags) then typeid specifies the dtid and fid: dtid|(fid<<16)
5502 Otherwise typeid should be -1.
5503 @param nitems: number of items in the member
5504
5505 @param target: target address of the offset expr. You may specify it as
5506 -1, ida will calculate it itself
5507 @param tdelta: offset target delta. usually 0
5508 @param reftype: see REF_... definitions
5509
5510 @note: The remaining arguments are allowed only if isOff0(flag) and you want
5511 to specify a complex offset expression
5512
5513 @return: !=0 - ok.
5514 """
5515 if isOff0(flag):
5516 return Eval('SetMemberType(%d, %d, %d, %d, %d, %d, %d, %d);' % (sid, member_offset, flag, typeid, nitems,
5517 target, tdelta, reftype))
5518 else:
5519 return Eval('SetMemberType(%d, %d, %d, %d, %d);' % (sid, member_offset, flag, typeid, nitems))
5520
5521
5522def SetMemberComment(sid, member_offset, comment, repeatable):
5523 """
5524 Change structure member comment
5525
5526 @param sid: structure type ID
5527 @param member_offset: offset of the member
5528 @param comment: new comment of the structure member
5529 @param repeatable: 1: change repeatable comment
5530 0: change regular comment
5531
5532 @return: != 0 - ok
5533 """
5534 s = idaapi.get_struc(sid)
5535 if not s:
5536 return 0
5537
5538 m = idaapi.get_member(s, member_offset)
5539 if not m:
5540 return 0
5541
5542 return idaapi.set_member_cmt(m, comment, repeatable)
5543
5544
5545def GetFchunkAttr(ea, attr):
5546 """
5547 Get a function chunk attribute
5548
5549 @param ea: any address in the chunk
5550 @param attr: one of: FUNCATTR_START, FUNCATTR_END, FUNCATTR_OWNER, FUNCATTR_REFQTY
5551
5552 @return: desired attribute or -1
5553 """
5554 func = idaapi.get_fchunk(ea)
5555 return _IDC_GetAttr(func, _FUNCATTRMAP, attr) if func else BADADDR
5556
5557
5558def SetFchunkAttr(ea, attr, value):
5559 """
5560 Set a function chunk attribute
5561
5562 @param ea: any address in the chunk
5563 @param attr: only FUNCATTR_START, FUNCATTR_END, FUNCATTR_OWNER
5564 @param value: desired value
5565
5566 @return: 0 if failed, 1 if success
5567 """
5568 if attr in [ FUNCATTR_START, FUNCATTR_END, FUNCATTR_OWNER ]:
5569 chunk = idaapi.get_fchunk(ea)
5570 if chunk:
5571 _IDC_SetAttr(chunk, _FUNCATTRMAP, attr, value)
5572 return idaapi.update_func(chunk)
5573 return 0
5574
5575
5576def GetFchunkReferer(ea, idx):
5577 """
5578 Get a function chunk referer
5579
5580 @param ea: any address in the chunk
5581 @param idx: referer index (0..GetFchunkAttr(FUNCATTR_REFQTY))
5582
5583 @return: referer address or BADADDR
5584 """
5585 return idaapi.get_fchunk_referer(ea, idx)
5586
5587
5588def NextFchunk(ea):
5589 """
5590 Get next function chunk
5591
5592 @param ea: any address
5593
5594 @return: the starting address of the next function chunk or BADADDR
5595
5596 @note: This function enumerates all chunks of all functions in the database
5597 """
5598 func = idaapi.get_next_fchunk(ea)
5599
5600 if func:
5601 return func.startEA
5602 else:
5603 return BADADDR
5604
5605
5606def PrevFchunk(ea):
5607 """
5608 Get previous function chunk
5609
5610 @param ea: any address
5611
5612 @return: the starting address of the function chunk or BADADDR
5613
5614 @note: This function enumerates all chunks of all functions in the database
5615 """
5616 func = idaapi.get_prev_fchunk(ea)
5617
5618 if func:
5619 return func.startEA
5620 else:
5621 return BADADDR
5622
5623
5624def AppendFchunk(funcea, ea1, ea2):
5625 """
5626 Append a function chunk to the function
5627
5628 @param funcea: any address in the function
5629 @param ea1: start of function tail
5630 @param ea2: end of function tail
5631 @return: 0 if failed, 1 if success
5632
5633 @note: If a chunk exists at the specified addresses, it must have exactly
5634 the specified boundaries
5635 """
5636 func = idaapi.get_func(funcea)
5637
5638 if not func:
5639 return 0
5640 else:
5641 return idaapi.append_func_tail(func, ea1, ea2)
5642
5643
5644def RemoveFchunk(funcea, tailea):
5645 """
5646 Remove a function chunk from the function
5647
5648 @param funcea: any address in the function
5649 @param tailea: any address in the function chunk to remove
5650
5651 @return: 0 if failed, 1 if success
5652 """
5653 func = idaapi.get_func(funcea)
5654
5655 if not func:
5656 return 0
5657 else:
5658 return idaapi.remove_func_tail(func, tailea)
5659
5660
5661def SetFchunkOwner(tailea, funcea):
5662 """
5663 Change the function chunk owner
5664
5665 @param tailea: any address in the function chunk
5666 @param funcea: the starting address of the new owner
5667
5668 @return: 0 if failed, 1 if success
5669
5670 @note: The new owner must already have the chunk appended before the call
5671 """
5672 tail = idaapi.get_func(tailea)
5673
5674 if not tail:
5675 return 0
5676 else:
5677 return idaapi.set_tail_owner(tail, funcea)
5678
5679
5680def FirstFuncFchunk(funcea):
5681 """
5682 Get the first function chunk of the specified function
5683
5684 @param funcea: any address in the function
5685
5686 @return: the function entry point or BADADDR
5687
5688 @note: This function returns the first (main) chunk of the specified function
5689 """
5690 func = idaapi.get_func(funcea)
5691 fci = idaapi.func_tail_iterator_t(func, funcea)
5692 if fci.main():
5693 return fci.chunk().startEA
5694 else:
5695 return BADADDR
5696
5697
5698def NextFuncFchunk(funcea, tailea):
5699 """
5700 Get the next function chunk of the specified function
5701
5702 @param funcea: any address in the function
5703 @param tailea: any address in the current chunk
5704
5705 @return: the starting address of the next function chunk or BADADDR
5706
5707 @note: This function returns the next chunk of the specified function
5708 """
5709 func = idaapi.get_func(funcea)
5710 fci = idaapi.func_tail_iterator_t(func, funcea)
5711 if not fci.main():
5712 return BADADDR
5713
5714 # Iterate and try to find the current chunk
5715 found = False
5716 while True:
5717 if fci.chunk().startEA <= tailea and \
5718 fci.chunk().endEA > tailea:
5719 found = True
5720 break
5721 if not fci.next():
5722 break
5723
5724 # Return the next chunk, if there is one
5725 if found and fci.next():
5726 return fci.chunk().startEA
5727 else:
5728 return BADADDR
5729
5730
5731# ----------------------------------------------------------------------------
5732# E N U M S
5733# ----------------------------------------------------------------------------
5734def GetEnumQty():
5735 """
5736 Get number of enum types
5737
5738 @return: number of enumerations
5739 """
5740 return idaapi.get_enum_qty()
5741
5742
5743def GetnEnum(idx):
5744 """
5745 Get ID of the specified enum by its serial number
5746
5747 @param idx: number of enum (0..GetEnumQty()-1)
5748
5749 @return: ID of enum or -1 if error
5750 """
5751 return idaapi.getn_enum(idx)
5752
5753
5754def GetEnumIdx(enum_id):
5755 """
5756 Get serial number of enum by its ID
5757
5758 @param enum_id: ID of enum
5759
5760 @return: (0..GetEnumQty()-1) or -1 if error
5761 """
5762 return idaapi.get_enum_idx(enum_id)
5763
5764
5765def GetEnum(name):
5766 """
5767 Get enum ID by the name of enum
5768
5769 Arguments:
5770 name - name of enum
5771
5772 returns: ID of enum or -1 if no such enum exists
5773 """
5774 return idaapi.get_enum(name)
5775
5776
5777def GetEnumName(enum_id):
5778 """
5779 Get name of enum
5780
5781 @param enum_id: ID of enum
5782
5783 @return: name of enum or empty string
5784 """
5785 return idaapi.get_enum_name(enum_id)
5786
5787
5788def GetEnumCmt(enum_id, repeatable):
5789 """
5790 Get comment of enum
5791
5792 @param enum_id: ID of enum
5793 @param repeatable: 0:get regular comment
5794 1:get repeatable comment
5795
5796 @return: comment of enum
5797 """
5798 return idaapi.get_enum_cmt(enum_id, repeatable)
5799
5800
5801def GetEnumSize(enum_id):
5802 """
5803 Get size of enum
5804
5805 @param enum_id: ID of enum
5806
5807 @return: number of constants in the enum
5808 Returns 0 if enum_id is bad.
5809 """
5810 return idaapi.get_enum_size(enum_id)
5811
5812
5813def GetEnumWidth(enum_id):
5814 """
5815 Get width of enum elements
5816
5817 @param enum_id: ID of enum
5818
5819 @return: log2(size of enum elements in bytes)+1
5820 possible returned values are 1..7
5821 1-1byte,2-2bytes,3-4bytes,4-8bytes,etc
5822 Returns 0 if enum_id is bad or the width is unknown.
5823 """
5824 return idaapi.get_enum_width(enum_id)
5825
5826
5827def GetEnumFlag(enum_id):
5828 """
5829 Get flag of enum
5830
5831 @param enum_id: ID of enum
5832
5833 @return: flags of enum. These flags determine representation
5834 of numeric constants (binary,octal,decimal,hex)
5835 in the enum definition. See start of this file for
5836 more information about flags.
5837 Returns 0 if enum_id is bad.
5838 """
5839 return idaapi.get_enum_flag(enum_id)
5840
5841
5842def GetConstByName(name):
5843 """
5844 Get member of enum - a symbolic constant ID
5845
5846 @param name: name of symbolic constant
5847
5848 @return: ID of constant or -1
5849 """
5850 return idaapi.get_enum_member_by_name(name)
5851
5852
5853def GetConstValue(const_id):
5854 """
5855 Get value of symbolic constant
5856
5857 @param const_id: id of symbolic constant
5858
5859 @return: value of constant or 0
5860 """
5861 return idaapi.get_enum_member_value(const_id)
5862
5863
5864def GetConstBmask(const_id):
5865 """
5866 Get bit mask of symbolic constant
5867
5868 @param const_id: id of symbolic constant
5869
5870 @return: bitmask of constant or 0
5871 ordinary enums have bitmask = -1
5872 """
5873 return idaapi.get_enum_member_bmask(const_id)
5874
5875
5876def GetConstEnum(const_id):
5877 """
5878 Get id of enum by id of constant
5879
5880 @param const_id: id of symbolic constant
5881
5882 @return: id of enum the constant belongs to.
5883 -1 if const_id is bad.
5884 """
5885 return idaapi.get_enum_member_enum(const_id)
5886
5887
5888def GetConstEx(enum_id, value, serial, bmask):
5889 """
5890 Get id of constant
5891
5892 @param enum_id: id of enum
5893 @param value: value of constant
5894 @param serial: serial number of the constant in the
5895 enumeration. See OpEnumEx() for details.
5896 @param bmask: bitmask of the constant
5897 ordinary enums accept only -1 as a bitmask
5898
5899 @return: id of constant or -1 if error
5900 """
5901 if bmask < 0:
5902 bmask &= BADADDR
5903 return idaapi.get_enum_member(enum_id, value, serial, bmask)
5904
5905
5906def GetFirstBmask(enum_id):
5907 """
5908 Get first bitmask in the enum (bitfield)
5909
5910 @param enum_id: id of enum (bitfield)
5911
5912 @return: the smallest bitmask of constant or -1
5913 no bitmasks are defined yet
5914 All bitmasks are sorted by their values
5915 as unsigned longs.
5916 """
5917 return idaapi.get_first_bmask(enum_id)
5918
5919
5920def GetLastBmask(enum_id):
5921 """
5922 Get last bitmask in the enum (bitfield)
5923
5924 @param enum_id: id of enum
5925
5926 @return: the biggest bitmask or -1 no bitmasks are defined yet
5927 All bitmasks are sorted by their values as unsigned longs.
5928 """
5929 return idaapi.get_last_bmask(enum_id)
5930
5931
5932def GetNextBmask(enum_id, value):
5933 """
5934 Get next bitmask in the enum (bitfield)
5935
5936 @param enum_id: id of enum
5937 @param value: value of the current bitmask
5938
5939 @return: value of a bitmask with value higher than the specified
5940 value. -1 if no such bitmasks exist.
5941 All bitmasks are sorted by their values
5942 as unsigned longs.
5943 """
5944 return idaapi.get_next_bmask(enum_id, value)
5945
5946
5947def GetPrevBmask(enum_id, value):
5948 """
5949 Get prev bitmask in the enum (bitfield)
5950
5951 @param enum_id: id of enum
5952 @param value: value of the current bitmask
5953
5954 @return: value of a bitmask with value lower than the specified
5955 value. -1 no such bitmasks exist.
5956 All bitmasks are sorted by their values as unsigned longs.
5957 """
5958 return idaapi.get_prev_bmask(enum_id, value)
5959
5960
5961def GetBmaskName(enum_id, bmask):
5962 """
5963 Get bitmask name (only for bitfields)
5964
5965 @param enum_id: id of enum
5966 @param bmask: bitmask of the constant
5967
5968 @return: name of bitmask or None
5969 """
5970 if bmask < 0:
5971 bmask &= BADADDR
5972 return idaapi.get_bmask_name(enum_id, bmask)
5973
5974
5975def GetBmaskCmt(enum_id, bmask, repeatable):
5976 """
5977 Get bitmask comment (only for bitfields)
5978
5979 @param enum_id: id of enum
5980 @param bmask: bitmask of the constant
5981 @param repeatable: type of comment, 0-regular, 1-repeatable
5982
5983 @return: comment attached to bitmask or None
5984 """
5985 if bmask < 0:
5986 bmask &= BADADDR
5987 return idaapi.get_bmask_cmt(enum_id, bmask, repeatable)
5988
5989
5990def SetBmaskName(enum_id, bmask, name):
5991 """
5992 Set bitmask name (only for bitfields)
5993
5994 @param enum_id: id of enum
5995 @param bmask: bitmask of the constant
5996 @param name: name of bitmask
5997
5998 @return: 1-ok, 0-failed
5999 """
6000 if bmask < 0:
6001 bmask &= BADADDR
6002 return idaapi.set_bmask_name(enum_id, bmask, name)
6003
6004
6005def SetBmaskCmt(enum_id, bmask, cmt, repeatable):
6006 """
6007 Set bitmask comment (only for bitfields)
6008
6009 @param enum_id: id of enum
6010 @param bmask: bitmask of the constant
6011 @param cmt: comment
6012 repeatable - type of comment, 0-regular, 1-repeatable
6013
6014 @return: 1-ok, 0-failed
6015 """
6016 if bmask < 0:
6017 bmask &= BADADDR
6018 return idaapi.set_bmask_cmt(enum_id, bmask, cmt, repeatable)
6019
6020
6021def GetFirstConst(enum_id, bmask):
6022 """
6023 Get first constant in the enum
6024
6025 @param enum_id: id of enum
6026 @param bmask: bitmask of the constant (ordinary enums accept only -1 as a bitmask)
6027
6028 @return: value of constant or -1 no constants are defined
6029 All constants are sorted by their values as unsigned longs.
6030 """
6031 if bmask < 0:
6032 bmask &= BADADDR
6033 return idaapi.get_first_enum_member(enum_id, bmask)
6034
6035
6036def GetLastConst(enum_id, bmask):
6037 """
6038 Get last constant in the enum
6039
6040 @param enum_id: id of enum
6041 @param bmask: bitmask of the constant (ordinary enums accept only -1 as a bitmask)
6042
6043 @return: value of constant or -1 no constants are defined
6044 All constants are sorted by their values
6045 as unsigned longs.
6046 """
6047 if bmask < 0:
6048 bmask &= BADADDR
6049 return idaapi.get_last_enum_member(enum_id, bmask)
6050
6051
6052def GetNextConst(enum_id, value, bmask):
6053 """
6054 Get next constant in the enum
6055
6056 @param enum_id: id of enum
6057 @param bmask: bitmask of the constant ordinary enums accept only -1 as a bitmask
6058 @param value: value of the current constant
6059
6060 @return: value of a constant with value higher than the specified
6061 value. -1 no such constants exist.
6062 All constants are sorted by their values as unsigned longs.
6063 """
6064 if bmask < 0:
6065 bmask &= BADADDR
6066 return idaapi.get_next_enum_member(enum_id, value, bmask)
6067
6068
6069def GetPrevConst(enum_id, value, bmask):
6070 """
6071 Get prev constant in the enum
6072
6073 @param enum_id: id of enum
6074 @param bmask : bitmask of the constant
6075 ordinary enums accept only -1 as a bitmask
6076 @param value: value of the current constant
6077
6078 @return: value of a constant with value lower than the specified
6079 value. -1 no such constants exist.
6080 All constants are sorted by their values as unsigned longs.
6081 """
6082 if bmask < 0:
6083 bmask &= BADADDR
6084 return idaapi.get_prev_enum_member(enum_id, value, bmask)
6085
6086
6087def GetConstName(const_id):
6088 """
6089 Get name of a constant
6090
6091 @param const_id: id of const
6092
6093 Returns: name of constant
6094 """
6095 name = idaapi.get_enum_member_name(const_id)
6096
6097 if not name:
6098 return ""
6099 else:
6100 return name
6101
6102
6103def GetConstCmt(const_id, repeatable):
6104 """
6105 Get comment of a constant
6106
6107 @param const_id: id of const
6108 @param repeatable: 0:get regular comment, 1:get repeatable comment
6109
6110 @return: comment string
6111 """
6112 cmt = idaapi.get_enum_member_cmt(const_id, repeatable)
6113
6114 if not cmt:
6115 return ""
6116 else:
6117 return cmt
6118
6119
6120def AddEnum(idx, name, flag):
6121 """
6122 Add a new enum type
6123
6124 @param idx: serial number of the new enum.
6125 If another enum with the same serial number
6126 exists, then all enums with serial
6127 numbers >= the specified idx get their
6128 serial numbers incremented (in other words,
6129 the new enum is put in the middle of the list of enums).
6130
6131 If idx >= GetEnumQty() or idx == -1
6132 then the new enum is created at the end of
6133 the list of enums.
6134
6135 @param name: name of the enum.
6136 @param flag: flags for representation of numeric constants
6137 in the definition of enum.
6138
6139 @return: id of new enum or BADADDR
6140 """
6141 if idx < 0:
6142 idx = idx & SIZE_MAX
6143 return idaapi.add_enum(idx, name, flag)
6144
6145
6146def DelEnum(enum_id):
6147 """
6148 Delete enum type
6149
6150 @param enum_id: id of enum
6151
6152 @return: None
6153 """
6154 idaapi.del_enum(enum_id)
6155
6156
6157def SetEnumIdx(enum_id, idx):
6158 """
6159 Give another serial number to a enum
6160
6161 @param enum_id: id of enum
6162 @param idx: new serial number.
6163 If another enum with the same serial number
6164 exists, then all enums with serial
6165 numbers >= the specified idx get their
6166 serial numbers incremented (in other words,
6167 the new enum is put in the middle of the list of enums).
6168
6169 If idx >= GetEnumQty() then the enum is
6170 moved to the end of the list of enums.
6171
6172 @return: comment string
6173 """
6174 return idaapi.set_enum_idx(enum_id, idx)
6175
6176
6177def SetEnumName(enum_id, name):
6178 """
6179 Rename enum
6180
6181 @param enum_id: id of enum
6182 @param name: new name of enum
6183
6184 @return: 1-ok,0-failed
6185 """
6186 return idaapi.set_enum_name(enum_id, name)
6187
6188
6189def SetEnumCmt(enum_id, cmt, repeatable):
6190 """
6191 Set comment of enum
6192
6193 @param enum_id: id of enum
6194 @param cmt: new comment for the enum
6195 @param repeatable: is the comment repeatable?
6196 - 0:set regular comment
6197 - 1:set repeatable comment
6198
6199 @return: 1-ok,0-failed
6200 """
6201 return idaapi.set_enum_cmt(enum_id, cmt, repeatable)
6202
6203
6204def SetEnumFlag(enum_id, flag):
6205 """
6206 Set flag of enum
6207
6208 @param enum_id: id of enum
6209 @param flag: flags for representation of numeric constants
6210 in the definition of enum.
6211
6212 @return: 1-ok,0-failed
6213 """
6214 return idaapi.set_enum_flag(enum_id, flag)
6215
6216
6217def SetEnumBf(enum_id, flag):
6218 """
6219 Set bitfield property of enum
6220
6221 @param enum_id: id of enum
6222 @param flag: flags
6223 - 1: convert to bitfield
6224 - 0: convert to ordinary enum
6225
6226 @return: 1-ok,0-failed
6227 """
6228 return idaapi.set_enum_bf(enum_id, flag)
6229
6230
6231def SetEnumWidth(enum_id, width):
6232 """
6233 Set width of enum elements
6234
6235 @param enum_id: id of enum
6236 @param width: element width in bytes
6237 allowed values: 0-unknown
6238 or 1..7: (log2 of the element size)+1
6239
6240 @return: 1-ok, 0-failed
6241 """
6242 return idaapi.set_enum_width(enum_id, width)
6243
6244
6245def IsBitfield(enum_id):
6246 """
6247 Is enum a bitfield?
6248
6249 @param enum_id: id of enum
6250
6251 @return: 1-yes, 0-no, ordinary enum
6252 """
6253 return idaapi.is_bf(enum_id)
6254
6255
6256def AddConstEx(enum_id, name, value, bmask):
6257 """
6258 Add a member of enum - a symbolic constant
6259
6260 @param enum_id: id of enum
6261 @param name: name of symbolic constant. Must be unique in the program.
6262 @param value: value of symbolic constant.
6263 @param bmask: bitmask of the constant
6264 ordinary enums accept only -1 as a bitmask
6265 all bits set in value should be set in bmask too
6266
6267 @return: 0-ok, otherwise error code (one of ENUM_MEMBER_ERROR_*)
6268 """
6269 if bmask < 0:
6270 bmask &= BADADDR
6271 return idaapi.add_enum_member(enum_id, name, value, bmask)
6272
6273
6274ENUM_MEMBER_ERROR_NAME = idaapi.ENUM_MEMBER_ERROR_NAME # already have member with this name (bad name)
6275ENUM_MEMBER_ERROR_VALUE = idaapi.ENUM_MEMBER_ERROR_VALUE # already have member with this value
6276ENUM_MEMBER_ERROR_ENUM = idaapi.ENUM_MEMBER_ERROR_ENUM # bad enum id
6277ENUM_MEMBER_ERROR_MASK = idaapi.ENUM_MEMBER_ERROR_MASK # bad bmask
6278ENUM_MEMBER_ERROR_ILLV = idaapi.ENUM_MEMBER_ERROR_ILLV # bad bmask and value combination (~bmask & value != 0)
6279
6280
6281def DelConstEx(enum_id, value, serial, bmask):
6282 """
6283 Delete a member of enum - a symbolic constant
6284
6285 @param enum_id: id of enum
6286 @param value: value of symbolic constant.
6287 @param serial: serial number of the constant in the
6288 enumeration. See OpEnumEx() for for details.
6289 @param bmask: bitmask of the constant ordinary enums accept
6290 only -1 as a bitmask
6291
6292 @return: 1-ok, 0-failed
6293 """
6294 if bmask < 0:
6295 bmask &= BADADDR
6296 return idaapi.del_enum_member(enum_id, value, serial, bmask)
6297
6298
6299def SetConstName(const_id, name):
6300 """
6301 Rename a member of enum - a symbolic constant
6302
6303 @param const_id: id of const
6304 @param name: new name of constant
6305
6306 @return: 1-ok, 0-failed
6307 """
6308 return idaapi.set_enum_member_name(const_id, name)
6309
6310
6311def SetConstCmt(const_id, cmt, repeatable):
6312 """
6313 Set a comment of a symbolic constant
6314
6315 @param const_id: id of const
6316 @param cmt: new comment for the constant
6317 @param repeatable: is the comment repeatable?
6318 0: set regular comment
6319 1: set repeatable comment
6320
6321 @return: 1-ok, 0-failed
6322 """
6323 return idaapi.set_enum_member_cmt(const_id, cmt, repeatable)
6324
6325#----------------------------------------------------------------------------
6326# A R R A Y S I N I D C
6327#----------------------------------------------------------------------------
6328
6329_IDC_ARRAY_PREFIX = "$ idc_array "
6330def __l2m1(v):
6331 """
6332 Long to minus 1: If the 'v' appears to be the
6333 'signed long' version of -1, then return -1.
6334 Otherwise, return 'v'.
6335 """
6336 if v == idaapi.BADNODE:
6337 return -1
6338 else:
6339 return v
6340
6341
6342
6343AR_LONG = idaapi.atag
6344"""Array of longs"""
6345
6346AR_STR = idaapi.stag
6347"""Array of strings"""
6348
6349
6350class __dummy_netnode(object):
6351 """
6352 Implements, in an "always failing" fashion, the
6353 netnode functions that are necessary for the
6354 array-related functions.
6355
6356 The sole purpose of this singleton class is to
6357 serve as a placeholder for netnode-manipulating
6358 functions, that don't want to each have to perform
6359 checks on the existence of the netnode.
6360 (..in other words: it avoids a bunch of if/else's).
6361
6362 See __GetArrayById() for more info.
6363 """
6364 def rename(self, *args): return 0
6365 def kill(self, *args): pass
6366 def index(self, *args): return -1
6367 def altset(self, *args): return 0
6368 def supset(self, *args): return 0
6369 def altval(self, *args): return 0
6370 def supval(self, *args): return 0
6371 def altdel(self, *args): return 0
6372 def supdel(self, *args): return 0
6373 def alt1st(self, *args): return -1
6374 def sup1st(self, *args): return -1
6375 def altlast(self, *args): return -1
6376 def suplast(self, *args): return -1
6377 def altnxt(self, *args): return -1
6378 def supnxt(self, *args): return -1
6379 def altprev(self, *args): return -1
6380 def supprev(self, *args): return -1
6381 def hashset(self, *args): return 0
6382 def hashval(self, *args): return 0
6383 def hashstr(self, *args): return 0
6384 def hashstr_buf(self, *args): return 0
6385 def hashset_idx(self, *args): return 0
6386 def hashset_buf(self, *args): return 0
6387 def hashval_long(self, *args): return 0
6388 def hashdel(self, *args): return 0
6389 def hash1st(self, *args): return 0
6390 def hashnxt(self, *args): return 0
6391 def hashprev(self, *args): return 0
6392 def hashlast(self, *args): return 0
6393__dummy_netnode.instance = __dummy_netnode()
6394
6395
6396
6397def __GetArrayById(array_id):
6398 """
6399 Get an array, by its ID.
6400
6401 This (internal) wrapper around 'idaaip.netnode(array_id)'
6402 will ensure a certain safety around the retrieval of
6403 arrays (by catching quite unexpect[ed|able] exceptions,
6404 and making sure we don't create & use `transient' netnodes).
6405
6406 @param array_id: A positive, valid array ID.
6407 """
6408 try:
6409 node = idaapi.netnode(array_id)
6410 nodename = node.name()
6411 if nodename is None or not nodename.startswith(_IDC_ARRAY_PREFIX):
6412 return __dummy_netnode.instance
6413 else:
6414 return node
6415 except NotImplementedError:
6416 return __dummy_netnode.instance
6417
6418
6419def CreateArray(name):
6420 """
6421 Create array.
6422
6423 @param name: The array name.
6424
6425 @return: -1 in case of failure, a valid array_id otherwise.
6426 """
6427 node = idaapi.netnode()
6428 res = node.create(_IDC_ARRAY_PREFIX + name)
6429 if res == False:
6430 return -1
6431 else:
6432 return node.index()
6433
6434
6435def GetArrayId(name):
6436 """
6437 Get array array_id, by name.
6438
6439 @param name: The array name.
6440
6441 @return: -1 in case of failure (i.e., no array with that
6442 name exists), a valid array_id otherwise.
6443 """
6444 return __l2m1(idaapi.netnode(_IDC_ARRAY_PREFIX + name, 0, False).index())
6445
6446
6447def RenameArray(array_id, newname):
6448 """
6449 Rename array, by its ID.
6450
6451 @param id: The ID of the array to rename.
6452 @param newname: The new name of the array.
6453
6454 @return: 1 in case of success, 0 otherwise
6455 """
6456 return __GetArrayById(array_id).rename(_IDC_ARRAY_PREFIX + newname) == 1
6457
6458
6459def DeleteArray(array_id):
6460 """
6461 Delete array, by its ID.
6462
6463 @param array_id: The ID of the array to delete.
6464 """
6465 __GetArrayById(array_id).kill()
6466
6467
6468def SetArrayLong(array_id, idx, value):
6469 """
6470 Sets the long value of an array element.
6471
6472 @param array_id: The array ID.
6473 @param idx: Index of an element.
6474 @param value: 32bit or 64bit value to store in the array
6475
6476 @return: 1 in case of success, 0 otherwise
6477 """
6478 return __GetArrayById(array_id).altset(idx, value)
6479
6480
6481def SetArrayString(array_id, idx, value):
6482 """
6483 Sets the string value of an array element.
6484
6485 @param array_id: The array ID.
6486 @param idx: Index of an element.
6487 @param value: String value to store in the array
6488
6489 @return: 1 in case of success, 0 otherwise
6490 """
6491 return __GetArrayById(array_id).supset(idx, value)
6492
6493
6494def GetArrayElement(tag, array_id, idx):
6495 """
6496 Get value of array element.
6497
6498 @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR
6499 @param array_id: The array ID.
6500 @param idx: Index of an element.
6501
6502 @return: Value of the specified array element. Note that
6503 this function may return char or long result. Unexistent
6504 array elements give zero as a result.
6505 """
6506 node = __GetArrayById(array_id)
6507 if tag == AR_LONG:
6508 return node.altval(idx, tag)
6509 elif tag == AR_STR:
6510 res = node.supval(idx, tag)
6511 return 0 if res is None else res
6512 else:
6513 return 0
6514
6515
6516def DelArrayElement(tag, array_id, idx):
6517 """
6518 Delete an array element.
6519
6520 @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR
6521 @param array_id: The array ID.
6522 @param idx: Index of an element.
6523
6524 @return: 1 in case of success, 0 otherwise.
6525 """
6526 node = __GetArrayById(array_id)
6527 if tag == AR_LONG:
6528 return node.altdel(idx, tag)
6529 elif tag == AR_STR:
6530 return node.supdel(idx, tag)
6531 else:
6532 return 0
6533
6534
6535def GetFirstIndex(tag, array_id):
6536 """
6537 Get index of the first existing array element.
6538
6539 @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR
6540 @param array_id: The array ID.
6541
6542 @return: -1 if the array is empty, otherwise index of first array
6543 element of given type.
6544 """
6545 node = __GetArrayById(array_id)
6546 if tag == AR_LONG:
6547 return __l2m1(node.alt1st(tag))
6548 elif tag == AR_STR:
6549 return __l2m1(node.sup1st(tag))
6550 else:
6551 return -1
6552
6553
6554def GetLastIndex(tag, array_id):
6555 """
6556 Get index of last existing array element.
6557
6558 @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR
6559 @param array_id: The array ID.
6560
6561 @return: -1 if the array is empty, otherwise index of first array
6562 element of given type.
6563 """
6564 node = __GetArrayById(array_id)
6565 if tag == AR_LONG:
6566 return __l2m1(node.altlast(tag))
6567 elif tag == AR_STR:
6568 return __l2m1(node.suplast(tag))
6569 else:
6570 return -1
6571
6572
6573def GetNextIndex(tag, array_id, idx):
6574 """
6575 Get index of the next existing array element.
6576
6577 @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR
6578 @param array_id: The array ID.
6579 @param idx: Index of the current element.
6580
6581 @return: -1 if no more elements, otherwise returns index of the
6582 next array element of given type.
6583 """
6584 node = __GetArrayById(array_id)
6585 try:
6586 if tag == AR_LONG:
6587 return __l2m1(node.altnxt(idx, tag))
6588 elif tag == AR_STR:
6589 return __l2m1(node.supnxt(idx, tag))
6590 else:
6591 return -1
6592 except OverflowError:
6593 # typically: An index of -1 was passed.
6594 return -1
6595
6596
6597def GetPrevIndex(tag, array_id, idx):
6598 """
6599 Get index of the previous existing array element.
6600
6601 @param tag: Tag of array, specifies one of two array types: AR_LONG, AR_STR
6602 @param array_id: The array ID.
6603 @param idx: Index of the current element.
6604
6605 @return: -1 if no more elements, otherwise returns index of the
6606 previous array element of given type.
6607 """
6608 node = __GetArrayById(array_id)
6609 try:
6610 if tag == AR_LONG:
6611 return __l2m1(node.altprev(idx, tag))
6612 elif tag == AR_STR:
6613 return __l2m1(node.supprev(idx, tag))
6614 else:
6615 return -1
6616 except OverflowError:
6617 # typically: An index of -1 was passed.
6618 return -1
6619
6620
6621# -------------------- hashes -----------------------
6622
6623def SetHashLong(hash_id, key, value):
6624 """
6625 Sets the long value of a hash element.
6626
6627 @param hash_id: The hash ID.
6628 @param key: Key of an element.
6629 @param value: 32bit or 64bit value to store in the hash
6630
6631 @return: 1 in case of success, 0 otherwise
6632 """
6633 return __GetArrayById(hash_id).hashset_idx(key, value)
6634
6635
6636def GetHashLong(hash_id, key):
6637 """
6638 Gets the long value of a hash element.
6639
6640 @param hash_id: The hash ID.
6641 @param key: Key of an element.
6642
6643 @return: the 32bit or 64bit value of the element, or 0 if no such
6644 element.
6645 """
6646 return __GetArrayById(hash_id).hashval_long(key);
6647
6648
6649def SetHashString(hash_id, key, value):
6650 """
6651 Sets the string value of a hash element.
6652
6653 @param hash_id: The hash ID.
6654 @param key: Key of an element.
6655 @param value: string value to store in the hash
6656
6657 @return: 1 in case of success, 0 otherwise
6658 """
6659 return __GetArrayById(hash_id).hashset_buf(key, value)
6660
6661
6662def GetHashString(hash_id, key):
6663 """
6664 Gets the string value of a hash element.
6665
6666 @param hash_id: The hash ID.
6667 @param key: Key of an element.
6668
6669 @return: the string value of the element, or None if no such
6670 element.
6671 """
6672 return __GetArrayById(hash_id).hashstr_buf(key);
6673
6674
6675def DelHashElement(hash_id, key):
6676 """
6677 Delete a hash element.
6678
6679 @param hash_id: The hash ID.
6680 @param key: Key of an element
6681
6682 @return: 1 upon success, 0 otherwise.
6683 """
6684 return __GetArrayById(hash_id).hashdel(key)
6685
6686
6687def GetFirstHashKey(hash_id):
6688 """
6689 Get the first key in the hash.
6690
6691 @param hash_id: The hash ID.
6692
6693 @return: the key, 0 otherwise.
6694 """
6695 r = __GetArrayById(hash_id).hash1st()
6696 return 0 if r is None else r
6697
6698
6699def GetLastHashKey(hash_id):
6700 """
6701 Get the last key in the hash.
6702
6703 @param hash_id: The hash ID.
6704
6705 @return: the key, 0 otherwise.
6706 """
6707 r = __GetArrayById(hash_id).hashlast()
6708 return 0 if r is None else r
6709
6710
6711def GetNextHashKey(hash_id, key):
6712 """
6713 Get the next key in the hash.
6714
6715 @param hash_id: The hash ID.
6716 @param key: The current key.
6717
6718 @return: the next key, 0 otherwise
6719 """
6720 r = __GetArrayById(hash_id).hashnxt(key)
6721 return 0 if r is None else r
6722
6723
6724def GetPrevHashKey(hash_id, key):
6725 """
6726 Get the previous key in the hash.
6727
6728 @param hash_id: The hash ID.
6729 @param key: The current key.
6730
6731 @return: the previous key, 0 otherwise
6732 """
6733 r = __GetArrayById(hash_id).hashprev(key)
6734 return 0 if r is None else r
6735
6736
6737
6738
6739#----------------------------------------------------------------------------
6740# S O U R C E F I L E / L I N E N U M B E R S
6741#----------------------------------------------------------------------------
6742def AddSourceFile(ea1, ea2, filename):
6743 """
6744 Mark a range of address as belonging to a source file
6745 An address range may belong only to one source file.
6746 A source file may be represented by several address ranges.
6747
6748 @param ea1: linear address of start of the address range
6749 @param ea2: linear address of end of the address range
6750 @param filename: name of source file.
6751
6752 @return: 1-ok, 0-failed.
6753
6754 @note: IDA can keep information about source files used to create the program.
6755 Each source file is represented by a range of addresses.
6756 A source file may contains several address ranges.
6757 """
6758 return idaapi.add_sourcefile(ea1, ea2, filename)
6759
6760
6761def GetSourceFile(ea):
6762 """
6763 Get name of source file occupying the given address
6764
6765 @param ea: linear address
6766
6767 @return: NULL - source file information is not found
6768 otherwise returns pointer to file name
6769 """
6770 return idaapi.get_sourcefile(ea)
6771
6772
6773def DelSourceFile(ea):
6774 """
6775 Delete information about the source file
6776
6777 @param ea: linear address belonging to the source file
6778
6779 @return: NULL - source file information is not found
6780 otherwise returns pointer to file name
6781 """
6782 return idaapi.del_sourcefile(ea)
6783
6784
6785def SetLineNumber(ea, lnnum):
6786 """
6787 Set source line number
6788
6789 @param ea: linear address
6790 @param lnnum: number of line in the source file
6791
6792 @return: None
6793 """
6794 idaapi.set_source_linnum(ea, lnnum)
6795
6796
6797def GetLineNumber(ea):
6798 """
6799 Get source line number
6800
6801 @param ea: linear address
6802
6803 @return: number of line in the source file or -1
6804 """
6805 return idaapi.get_source_linnum(ea)
6806
6807
6808def DelLineNumber(ea):
6809 """
6810 Delete information about source line number
6811
6812 @param ea: linear address
6813
6814 @return: None
6815 """
6816 idaapi.del_source_linnum(ea)
6817
6818
6819#----------------------------------------------------------------------------
6820# T Y P E L I B R A R I E S
6821#----------------------------------------------------------------------------
6822
6823def LoadTil(name):
6824 """
6825 Load a type library
6826
6827 @param name: name of type library.
6828 @return: 1-ok, 0-failed.
6829 """
6830 til = idaapi.add_til2(name, idaapi.ADDTIL_DEFAULT)
6831
6832 if til:
6833 return 1
6834 else:
6835 return 0
6836
6837
6838def Til2Idb(idx, type_name):
6839 """
6840 Copy information from type library to database
6841 Copy structure, union, or enum definition from the type library
6842 to the IDA database.
6843
6844 @param idx: the position of the new type in the list of
6845 types (structures or enums) -1 means at the end of the list
6846 @param type_name: name of type to copy
6847
6848 @return: BADNODE-failed, otherwise the type id (structure id or enum id)
6849 """
6850 return idaapi.import_type(idaapi.cvar.idati, idx, type_name)
6851
6852
6853def GetType(ea):
6854 """
6855 Get type of function/variable
6856
6857 @param ea: the address of the object
6858
6859 @return: type string or None if failed
6860 """
6861 return idaapi.idc_get_type(ea)
6862
6863def SizeOf(typestr):
6864 """
6865 Returns the size of the type. It is equivalent to IDC's sizeof().
6866 Use name, tp, fld = idc.ParseType() ; SizeOf(tp) to retrieve the size
6867 @return: -1 if typestring is not valid otherwise the size of the type
6868 """
6869 return idaapi.calc_type_size(idaapi.cvar.idati, typestr)
6870
6871def GetTinfo(ea):
6872 """
6873 Get type information of function/variable as 'typeinfo' object
6874
6875 @param ea: the address of the object
6876 @return: None on failure, or (type, fields) tuple.
6877 """
6878 return idaapi.idc_get_type_raw(ea)
6879
6880def GetLocalTinfo(ordinal):
6881 """
6882 Get local type information as 'typeinfo' object
6883
6884 @param ordinal: slot number (1...NumberOfLocalTypes)
6885 @return: None on failure, or (type, fields, name) tuple.
6886 """
6887 return idaapi.idc_get_local_type_raw(ordinal)
6888
6889def GuessType(ea):
6890 """
6891 Guess type of function/variable
6892
6893 @param ea: the address of the object, can be the structure member id too
6894
6895 @return: type string or None if failed
6896 """
6897 return idaapi.idc_guess_type(ea)
6898
6899TINFO_GUESSED = 0x0000 # this is a guessed type
6900TINFO_DEFINITE = 0x0001 # this is a definite type
6901TINFO_DELAYFUNC = 0x0002 # if type is a function and no function exists at ea,
6902 # schedule its creation and argument renaming to
6903 # auto-analysis otherwise try to create it immediately
6904
6905def ApplyType(ea, py_type, flags = TINFO_DEFINITE):
6906 """
6907 Apply the specified type to the address
6908
6909 @param ti: Type info. 'idaapi.cvar.idati' can be passed.
6910 @param py_type: typeinfo tuple (type, fields) as GetTinfo() returns
6911 or tuple (name, type, fields) as ParseType() returns
6912 or None
6913 if specified as None, then the
6914 item associated with 'ea' will be deleted.
6915 @param ea: the address of the object
6916 @param flags: combination of TINFO_... constants or 0
6917 @return: Boolean
6918 """
6919
6920 if py_type != None:
6921 if len(py_type) == 3:
6922 pt = py_type[1:] # skip name component
6923 else:
6924 pt = py_type
6925 return idaapi.apply_type(idaapi.cvar.idati, pt[0], pt[1], ea, flags)
6926 if idaapi.has_ti(ea):
6927 idaapi.del_tinfo(ea)
6928 return True
6929 return False
6930
6931def SetType(ea, newtype):
6932 """
6933 Set type of function/variable
6934
6935 @param ea: the address of the object
6936 @param newtype: the type string in C declaration form.
6937 Must contain the closing ';'
6938 if specified as an empty string, then the
6939 item associated with 'ea' will be deleted.
6940
6941 @return: 1-ok, 0-failed.
6942 """
6943 if newtype is not '':
6944 pt = ParseType(newtype, 0)
6945 if pt is None:
6946 # parsing failed
6947 return None
6948 else:
6949 pt = None
6950 return ApplyType(ea, pt, TINFO_DEFINITE)
6951
6952def ParseType(inputtype, flags):
6953 """
6954 Parse type declaration
6955
6956 @param inputtype: file name or C declarations (depending on the flags)
6957 @param flags: combination of PT_... constants or 0
6958
6959 @return: None on failure or (name, type, fields) tuple
6960 """
6961 if len(inputtype) != 0 and inputtype[-1] != ';':
6962 inputtype = inputtype + ';'
6963 return idaapi.idc_parse_decl(idaapi.cvar.idati, inputtype, flags)
6964
6965def ParseTypes(inputtype, flags = 0):
6966 """
6967 Parse type declarations
6968
6969 @param inputtype: file name or C declarations (depending on the flags)
6970 @param flags: combination of PT_... constants or 0
6971
6972 @return: number of parsing errors (0 no errors)
6973 """
6974 return idaapi.idc_parse_types(inputtype, flags)
6975
6976
6977PT_FILE = 0x0001 # input if a file name (otherwise contains type declarations)
6978PT_SILENT = 0x0002 # silent mode
6979PT_PAKDEF = 0x0000 # default pack value
6980PT_PAK1 = 0x0010 # #pragma pack(1)
6981PT_PAK2 = 0x0020 # #pragma pack(2)
6982PT_PAK4 = 0x0030 # #pragma pack(4)
6983PT_PAK8 = 0x0040 # #pragma pack(8)
6984PT_PAK16 = 0x0050 # #pragma pack(16)
6985PT_HIGH = 0x0080 # assume high level prototypes
6986 # (with hidden args, etc)
6987PT_LOWER = 0x0100 # lower the function prototypes
6988
6989
6990def GetMaxLocalType():
6991 """
6992 Get number of local types + 1
6993
6994 @return: value >= 1. 1 means that there are no local types.
6995 """
6996 return idaapi.get_ordinal_qty(idaapi.cvar.idati)
6997
6998
6999def SetLocalType(ordinal, input, flags):
7000 """
7001 Parse one type declaration and store it in the specified slot
7002
7003 @param ordinal: slot number (1...NumberOfLocalTypes)
7004 -1 means allocate new slot or reuse the slot
7005 of the existing named type
7006 @param input: C declaration. Empty input empties the slot
7007 @param flags: combination of PT_... constants or 0
7008
7009 @return: slot number or 0 if error
7010 """
7011 return idaapi.idc_set_local_type(ordinal, input, flags)
7012
7013
7014def GetLocalType(ordinal, flags):
7015 """
7016 Retrieve a local type declaration
7017 @param flags: any of PRTYPE_* constants
7018 @return: local type as a C declaration or ""
7019 """
7020 (type, fields) = GetLocalTinfo(ordinal)
7021 if type:
7022 name = GetLocalTypeName(ordinal)
7023 return idaapi.idc_print_type(type, fields, name, flags)
7024 return ""
7025
7026PRTYPE_1LINE = 0x0000 # print to one line
7027PRTYPE_MULTI = 0x0001 # print to many lines
7028PRTYPE_TYPE = 0x0002 # print type declaration (not variable declaration)
7029PRTYPE_PRAGMA = 0x0004 # print pragmas for alignment
7030
7031
7032def GetLocalTypeName(ordinal):
7033 """
7034 Retrieve a local type name
7035
7036 @param ordinal: slot number (1...NumberOfLocalTypes)
7037
7038 returns: local type name or None
7039 """
7040 return idaapi.idc_get_local_type_name(ordinal)
7041
7042
7043# ----------------------------------------------------------------------------
7044# H I D D E N A R E A S
7045# ----------------------------------------------------------------------------
7046def HideArea(start, end, description, header, footer, color):
7047 """
7048 Hide an area
7049
7050 Hidden areas - address ranges which can be replaced by their descriptions
7051
7052 @param start: area start
7053 @param end: area end
7054 @param description: description to display if the area is collapsed
7055 @param header: header lines to display if the area is expanded
7056 @param footer: footer lines to display if the area is expanded
7057 @param color: RGB color code (-1 means default color)
7058
7059 @returns: !=0 - ok
7060 """
7061 return idaapi.add_hidden_area(start, end, description, header, footer, color)
7062
7063
7064def SetHiddenArea(ea, visible):
7065 """
7066 Set hidden area state
7067
7068 @param ea: any address belonging to the hidden area
7069 @param visible: new state of the area
7070
7071 @return: != 0 - ok
7072 """
7073 ha = idaapi.get_hidden_area(ea)
7074
7075 if not ha:
7076 return 0
7077 else:
7078 ha.visible = visible
7079 return idaapi.update_hidden_area(ha)
7080
7081
7082def DelHiddenArea(ea):
7083 """
7084 Delete a hidden area
7085
7086 @param ea: any address belonging to the hidden area
7087 @returns: != 0 - ok
7088 """
7089 return idaapi.del_hidden_area(ea)
7090
7091
7092#--------------------------------------------------------------------------
7093# D E B U G G E R I N T E R F A C E
7094#--------------------------------------------------------------------------
7095def LoadDebugger(dbgname, use_remote):
7096 """
7097 Load the debugger
7098
7099 @param dbgname: debugger module name Examples: win32, linux, mac.
7100 @param use_remote: 0/1: use remote debugger or not
7101
7102 @note: This function is needed only when running idc scripts from the command line.
7103 In other cases IDA loads the debugger module automatically.
7104 """
7105 return idaapi.load_debugger(dbgname, use_remote)
7106
7107
7108def StartDebugger(path, args, sdir):
7109 """
7110 Launch the debugger
7111
7112 @param path: path to the executable file.
7113 @param args: command line arguments
7114 @param sdir: initial directory for the process
7115
7116 @return: -1-failed, 0-cancelled by the user, 1-ok
7117
7118 @note: For all args: if empty, the default value from the database will be used
7119 See the important note to the StepInto() function
7120 """
7121 return idaapi.start_process(path, args, sdir)
7122
7123
7124def StopDebugger():
7125 """
7126 Stop the debugger
7127 Kills the currently debugger process and returns to the disassembly mode
7128
7129 @return: success
7130 """
7131 return idaapi.exit_process()
7132
7133
7134def PauseProcess():
7135 """
7136 Suspend the running process
7137 Tries to suspend the process. If successful, the PROCESS_SUSPEND
7138 debug event will arrive (see GetDebuggerEvent)
7139
7140 @return: success
7141
7142 @note: To resume a suspended process use the GetDebuggerEvent function.
7143 See the important note to the StepInto() function
7144 """
7145 return idaapi.suspend_process()
7146
7147
7148def GetProcessQty():
7149 """
7150 Take a snapshot of running processes and return their number.
7151 """
7152 return idaapi.get_process_qty()
7153
7154
7155def GetProcessPid(idx):
7156 """
7157 Get the process ID of a running process
7158
7159 @param idx: number of process, is in range 0..GetProcessQty()-1
7160
7161 @return: 0 if failure
7162 """
7163 pinfo = idaapi.process_info_t()
7164 pid = idaapi.get_process_info(idx, pinfo)
7165 if pid != idaapi.NO_PROCESS:
7166 return pinfo.pid
7167 else:
7168 return 0
7169
7170
7171def GetProcessName(idx):
7172 """
7173 Get the name of a running process
7174
7175 @param idx: number of process, is in range 0..GetProcessQty()-1
7176
7177 @return: None if failure
7178 """
7179 pinfo = idaapi.process_info_t()
7180 pid = idaapi.get_process_info(idx, pinfo)
7181 return None if pid == idaapi.NO_PROCESS else pinfo.name
7182
7183
7184def AttachProcess(pid, event_id):
7185 """
7186 Attach the debugger to a running process
7187
7188 @param pid: PID of the process to attach to. If NO_PROCESS, a dialog box
7189 will interactively ask the user for the process to attach to.
7190 @param event_id: reserved, must be -1
7191
7192 @return:
7193 - -2: impossible to find a compatible process
7194 - -1: impossible to attach to the given process (process died, privilege
7195 needed, not supported by the debugger plugin, ...)
7196 - 0: the user cancelled the attaching to the process
7197 - 1: the debugger properly attached to the process
7198 @note: See the important note to the StepInto() function
7199 """
7200 return idaapi.attach_process(pid, event_id)
7201
7202
7203def DetachProcess():
7204 """
7205 Detach the debugger from the debugged process.
7206
7207 @return: success
7208 """
7209 return idaapi.detach_process()
7210
7211
7212def GetThreadQty():
7213 """
7214 Get number of threads.
7215
7216 @return: number of threads
7217 """
7218 return idaapi.get_thread_qty()
7219
7220
7221def GetThreadId(idx):
7222 """
7223 Get the ID of a thread
7224
7225 @param idx: number of thread, is in range 0..GetThreadQty()-1
7226
7227 @return: -1 if failure
7228 """
7229 return idaapi.getn_thread(idx)
7230
7231
7232def GetCurrentThreadId():
7233 """
7234 Get current thread ID
7235
7236 @return: -1 if failure
7237 """
7238 return idaapi.get_current_thread()
7239
7240
7241def SelectThread(tid):
7242 """
7243 Select the given thread as the current debugged thread.
7244
7245 @param tid: ID of the thread to select
7246
7247 @return: success
7248
7249 @note: The process must be suspended to select a new thread.
7250 """
7251 return idaapi.select_thread(tid)
7252
7253
7254def SuspendThread(tid):
7255 """
7256 Suspend thread
7257
7258 @param tid: thread id
7259
7260 @return: -1:network error, 0-failed, 1-ok
7261
7262 @note: Suspending a thread may deadlock the whole application if the suspended
7263 was owning some synchronization objects.
7264 """
7265 return idaapi.suspend_thread(tid)
7266
7267
7268def ResumeThread(tid):
7269 """
7270 Resume thread
7271
7272 @param tid: thread id
7273
7274 @return: -1:network error, 0-failed, 1-ok
7275 """
7276 return idaapi.resume_thread(tid)
7277
7278
7279def _get_modules():
7280 """
7281 INTERNAL: Enumerate process modules
7282 """
7283 module = idaapi.module_info_t()
7284 result = idaapi.get_first_module(module)
7285 while result:
7286 yield module
7287 result = idaapi.get_next_module(module)
7288
7289
7290def GetFirstModule():
7291 """
7292 Enumerate process modules
7293
7294 @return: first module's base address or None on failure
7295 """
7296 for module in _get_modules():
7297 return module.base
7298 else:
7299 return None
7300
7301
7302def GetNextModule(base):
7303 """
7304 Enumerate process modules
7305
7306 @param base: previous module's base address
7307
7308 @return: next module's base address or None on failure
7309 """
7310 foundit = False
7311 for module in _get_modules():
7312 if foundit:
7313 return module.base
7314 if module.base == base:
7315 foundit = True
7316 else:
7317 return None
7318
7319
7320def GetModuleName(base):
7321 """
7322 Get process module name
7323
7324 @param base: the base address of the module
7325
7326 @return: required info or None
7327 """
7328 for module in _get_modules():
7329 if module.base == base:
7330 return module.name
7331 else:
7332 return 0
7333
7334
7335def GetModuleSize(base):
7336 """
7337 Get process module size
7338
7339 @param base: the base address of the module
7340
7341 @return: required info or -1
7342 """
7343 for module in _get_modules():
7344 if module.base == base:
7345 return module.size
7346 else:
7347 return -1
7348
7349
7350def StepInto():
7351 """
7352 Execute one instruction in the current thread.
7353 Other threads are kept suspended.
7354
7355 @return: success
7356
7357 @note: You must call GetDebuggerEvent() after this call
7358 in order to find out what happened. Normally you will
7359 get the STEP event but other events are possible (for example,
7360 an exception might occur or the process might exit).
7361 This remark applies to all execution control functions.
7362 The event codes depend on the issued command.
7363 """
7364 return idaapi.step_into()
7365
7366
7367def StepOver():
7368 """
7369 Execute one instruction in the current thread,
7370 but without entering into functions
7371 Others threads keep suspended.
7372 See the important note to the StepInto() function
7373
7374 @return: success
7375 """
7376 return idaapi.step_over()
7377
7378
7379def RunTo(ea):
7380 """
7381 Execute the process until the given address is reached.
7382 If no process is active, a new process is started.
7383 See the important note to the StepInto() function
7384
7385 @return: success
7386 """
7387 return idaapi.run_to(ea)
7388
7389
7390def StepUntilRet():
7391 """
7392 Execute instructions in the current thread until
7393 a function return instruction is reached.
7394 Other threads are kept suspended.
7395 See the important note to the StepInto() function
7396
7397 @return: success
7398 """
7399 return idaapi.step_until_ret()
7400
7401
7402def GetDebuggerEvent(wfne, timeout):
7403 """
7404 Wait for the next event
7405 This function (optionally) resumes the process
7406 execution and wait for a debugger event until timeout
7407
7408 @param wfne: combination of WFNE_... constants
7409 @param timeout: number of seconds to wait, -1-infinity
7410
7411 @return: debugger event codes, see below
7412 """
7413 return idaapi.wait_for_next_event(wfne, timeout)
7414
7415
7416def ResumeProcess():
7417 return GetDebuggerEvent(WFNE_CONT|WFNE_NOWAIT, 0)
7418
7419def SendDbgCommand(cmd):
7420 """Sends a command to the debugger module and returns the output string.
7421 An exception will be raised if the debugger is not running or the current debugger does not export
7422 the 'SendDbgCommand' IDC command.
7423 """
7424 s = Eval('SendDbgCommand("%s");' % idaapi.str2user(cmd))
7425 if s.startswith("IDC_FAILURE"):
7426 raise Exception, "Debugger command is available only when the debugger is active!"
7427 return s
7428
7429# wfne flag is combination of the following:
7430WFNE_ANY = 0x0001 # return the first event (even if it doesn't suspend the process)
7431 # if the process is still running, the database
7432 # does not reflect the memory state. you might want
7433 # to call RefreshDebuggerMemory() in this case
7434WFNE_SUSP = 0x0002 # wait until the process gets suspended
7435WFNE_SILENT = 0x0004 # 1: be slient, 0:display modal boxes if necessary
7436WFNE_CONT = 0x0008 # continue from the suspended state
7437WFNE_NOWAIT = 0x0010 # do not wait for any event, immediately return DEC_TIMEOUT
7438 # (to be used with WFNE_CONT)
7439
7440# debugger event codes
7441NOTASK = -2 # process does not exist
7442DBG_ERROR = -1 # error (e.g. network problems)
7443DBG_TIMEOUT = 0 # timeout
7444PROCESS_START = 0x00000001 # New process started
7445PROCESS_EXIT = 0x00000002 # Process stopped
7446THREAD_START = 0x00000004 # New thread started
7447THREAD_EXIT = 0x00000008 # Thread stopped
7448BREAKPOINT = 0x00000010 # Breakpoint reached
7449STEP = 0x00000020 # One instruction executed
7450EXCEPTION = 0x00000040 # Exception
7451LIBRARY_LOAD = 0x00000080 # New library loaded
7452LIBRARY_UNLOAD = 0x00000100 # Library unloaded
7453INFORMATION = 0x00000200 # User-defined information
7454SYSCALL = 0x00000400 # Syscall (not used yet)
7455WINMESSAGE = 0x00000800 # Window message (not used yet)
7456PROCESS_ATTACH = 0x00001000 # Attached to running process
7457PROCESS_DETACH = 0x00002000 # Detached from process
7458PROCESS_SUSPEND = 0x00004000 # Process has been suspended
7459
7460
7461def RefreshDebuggerMemory():
7462 """
7463 Refresh debugger memory
7464 Upon this call IDA will forget all cached information
7465 about the debugged process. This includes the segmentation
7466 information and memory contents (register cache is managed
7467 automatically). Also, this function refreshes exported name
7468 from loaded DLLs.
7469 You must call this function before using the segmentation
7470 information, memory contents, or names of a non-suspended process.
7471 This is an expensive call.
7472 """
7473 return idaapi.refresh_debugger_memory()
7474
7475
7476def TakeMemorySnapshot(only_loader_segs):
7477 """
7478 Take memory snapshot of the debugged process
7479
7480 @param only_loader_segs: 0-copy all segments to idb
7481 1-copy only SFL_LOADER segments
7482 """
7483 return idaapi.take_memory_snapshot(only_loader_segs)
7484
7485
7486def GetProcessState():
7487 """
7488 Get debugged process state
7489
7490 @return: one of the DBG_... constants (see below)
7491 """
7492 return idaapi.get_process_state()
7493
7494DSTATE_SUSP = -1 # process is suspended
7495DSTATE_NOTASK = 0 # no process is currently debugged
7496DSTATE_RUN = 1 # process is running
7497DSTATE_RUN_WAIT_ATTACH = 2 # process is running, waiting for process properly attached
7498DSTATE_RUN_WAIT_END = 3 # process is running, but the user asked to kill/detach the process
7499 # remark: in this case, most events are ignored
7500
7501"""
7502 Get various information about the current debug event
7503 These functions are valid only when the current event exists
7504 (the process is in the suspended state)
7505"""
7506
7507# For all events:
7508
7509def GetEventId():
7510 """
7511 Get ID of debug event
7512
7513 @return: event ID
7514 """
7515 ev = idaapi.get_debug_event()
7516 assert ev, "Could not retrieve debug event"
7517 return ev.eid
7518
7519
7520def GetEventPid():
7521 """
7522 Get process ID for debug event
7523
7524 @return: process ID
7525 """
7526 ev = idaapi.get_debug_event()
7527 assert ev, "Could not retrieve debug event"
7528 return ev.pid
7529
7530
7531def GetEventTid():
7532 """
7533 Get type ID for debug event
7534
7535 @return: type ID
7536 """
7537 ev = idaapi.get_debug_event()
7538 assert ev, "Could not retrieve debug event"
7539 return ev.tid
7540
7541
7542def GetEventEa():
7543 """
7544 Get ea for debug event
7545
7546 @return: ea
7547 """
7548 ev = idaapi.get_debug_event()
7549 assert ev, "Could not retrieve debug event"
7550 return ev.ea
7551
7552
7553def IsEventHandled():
7554 """
7555 Is the debug event handled?
7556
7557 @return: boolean
7558 """
7559 ev = idaapi.get_debug_event()
7560 assert ev, "Could not retrieve debug event"
7561 return ev.handled
7562
7563
7564# For PROCESS_START, PROCESS_ATTACH, LIBRARY_LOAD events:
7565
7566def GetEventModuleName():
7567 """
7568 Get module name for debug event
7569
7570 @return: module name
7571 """
7572 ev = idaapi.get_debug_event()
7573 assert ev, "Could not retrieve debug event"
7574 return idaapi.get_event_module_name(ev)
7575
7576
7577def GetEventModuleBase():
7578 """
7579 Get module base for debug event
7580
7581 @return: module base
7582 """
7583 ev = idaapi.get_debug_event()
7584 assert ev, "Could not retrieve debug event"
7585 return idaapi.get_event_module_base(ev)
7586
7587
7588def GetEventModuleSize():
7589 """
7590 Get module size for debug event
7591
7592 @return: module size
7593 """
7594 ev = idaapi.get_debug_event()
7595 assert ev, "Could not retrieve debug event"
7596 return idaapi.get_event_module_size(ev)
7597
7598
7599def GetEventExitCode():
7600 """
7601 Get exit code for debug event
7602
7603 @return: exit code for PROCESS_EXIT, THREAD_EXIT events
7604 """
7605 ev = idaapi.get_debug_event()
7606 assert ev, "Could not retrieve debug event"
7607 return ev.exit_code
7608
7609
7610def GetEventInfo():
7611 """
7612 Get debug event info
7613
7614 @return: event info: for LIBRARY_UNLOAD (unloaded library name)
7615 for INFORMATION (message to display)
7616 """
7617 ev = idaapi.get_debug_event()
7618 assert ev, "Could not retrieve debug event"
7619 return idaapi.get_event_info(ev)
7620
7621
7622def GetEventBptHardwareEa():
7623 """
7624 Get hardware address for BREAKPOINT event
7625
7626 @return: hardware address
7627 """
7628 ev = idaapi.get_debug_event()
7629 assert ev, "Could not retrieve debug event"
7630 return idaapi.get_event_bpt_hea(ev)
7631
7632
7633def GetEventExceptionCode():
7634 """
7635 Get exception code for EXCEPTION event
7636
7637 @return: exception code
7638 """
7639 ev = idaapi.get_debug_event()
7640 assert ev, "Could not retrieve debug event"
7641 return idaapi.get_event_exc_code(ev)
7642
7643
7644def GetEventExceptionEa():
7645 """
7646 Get address for EXCEPTION event
7647
7648 @return: adress of exception
7649 """
7650 ev = idaapi.get_debug_event()
7651 assert ev, "Could not retrieve debug event"
7652 return idaapi.get_event_exc_ea(ev)
7653
7654
7655def CanExceptionContinue():
7656 """
7657 Can it continue after EXCEPTION event?
7658
7659 @return: boolean
7660 """
7661 ev = idaapi.get_debug_event()
7662 assert ev, "Could not retrieve debug event"
7663 return idaapi.can_exc_continue(ev)
7664
7665
7666def GetEventExceptionInfo():
7667 """
7668 Get info for EXCEPTION event
7669
7670 @return: info string
7671 """
7672 ev = idaapi.get_debug_event()
7673 assert ev, "Could not retrieve debug event"
7674 return idaapi.get_event_exc_info(ev)
7675
7676
7677def SetDebuggerOptions(opt):
7678 """
7679 Get/set debugger options
7680
7681 @param opt: combination of DOPT_... constants
7682
7683 @return: old options
7684 """
7685 return idaapi.set_debugger_options(opt)
7686
7687
7688DOPT_SEGM_MSGS = 0x00000001 # print messages on debugger segments modifications
7689DOPT_START_BPT = 0x00000002 # break on process start
7690DOPT_THREAD_MSGS = 0x00000004 # print messages on thread start/exit
7691DOPT_THREAD_BPT = 0x00000008 # break on thread start/exit
7692DOPT_BPT_MSGS = 0x00000010 # print message on breakpoint
7693DOPT_LIB_MSGS = 0x00000040 # print message on library load/unlad
7694DOPT_LIB_BPT = 0x00000080 # break on library load/unlad
7695DOPT_INFO_MSGS = 0x00000100 # print message on debugging information
7696DOPT_INFO_BPT = 0x00000200 # break on debugging information
7697DOPT_REAL_MEMORY = 0x00000400 # don't hide breakpoint instructions
7698DOPT_REDO_STACK = 0x00000800 # reconstruct the stack
7699DOPT_ENTRY_BPT = 0x00001000 # break on program entry point
7700DOPT_EXCDLG = 0x00006000 # exception dialogs:
7701
7702EXCDLG_NEVER = 0x00000000 # never display exception dialogs
7703EXCDLG_UNKNOWN = 0x00002000 # display for unknown exceptions
7704EXCDLG_ALWAYS = 0x00006000 # always display
7705
7706DOPT_LOAD_DINFO = 0x00008000 # automatically load debug files (pdb)
7707
7708
7709def GetDebuggerEventCondition():
7710 """
7711 Return the debugger event condition
7712 """
7713 return idaapi.get_debugger_event_cond()
7714
7715
7716def SetDebuggerEventCondition(cond):
7717 """
7718 Set the debugger event condition
7719 """
7720 return idaapi.set_debugger_event_cond(cond)
7721
7722
7723def SetRemoteDebugger(hostname, password, portnum):
7724 """
7725 Set remote debugging options
7726
7727 @param hostname: remote host name or address if empty, revert to local debugger
7728 @param password: password for the debugger server
7729 @param portnum: port number to connect (-1: don't change)
7730
7731 @return: nothing
7732 """
7733 return idaapi.set_remote_debugger(hostname, password, portnum)
7734
7735
7736def GetExceptionQty():
7737 """
7738 Get number of defined exception codes
7739 """
7740 return idaapi.get_exception_qty()
7741
7742
7743def GetExceptionCode(idx):
7744 """
7745 Get exception code
7746
7747 @param idx: number of exception in the vector (0..GetExceptionQty()-1)
7748
7749 @return: exception code (0 - error)
7750 """
7751 return idaapi.get_exception_code(idx)
7752
7753
7754def GetExceptionName(code):
7755 """
7756 Get exception information
7757
7758 @param code: exception code
7759
7760 @return: "" on error
7761 """
7762 return idaapi.get_exception_name(code)
7763
7764
7765def GetExceptionFlags(code):
7766 """
7767 Get exception information
7768
7769 @param code: exception code
7770
7771 @return: -1 on error
7772 """
7773 return idaapi.get_exception_flags(code)
7774
7775def DefineException(code, name, desc, flags):
7776 """
7777 Add exception handling information
7778
7779 @param code: exception code
7780 @param name: exception name
7781 @param desc: exception description
7782 @param flags: exception flags (combination of EXC_...)
7783
7784 @return: failure description or ""
7785 """
7786 return idaapi.define_exception(code, name, desc, flags)
7787
7788EXC_BREAK = 0x0001 # break on the exception
7789EXC_HANDLE = 0x0002 # should be handled by the debugger?
7790
7791
7792def SetExceptionFlags(code, flags):
7793 """
7794 Set exception flags
7795
7796 @param code: exception code
7797 @param flags: exception flags (combination of EXC_...)
7798 """
7799 return idaapi.set_exception_flags(code, flags)
7800
7801
7802def ForgetException(code):
7803 """
7804 Delete exception handling information
7805
7806 @param code: exception code
7807 """
7808 return idaapi.forget_exception(code)
7809
7810
7811def GetRegValue(name):
7812 """
7813 Get register value
7814
7815 @param name: the register name
7816
7817 @note: The debugger should be running. otherwise the function fails
7818 the register name should be valid.
7819 It is not necessary to use this function to get register values
7820 because a register name in the script will do too.
7821
7822 @return: register value (integer or floating point)
7823 """
7824 rv = idaapi.regval_t()
7825 res = idaapi.get_reg_val(name, rv)
7826 assert res, "get_reg_val() failed, bogus register name ('%s') perhaps?" % name
7827 return rv.ival
7828
7829
7830def SetRegValue(value, name):
7831 """
7832 Set register value
7833
7834 @param name: the register name
7835 @param value: new register value
7836
7837 @note: The debugger should be running
7838 It is not necessary to use this function to set register values.
7839 A register name in the left side of an assignment will do too.
7840 """
7841 rv = idaapi.regval_t()
7842 if type(value) == types.StringType:
7843 value = int(value, 16)
7844 elif type(value) != types.IntType and type(value) != types.LongType:
7845 print "SetRegValue: value must be integer!"
7846 return BADADDR
7847
7848 if value < 0:
7849 #ival_set cannot handle negative numbers
7850 value &= 0xFFFFFFFF
7851
7852 rv.ival = value
7853 return idaapi.set_reg_val(name, rv)
7854
7855
7856def GetBptQty():
7857 """
7858 Get number of breakpoints.
7859
7860 @return: number of breakpoints
7861 """
7862 return idaapi.get_bpt_qty()
7863
7864
7865def GetBptEA(n):
7866 """
7867 Get breakpoint address
7868
7869 @param n: number of breakpoint, is in range 0..GetBptQty()-1
7870
7871 @return: addresss of the breakpoint or BADADDR
7872 """
7873 bpt = idaapi.bpt_t()
7874
7875 if idaapi.getn_bpt(n, bpt):
7876 return bpt.ea
7877 else:
7878 return BADADDR
7879
7880
7881def GetBptAttr(ea, bptattr):
7882 """
7883 Get the characteristics of a breakpoint
7884
7885 @param ea: any address in the breakpoint range
7886 @param bptattr: the desired attribute code, one of BPTATTR_... constants
7887
7888 @return: the desired attribute value or -1
7889 """
7890 bpt = idaapi.bpt_t()
7891
7892 if not idaapi.get_bpt(ea, bpt):
7893 return -1
7894 else:
7895 if bptattr == BPTATTR_EA:
7896 return bpt.ea
7897 if bptattr == BPTATTR_SIZE:
7898 return bpt.size
7899 if bptattr == BPTATTR_TYPE:
7900 return bpt.type
7901 if bptattr == BPTATTR_COUNT:
7902 return bpt.pass_count
7903 if bptattr == BPTATTR_FLAGS:
7904 return bpt.flags
7905 if bptattr == BPTATTR_COND:
7906 return bpt.condition
7907 return -1
7908
7909
7910BPTATTR_EA = 1 # starting address of the breakpoint
7911BPTATTR_SIZE = 2 # size of the breakpoint (undefined for software breakpoint)
7912
7913# type of the breakpoint
7914BPTATTR_TYPE = 3
7915
7916# Breakpoint types:
7917BPT_WRITE = 1 # Hardware: Write access
7918BPT_RDWR = 3 # Hardware: Read/write access
7919BPT_SOFT = 4 # Software breakpoint
7920BPT_EXEC = 8 # Hardware: Execute instruction
7921BPT_DEFAULT = (BPT_SOFT|BPT_EXEC); # Choose bpt type automaticaly
7922
7923BPTATTR_COUNT = 4
7924BPTATTR_FLAGS = 5
7925BPT_BRK = 0x001 # the debugger stops on this breakpoint
7926BPT_TRACE = 0x002 # the debugger adds trace information when this breakpoint is reached
7927BPT_UPDMEM = 0x004 # refresh the memory layout and contents before evaluating bpt condition
7928BPT_ENABLED = 0x008 # enabled?
7929BPT_LOWCND = 0x010 # condition is calculated at low level (on the server side)
7930BPT_TRACEON = 0x020 # enable tracing when the breakpoint is reached
7931BPT_TRACE_INSN = 0x040 # instruction tracing
7932BPT_TRACE_FUNC = 0x080 # function tracing
7933BPT_TRACE_BBLK = 0x100 # basic block tracing
7934
7935BPTATTR_COND = 6 # Breakpoint condition. NOTE: the return value is a string in this case
7936
7937# Breakpoint location type:
7938BPLT_ABS = 0 # Absolute address. Attributes:
7939 # - locinfo: absolute address
7940
7941BPLT_REL = 1 # Module relative address. Attributes:
7942 # - locpath: the module path
7943 # - locinfo: offset from the module base address
7944
7945BPLT_SYM = 2 # Symbolic name. The name will be resolved on DLL load/unload
7946 # events and on naming an address. Attributes:
7947 # - locpath: symbol name
7948 # - locinfo: offset from the symbol base address
7949
7950
7951def SetBptAttr(address, bptattr, value):
7952 """
7953 modifiable characteristics of a breakpoint
7954
7955 @param address: any address in the breakpoint range
7956 @param bptattr: the attribute code, one of BPTATTR_* constants
7957 BPTATTR_CND is not allowed, see SetBptCnd()
7958 @param value: the attibute value
7959
7960 @return: success
7961 """
7962 bpt = idaapi.bpt_t()
7963
7964 if not idaapi.get_bpt(address, bpt):
7965 return False
7966 else:
7967 if bptattr not in [ BPTATTR_SIZE, BPTATTR_TYPE, BPTATTR_FLAGS, BPTATTR_COUNT ]:
7968 return False
7969 if bptattr == BPTATTR_SIZE:
7970 bpt.size = value
7971 if bptattr == BPTATTR_TYPE:
7972 bpt.type = value
7973 if bptattr == BPTATTR_COUNT:
7974 bpt.pass_count = value
7975 if bptattr == BPTATTR_FLAGS:
7976 bpt.flags = value
7977
7978 idaapi.update_bpt(bpt)
7979 return True
7980
7981def SetBptCndEx(ea, cnd, is_lowcnd):
7982 """
7983 Set breakpoint condition
7984
7985 @param ea: any address in the breakpoint range
7986 @param cnd: breakpoint condition
7987 @param is_lowcnd: 0 - regular condition, 1 - low level condition
7988
7989 @return: success
7990 """
7991 bpt = idaapi.bpt_t()
7992
7993 if not idaapi.get_bpt(ea, bpt):
7994 return False
7995
7996 bpt.condition = cnd
7997 if is_lowcnd:
7998 bpt.flags |= BPT_LOWCND
7999 else:
8000 bpt.flags &= ~BPT_LOWCND
8001
8002 return idaapi.update_bpt(bpt)
8003
8004
8005def SetBptCnd(ea, cnd):
8006 """
8007 Set breakpoint condition
8008
8009 @param ea: any address in the breakpoint range
8010 @param cnd: breakpoint condition
8011
8012 @return: success
8013 """
8014 return SetBptCndEx(ea, cnd, 0)
8015
8016
8017def AddBptEx(ea, size, bpttype):
8018 """
8019 Add a new breakpoint
8020
8021 @param ea: any address in the process memory space:
8022 @param size: size of the breakpoint (irrelevant for software breakpoints):
8023 @param bpttype: type of the breakpoint (one of BPT_... constants)
8024
8025 @return: success
8026
8027 @note: Only one breakpoint can exist at a given address.
8028 """
8029 return idaapi.add_bpt(ea, size, bpttype)
8030
8031
8032def AddBpt(ea):
8033 return AddBptEx(ea, 0, BPT_DEFAULT)
8034
8035
8036def DelBpt(ea):
8037 """
8038 Delete breakpoint
8039
8040 @param ea: any address in the process memory space:
8041
8042 @return: success
8043 """
8044 return idaapi.del_bpt(ea)
8045
8046
8047def EnableBpt(ea, enable):
8048 """
8049 Enable/disable breakpoint
8050
8051 @param ea: any address in the process memory space
8052
8053 @return: success
8054
8055 @note: Disabled breakpoints are not written to the process memory
8056 """
8057 return idaapi.enable_bpt(ea, enable)
8058
8059
8060def CheckBpt(ea):
8061 """
8062 Check a breakpoint
8063
8064 @param ea: address in the process memory space
8065
8066 @return: one of BPTCK_... constants
8067 """
8068 return idaapi.check_bpt(ea)
8069
8070BPTCK_NONE = -1 # breakpoint does not exist
8071BPTCK_NO = 0 # breakpoint is disabled
8072BPTCK_YES = 1 # breakpoint is enabled
8073BPTCK_ACT = 2 # breakpoint is active (written to the process)
8074
8075
8076def EnableTracing(trace_level, enable):
8077 """
8078 Enable step tracing
8079
8080 @param trace_level: what kind of trace to modify
8081 @param enable: 0: turn off, 1: turn on
8082
8083 @return: success
8084 """
8085 assert trace_level in [ TRACE_STEP, TRACE_INSN, TRACE_FUNC ], \
8086 "trace_level must be one of TRACE_* constants"
8087
8088 if trace_level == TRACE_STEP:
8089 return idaapi.enable_step_trace(enable)
8090
8091 if trace_level == TRACE_INSN:
8092 return idaapi.enable_insn_trace(enable)
8093
8094 if trace_level == TRACE_FUNC:
8095 return idaapi.enable_func_trace(enable)
8096
8097 return False
8098
8099TRACE_STEP = 0x0 # lowest level trace. trace buffers are not maintained
8100TRACE_INSN = 0x1 # instruction level trace
8101TRACE_FUNC = 0x2 # function level trace (calls & rets)
8102
8103
8104def GetStepTraceOptions():
8105 """
8106 Get step current tracing options
8107
8108 @return: a combination of ST_... constants
8109 """
8110 return idaapi.get_step_trace_options()
8111
8112
8113def SetStepTraceOptions(options):
8114 """
8115 Set step current tracing options.
8116 @param options: combination of ST_... constants
8117 """
8118 return idaapi.set_step_trace_options(options)
8119
8120
8121ST_OVER_DEBUG_SEG = 0x01 # step tracing will be disabled when IP is in a debugger segment
8122ST_OVER_LIB_FUNC = 0x02 # step tracing will be disabled when IP is in a library function
8123ST_ALREADY_LOGGED = 0x04 # step tracing will be disabled when IP is already logged
8124ST_SKIP_LOOPS = 0x08 # step tracing will try to skip loops already recorded
8125
8126def LoadTraceFile(filename):
8127 """
8128 Load a previously recorded binary trace file
8129 @param filename: trace file
8130 """
8131 return idaapi.load_trace_file(filename)
8132
8133def SaveTraceFile(filename, description):
8134 """
8135 Save current trace to a binary trace file
8136 @param filename: trace file
8137 @param description: trace description
8138 """
8139 return idaapi.save_trace_file(filename, description)
8140
8141def CheckTraceFile(filename):
8142 """
8143 Check the given binary trace file
8144 @param filename: trace file
8145 """
8146 return idaapi.is_valid_trace_file(filename)
8147
8148def DiffTraceFile(filename):
8149 """
8150 Diff current trace buffer against given trace
8151 @param filename: trace file
8152 """
8153 return idaapi.diff_trace_file(filename)
8154
8155def ClearTraceFile(filename):
8156 """
8157 Clear the current trace buffer
8158 """
8159 return idaapi.clear_trace()
8160
8161def GetTraceDesc(filename):
8162 """
8163 Get the trace description of the given binary trace file
8164 @param filename: trace file
8165 """
8166 return idaapi.get_trace_file_desc(filename)
8167
8168def SetTraceDesc(filename, description):
8169 """
8170 Update the trace description of the given binary trace file
8171 @param filename: trace file
8172 @description: trace description
8173 """
8174 return idaapi.set_trace_file_desc(filename, description)
8175
8176def GetMaxTev():
8177 """
8178 Return the total number of recorded events
8179 """
8180 return idaapi.get_tev_qty()
8181
8182def GetTevEa(tev):
8183 """
8184 Return the address of the specified event
8185 @param tev: event number
8186 """
8187 return idaapi.get_tev_ea(tev)
8188
8189TEV_NONE = 0 # no event
8190TEV_INSN = 1 # an instruction trace
8191TEV_CALL = 2 # a function call trace
8192TEV_RET = 3 # a function return trace
8193TEV_BPT = 4 # write, read/write, execution trace
8194TEV_MEM = 5 # memory layout changed
8195TEV_EVENT = 6 # debug event
8196
8197def GetTevType(tev):
8198 """
8199 Return the type of the specified event (TEV_... constants)
8200 @param tev: event number
8201 """
8202 return idaapi.get_tev_type(tev)
8203
8204def GetTevTid(tev):
8205 """
8206 Return the thread id of the specified event
8207 @param tev: event number
8208 """
8209 return idaapi.get_tev_tid(tev)
8210
8211def GetTevRegVal(tev, reg):
8212 """
8213 Return the register value for the specified event
8214 @param tev: event number
8215 @param reg: register name (like EAX, RBX, ...)
8216 """
8217 return idaapi.get_tev_reg_val(tev, reg)
8218
8219def GetTevRegMemQty(tev):
8220 """
8221 Return the number of memory addresses recorded for the specified event
8222 @param tev: event number
8223 """
8224 return idaapi.get_tev_reg_mem_qty(tev)
8225
8226def GetTevRegMem(tev, idx):
8227 """
8228 Return the memory pointed by 'index' for the specified event
8229 @param tev: event number
8230 @param idx: memory address index
8231 """
8232 return idaapi.get_tev_reg_mem(tev, idx)
8233
8234def GetTevRegMemEa(tev, idx):
8235 """
8236 Return the address pointed by 'index' for the specified event
8237 @param tev: event number
8238 @param idx: memory address index
8239 """
8240 return idaapi.get_tev_reg_mem_ea(tev, idx)
8241
8242def GetTevCallee(tev):
8243 """
8244 Return the address of the callee for the specified event
8245 @param tev: event number
8246 """
8247 return idaapi.get_call_tev_callee(tev)
8248
8249def GetTevReturn(tev):
8250 """
8251 Return the return address for the specified event
8252 @param tev: event number
8253 """
8254 return idaapi.get_ret_tev_return(tev)
8255
8256def GetBptTevEa(tev):
8257 """
8258 Return the address of the specified TEV_BPT event
8259 @param tev: event number
8260 """
8261 return idaapi.get_bpt_tev_ea(tev)
8262
8263
8264#--------------------------------------------------------------------------
8265# C O L O R S
8266#--------------------------------------------------------------------------
8267
8268def GetColor(ea, what):
8269 """
8270 Get item color
8271
8272 @param ea: address of the item
8273 @param what: type of the item (one of CIC_* constants)
8274
8275 @return: color code in RGB (hex 0xBBGGRR)
8276 """
8277 if what not in [ CIC_ITEM, CIC_FUNC, CIC_SEGM ]:
8278 raise ValueError, "'what' must be one of CIC_ITEM, CIC_FUNC and CIC_SEGM"
8279
8280 if what == CIC_ITEM:
8281 return idaapi.get_item_color(ea)
8282
8283 if what == CIC_FUNC:
8284 func = idaapi.get_func(ea)
8285 if func:
8286 return func.color
8287 else:
8288 return DEFCOLOR
8289
8290 if what == CIC_SEGM:
8291 seg = idaapi.getseg(ea)
8292 if seg:
8293 return seg.color
8294 else:
8295 return DEFCOLOR
8296
8297# color item codes:
8298CIC_ITEM = 1 # one instruction or data
8299CIC_FUNC = 2 # function
8300CIC_SEGM = 3 # segment
8301
8302DEFCOLOR = 0xFFFFFFFF # Default color
8303
8304
8305def SetColor(ea, what, color):
8306 """
8307 Set item color
8308
8309 @param ea: address of the item
8310 @param what: type of the item (one of CIC_* constants)
8311 @param color: new color code in RGB (hex 0xBBGGRR)
8312
8313 @return: success (True or False)
8314 """
8315 if what not in [ CIC_ITEM, CIC_FUNC, CIC_SEGM ]:
8316 raise ValueError, "'what' must be one of CIC_ITEM, CIC_FUNC and CIC_SEGM"
8317
8318 if what == CIC_ITEM:
8319 return idaapi.set_item_color(ea, color)
8320
8321 if what == CIC_FUNC:
8322 func = idaapi.get_func(ea)
8323 if func:
8324 func.color = color
8325 return bool(idaapi.update_func(func))
8326 else:
8327 return False
8328
8329 if what == CIC_SEGM:
8330 seg = idaapi.getseg(ea)
8331 if seg:
8332 seg.color = color
8333 return bool(seg.update())
8334 else:
8335 return False
8336
8337
8338#--------------------------------------------------------------------------
8339# X M L
8340#--------------------------------------------------------------------------
8341
8342def SetXML(path, name, value):
8343 """
8344 Set or update one or more XML values.
8345
8346 @param path: XPath expression of elements where to create value(s)
8347 @param name: name of the element/attribute
8348 (use @XXX for an attribute) to create.
8349 If 'name' is empty, the elements or
8350 attributes returned by XPath are directly
8351 updated to contain the new 'value'.
8352 @param value: value of the element/attribute
8353
8354 @return: success (True or False)
8355 """
8356 return idaapi.set_xml(path, name, value)
8357
8358
8359def GetXML(path):
8360 """
8361 Get one XML value.
8362
8363 @param path: XPath expression to an element
8364 or attribute whose value is requested
8365
8366 @return: the value, None if failed
8367 """
8368 v = idaapi.value_t()
8369 if idaapi.get_xml(path):
8370 return v.str
8371 else:
8372 return None
8373
8374
8375#----------------------------------------------------------------------------
8376# A R M S P E C I F I C
8377#----------------------------------------------------------------------------
8378def ArmForceBLJump(ea):
8379 """
8380 Some ARM compilers in Thumb mode use BL (branch-and-link)
8381 instead of B (branch) for long jumps, since BL has more range.
8382 By default, IDA tries to determine if BL is a jump or a call.
8383 You can override IDA's decision using commands in Edit/Other menu
8384 (Force BL call/Force BL jump) or the following two functions.
8385
8386 Force BL instruction to be a jump
8387
8388 @param ea: address of the BL instruction
8389
8390 @return: 1-ok, 0-failed
8391 """
8392 return Eval("ArmForceBLJump(0x%x)"%ea)
8393
8394
8395def ArmForceBLCall(ea):
8396 """
8397 Force BL instruction to be a call
8398
8399 @param ea: address of the BL instruction
8400
8401 @return: 1-ok, 0-failed
8402 """
8403 return Eval("ArmForceBLCall(0x%x)"%ea)
8404
8405
8406#--------------------------------------------------------------------------
8407# Compatibility macros:
8408def Compile(file): return CompileEx(file, 1)
8409def OpOffset(ea,base): return OpOff(ea,-1,base)
8410def OpNum(ea): return OpNumber(ea,-1)
8411def OpChar(ea): return OpChr(ea,-1)
8412def OpSegment(ea): return OpSeg(ea,-1)
8413def OpDec(ea): return OpDecimal(ea,-1)
8414def OpAlt1(ea, opstr): return OpAlt(ea, 0, opstr)
8415def OpAlt2(ea, opstr): return OpAlt(ea, 1, opstr)
8416def StringStp(x): return SetCharPrm(INF_ASCII_BREAK,x)
8417def LowVoids(x): return SetLongPrm(INF_LOW_OFF,x)
8418def HighVoids(x): return SetLongPrm(INF_HIGH_OFF,x)
8419def TailDepth(x): return SetLongPrm(INF_MAXREF,x)
8420def Analysis(x): return SetCharPrm(INF_AUTO,x)
8421def Tabs(x): return SetCharPrm(INF_ENTAB,x)
8422#def Comments(x): SetCharPrm(INF_CMTFLAG,((x) ? (SW_ALLCMT|GetCharPrm(INF_CMTFLAG)) : (~SW_ALLCMT&GetCharPrm(INF_CMTFLAG))))
8423def Voids(x): return SetCharPrm(INF_VOIDS,x)
8424def XrefShow(x): return SetCharPrm(INF_XREFNUM,x)
8425def Indent(x): return SetCharPrm(INF_INDENT,x)
8426def CmtIndent(x): return SetCharPrm(INF_COMMENT,x)
8427def AutoShow(x): return SetCharPrm(INF_SHOWAUTO,x)
8428def MinEA(): return GetLongPrm(INF_MIN_EA)
8429def MaxEA(): return GetLongPrm(INF_MAX_EA)
8430def BeginEA(): return GetLongPrm(INF_BEGIN_EA)
8431def set_start_cs(x): return SetLongPrm(INF_START_CS,x)
8432def set_start_ip(x): return SetLongPrm(INF_START_IP,x)
8433
8434def WriteMap(filepath):
8435 return GenerateFile(OFILE_MAP, filepath, 0, BADADDR, GENFLG_MAPSEG|GENFLG_MAPNAME)
8436
8437def WriteTxt(filepath, ea1, ea2):
8438 return GenerateFile(OFILE_ASM, filepath, ea1, ea2, 0)
8439
8440def WriteExe(filepath):
8441 return GenerateFile(OFILE_EXE, filepath, 0, BADADDR, 0)
8442
8443
8444UTP_STRUCT = idaapi.UTP_STRUCT
8445UTP_ENUM = idaapi.UTP_ENUM
8446
8447
8448def BeginTypeUpdating(utp):
8449 """
8450 Begin type updating. Use this function if you
8451 plan to call AddEnumConst or similar type modification functions
8452 many times or from inside a loop
8453
8454 @param utp: one of UTP_xxxx consts
8455 @return: None
8456 """
8457 return idaapi.begin_type_updating(utp)
8458
8459
8460def EndTypeUpdating(utp):
8461 """
8462 End type updating. Refreshes the type system
8463 at the end of type modification operations
8464
8465 @param utp: one of idaapi.UTP_xxxx consts
8466 @return: None
8467 """
8468 return idaapi.end_type_updating(utp)
8469
8470
8471def AddConst(enum_id, name,value): return AddConstEx(enum_id, name, value, idaapi.BADADDR)
8472def AddStruc(index, name): return AddStrucEx(index,name, 0)
8473def AddUnion(index, name): return AddStrucEx(index,name, 1)
8474def OpStroff(ea, n, strid): return OpStroffEx(ea,n,strid, 0)
8475def OpEnum(ea, n, enumid): return OpEnumEx(ea,n,enumid, 0)
8476def DelConst(constid, v, mask): return DelConstEx(constid, v, 0, mask)
8477def GetConst(constid, v, mask): return GetConstEx(constid, v, 0, mask)
8478def AnalyseArea(sEA, eEA): return AnalyzeArea(sEA,eEA)
8479
8480def MakeStruct(ea, name): return MakeStructEx(ea, -1, name)
8481def MakeCustomData(ea, size, dtid, fid): return MakeCustomDataEx(ea, size, dtid, fid)
8482def Name(ea): return NameEx(BADADDR, ea)
8483def GetTrueName(ea): return GetTrueNameEx(BADADDR, ea)
8484def MakeName(ea, name): return MakeNameEx(ea,name,SN_CHECK)
8485
8486#def GetFrame(ea): return GetFunctionAttr(ea, FUNCATTR_FRAME)
8487#def GetFrameLvarSize(ea): return GetFunctionAttr(ea, FUNCATTR_FRSIZE)
8488#def GetFrameRegsSize(ea): return GetFunctionAttr(ea, FUNCATTR_FRREGS)
8489#def GetFrameArgsSize(ea): return GetFunctionAttr(ea, FUNCATTR_ARGSIZE)
8490#def GetFunctionFlags(ea): return GetFunctionAttr(ea, FUNCATTR_FLAGS)
8491#def SetFunctionFlags(ea, flags): return SetFunctionAttr(ea, FUNCATTR_FLAGS, flags)
8492
8493#def SegStart(ea): return GetSegmentAttr(ea, SEGATTR_START)
8494#def SegEnd(ea): return GetSegmentAttr(ea, SEGATTR_END)
8495#def SetSegmentType(ea, type): return SetSegmentAttr(ea, SEGATTR_TYPE, type)
8496
8497def SegCreate(a1, a2, base, use32, align, comb): return AddSeg(a1, a2, base, use32, align, comb)
8498def SegDelete(ea, flags): return DelSeg(ea, flags)
8499def SegBounds(ea, startea, endea, flags): return SetSegBounds(ea, startea, endea, flags)
8500def SegRename(ea, name): return RenameSeg(ea, name)
8501def SegClass(ea, segclass): return SetSegClass(ea, segclass)
8502def SegAddrng(ea, bitness): return SetSegAddressing(ea, bitness)
8503def SegDefReg(ea, reg, value): return SetSegDefReg(ea, reg, value)
8504
8505
8506def Comment(ea): return GetCommentEx(ea, 0)
8507"""Returns the regular comment or None"""
8508
8509def RptCmt(ea): return GetCommentEx(ea, 1)
8510"""Returns the repeatable comment or None"""
8511
8512def SetReg(ea, reg, value): return SetRegEx(ea, reg, value, SR_user)
8513
8514
8515# Convenience functions:
8516def here(): return ScreenEA()
8517def isEnabled(ea): return (PrevAddr(ea+1)==ea)
8518
8519# Obsolete segdel macros:
8520SEGDEL_PERM = 0x0001 # permanently, i.e. disable addresses
8521SEGDEL_KEEP = 0x0002 # keep information (code & data, etc)
8522SEGDEL_SILENT = 0x0004 # be silent
8523
8524ARGV = []
8525"""The command line arguments passed to IDA via the -S switch."""
8526
8527# END OF IDC COMPATIBILY CODE