hexrays.hpp
Go to the documentation of this file.
1 /*
2  * Hex-Rays Decompiler project
3  * Copyright (c) 1990-2018 Hex-Rays
4  * ALL RIGHTS RESERVED.
5  *
6  * There are 2 representations of the binary code in the decompiler:
7  * - microcode: processor instructions are translated into it and then
8  * the decompiler optimizes and transforms it
9  * - ctree: ctree is built from the optimized microcode and represents
10  * AST-like tree with C statements and expressions. It can
11  * be printed as C code.
12  *
13  * Microcode is represented by the following classes:
14  * mbl_array_t keeps general info about the decompiled code and
15  * array of basic blocks. usually mbl_array_t is named 'mba'
16  * mblock_t a basic block. includes list of instructions
17  * minsn_t an instruction. contains 3 operands: left, right, and
18  * destination
19  * mop_t an operand. depending on its type may hold various info
20  * like a number, register, stack variable, etc.
21  * mlist_t list of memory or register locations; can hold vast areas
22  * of memory and multiple registers. this class is used
23  * very extensively in the decompiler. it may represent
24  * list of locations accessed by an instruction or even
25  * an entire basic block. it is also used as argument of
26  * many functions. for example, there is a function
27  * that searches for an instruction that refers to a mlist_t.
28  * See http://www.hexblog.com/?p=1232 for some pictures
29  *
30  * Ctree is represented by:
31  * cfunc_t keeps general info about the decompiled code, including a
32  * pointer to mbl_array_t. deleting cfunc_t will delete
33  * mbl_array_t too (however, decompiler returns cfuncptr_t,
34  * which is a reference counting object and deletes the
35  * underlying function as soon as all references to it go
36  * out of scope). cfunc_t has 'body', which represents the
37  * decompiled function body as cinsn_t.
38  * cinsn_t a C statement. can be a compound statement or any other
39  * legal C statements (like if, for, while, return,
40  * expression-statement, etc). depending on the statement
41  * type has pointers to additional info. for example, the
42  * 'if' statement has poiner to cif_t, which holds the
43  * 'if' condition, 'then' branch, and optionally 'else'
44  * branch. Please note that despite of the name cinsn_t
45  * we say "statements", not "instructions". For us
46  * instructions are part of microcode, not ctree.
47  * cexpr_t a C expression. is used as part of a C statement, when
48  * necessary. cexpr_t has 'type' field, which keeps the
49  * expression type.
50  * citem_t a base class for cinsn_t and cexpr_t, holds common info
51  * like the address, label, and opcode.
52  * cnumber_t a constant 64-bit number. in addition to its value also
53  * holds information how to represent it: decimal, hex, or
54  * as a symbolic constant (enum member). please note that
55  * numbers are represented by another class (mnumber_t)
56  * in microcode.
57  * See http://www.hexblog.com/?p=107 for some pictures and more details
58  *
59  * Both microcode and ctree use the following class:
60  * lvar_t a local variable. may represent a stack or register
61  * variable. a variable has a name, type, location, etc.
62  * the list of variables is stored in mba->vars.
63  * lvar_locator_t holds a variable location (vdloc_t) and its definition
64  * address.
65  * vdloc_t describes a variable location, like a register number,
66  * a stack offset, or, in complex cases, can be a mix of
67  * register and stack locations. very similar to argloc_t,
68  * which is used in ida. the differences between argloc_t
69  * and vdloc_t are:
70  * - vdloc_t never uses ARGLOC_REG2
71  * - vdloc_t uses micro register numbers instead of
72  * processor register numbers
73  * - the stack offsets are never negative in vdloc_t, while
74  * in argloc_t there can be negative offsets
75  *
76  * The above are the most important classes in this header file. There are
77  * many auxiliary classes, please see their definitions below.
78  *
79  */
80 
81 #ifndef __HEXRAYS_HPP
82 #define __HEXRAYS_HPP
83 
84 #include <pro.h>
85 #include <fpro.h>
86 #include <ida.hpp>
87 #include <idp.hpp>
88 #include <gdl.hpp>
89 #include <ieee.h>
90 #include <loader.hpp>
91 #include <kernwin.hpp>
92 #include <typeinf.hpp>
93 #include <set>
94 #include <map>
95 #include <deque>
96 #include <queue>
97 #include <algorithm>
98 
99 /*
100  * We can imagine a virtual micro machine that executes microcode.
101  * This virtual micro machine has many registers.
102  * Each register is 8 bits wide. During translation of processor
103  * instructions into microcode, multibyte processor registers are mapped
104  * to adjacent microregisters. Processor condition codes are also
105  * represented by microregisters. The microregisters are grouped
106  * into following groups:
107  * 0..7: condition codes
108  * 8..n: all processor registers (including fpu registers, if necessary)
109  * this range may also include temporary registers used during
110  * the initial microcode generation
111  * n.. : so called kernel registers; they are used during optimization
112  * see is_kreg()
113  *
114  * Each micro-instruction (minsn_t) has zero to three operands.
115  * Some of the possible operands types are:
116  * - immediate value
117  * - register
118  * - memory reference
119  * - result of another micro-instruction
120  *
121  * The operands (mop_t) are l (left), r (right), d (destination).
122  * An example of a microinstruction:
123  * add r0.4, #8.4, r2.4
124  * which means 'add constant 8 to r0 and place the result into r2'.
125  * where the left operand is 'r0', its size is 4 bytes (r0.4)
126  * the right operand is constant '8', its size is 4 bytes (#8.4)
127  * the destination operand is 'r2', its size is 4 bytes (r2.4)
128  * 'd' is almost always the destination but there are exceptions.
129  * See mcode_modifies_d(). For example, stx does not modify 'd'.
130  * See the opcode map below for the list of microinstructions and their
131  * operands. Most instructions are very simple and do not need
132  * detailed explanations. There are no side effects.
133  *
134  * Each operand has a size specifier. The following sizes can be used in
135  * practically all contexts: 1, 2, 4, 8, 16 bytes. Floating types may have
136  * other sizes. Functions may return objects of arbitrary size, as well as
137  * operations upon UDT's (user-defined types, which are structs are unions).
138  *
139  * Memory is considered to consist of several segments.
140  * A memory reference is made using a (selector, offset) pair.
141  * A selector is always 2 bytes long. An offset can be 2 or 4 bytes long.
142  * Currently the selectors are not used very much. The decompiler tries to
143  * resolve (selector, offset) pairs into direct memory references at each
144  * opportunity and then operates on mop_v operands. In other words,
145  * while the decompiler can handle segmented memory models, internally
146  * it still uses simple linear addresses.
147  *
148  * The following memory regions are recognized:
149  * - GLBLOW global memory: low part, everything below the stack
150  * - LVARS stack: local variables
151  * - RETADDR stack: return address
152  * - SHADOW stack: shadow arguments
153  * - ARGS stack: regular stack arguments
154  * - GLBHIGH global memory: high part, everything above the stack
155  * Any stack region may be empty. Objects residing in one memory region
156  * are considered to be completely distinct from objects in other regions.
157  * We allocate the stack frame in some memory region, which is not
158  * allocated for any purposes in IDA. This permits us to use linear addresses
159  * for all memory references, including the stack frame.
160  *
161  * If the operand size is bigger than a byte then the register
162  * operand references a block of registers. For example:
163  *
164  * ldc #1.4, r8.4
165  *
166  * loads a constant 1 to registers 8, 9, 10, 11:
167  *
168  * #1 -> r8
169  * #0 -> r9
170  * #0 -> r10
171  * #0 -> r11
172  *
173  * This example uses little-endian byte ordering.
174  * Big-endian byte ordering is supported too. Registers are always little-
175  * endian, regardless of the memory endianness.
176  *
177  * Each instruction has 'next' and 'prev' fields that are used to form
178  * a doubly linked list. Such lists are present for each basic block (mblock_t).
179  * Basic blocks have other attributes, including:
180  * - dead_at_start: list of dead locations at the block start
181  * - maybuse: list of locations the block may use
182  * - maybdef: list of locations the block may define (or spoil)
183  * - mustbuse: list of locations the block will certainly use
184  * - mustbdef: list of locations the block will certainly define
185  * - dnu: list of locations the block will certainly define
186  * but will not use (registers or non-aliasable stkack vars)
187  *
188  * These lists are represented by the mlist_t class. It consists of 2 parts:
189  * - rlist_t: list of microregisters (possibly including virtual stack locations)
190  * - ivlset_t: list of memory locations represented as intervals
191  * we use linear addresses in this list.
192  * The mlist_t class is used quite often. For example, to find what an operand
193  * can spoil, we build its 'maybe-use' list. Then we can find out if this list
194  * is accessed using the is_accessed() or is_accessed_globally() functions.
195  *
196  * All basic blocks of the decompiled function constitute an array called
197  * mbl_array_t (array of microblocks). This is a huge class that has too
198  * many fields to describe here (some of the fields are not visible in the sdk)
199  * The most importants ones are:
200  * - stack frame: frregs, stacksize, etc
201  * - memory: aliased, restricted, and other ranges
202  * - type: type of the current function, its arguments (argidx) and
203  * local variables (vars)
204  * - natural: array of pointers to basic blocks. the basic blocks
205  * are also accessible as a doubly linked list starting from 'blocks'.
206  * - bg: control flow graph. the graph gives access to the use-def
207  * chains that describe data dependencies between basic blocks
208  *
209  */
210 
211 #ifdef __NT__
212 #pragma warning(push)
213 #pragma warning(disable:4062) // enumerator 'x' in switch of enum 'y' is not handled
214 #pragma warning(disable:4265) // virtual functions without virtual destructor
215 #endif
216 
217 #define hexapi ///< Public functions are marked with this keyword
218 
219 // Warning suppressions for PVS Studio:
220 //-V:2:654 The condition '2' of loop is always true.
221 //-V::719 The switch statement does not cover all values
222 //-V:verify:678
223 //-V:chain_keeper_t:690 copy ctr will be generated
224 //-V:add_block:656 call to the same function
225 //-V:add:792 The 'add' function located to the right of the operator '|' will be called regardless of the value of the left operand
226 //-V:sub:792 The 'sub' function located to the right of the operator '|' will be called regardless of the value of the left operand
227 //-V:intersect:792 The 'intersect' function located to the right of the operator '|' will be called regardless of the value of the left operand
228 // Lint suppressions:
229 //lint -sem(mop_t::_make_cases, custodial(1))
230 //lint -sem(mop_t::_make_pair, custodial(1))
231 //lint -sem(mop_t::_make_callinfo, custodial(1))
232 //lint -sem(mop_t::_make_insn, custodial(1))
233 //lint -sem(mop_t::make_insn, custodial(1))
234 
235 // Microcode level forward definitions:
236 class mop_t; // microinstruction operand
237 class mop_pair_t; // pair of operands. example, :(edx.4,eax.4).8
238 class mop_addr_t; // address of an operand. example: &global_var
239 class mcallinfo_t; // function call info. example: <cdecl:"int x" #10.4>.8
240 class mcases_t; // jump table cases. example: {0 => 12, 1 => 13}
241 class minsn_t; // microinstruction
242 class mblock_t; // basic block
243 class mbl_array_t; // array of blocks, represents microcode for a function
244 class codegen_t; // helper class to generate the initial microcode
245 class mbl_graph_t; // control graph of microcode
246 struct vdui_t; // widget representing the pseudocode window
247 struct hexrays_failure_t; // decompilation failure object, is thrown by exceptions
248 struct mba_stats_t; // statistics about decompilation of a function
249 struct mlist_t; // list of memory and register locations
250 struct voff_t; // value offset (microregister number or stack offset)
251 typedef std::set<voff_t> voff_set_t;
252 struct vivl_t; // value interval (register or stack range)
253 typedef int mreg_t; ///< Micro register
254 
255 // Ctree level forward definitions:
256 struct cfunc_t; // result of decompilation, the highest level object
257 struct citem_t; // base class for cexpr_t and cinsn_t
258 struct cexpr_t; // C expression
259 struct cinsn_t; // C statement
260 struct cblock_t; // C statement block (sequence of statements)
261 struct cswitch_t; // C switch statement
262 struct carg_t; // call argument
263 struct carglist_t; // vector of call arguments
264 
265 typedef std::set<ea_t> easet_t;
266 typedef std::set<minsn_t *> minsn_ptr_set_t;
267 typedef std::set<qstring> strings_t;
268 typedef qvector<minsn_t*> minsnptrs_t;
269 typedef qvector<mop_t*> mopptrs_t;
270 typedef qvector<mop_t> mopvec_t;
271 typedef qvector<uint64> uint64vec_t;
272 typedef qvector<mreg_t> mregvec_t;
273 
274 // Function frames must be smaller than this value, otherwise
275 // the decompiler will bail out with MERR_HUGESTACK
276 #define MAX_SUPPORTED_STACK_SIZE 0x100000 // 1MB
277 
278 typedef uint64 uvlr_t;
279 typedef int64 svlr_t;
280 enum { MAX_VLR_SIZE = sizeof(uvlr_t) };
281 const uvlr_t MAX_VALUE = uvlr_t(-1);
282 const svlr_t MAX_SVALUE = svlr_t(uvlr_t(-1) >> 1);
283 const svlr_t MIN_SVALUE = ~MAX_SVALUE;
284 
285 enum cmpop_t
286 { // the order of comparisons is the same as in microcode opcodes
287  CMP_NZ,
288  CMP_Z,
289  CMP_AE,
290  CMP_B,
291  CMP_A,
292  CMP_BE,
293  CMP_GT,
294  CMP_GE,
295  CMP_LT,
296  CMP_LE,
297 };
298 
299 //-------------------------------------------------------------------------
300 // value-range class to keep possible operand value(s).
301 class valrng_t
302 {
303 protected:
304  int flags;
305 #define VLR_TYPE 0x0F // valrng_t type
306 #define VLR_NONE 0x00 // no values
307 #define VLR_ALL 0x01 // all values
308 #define VLR_IVLS 0x02 // union of disjoint intervals
309 #define VLR_RANGE 0x03 // strided range
310 #define VLR_SRANGE 0x04 // strided range with signed bound
311 #define VLR_BITS 0x05 // known bits
312 #define VLR_SECT 0x06 // intersection of sub-ranges
313  // each sub-range should be simple or union
314 #define VLR_UNION 0x07 // union of sub-ranges
315  // each sub-range should be simple or
316  // intersection
317  int size; // operand size: 1,2,4,8 bytes
318  // all values must fall within the size
319  union
320  {
321  struct // VLR_RANGE/VLR_SRANGE
322  { // values that are between VALUE and LIMIT
323  // and conform to: value+stride*N
324  uvlr_t value; // the main/initial value
325  uvlr_t limit; // the final value
326  // we adjust LIMIT to be on the STRIDE lattice
327  svlr_t stride; // stride between values
328  };
329  struct // VLR_BITS
330  {
331  uvlr_t zeroes; // bits known to be clear
332  uvlr_t ones; // bits known to be set
333  };
334  char reserved[sizeof(qvector<int>)];
335  // VLR_IVLS/VLR_SECT/VLR_UNION
336  };
337  void hexapi clear(void);
338  void hexapi copy(const valrng_t &r);
339  valrng_t &hexapi assign(const valrng_t &r);
340 
341 public:
342  valrng_t(int size_ = MAX_VLR_SIZE)
343  : flags(VLR_NONE), size(size_), value(0), limit(0), stride(0) {}
344  valrng_t(const valrng_t &r) { copy(r); }
345  ~valrng_t(void) { clear(); }
346  valrng_t &operator=(const valrng_t &r) { return assign(r); }
347  void swap(valrng_t &r) { qswap(*this, r); }
348  DECLARE_COMPARISONS(valrng_t);
349  DEFINE_MEMORY_ALLOCATION_FUNCS()
350 
351  void set_none(void) { clear(); }
352  void set_all(void) { clear(); flags = VLR_ALL; }
353  void hexapi set_eq(uvlr_t v);
354  void hexapi set_cmp(cmpop_t cmp, uvlr_t _value);
355 
356  // reduce size
357  // it returns "true" if size is changed successfully.
358  // otherwise THIS may be in incorrect state.
359  // example: valrng_t vr(2); vr.set_eq(0x100); assert(!vr.set_size(1));
360  bool hexapi reduce_size(int new_size);
361  // extend size
362  void hexapi extend_size(int new_size, bool sign_extension);
363 
364  // Perform intersection or union or inversion.
365  // \return did we change something in THIS?
366  bool hexapi intersect_with(const valrng_t &r);
367  bool hexapi unite_with(const valrng_t &r);
368  void hexapi inverse(); // works for VLR_IVLS only
369 
370  bool empty(void) const { return flags == VLR_NONE; }
371  bool all_values(void) const { return flags == VLR_ALL; }
372  bool hexapi has(uvlr_t v) const;
373 
374  void hexapi print(qstring *vout) const;
375  const char *hexapi dstr(void) const;
376 
377  bool hexapi cvt_to_single_value(uvlr_t *v) const;
378  bool hexapi cvt_to_cmp(cmpop_t *cmp, uvlr_t *val, bool strict) const;
379 
380  int get_size() const { return size; }
381  static uvlr_t max_value(int size_)
382  {
383  return size_ == MAX_VLR_SIZE
384  ? MAX_VALUE
385  : (uvlr_t(1) << (size_ * 8)) - 1;
386  }
387  static uvlr_t min_svalue(int size_)
388  {
389  return size_ == MAX_VLR_SIZE
390  ? MIN_SVALUE
391  : (uvlr_t(1) << (size_ * 8 - 1));
392  }
393  static uvlr_t max_svalue(int size_)
394  {
395  return size_ == MAX_VLR_SIZE
396  ? MAX_SVALUE
397  : (uvlr_t(1) << (size_ * 8 - 1)) - 1;
398  }
399  uvlr_t max_value() const { return max_value(size); }
400  uvlr_t min_svalue() const { return min_svalue(size); }
401  uvlr_t max_svalue() const { return max_svalue(size); }
402 };
403 DECLARE_TYPE_AS_MOVABLE(valrng_t);
404 
405 //-------------------------------------------------------------------------
406 // possible memory and register access types.
407 enum access_type_t
408 {
409  NO_ACCESS = 0,
410  WRITE_ACCESS = 1,
411  READ_ACCESS = 2,
412  RW_ACCESS = WRITE_ACCESS | READ_ACCESS,
413 };
414 
415 // Are we looking for 'must access' or 'may access' information?
416 // 'must access' means that the code will always access the specified location(s)
417 // 'may access' means that the code may in some cases access the specified location(s)
418 // Example: ldx cs.2, r0.4, r1.4
419 // MUST_ACCESS: r0.4 and r1.4, usually displayed as r0.8 because r0 and r1 are adjacent
420 // MAY_ACCESS: r0.4 and r1.4, and all aliasable memory, because
421 // ldx may access any part of the aliasable memory
422 typedef int maymust_t;
423 const maymust_t
424  // One of the following two bits should be specified:
425  MUST_ACCESS = 0x00, // access information we can count on
426  MAY_ACCESS = 0x01, // access information we should take into account
427  // Optionally combined with the following bits:
428  MAYMUST_ACCESS_MASK = 0x01,
429 
430  ONE_ACCESS_TYPE = 0x20, // for find_first_use():
431  // use only the specified maymust access type
432  // (by default it inverts the access type for def-lists)
433  INCLUDE_SPOILED_REGS = 0x40, // for build_def_list() with MUST_ACCESS:
434  // include spoiled registers in the list
435  EXCLUDE_PASS_REGS = 0x80, // for build_def_list() with MAY_ACCESS:
436  // exclude pass_regs from the list
437  FULL_XDSU = 0x100, // for build_def_list():
438  // if xds/xdu source and targets are the same
439  // treat it as if xdsu redefines the entire destination
440  WITH_ASSERTS = 0x200, // for find_first_use():
441  // do not ignore assertions
442  EXCLUDE_VOLATILE = 0x400, // for build_def_list():
443  // exclude volatile memory from the list
444  INCLUDE_UNUSED_SRC = 0x800, // for build_use_list():
445  // do not exclude unused source bytes for m_and/m_or insns
446  INCLUDE_DEAD_RETREGS = 0x1000, // for build_def_list():
447  // include dead returned registers in the list
448  INCLUDE_RESTRICTED = 0x2000; // for MAY_ACCESS: include restricted memory
449 
450 inline THREAD_SAFE bool is_may_access(maymust_t maymust)
451 {
452  return (maymust & MAYMUST_ACCESS_MASK) != MUST_ACCESS;
453 }
454 
455 //-------------------------------------------------------------------------
456 /// \defgroup MERR_ Microcode error codes
457 //@{
459 {
460  MERR_OK = 0, ///< ok
461  MERR_BLOCK = 1, ///< no error, switch to new block
462  MERR_INTERR = -1, ///< internal error
463  MERR_INSN = -2, ///< can not convert to microcode
464  MERR_MEM = -3, ///< not enough memory
465  MERR_BADBLK = -4, ///< bad block found
466  MERR_BADSP = -5, ///< positive sp value has been found
467  MERR_PROLOG = -6, ///< prolog analysis failed
468  MERR_SWITCH = -7, ///< wrong switch idiom
469  MERR_EXCEPTION = -8, ///< exception analysis failed
470  MERR_HUGESTACK = -9, ///< stack frame is too big
471  MERR_LVARS = -10, ///< local variable allocation failed
472  MERR_BITNESS = -11, ///< only 32/16bit functions can be decompiled
473  MERR_BADCALL = -12, ///< could not determine call arguments
474  MERR_BADFRAME = -13, ///< function frame is wrong
475  MERR_UNKTYPE = -14, ///< undefined type %s (currently unused error code)
476  MERR_BADIDB = -15, ///< inconsistent database information
477  MERR_SIZEOF = -16, ///< wrong basic type sizes in compiler settings
478  MERR_REDO = -17, ///< redecompilation has been requested
479  MERR_CANCELED = -18, ///< decompilation has been cancelled
480  MERR_RECDEPTH = -19, ///< max recursion depth reached during lvar allocation
481  MERR_OVERLAP = -20, ///< variables would overlap: %s
482  MERR_PARTINIT = -21, ///< partially initialized variable %s
483  MERR_COMPLEX = -22, ///< too complex function
484  MERR_LICENSE = -23, ///< no license available
485  MERR_ONLY32 = -24, ///< only 32-bit functions can be decompiled for the current database
486  MERR_ONLY64 = -25, ///< only 64-bit functions can be decompiled for the current database
487  MERR_BUSY = -26, ///< already decompiling a function
488  MERR_FARPTR = -27, ///< far memory model is supported only for pc
489  MERR_EXTERN = -28, ///< special segments can not be decompiled
490  MERR_FUNCSIZE = -29, ///< too big function
491  MERR_BADRANGES = -30, ///< bad input ranges
492  MERR_STOP = -31, ///< no error, stop the analysis
493  MERR_MAX_ERR = 31,
494  MERR_LOOP = -32, ///< internal code: redo last loop (never reported)
495 };
496 //@}
497 
498 /// Get textual description of an error code
499 /// \param out the output buffer for the error description
500 /// \param code \ref MERR_
501 /// \param mba the microcode array
502 /// \return the error address
503 
504 ea_t hexapi get_merror_desc(qstring *out, merror_t code, mbl_array_t *mba);
505 
506 ///------------------------------------------------------------------------
507 /// Map a processor register to microregister.
508 /// \param reg processor register number
509 /// \return microregister register id or mr_none
510 
511 mreg_t hexapi reg2mreg(int reg);
512 
513 
514 /// Map a microregister to processor register.
515 /// \param reg microregister number
516 /// \param width size of microregister in bytes
517 /// \return processor register id or -1
518 
519 int hexapi mreg2reg(mreg_t reg, int width);
520 
521 
522 //-------------------------------------------------------------------------
523 /// User defined callback to optimize individual microcode instructions
524 struct optinsn_t
525 {
526  /// Optimize an instruction.
527  /// \param blk current basic block. maybe NULL, which means that
528  /// the instruction must be optimized without context
529  /// \param ins instruction to optimize; it is always a top-level instruction.
530  /// the callback may not delete the instruction but may
531  /// convert it into nop (see mblock_t::make_nop). to optimize
532  /// sub-instructions, visit them using minsn_visitor_t.
533  /// sub-instructions may not be converted int nop but
534  /// can be converted to "mov x,x". for example:
535  /// add x,0,x => mov x,x
536  /// \return number of changes made to the instruction.
537  /// if after this call the instruction's use/def lists have changed,
538  /// you must mark the block level lists as dirty (see mark_lists_dirty)
539  virtual int idaapi func(mblock_t *blk, minsn_t *ins) = 0;
540 };
541 
542 /// Install an instruction level custom optimizer
543 /// \param opt an instance of optinsn_t. can not be destroyed before calling
544 /// remove_optinsn_handler().
546 
547 /// Remove an instruction level custom optimizer
549 
550 /// User defined callback to optimize microcode blocks
552 {
553  /// Optimize a block.
554  /// This function usually performs the optimizations that require analyzing
555  /// the entire block and/or its neighbors. For example it can recognize
556  /// patterns and perform conversions like:
557  /// b0: b0:
558  /// ... ...
559  /// jnz x, 0, @b2 => jnz x, 0, @b2
560  /// b1: b1:
561  /// add x, 0, y mov x, y
562  /// ... ...
563  /// \param blk Basic block to optimize as a whole.
564  /// \return number of changes made to the block. See also mark_lists_dirty.
565  virtual int idaapi func(mblock_t *blk) = 0;
566 };
567 
568 /// Install a block level custom optimizer.
569 /// \param opt an instance of optblock_t. can not be destroyed before calling
570 /// remove_optblock_handler().
572 
573 /// Remove a block level custom optimizer
575 
576 
577 //-------------------------------------------------------------------------
578 // List of microinstruction opcodes.
579 // The order of setX and jX insns is important, it is used in the code.
580 
581 // Instructions marked with *F may have the FPINSN bit set and operate on fp values
582 // Instructions marked with +F must have the FPINSN bit set. They always operate on fp values
583 // Other instructions do not operate on fp values.
584 
585 enum mcode_t
586 {
587  m_nop = 0x00, // nop // no operation
588  m_stx = 0x01, // stx l, {r=sel, d=off} // store register to memory *F
589  m_ldx = 0x02, // ldx {l=sel,r=off}, d // load register from memory *F
590  m_ldc = 0x03, // ldc l=const, d // load constant
591  m_mov = 0x04, // mov l, d // move *F
592  m_neg = 0x05, // neg l, d // negate
593  m_lnot = 0x06, // lnot l, d // logical not
594  m_bnot = 0x07, // bnot l, d // bitwise not
595  m_xds = 0x08, // xds l, d // extend (signed)
596  m_xdu = 0x09, // xdu l, d // extend (unsigned)
597  m_low = 0x0A, // low l, d // take low part
598  m_high = 0x0B, // high l, d // take high part
599  m_add = 0x0C, // add l, r, d // l + r -> dst
600  m_sub = 0x0D, // sub l, r, d // l - r -> dst
601  m_mul = 0x0E, // mul l, r, d // l * r -> dst
602  m_udiv = 0x0F, // udiv l, r, d // l / r -> dst
603  m_sdiv = 0x10, // sdiv l, r, d // l / r -> dst
604  m_umod = 0x11, // umod l, r, d // l % r -> dst
605  m_smod = 0x12, // smod l, r, d // l % r -> dst
606  m_or = 0x13, // or l, r, d // bitwise or
607  m_and = 0x14, // and l, r, d // bitwise and
608  m_xor = 0x15, // xor l, r, d // bitwise xor
609  m_shl = 0x16, // shl l, r, d // shift logical left
610  m_shr = 0x17, // shr l, r, d // shift logical right
611  m_sar = 0x18, // sar l, r, d // shift arithmetic right
612  m_cfadd = 0x19, // cfadd l, r, d=carry // calculate carry bit of (l+r)
613  m_ofadd = 0x1A, // ofadd l, r, d=overf // calculate overflow bit of (l+r)
614  m_cfshl = 0x1B, // cfshl l, r, d=carry // calculate carry bit of (l<<r)
615  m_cfshr = 0x1C, // cfshr l, r, d=carry // calculate carry bit of (l>>r)
616  m_sets = 0x1D, // sets l, d=byte SF=1 Sign
617  m_seto = 0x1E, // seto l, r, d=byte OF=1 Overflow of (l-r)
618  m_setp = 0x1F, // setp l, r, d=byte PF=1 Unordered/Parity *F
619  m_setnz = 0x20, // setnz l, r, d=byte ZF=0 Not Equal *F
620  m_setz = 0x21, // setz l, r, d=byte ZF=1 Equal *F
621  m_setae = 0x22, // setae l, r, d=byte CF=0 Above or Equal *F
622  m_setb = 0x23, // setb l, r, d=byte CF=1 Below *F
623  m_seta = 0x24, // seta l, r, d=byte CF=0 & ZF=0 Above *F
624  m_setbe = 0x25, // setbe l, r, d=byte CF=1 | ZF=1 Below or Equal *F
625  m_setg = 0x26, // setg l, r, d=byte SF=OF & ZF=0 Greater
626  m_setge = 0x27, // setge l, r, d=byte SF=OF Greater or Equal
627  m_setl = 0x28, // setl l, r, d=byte SF!=OF Less
628  m_setle = 0x29, // setle l, r, d=byte SF!=OF | ZF=1 Less or Equal
629  m_jcnd = 0x2A, // jcnd l, d // d is mop_v or mop_b
630  m_jnz = 0x2B, // jnz l, r, d // ZF=0 Not Equal *F
631  m_jz = 0x2C, // jz l, r, d // ZF=1 Equal *F
632  m_jae = 0x2D, // jae l, r, d // CF=0 Above or Equal *F
633  m_jb = 0x2E, // jb l, r, d // CF=1 Below *F
634  m_ja = 0x2F, // ja l, r, d // CF=0 & ZF=0 Above *F
635  m_jbe = 0x30, // jbe l, r, d // CF=1 | ZF=1 Below or Equal *F
636  m_jg = 0x31, // jg l, r, d // SF=OF & ZF=0 Greater
637  m_jge = 0x32, // jge l, r, d // SF=OF Greater or Equal
638  m_jl = 0x33, // jl l, r, d // SF!=OF Less
639  m_jle = 0x34, // jle l, r, d // SF!=OF | ZF=1 Less or Equal
640  m_jtbl = 0x35, // jtbl l, r=mcases // Table jump
641  m_ijmp = 0x36, // ijmp {r=sel, d=off} // indirect unconditional jump
642  m_goto = 0x37, // goto l // l is mop_v or mop_b
643  m_call = 0x38, // call l d // l is mop_v or mop_b or mop_h
644  m_icall = 0x39, // icall {l=sel, r=off} d // indirect call
645  m_ret = 0x3A, // ret
646  m_push = 0x3B, // push l
647  m_pop = 0x3C, // pop d
648  m_und = 0x3D, // und d // undefine
649  m_ext = 0x3E, // ext in1, in2, out1 // external insn, not microcode *F
650  m_f2i = 0x3F, // f2i l, d int(l) => d; convert fp -> integer +F
651  m_f2u = 0x40, // f2u l, d uint(l)=> d; convert fp -> uinteger +F
652  m_i2f = 0x41, // i2f l, d fp(l) => d; convert integer -> fp e +F
653  m_u2f = 0x42, // i2f l, d fp(l) => d; convert uinteger -> fp +F
654  m_f2f = 0x43, // f2f l, d l => d; change fp precision +F
655  m_fneg = 0x44, // fneg l, d -l => d; change sign +F
656  m_fadd = 0x45, // fadd l, r, d l + r => d; add +F
657  m_fsub = 0x46, // fsub l, r, d l - r => d; subtract +F
658  m_fmul = 0x47, // fmul l, r, d l * r => d; multiply +F
659  m_fdiv = 0x48, // fdiv l, r, d l / r => d; divide +F
660 #define m_max 0x49 // first unused opcode
661 };
662 
663 /// Must an instruction with the given opcode be the last one in a block?
664 /// Such opcodes are called closing opcodes.
665 /// \param mcode instruction opcode
666 /// \param including_calls should m_call/m_icall be considered as the closing opcodes?
667 /// If this function returns true, the opcode can not appear in the middle
668 /// of a block. Calls are a special case because before MMAT_CALLS they are
669 /// closing opcodes. Afteer MMAT_CALLS that are not considered as closing opcodes.
670 
671 bool hexapi must_mcode_close_block(mcode_t mcode, bool including_calls);
672 
673 
674 /// May opcode be propagates?
675 /// Such opcodes can be used in sub-instructions (nested instructions)
676 /// There is a handful of non-propagatable opcodes, like jumps, ret, nop, etc
677 /// All other regular opcodes are propagatable and may appear in a nested
678 /// instruction.
679 
680 bool hexapi is_mcode_propagatable(mcode_t mcode);
681 
682 
683 // Is add or sub instruction?
684 inline THREAD_SAFE bool is_mcode_addsub(mcode_t mcode) { return mcode == m_add || mcode == m_sub; }
685 // Is xds or xdu instruction? We use 'xdsu' as a shortcut for 'xds or xdu'
686 inline THREAD_SAFE bool is_mcode_xdsu(mcode_t mcode) { return mcode == m_xds || mcode == m_xdu; }
687 // Is a 'set' instruction? (an instruction that sets a condition code)
688 inline THREAD_SAFE bool is_mcode_set(mcode_t mcode) { return mcode >= m_sets && mcode <= m_setle; }
689 // Is a 1-operand 'set' instruction? Only 'sets' is in this group
690 inline THREAD_SAFE bool is_mcode_set1(mcode_t mcode) { return mcode == m_sets; }
691 // Is a 1-operand conditional jump instruction? Only 'jcnd' is in this group
692 inline THREAD_SAFE bool is_mcode_j1(mcode_t mcode) { return mcode == m_jcnd; }
693 // Is a conditional jump?
694 inline THREAD_SAFE bool is_mcode_jcond(mcode_t mcode) { return mcode >= m_jcnd && mcode <= m_jle; }
695 // Is a 'set' instruction that can be converted into a conditional jump?
696 inline THREAD_SAFE bool is_mcode_convertible_to_jmp(mcode_t mcode) { return mcode >= m_setnz && mcode <= m_setle; }
697 // Is a conditional jump instruction that can be converted into a 'set'?
698 inline THREAD_SAFE bool is_mcode_convertible_to_set(mcode_t mcode) { return mcode >= m_jnz && mcode <= m_jle; }
699 // Is a call instruction? (direct or indirect)
700 inline THREAD_SAFE bool is_mcode_call(mcode_t mcode) { return mcode == m_call || mcode == m_icall; }
701 // Must be an FPU instruction?
702 inline THREAD_SAFE bool is_mcode_fpu(mcode_t mcode) { return mcode >= m_f2i; }
703 // Is a commutative instruction?
704 inline THREAD_SAFE bool is_mcode_commutative(mcode_t mcode)
705 {
706  return mcode == m_add
707  || mcode == m_mul
708  || mcode == m_or
709  || mcode == m_and
710  || mcode == m_xor
711  || mcode == m_setz
712  || mcode == m_setnz
713  || mcode == m_cfadd
714  || mcode == m_ofadd;
715 }
716 // Is a shift instruction?
717 inline THREAD_SAFE bool is_mcode_shift(mcode_t mcode)
718 {
719  return mcode == m_shl
720  || mcode == m_shr
721  || mcode == m_sar;
722 }
723 
724 // Convert setX opcode into corresponding jX opcode
725 // This function relies on the order of setX and jX opcodes!
726 inline THREAD_SAFE mcode_t set2jcnd(mcode_t code)
727 {
728  return mcode_t(code - m_setnz + m_jnz);
729 }
730 
731 // Convert setX opcode into corresponding jX opcode
732 // This function relies on the order of setX and jX opcodes!
733 inline THREAD_SAFE mcode_t jcnd2set(mcode_t code)
734 {
735  return mcode_t(code + m_setnz - m_jnz);
736 }
737 
738 // Negate a conditional opcode.
739 // Conditional jumps can be negated, example: jle -> jg
740 // 'Set' instruction can be negated, example: seta -> setbe
741 // If the opcode can not be negated, return m_nop
742 mcode_t hexapi negate_mcode_relation(mcode_t code);
743 
744 
745 // Swap a conditional opcode.
746 // Only conditional jumps and set instructions can be swapped.
747 // The returned opcode the one required for swapped operands.
748 // Example "x > y" is the same as "y < x", therefore swap(m_jg) is m_jl.
749 // If the opcode can not be swapped, return m_nop
750 
751 mcode_t hexapi swap_mcode_relation(mcode_t code);
752 
753 // Return the opcode that performs signed operation.
754 // Examples: jae -> jge; udiv -> sdiv
755 // If the opcode can not be transformed into signed form, simply return it.
756 
757 mcode_t hexapi get_signed_mcode(mcode_t code);
758 
759 
760 // Return the opcode that performs unsigned operation.
761 // Examples: jl -> jb; xds -> xdu
762 // If the opcode can not be transformed into unsigned form, simply return it.
763 
764 mcode_t hexapi get_unsigned_mcode(mcode_t code);
765 
766 // Does the opcode perform a signed operation?
767 inline bool is_signed_mcode(mcode_t code) { return get_unsigned_mcode(code) != code; }
768 // Does the opcode perform a unsigned operation?
769 inline bool is_unsigned_mcode(mcode_t code) { return get_signed_mcode(code) != code; }
770 
771 
772 // Does the 'd' operand gets modified by the instruction?
773 // Example: "add l,r,d" modifies d, while instructions
774 // like jcnd, ijmp, stx does not modify it.
775 // Note: this function returns 'true' for m_ext but it may be wrong.
776 // Use minsn_t::modifes_d() if you have minsn_t.
777 
778 bool hexapi mcode_modifies_d(mcode_t mcode);
779 
780 
781 // Processor condition codes are mapped to the first microregisters
782 // The order is important, see mop_t::is_cc()
783 const mreg_t mr_none = mreg_t(-1);
784 const mreg_t mr_cf = mreg_t(0); // carry bit
785 const mreg_t mr_zf = mreg_t(1); // zero bit
786 const mreg_t mr_sf = mreg_t(2); // sign bit
787 const mreg_t mr_of = mreg_t(3); // overflow bit
788 const mreg_t mr_pf = mreg_t(4); // parity bit
789 const int cc_count = mr_pf - mr_cf + 1; // number of condition code registers
790 const mreg_t mr_cc = mreg_t(5); // synthetic condition code, used internally
791 const mreg_t mr_first = mreg_t(8); // the first processor specific register
792 
793 //------------------------------------------------------------------------
794 /// Macro to declare standard inline comparison operators
795 #define DECLARE_COMPARISON_OPERATORS(type) \
796  bool operator==(const type &r) const { return compare(r) == 0; } \
797  bool operator!=(const type &r) const { return compare(r) != 0; } \
798  bool operator< (const type &r) const { return compare(r) < 0; } \
799  bool operator> (const type &r) const { return compare(r) > 0; } \
800  bool operator<=(const type &r) const { return compare(r) <= 0; } \
801  bool operator>=(const type &r) const { return compare(r) >= 0; }
802 
803 /// Macro to declare comparisons for our classes
804 /// All comparison operators call the compare() function which returns -1/0/1
805 #define DECLARE_COMPARISONS(type) \
806  DECLARE_COMPARISON_OPERATORS(type) \
807  friend int compare(const type &a, const type &b) { return a.compare(b); } \
808  int compare(const type &r) const
809 
810 /// Operand locator.
811 /// It is used to denote a particular operand in the ctree, for example,
812 /// when the user right clicks on a constant and requests to represent it, say,
813 /// as a hexadecimal number.
815 {
816 private:
817  // forbid the default constructor, force the user to initialize objects of this class.
818  operand_locator_t(void) {}
819 public:
820  ea_t ea; ///< address of the original processor instruction
821  int opnum; ///< operand number in the instruction
822  operand_locator_t(ea_t _ea, int _opnum) : ea(_ea), opnum(_opnum) {}
824  DEFINE_MEMORY_ALLOCATION_FUNCS()
825 };
826 
827 //-------------------------------------------------------------------------
828 /// Number representation.
829 /// This structure holds information about a number format.
831 {
832  DEFINE_MEMORY_ALLOCATION_FUNCS()
833  flags_t flags; ///< ida flags, which describe number radix, enum, etc
834  char opnum; ///< operand number: 0..UA_MAXOP
835  char props; ///< properties: combination of NF_ bits (\ref NF_)
836 /// \defgroup NF_ Number format property bits
837 /// Used in number_format_t::props
838 //@{
839 #define NF_FIXED 0x01 ///< number format has been defined by the user
840 #define NF_NEGDONE 0x02 ///< temporary internal bit: negation has been performed
841 #define NF_BINVDONE 0x04 ///< temporary internal bit: inverting bits is done
842 #define NF_NEGATE 0x08 ///< The user asked to negate the constant
843 #define NF_BITNOT 0x10 ///< The user asked to invert bits of the constant
844 #define NF_STROFF 0x20 ///< internal bit: used as stroff, valid iff is_stroff()
845 //@}
846  uchar serial; ///< for enums: constant serial number
847  char org_nbytes; ///< original number size in bytes
848  qstring type_name; ///< for stroffs: structure for offsetof()\n
849  ///< for enums: enum name
850  /// Contructor
851  number_format_t(int _opnum=0)
852  : flags(0), opnum(char(_opnum)), props(0), serial(0), org_nbytes(0) {}
853  /// Get number radix
854  /// \return 2,8,10, or 16
855  int get_radix(void) const { return ::get_radix(flags, opnum); }
856  /// Is number representation fixed?
857  /// Fixed representation can not be modified by the decompiler
858  bool is_fixed(void) const { return props != 0; }
859  /// Is a hexadecimal number?
860  bool is_hex(void) const { return ::is_numop(flags, opnum) && get_radix() == 16; }
861  /// Is a decimal number?
862  bool is_dec(void) const { return ::is_numop(flags, opnum) && get_radix() == 10; }
863  /// Is a octal number?
864  bool is_oct(void) const { return ::is_numop(flags, opnum) && get_radix() == 8; }
865  /// Is a symbolic constant?
866  bool is_enum(void) const { return ::is_enum(flags, opnum); }
867  /// Is a character constant?
868  bool is_char(void) const { return ::is_char(flags, opnum); }
869  /// Is a structure field offset?
870  bool is_stroff(void) const { return ::is_stroff(flags, opnum); }
871  /// Is a number?
872  bool is_numop(void) const { return !is_enum() && !is_char() && !is_stroff(); }
873  /// Does the number need to be negated or bitwise negated?
874  /// Returns true if the user requested a negation but it is not done yet
875  bool needs_to_be_inverted(void) const
876  {
877  return (props & (NF_NEGATE|NF_BITNOT)) != 0 // the user requested it
878  && (props & (NF_NEGDONE|NF_BINVDONE)) == 0; // not done yet
879  }
880 };
881 
882 // Number formats are attached to (ea,opnum) pairs
883 typedef std::map<operand_locator_t, number_format_t> user_numforms_t;
884 
885 //-------------------------------------------------------------------------
886 /// Base helper class to convert binary data structures into text.
887 /// Other classes are derived from this class.
889 {
890  qstring tmpbuf;
891  int hdrlines; ///< number of header lines (prototype+typedef+lvars)
892  ///< valid at the end of print process
893  /// Print.
894  /// This function is called to generate a portion of the output text.
895  /// The output text may contain color codes.
896  /// \return the number of printed characters
897  /// \param indent number of spaces to generate as prefix
898  /// \param format printf-style format specifier
899  /// \return length of printed string
900  AS_PRINTF(3, 4) virtual int hexapi print(int indent, const char *format,...);
901  DEFINE_MEMORY_ALLOCATION_FUNCS()
902 };
903 
904 /// Helper class to convert cfunc_t into text.
905 struct vc_printer_t : public vd_printer_t
906 {
907  const cfunc_t *func; ///< cfunc_t to generate text for
908  char lastchar; ///< internal: last printed character
909  /// Constructor
910  vc_printer_t(const cfunc_t *f) : func(f), lastchar(0) {}
911  /// Are we generating one-line text representation?
912  /// \return \c true if the output will occupy one line without line breaks
913  virtual bool idaapi oneliner(void) const { return false; }
914 };
915 
916 /// Helper class to convert binary data structures into text and put into a file.
918 {
919  FILE *fp; ///< Output file pointer
920  /// Print.
921  /// This function is called to generate a portion of the output text.
922  /// The output text may contain color codes.
923  /// \return the number of printed characters
924  /// \param indent number of spaces to generate as prefix
925  /// \param format printf-style format specifier
926  /// \return length of printed string
927  AS_PRINTF(3, 4) int hexapi print(int indent, const char *format, ...);
928  /// Constructor
929  file_printer_t(FILE *_fp) : fp(_fp) {}
930 };
931 
932 /// Helper class to convert cfunc_t into a text string
934 {
935  bool with_tags; ///< Generate output with color tags
936  qstring &s; ///< Reference to the output string
937  /// Constructor
938  qstring_printer_t(const cfunc_t *f, qstring &_s, bool tags)
939  : vc_printer_t(f), with_tags(tags), s(_s) {}
940  /// Print.
941  /// This function is called to generate a portion of the output text.
942  /// The output text may contain color codes.
943  /// \return the number of printed characters
944  /// \param indent number of spaces to generate as prefix
945  /// \param format printf-style format specifier
946  /// \return length of the printed string
947  AS_PRINTF(3, 4) int hexapi print(int indent, const char *format, ...);
948 };
949 
950 //-------------------------------------------------------------------------
951 /// \defgroup type Type string related declarations
952 /// Type related functions and class.
953 //@{
954 
955 /// Print the specified type info.
956 /// This function can be used from a debugger by typing "tif->dstr()"
957 
958 const char *hexapi dstr(const tinfo_t *tif);
959 
960 
961 /// Verify a type string.
962 /// \return true if type string is correct
963 
964 bool hexapi is_type_correct(const type_t *ptr);
965 
966 
967 /// Is a small structure or union?
968 /// \return true if the type is a small UDT (user defined type).
969 /// Small UDTs fit into a register (or pair or registers) as a rule.
970 
971 bool hexapi is_small_struni(const tinfo_t &tif);
972 
973 
974 /// Is definitely a non-boolean type?
975 /// \return true if the type is a non-boolean type (non bool and well defined)
976 
977 bool hexapi is_nonbool_type(const tinfo_t &type);
978 
979 
980 /// Is a boolean type?
981 /// \return true if the type is a boolean type
982 
983 bool hexapi is_bool_type(const tinfo_t &type);
984 
985 
986 /// Is a pointer or array type?
987 inline THREAD_SAFE bool is_ptr_or_array(type_t t)
988 {
989  return is_type_ptr(t) || is_type_array(t);
990 }
991 
992 /// Is a pointer, array, or function type?
993 inline THREAD_SAFE bool is_paf(type_t t)
994 {
995  return is_ptr_or_array(t) || is_type_func(t);
996 }
997 
998 /// Is struct/union/enum definition (not declaration)?
999 inline THREAD_SAFE bool is_inplace_def(const tinfo_t &type)
1000 {
1001  return type.is_decl_complex() && !type.is_typeref();
1002 }
1003 
1004 /// Calculate number of partial subtypes.
1005 /// \return number of partial subtypes. The bigger is this number, the uglier is the type.
1006 
1007 int hexapi partial_type_num(const tinfo_t &type);
1008 
1009 
1010 /// Get a type of a floating point value with the specified width
1011 /// \returns type info object
1012 /// \param width width of the desired type
1013 
1014 tinfo_t hexapi get_float_type(int width);
1015 
1016 
1017 /// Create a type info by width and sign.
1018 /// Returns a simple type (examples: int, short) with the given width and sign.
1019 /// \param srcwidth size of the type in bytes
1020 /// \param sign sign of the type
1021 
1022 tinfo_t hexapi get_int_type_by_width_and_sign(int srcwidth, type_sign_t sign);
1023 
1024 
1025 /// Create a partial type info by width.
1026 /// Returns a partially defined type (examples: _DWORD, _BYTE) with the given width.
1027 /// \param size size of the type in bytes
1028 
1029 tinfo_t hexapi get_unk_type(int size);
1030 
1031 
1032 /// Generate a dummy pointer type
1033 /// \param ptrsize size of pointed object
1034 /// \param isfp is floating point object?
1035 
1036 tinfo_t hexapi dummy_ptrtype(int ptrsize, bool isfp);
1037 
1038 
1039 /// Get type of a structure field.
1040 /// This function performs validity checks of the field type. Wrong types are rejected.
1041 /// \param mptr structure field
1042 /// \param type pointer to the variable where the type is returned. This parameter can be NULL.
1043 /// \return false if failed
1044 
1045 bool hexapi get_member_type(const member_t *mptr, tinfo_t *type);
1046 
1047 
1048 /// Create a pointer type.
1049 /// This function performs the following conversion: "type" -> "type*"
1050 /// \param type object type.
1051 /// \return "type*". for example, if 'char' is passed as the argument,
1052 // the function will return 'char *'
1053 
1054 tinfo_t hexapi make_pointer(const tinfo_t &type);
1055 
1056 
1057 /// Create a reference to a named type.
1058 /// \param name type name
1059 /// \return type which refers to the specified name. For example, if name is "DWORD",
1060 /// the type info which refers to "DWORD" is created.
1061 
1062 tinfo_t hexapi create_typedef(const char *name);
1063 
1064 
1065 /// Create a reference to an ordinal type.
1066 /// \param n ordinal number of the type
1067 /// \return type which refers to the specified ordianl. For example, if n is 1,
1068 /// the type info which refers to ordinal type 1 is created.
1069 
1070 inline tinfo_t create_typedef(int n)
1071 {
1072  tinfo_t tif;
1073  tif.create_typedef(NULL, n);
1074  return tif;
1075 }
1076 
1077 /// Type source (where the type information comes from)
1079 {
1080  GUESSED_NONE, // not guessed, specified by the user
1081  GUESSED_WEAK, // not guessed, comes from idb
1082  GUESSED_FUNC, // guessed as a function
1083  GUESSED_DATA, // guessed as a data item
1084  TS_NOELL = 0x8000000, // can be used in set_type() to avoid merging into ellipsis
1085  TS_SHRINK = 0x4000000, // can be used in set_type() to prefer smaller arguments
1086  TS_DONTREF = 0x2000000, // do not mark type as referenced (referenced_types)
1087  TS_MASK = 0xE000000, // all high bits
1088 };
1089 
1090 
1091 /// Get a global type.
1092 /// Global types are types of addressable objects and struct/union/enum types
1093 /// \param id address or id of the object
1094 /// \param tif buffer for the answer
1095 /// \param guess what kind of types to consider
1096 /// \return success
1097 
1098 bool hexapi get_type(uval_t id, tinfo_t *tif, type_source_t guess);
1099 
1100 
1101 /// Set a global type.
1102 /// \param id address or id of the object
1103 /// \param tif new type info
1104 /// \param source where the type comes from
1105 /// \param force true means to set the type as is, false means to merge the
1106 /// new type with the possibly existing old type info.
1107 /// \return success
1108 
1109 bool hexapi set_type(uval_t id, const tinfo_t &tif, type_source_t source, bool force=false);
1110 
1111 //@}
1112 
1113 //-------------------------------------------------------------------------
1114 // We use our own class to store argument and variable locations.
1115 // It is called vdloc_t that stands for 'vd location'.
1116 // 'vd' is the internal name of the decompiler, it stands for 'visual decompiler'.
1117 // The main differences between vdloc and argloc_t:
1118 // ALOC_REG1: the offset is always 0, so it is not used. the register number
1119 // uses the whole ~VLOC_MASK field.
1120 // ALOCK_STKOFF: stack offsets are always positive because they are based on
1121 // the lowest value of sp in the function.
1122 class vdloc_t : public argloc_t
1123 {
1124  int regoff(void); // inaccessible & undefined: regoff() should not be used
1125 public:
1126  // Get the register number.
1127  // This function works only for ALOC_REG1 and ALOC_REG2 location types.
1128  // It uses all available bits for register number for ALOC_REG1
1129  int reg1(void) const { return atype() == ALOC_REG2 ? argloc_t::reg1() : get_reginfo(); }
1130 
1131  // Set vdloc to point to the specified register without cleaning it up.
1132  // This is a dangerous function, use set_reg1() instead unless you understand
1133  // what it means to cleanup an argloc.
1134  void _set_reg1(int r1) { argloc_t::_set_reg1(r1, r1>>16); }
1135 
1136  // Set vdloc to point to the specified register.
1137  void set_reg1(int r1) { cleanup_argloc(this); _set_reg1(r1); }
1138 
1139  // Use member functions of argloc_t for other location types.
1140 
1141  // Return textual representation.
1142  // Note: this and all other dstr() functions can be used from a debugger.
1143  // It is much easier than to inspect the memory contents byte by byte.
1144  const char *hexapi dstr(int width=0) const;
1146  bool hexapi is_aliasable(const mbl_array_t *mb, int size) const;
1147 };
1148 
1149 /// Print vdloc.
1150 /// Since vdloc does not always carry the size info, we pass it as NBYTES..
1151 void hexapi print_vdloc(qstring *vout, const vdloc_t &loc, int nbytes);
1152 
1153 //-------------------------------------------------------------------------
1154 /// Do two arglocs overlap?
1155 bool hexapi arglocs_overlap(const vdloc_t &loc1, size_t w1, const vdloc_t &loc2, size_t w2);
1156 
1157 /// Local variable locator.
1158 /// Local variables are located using definition ea and location.
1159 /// Each variable must have a unique locator, this is how we tell them apart.
1161 {
1162  vdloc_t location; ///< Variable location.
1163  ea_t defea; ///< Definition address. The address of an instruction
1164  ///< that initializes the variable. This value is
1165  ///< assigned to each lvar by lvar allocator.
1166  ///< BADADDR for function arguments
1167  lvar_locator_t(void) : defea(BADADDR) {}
1168  lvar_locator_t(const vdloc_t &loc, ea_t ea) : location(loc), defea(ea) {}
1169  /// Get offset of the varialbe in the stack frame.
1170  /// \return a non-negative value for stack variables. The value is
1171  /// an offset from the bottom of the stack frame in terms of
1172  /// vd-offsets.
1173  /// negative values mean error (not a stack variable)
1174  sval_t get_stkoff(void) const
1175  {
1176  return location.is_stkoff() ? location.stkoff() : -1;
1177  }
1178  /// Is variable located on one register?
1179  bool is_reg1(void) const { return location.is_reg1(); }
1180  /// Is variable located on two registers?
1181  bool is_reg2(void) const { return location.is_reg2(); }
1182  /// Is variable located on register(s)?
1183  bool is_reg_var(void) const { return location.is_reg(); }
1184  /// Is variable located on the stack?
1185  bool is_stk_var(void) const { return location.is_stkoff(); }
1186  /// Is variable scattered?
1187  bool is_scattered(void) const { return location.is_scattered(); }
1188  /// Get the register number of the variable
1189  mreg_t get_reg1(void) const { return location.reg1(); }
1190  /// Get the number of the second register (works only for ALOC_REG2 lvars)
1191  mreg_t get_reg2(void) const { return location.reg2(); }
1192  /// Get information about scattered variable
1193  const scattered_aloc_t &get_scattered(void) const { return location.scattered(); }
1194  scattered_aloc_t &get_scattered(void) { return location.scattered(); }
1196  DEFINE_MEMORY_ALLOCATION_FUNCS()
1197  // Debugging: get textual representation of a lvar locator.
1198  const char *hexapi dstr(void) const;
1199 };
1200 
1201 /// Definition of a local variable (register or stack) #var #lvar
1202 class lvar_t : public lvar_locator_t
1203 {
1204  friend class mbl_array_t;
1205  int flags; ///< \ref CVAR_
1206 /// \defgroup CVAR_ Local variable property bits
1207 /// Used in lvar_t::flags
1208 //@{
1209 #define CVAR_USED 0x00000001 ///< is used in the code?
1210 #define CVAR_TYPE 0x00000002 ///< the type is defined?
1211 #define CVAR_NAME 0x00000004 ///< has nice name?
1212 #define CVAR_MREG 0x00000008 ///< corresponding mregs were replaced?
1213 #define CVAR_NOWD 0x00000010 ///< width is unknown
1214 #define CVAR_UNAME 0x00000020 ///< user-defined name
1215 #define CVAR_UTYPE 0x00000040 ///< user-defined type
1216 #define CVAR_RESULT 0x00000080 ///< function result variable
1217 #define CVAR_ARG 0x00000100 ///< function argument
1218 #define CVAR_FAKE 0x00000200 ///< fake return variable
1219 #define CVAR_OVER 0x00000400 ///< overlapping variable
1220 #define CVAR_FLOAT 0x00000800 ///< used in a fpu insn
1221 #define CVAR_SPOILED 0x00001000 ///< internal flag, do not use: spoiled var
1222 #define CVAR_MAPDST 0x00002000 ///< other variables are mapped to this var
1223 #define CVAR_PARTIAL 0x00004000 ///< variable type is partialy defined
1224 #define CVAR_THISARG 0x00008000 ///< 'this' argument of c++ member functions
1225 #define CVAR_FORCED 0x00010000 ///< variable was created by an explicit request
1226  ///< otherwise we could reuse an existing var
1227 //@}
1228 
1229 public:
1230  qstring name; ///< variable name.
1231  ///< use mbl_array_t::set_nice_lvar_name() and
1232  ///< mbl_array_t::set_user_lvar_name() to modify it
1233  qstring cmt; ///< variable comment string
1234  tinfo_t tif; ///< variable type
1235  int width; ///< variable size in bytes
1236  int defblk; ///< first block defining the variable.
1237  ///< 0 for args, -1 if unknown
1238  uint64 divisor; ///< max known divisor of the variable
1239 
1240  lvar_t(void) : flags(CVAR_USED), width(0), defblk(-1), divisor(0) {}
1241  lvar_t(const qstring &n, const vdloc_t &l, ea_t e, const tinfo_t &t, int w, int db)
1242  : lvar_locator_t(l, e), flags(CVAR_USED), name(n), tif(t), width(w),
1243  defblk(db), divisor(0) {}
1244  lvar_t(mreg_t reg, int width, const tinfo_t &type, int nblock, ea_t defea);
1245  // Debugging: get textual representation of a local variable.
1246  const char *hexapi dstr(void) const;
1247 
1248  /// Is the variable used in the code?
1249  bool used(void) const { return (flags & CVAR_USED) != 0; }
1250  /// Has the variable a type?
1251  bool typed(void) const { return (flags & CVAR_TYPE) != 0; }
1252  /// Have corresponding microregs been replaced by references to this variable?
1253  bool mreg_done(void) const { return (flags & CVAR_MREG) != 0; }
1254  /// Does the variable have a nice name?
1255  bool has_nice_name(void) const { return (flags & CVAR_NAME) != 0; }
1256  /// Do we know the width of the variable?
1257  bool is_unknown_width(void) const { return (flags & CVAR_NOWD) != 0; }
1258  /// Has any user-defined information?
1259  bool has_user_info(void) const { return (flags & (CVAR_UNAME|CVAR_UTYPE)) != 0 || !cmt.empty(); }
1260  /// Has user-defined name?
1261  bool has_user_name(void) const { return (flags & CVAR_UNAME) != 0; }
1262  /// Has user-defined type?
1263  bool has_user_type(void) const { return (flags & CVAR_UTYPE) != 0; }
1264  /// Is the function result?
1265  bool is_result_var(void) const { return (flags & CVAR_RESULT) != 0; }
1266  /// Is the function argument?
1267  bool is_arg_var(void) const { return (flags & CVAR_ARG) != 0; }
1268  /// Is the promoted function argument?
1269  bool hexapi is_promoted_arg(void) const;
1270  /// Is fake return variable?
1271  bool is_fake_var(void) const { return (flags & CVAR_FAKE) != 0; }
1272  /// Is overlapped variable?
1273  bool is_overlapped_var(void) const { return (flags & CVAR_OVER) != 0; }
1274  /// Used by a fpu insn?
1275  bool is_floating_var(void) const { return (flags & CVAR_FLOAT) != 0; }
1276  /// Is spoiled var? (meaningful only during lvar allocation)
1277  bool is_spoiled_var(void) const { return (flags & CVAR_SPOILED) != 0; }
1278  /// Other variable(s) map to this var?
1279  bool is_partialy_typed(void) const { return (flags & CVAR_PARTIAL) != 0; }
1280  /// Other variable(s) map to this var?
1281  bool is_mapdst_var(void) const { return (flags & CVAR_MAPDST) != 0; }
1282  /// Is 'this' argument of a C++ member function?
1283  bool is_thisarg(void) const { return (flags & CVAR_THISARG) != 0; }
1284  /// Is a forced variable?
1285  bool is_forced_var(void) const { return (flags & CVAR_FORCED) != 0; }
1286  void set_used(void) { flags |= CVAR_USED; }
1287  void clear_used(void) { flags &= ~CVAR_USED; }
1288  void set_typed(void) { flags |= CVAR_TYPE; }
1289  void set_non_typed(void) { flags &= ~CVAR_TYPE; }
1290  void clr_user_info(void) { flags &= ~(CVAR_UNAME|CVAR_UTYPE); }
1291  void set_user_name(void) { flags |= CVAR_NAME|CVAR_UNAME; }
1292  void set_user_type(void) { flags |= CVAR_TYPE|CVAR_UTYPE; }
1293  void clr_user_type(void) { flags &= ~CVAR_UTYPE; }
1294  void clr_user_name(void) { flags &= ~CVAR_UNAME; }
1295  void set_mreg_done(void) { flags |= CVAR_MREG; }
1296  void clr_mreg_done(void) { flags &= ~CVAR_MREG; }
1297  void set_unknown_width(void) { flags |= CVAR_NOWD; }
1298  void clr_unknown_width(void) { flags &= ~CVAR_NOWD; }
1299  void set_arg_var(void) { flags |= CVAR_ARG; }
1300  void clr_arg_var(void) { flags &= ~(CVAR_ARG|CVAR_THISARG); }
1301  void set_fake_var(void) { flags |= CVAR_FAKE; }
1302  void clr_fake_var(void) { flags &= ~CVAR_FAKE; }
1303  void set_overlapped_var(void) { flags |= CVAR_OVER; }
1304  void clr_overlapped_var(void) { flags &= ~CVAR_OVER; }
1305  void set_floating_var(void) { flags |= CVAR_FLOAT; }
1306  void clr_floating_var(void) { flags &= ~CVAR_FLOAT; }
1307  void set_spoiled_var(void) { flags |= CVAR_SPOILED; }
1308  void clr_spoiled_var(void) { flags &= ~CVAR_SPOILED; }
1309  void set_mapdst_var(void) { flags |= CVAR_MAPDST; }
1310  void clr_mapdst_var(void) { flags &= ~CVAR_MAPDST; }
1311  void set_partialy_typed(void) { flags |= CVAR_PARTIAL; }
1312  void clr_partialy_typed(void) { flags &= ~CVAR_PARTIAL; }
1313  void set_thisarg(void) { flags |= CVAR_THISARG; }
1314  void clr_thisarg(void) { flags &= ~CVAR_THISARG; }
1315  void set_forced_var(void) { flags |= CVAR_FORCED; }
1316  void clr_forced_var(void) { flags &= ~CVAR_FORCED; }
1317 
1318  /// Do variables overlap?
1319  bool has_common(const lvar_t &v) const
1320  {
1321  return arglocs_overlap(location, width, v.location, v.width);
1322  }
1323  /// Does the variable overlap with the specified location?
1324  bool has_common_bit(const vdloc_t &loc, asize_t width2) const
1325  {
1326  return arglocs_overlap(location, width, loc, width2);
1327  }
1328  /// Get variable type
1329  const tinfo_t &type(void) const { return tif; }
1330  tinfo_t &type(void) { return tif; }
1331 
1332  /// Check if the variable accept the specified type.
1333  /// Some types are forbidden (void, function types, wrong arrays, etc)
1334  bool hexapi accepts_type(const tinfo_t &t);
1335 
1336  /// Set variable type without any validation.
1337  void force_lvar_type(const tinfo_t &t);
1338 
1339  /// Set variable type
1340  /// Note: this function does not modify the idb, only the lvar instance
1341  /// in the memory. for permanent changes see modify_user_lvars()
1342  /// \param t new type
1343  /// \param may_fail if false and type is bad, interr
1344  /// \return success
1345  bool hexapi set_lvar_type(const tinfo_t &t, bool may_fail=false);
1346 
1347  /// Set final variable type.
1348  void set_final_lvar_type(const tinfo_t &t)
1349  {
1350  set_lvar_type(t);
1351  set_typed();
1352  }
1353 
1354  /// Change the variable width.
1355  /// We call the variable size 'width', it is represents the number of bytes.
1356  /// This function also changes the variable type.
1357  /// \param w new width
1358  /// \param svw_flags combination of SVW_... bits
1359  /// \return success
1360  bool hexapi set_width(int w, int svw_flags=0);
1361 #define SVW_INT 0x00 // integer value
1362 #define SVW_FLOAT 0x01 // floating point value
1363 #define SVW_SOFT 0x02 // may fail and return false;
1364  // if this bit is not set and the type is bad, interr
1365 
1366  /// Append local variable to mlist.
1367  /// \param lst list to append to
1368  /// \param if true, append padding bytes in case of scattered lvar
1369  void hexapi append_list(mlist_t *lst, bool pad_if_scattered=false) const;
1370 
1371  /// Is the variable aliasable?
1372  /// \param mba ptr to the current mbl_array_t
1373  /// Aliasable variables may be modified indirectly (through a pointer)
1374  bool is_aliasable(const mbl_array_t *mba) const
1375  {
1376  return location.is_aliasable(mba, width);
1377  }
1378 
1379 };
1380 DECLARE_TYPE_AS_MOVABLE(lvar_t);
1381 
1382 /// Vector of local variables
1383 struct lvars_t : public qvector<lvar_t>
1384 {
1385  /// Find input variable at the specified location.
1386  /// \param argloc variable location
1387  /// \param _size variable size
1388  /// \return -1 if failed, otherwise the index into the variables vector.
1389  int find_input_lvar(const vdloc_t &argloc, int _size) { return find_lvar(argloc, _size, 0); }
1390 
1391 
1392  /// Find stack variable at the specified location.
1393  /// \param spoff offset from the minimal sp
1394  /// \param width variable size
1395  /// \return -1 if failed, otherwise the index into the variables vector.
1396  int hexapi find_stkvar(int32 spoff, int width);
1397 
1398 
1399  /// Find variable at the specified location.
1400  /// \param ll variable location
1401  /// \return pointer to variable or NULL
1402  lvar_t *hexapi find(const lvar_locator_t &ll);
1403 
1404 
1405  /// Find variable at the specified location.
1406  /// \param location variable location
1407  /// \param width variable size
1408  /// \param defblk definition block of the lvar. -1 means any block
1409  /// \return -1 if failed, otherwise the index into the variables vector.
1410  int hexapi find_lvar(const vdloc_t &location, int width, int defblk=-1);
1411 };
1412 
1413 /// Saved user settings for local variables: name, type, comment.
1415 {
1416  lvar_locator_t ll; ///< Variable locator
1417  qstring name; ///< Name
1418  tinfo_t type; ///< Type
1419  qstring cmt; ///< Comment
1420  ssize_t size; ///< Type size (if not initialized then -1)
1421  int flags; ///< \ref LVINF_
1422 /// \defgroup LVINF_ saved user lvar info property bits
1423 /// Used in lvar_saved_info_t::flags
1424 //@{
1425 #define LVINF_KEEP 0x0001 ///< preserve saved user settings regardless of vars
1426  ///< for example, if a var loses all its
1427  ///< user-defined attributes or even gets
1428  ///< destroyed, keep its lvar_saved_info_t.
1429  ///< this is used for ephemeral variables that
1430  ///< get destroyed by macro recognition.
1431 #define LVINF_FORCE 0x0002 ///< force allocation of a new variable.
1432  ///< forces the decompiler to create a new
1433  ///< variable at ll.defea
1434 //@}
1435  lvar_saved_info_t(void) : size(BADSIZE), flags(0) {}
1436  bool has_info(void) const
1437  {
1438  return !name.empty() || !type.empty() || !cmt.empty() || is_forced_lvar();
1439  }
1440  bool operator==(const lvar_saved_info_t &r) const
1441  {
1442  return name == r.name
1443  && cmt == r.cmt
1444  && ll == r.ll
1445  && type == r.type;
1446  }
1447  bool operator!=(const lvar_saved_info_t &r) const { return !(*this == r); }
1448  bool is_kept(void) const { return (flags & LVINF_KEEP) != 0; }
1449  void clear_keep(void) { flags &= ~LVINF_KEEP; }
1450  void set_keep(void) { flags |= LVINF_KEEP; }
1451  bool is_forced_lvar(void) const { return (flags & LVINF_FORCE) != 0; }
1452  void set_forced_lvar(void) { flags |= LVINF_FORCE; }
1453  void clr_forced_lvar(void) { flags &= ~LVINF_FORCE; }
1454 };
1455 DECLARE_TYPE_AS_MOVABLE(lvar_saved_info_t);
1456 typedef qvector<lvar_saved_info_t> lvar_saved_infos_t;
1457 
1458 /// Local variable mapping (is used to merge variables)
1459 typedef std::map<lvar_locator_t, lvar_locator_t> lvar_mapping_t;
1460 
1461 /// All user-defined information about local variables
1463 {
1464  /// User-specified names, types, comments for lvars. Variables without
1465  /// user-specified info are not present in this vector.
1466  lvar_saved_infos_t lvvec;
1467 
1468  /// Local variable mapping (used for merging variables)
1469  lvar_mapping_t lmaps;
1470 
1471  /// Delta to add to IDA stack offset to calculate Hex-Rays stack offsets.
1472  /// Should be set by the caller before calling save_user_lvar_settings();
1474 
1475  /// Various flags. Possible values are from \ref ULV_
1477 /// \defgroup ULV_ lvar_uservec_t property bits
1478 /// Used in lvar_uservec_t::ulv_flags
1479 //@{
1480 #define ULV_PRECISE_DEFEA 0x0001 ///< Use precise defea's for lvar locations
1481 //@}
1482 
1483  lvar_uservec_t(void) : stkoff_delta(0), ulv_flags(ULV_PRECISE_DEFEA) {}
1484  void swap(lvar_uservec_t &r)
1485  {
1486  lvvec.swap(r.lvvec);
1487  lmaps.swap(r.lmaps);
1488  std::swap(stkoff_delta, r.stkoff_delta);
1489  std::swap(ulv_flags, r.ulv_flags);
1490  }
1491 
1492  /// find saved user settings for given var
1494  {
1495  for ( lvar_saved_infos_t::iterator p=lvvec.begin(); p != lvvec.end(); ++p )
1496  {
1497  if ( p->ll == vloc )
1498  return p;
1499  }
1500  return NULL;
1501  }
1502 
1503  /// Preserve user settings for given var
1504  void keep_info(const lvar_t &v)
1505  {
1506  lvar_saved_info_t *p = find_info(v);
1507  if ( p != NULL )
1508  p->set_keep();
1509  }
1510 };
1511 
1512 /// Restore user defined local variable settings in the database.
1513 /// \param func_ea entry address of the function
1514 /// \param lvinf ptr to output buffer
1515 /// \return success
1516 
1517 bool hexapi restore_user_lvar_settings(lvar_uservec_t *lvinf, ea_t func_ea);
1518 
1519 
1520 /// Save user defined local variable settings into the database.
1521 /// \param func_ea entry address of the function
1522 /// \param lvinf user-specified info about local variables
1523 
1524 void hexapi save_user_lvar_settings(ea_t func_ea, const lvar_uservec_t &lvinf);
1525 
1526 
1527 /// Helper class to modify saved local variable settings.
1529 {
1530  /// Modify lvar settings.
1531  /// Returns: true-modified
1532  virtual bool idaapi modify_lvars(lvar_uservec_t *lvinf) = 0;
1533 };
1534 
1535 /// Modify saved local variable settings.
1536 /// \param entry_ea function start address
1537 /// \param mlv local variable modifier
1538 /// \return true if modified variables
1539 
1540 bool hexapi modify_user_lvars(ea_t entry_ea, user_lvar_modifier_t &mlv);
1541 
1542 
1543 //-------------------------------------------------------------------------
1544 /// User-defined function calls
1545 struct udcall_t
1546 {
1547  qstring name; // name of the function
1548  tinfo_t tif; // function prototype
1549 };
1550 
1551 // All user-defined function calls (map address -> udcall)
1552 typedef std::map<ea_t, udcall_t> udcall_map_t;
1553 
1554 /// Restore user defined function calls from the database.
1555 /// \param udcalls ptr to output buffer
1556 /// \param func_ea entry address of the function
1557 /// \return success
1558 
1559 bool hexapi restore_user_defined_calls(udcall_map_t *udcalls, ea_t func_ea);
1560 
1561 
1562 /// Save user defined local function calls into the database.
1563 /// \param func_ea entry address of the function
1564 /// \param udcalls user-specified info about user defined function calls
1565 
1566 void hexapi save_user_defined_calls(ea_t func_ea, const udcall_map_t &udcalls);
1567 
1568 
1569 /// Convert function type declaration into internal structure
1570 /// \param udc - pointer to output structure
1571 /// \param decl - function type declaration
1572 /// \param silent - if TRUE: do not show warning in case of incorrect type
1573 /// \return success
1574 
1575 bool hexapi parse_user_call(udcall_t *udc, const char *decl, bool silent);
1576 
1577 
1578 /// try to generate user-defined call for an instruction
1579 /// \return \ref MERR_ code:
1580 /// MERR_OK - user-defined call generated
1581 /// else - error (MERR_INSN == inacceptable udc.tif)
1582 
1584 
1585 
1586 //-------------------------------------------------------------------------
1587 /// Generic microcode generator class.
1588 /// An instance of a derived class can be registered to be used for
1589 /// non-standard microcode generation. Before microcode generation for an
1590 /// instruction all registered object will be visited by the following way:
1591 /// if ( filter->match(cdg) )
1592 /// code = filter->apply(cdg);
1593 /// if ( code == MERR_OK )
1594 /// continue; // filter generated microcode, go to the next instruction
1596 {
1597  /// check if the filter object is to be appied
1598  /// \return success
1599  virtual bool match(codegen_t &cdg) = 0;
1600 
1601  /// generate microcode for an instruction
1602  /// \return MERR_... code:
1603  /// MERR_OK - user-defined call generated, go to the next instruction
1604  /// MERR_INSN - not generated - the caller should try the standard way
1605  /// else - error
1606  virtual merror_t apply(codegen_t &cdg) = 0;
1607 };
1608 
1609 /// register/unregister non-standard microcode generator
1610 /// \param filter - microcode generator object
1611 /// \param install - TRUE - register the object, FALSE - unregister
1612 void hexapi install_microcode_filter(microcode_filter_t *filter, bool install=true);
1613 
1614 //-------------------------------------------------------------------------
1615 /// Abstract class: User-defined call generator
1616 /// derived classes should implement method 'match'
1618 {
1619  udcall_t udc;
1620 
1621 public:
1622  /// return true if the filter object should be appied to given instruction
1623  virtual bool match(codegen_t &cdg) = 0;
1624 
1625  bool hexapi init(const char *decl);
1626  virtual merror_t hexapi apply(codegen_t &cdg);
1627 };
1628 
1629 //-------------------------------------------------------------------------
1630 typedef size_t mbitmap_t;
1631 const size_t bitset_width = sizeof(mbitmap_t) * CHAR_BIT;
1632 const size_t bitset_align = bitset_width - 1;
1633 const size_t bitset_shift = 6;
1634 
1635 /// Bit set class. See https://en.wikipedia.org/wiki/Bit_array
1637 {
1638  mbitmap_t *bitmap; ///< pointer to bitmap
1639  size_t high; ///< highest bit+1 (multiply of bitset_width)
1640 
1641 public:
1642  bitset_t(void) : bitmap(NULL), high(0) {}
1643  hexapi bitset_t(const bitset_t &m); // copy constructor
1644  ~bitset_t(void)
1645  {
1646  qfree(bitmap);
1647  bitmap = NULL;
1648  }
1649  void swap(bitset_t &r)
1650  {
1651  std::swap(bitmap, r.bitmap);
1652  std::swap(high, r.high);
1653  }
1654  bitset_t &operator=(const bitset_t &m) { return copy(m); }
1655  bitset_t &hexapi copy(const bitset_t &m); // assignment operator
1656  bool hexapi add(int bit); // add a bit
1657  bool hexapi add(int bit, int width); // add bits
1658  bool hexapi add(const bitset_t &ml); // add another bitset
1659  bool hexapi sub(int bit); // delete a bit
1660  bool hexapi sub(int bit, int width); // delete bits
1661  bool hexapi sub(const bitset_t &ml); // delete another bitset
1662  bool hexapi cut_at(int maxbit); // delete bits >= maxbit
1663  void hexapi shift_down(int shift); // shift bits down
1664  bool hexapi has(int bit) const; // test presence of a bit
1665  bool hexapi has_all(int bit, int width) const; // test presence of bits
1666  bool hexapi has_any(int bit, int width) const; // test presence of bits
1667  void print(
1668  qstring *vout,
1669  int (*get_bit_name)(qstring *out, int bit, int width, void *ud)=NULL,
1670  void *ud=NULL) const;
1671  const char *hexapi dstr(void) const;
1672  bool hexapi empty(void) const; // is empty?
1673  int hexapi count(void) const; // number of set bits
1674  int hexapi count(int bit) const; // get number set bits starting from 'bit'
1675  int hexapi last(void) const; // get the number of the last bit (-1-no bits)
1676  void clear(void) { high = 0; } // make empty
1677  void hexapi fill_with_ones(int maxbit);
1678  bool fill_gaps(int total_nbits);
1679  bool hexapi has_common(const bitset_t &ml) const; // has common elements?
1680  bool hexapi intersect(const bitset_t &ml); // intersect sets. returns true if changed
1681  bool hexapi is_subset_of(const bitset_t &ml) const; // is subset of?
1682  bool includes(const bitset_t &ml) const { return ml.is_subset_of(*this); }
1683  void extract(intvec_t &out) const;
1684  DECLARE_COMPARISONS(bitset_t);
1685  DEFINE_MEMORY_ALLOCATION_FUNCS()
1686 #ifndef SWIG
1687  class iterator
1688  {
1689  friend class bitset_t;
1690  int i;
1691  iterator(int n) : i(n) {}
1692  public:
1693  bool operator==(const iterator &n) const { return i == n.i; }
1694  bool operator!=(const iterator &n) const { return i != n.i; }
1695  int operator*(void) const { return i; }
1696  };
1697  typedef iterator const_iterator;
1698  iterator itat(int n) const { return iterator(goup(n)); }
1699  iterator begin(void) const { return itat(0); }
1700  iterator end(void) const { return iterator(high); }
1701  int front(void) const { return *begin(); }
1702  int back(void) const { return *end(); }
1703  void inc(iterator &p, int n=1) const { p.i = goup(p.i+n); }
1704 #endif
1705 private:
1706  int hexapi goup(int reg) const;
1707 };
1708 DECLARE_TYPE_AS_MOVABLE(bitset_t);
1709 typedef qvector<bitset_t> array_of_bitsets;
1710 
1711 //-------------------------------------------------------------------------
1712 template <class T>
1713 struct ivl_tpl // an interval
1714 {
1715 protected:
1716  // forbid the default constructor
1717  ivl_tpl(void) {}
1718 public:
1719  T off;
1720  T size;
1721  ivl_tpl(T _off, T _size) : off(_off), size(_size) {}
1722  bool valid() const { return last() >= off; }
1723  T end() const { return off + size; }
1724  T last() const { return off + size - 1; }
1725 
1727  int compare(const ivl_tpl &r) const;
1728  DEFINE_MEMORY_ALLOCATION_FUNCS()
1729 };
1730 
1731 //-------------------------------------------------------------------------
1732 struct ivl_t : public ivl_tpl<uval_t> // an interval
1733 {
1734 private:
1735  typedef ivl_tpl<uval_t> inherited;
1736  // forbid the default constructor
1737  ivl_t(void) {}
1738  // ...except for use in a vector
1739  friend class qvector<ivl_t>;
1740 
1741 public:
1742  ivl_t(uval_t _off, uval_t _size) : inherited(_off,_size) {}
1743  bool empty(void) const { return size == 0; }
1744  void clear(void) { size = 0; }
1745  void print(qstring *vout) const;
1746  const char *hexapi dstr(void) const;
1747 
1748  bool extend_to_cover(const ivl_t &r) // extend interval to cover 'r'
1749  {
1750  uval_t new_end = end();
1751  bool changed = false;
1752  if ( off > r.off )
1753  {
1754  off = r.off;
1755  changed = true;
1756  }
1757  if ( new_end < r.end() )
1758  {
1759  new_end = r.end();
1760  changed = true;
1761  }
1762  if ( changed )
1763  size = new_end - off;
1764  return changed;
1765  }
1766  void intersect(const ivl_t &r)
1767  {
1768  uval_t new_off = qmax(off, r.off);
1769  uval_t new_end = end();
1770  if ( new_end > r.end() )
1771  new_end = r.end();
1772  if ( new_off < new_end )
1773  {
1774  off = new_off;
1775  size = new_end - off;
1776  }
1777  else
1778  {
1779  size = 0;
1780  }
1781  }
1782 
1783  // do *this and ivl overlap?
1784  bool overlap(const ivl_t &ivl) const
1785  {
1786  return interval::overlap(off, size, ivl.off, ivl.size);
1787  }
1788  // does *this include ivl?
1789  bool includes(const ivl_t &ivl) const
1790  {
1791  return interval::includes(off, size, ivl.off, ivl.size);
1792  }
1793  // does *this contain off2?
1794  bool contains(uval_t off2) const
1795  {
1796  return interval::contains(off, size, off2);
1797  }
1798 
1799  DECLARE_COMPARISONS(ivl_t);
1800  static const ivl_t allmem;
1801 #define ALLMEM ivl_t::allmem
1802 };
1803 DECLARE_TYPE_AS_MOVABLE(ivl_t);
1804 
1805 //-------------------------------------------------------------------------
1807 {
1808  ivl_t ivl;
1809  const char *whole; // name of the whole interval
1810  const char *part; // prefix to use for parts of the interval (e.g. sp+4)
1811  ivl_with_name_t(): ivl(0, BADADDR), whole("<unnamed inteval>"), part(NULL) {}
1812  DEFINE_MEMORY_ALLOCATION_FUNCS()
1813 };
1814 
1815 //-------------------------------------------------------------------------
1816 template <class Ivl, class T>
1817 class ivlset_tpl // set of intervals
1818 {
1819 protected:
1820  typedef qvector<Ivl> bag_t;
1821  bag_t bag;
1822  bool verify(void) const;
1823  // we do not store the empty intervals in bag so size == 0 denotes
1824  // MAX_VALUE<T>+1, e.g. 0x100000000 for uint32
1825  static bool ivl_all_values(const Ivl &ivl) { return ivl.off == 0 && ivl.size == 0; }
1826 
1827 public:
1828  ivlset_tpl(void) {}
1829  ivlset_tpl(const Ivl &ivl) { if ( ivl.valid() ) bag.push_back(ivl); }
1830  DEFINE_MEMORY_ALLOCATION_FUNCS()
1831 
1832  void swap(ivlset_tpl &r) { bag.swap(r.bag); }
1833  bool add(const Ivl &ivl);
1834  bool add(const ivlset_tpl &ivs);
1835  bool sub(const Ivl &ivl);
1836  bool sub(const ivlset_tpl &ivs);
1837  bool has_common(const Ivl &ivl, bool strict=false) const;
1838  T count(void) const; // sum of the interval sizes
1839  const Ivl &getivl(int idx) const { return bag[idx]; }
1840  const Ivl &lastivl(void) const { return bag.back(); }
1841  size_t nivls(void) const { return bag.size(); }
1842  bool empty(void) const { return bag.empty(); }
1843  void clear(void) { bag.clear(); }
1844  void qclear(void) { bag.qclear(); }
1845  bool all_values() const { return nivls() == 1 && ivl_all_values(bag[0]); }
1846  void set_all_values() { clear(); bag.push_back(Ivl(0, 0)); }
1847  bool has_common(const ivlset_tpl &ivs) const;
1848  bool contains(T off) const;
1849  bool includes(const ivlset_tpl &ivs) const;
1850  bool intersect(const ivlset_tpl &ivs);
1851  bool is_subset_of(const ivlset_tpl &ivs) const { return ivs.includes(*this); }
1852  bool single_value(T v) const { return nivls() == 1 && bag[0].off == v && bag[0].size == 1; }
1853 
1855  int compare(const ivlset_tpl &r) const;
1856  bool operator==(const Ivl &v) const { return nivls() == 1 && bag[0] == v; }
1857  bool operator!=(const Ivl &v) const { return !(*this == v); }
1858 
1859  typedef typename bag_t::iterator iterator;
1860  typedef typename bag_t::const_iterator const_iterator;
1861  const_iterator begin(void) const { return bag.begin(); }
1862  const_iterator end(void) const { return bag.end(); }
1863  iterator begin(void) { return bag.begin(); }
1864  iterator end(void) { return bag.end(); }
1865 };
1866 
1867 //-------------------------------------------------------------------------
1868 /// Set of address intervals.
1869 /// Bit arrays are efficient only for small sets. Potentially huge
1870 /// sets, like memory ranges, require another representation.
1871 /// ivlset_t is used for a list of memory locations in our decompiler.
1872 struct ivlset_t : public ivlset_tpl<ivl_t, uval_t>
1873 {
1875  ivlset_t() {}
1876  ivlset_t(const ivl_t &ivl) : inherited(ivl) {}
1877  bool hexapi add(const ivl_t &ivl);
1878  bool add(ea_t ea, asize_t size) { return add(ivl_t(ea, size)); }
1879  bool hexapi add(const ivlset_t &ivs);
1880  bool hexapi addmasked(const ivlset_t &ivs, const ivl_t &mask);
1881  bool hexapi sub(const ivl_t &ivl);
1882  bool sub(ea_t ea, asize_t size) { return sub(ivl_t(ea, size)); }
1883  bool hexapi sub(const ivlset_t &ivs);
1884  bool hexapi has_common(const ivl_t &ivl, bool strict=false) const;
1885  void hexapi print(qstring *vout) const;
1886  const char *hexapi dstr(void) const;
1887  asize_t hexapi count(void) const;
1888  bool hexapi has_common(const ivlset_t &ivs) const;
1889  bool hexapi contains(uval_t off) const;
1890  bool hexapi includes(const ivlset_t &ivs) const;
1891  bool hexapi intersect(const ivlset_t &ivs);
1892 
1894 
1895 };
1896 DECLARE_TYPE_AS_MOVABLE(ivlset_t);
1897 typedef qvector<ivlset_t> array_of_ivlsets;
1898 int hexapi get_mreg_name(qstring *out, int bit, int width, void *ud=NULL);
1899 //-------------------------------------------------------------------------
1900 // We use bitset_t to keep list of registers.
1901 // This is the most optimal storage for them.
1902 class rlist_t : public bitset_t
1903 {
1904 public:
1905  rlist_t(void) {}
1906  rlist_t(const rlist_t &m) : bitset_t(m)
1907  {
1908  }
1909  rlist_t(mreg_t reg, int width) { add(reg, width); }
1910  ~rlist_t(void) {}
1911  void hexapi print(qstring *vout) const;
1912  const char *hexapi dstr(void) const;
1913 };
1914 DECLARE_TYPE_AS_MOVABLE(rlist_t);
1915 
1916 //-------------------------------------------------------------------------
1917 // Microlist: list of register and memory locations
1918 struct mlist_t
1919 {
1920  rlist_t reg; // registers
1921  ivlset_t mem; // memory locations
1922 
1923  mlist_t(void) {}
1924  mlist_t(const ivl_t &ivl) : mem(ivl) {}
1925  mlist_t(mreg_t r, int size) : reg(r, size) {}
1926 
1927  void swap(mlist_t &r) { reg.swap(r.reg); mem.swap(r.mem); }
1928  bool hexapi addmem(ea_t ea, asize_t size);
1929  bool add(mreg_t r, int size) { return add(mlist_t(r, size)); } // also see append_def_list()
1930  bool add(const rlist_t &r) { return reg.add(r); }
1931  bool add(const ivl_t &ivl) { return add(mlist_t(ivl)); }
1932  bool add(const mlist_t &lst) { return reg.add(lst.reg) | mem.add(lst.mem); }
1933  bool sub(mreg_t r, int size) { return sub(mlist_t(r, size)); }
1934  bool sub(const ivl_t &ivl) { return sub(mlist_t(ivl)); }
1935  bool sub(const mlist_t &lst) { return reg.sub(lst.reg) | mem.sub(lst.mem); }
1936  asize_t count(void) const { return reg.count() + mem.count(); }
1937  void hexapi print(qstring *vout) const;
1938  const char *hexapi dstr(void) const;
1939  bool empty(void) const { return reg.empty() && mem.empty(); }
1940  void clear(void) { reg.clear(); mem.clear(); }
1941  bool has(mreg_t r) const { return reg.has(r); }
1942  bool has_all(mreg_t r, int size) const { return reg.has_all(r, size); }
1943  bool has_any(mreg_t r, int size) const { return reg.has_any(r, size); }
1944  bool has_memory(void) const { return !mem.empty(); }
1945  bool has_allmem(void) const { return mem == ALLMEM; }
1946  bool has_common(const mlist_t &lst) const { return reg.has_common(lst.reg) || mem.has_common(lst.mem); }
1947  bool includes(const mlist_t &lst) const { return reg.includes(lst.reg) && mem.includes(lst.mem); }
1948  bool intersect(const mlist_t &lst) { return reg.intersect(lst.reg) | mem.intersect(lst.mem); }
1949  bool is_subset_of(const mlist_t &lst) const { return lst.includes(*this); }
1950 
1952  DEFINE_MEMORY_ALLOCATION_FUNCS()
1953 };
1954 DECLARE_TYPE_AS_MOVABLE(mlist_t);
1955 typedef qvector<mlist_t> mlistvec_t;
1956 DECLARE_TYPE_AS_MOVABLE(mlistvec_t);
1957 
1958 //-------------------------------------------------------------------------
1959 // abstract graph interface
1960 class simple_graph_t : public gdl_graph_t
1961 {
1962 public:
1963  qstring title;
1964  bool colored_gdl_edges;
1965 private:
1966  friend class iterator;
1967  virtual int goup(int node) const;
1968 };
1969 
1970 //-------------------------------------------------------------------------
1971 // Since our data structures are quite complex, we use the visitor pattern
1972 // in many our algorthims. This functionality is available for plugins too.
1973 // https://en.wikipedia.org/wiki/Visitor_pattern
1974 
1975 // All our visitor callbacks return an integer value.
1976 // Visiting is interrupted as soon an the return value is non-zero.
1977 // This non-zero value is returned as the result of the for_all_... function.
1978 // If for_all_... returns 0, it means that it successfully visited all items.
1979 
1980 /// The context info used by visitors
1982 {
1983  mbl_array_t *mba; // current block array
1984  mblock_t *blk; // current block
1985  minsn_t *topins; // top level instruction (parent of curins or curins itself)
1986  minsn_t *curins; // currently visited instruction
1988  mbl_array_t *_mba=NULL,
1989  mblock_t *_blk=NULL,
1990  minsn_t *_topins=NULL)
1991  : mba(_mba), blk(_blk), topins(_topins), curins(NULL) {}
1992  DEFINE_MEMORY_ALLOCATION_FUNCS()
1993  bool really_alloc(void) const;
1994 };
1995 
1996 /// Micro instruction visitor.
1997 /// See mbl_array_t::for_all_topinsns, minsn_t::for_all_insns,
1998 /// mblock_::for_all_insns, mbl_array_t::for_all_insns
2000 {
2002  mbl_array_t *_mba=NULL,
2003  mblock_t *_blk=NULL,
2004  minsn_t *_topins=NULL)
2005  : op_parent_info_t(_mba, _blk, _topins) {}
2006  virtual int idaapi visit_minsn(void) = 0;
2007 };
2008 
2009 /// Micro operand visitor.
2010 /// See mop_t::for_all_ops, minsn_t::for_all_ops, mblock_t::for_all_insns,
2011 /// mbl_array_t::for_all_insns
2013 {
2014  mop_visitor_t(
2015  mbl_array_t *_mba=NULL,
2016  mblock_t *_blk=NULL,
2017  minsn_t *_topins=NULL)
2018  : op_parent_info_t(_mba, _blk, _topins), prune(false) {}
2019  /// Should skip sub-operands of the current operand?
2020  /// visit_mop() may set 'prune=true' for that.
2021  bool prune;
2022  virtual int idaapi visit_mop(mop_t *op, const tinfo_t *type, bool is_target) = 0;
2023 };
2024 
2025 /// Scattered mop: visit each of the scattered locations as a separate mop.
2026 /// See mop_t::for_all_scattered_submops
2028 {
2029  virtual int idaapi visit_scif_mop(const mop_t &r, int off) = 0;
2030 };
2031 
2032 // Used operand visitor.
2033 // See mblock_t::for_all_uses
2035 {
2036  minsn_t *topins;
2037  minsn_t *curins;
2038  bool changed;
2039  mlist_t *list;
2040  mlist_mop_visitor_t(void): topins(NULL), curins(NULL), changed(false), list(NULL) {}
2041  virtual int idaapi visit_mop(mop_t *op) = 0;
2042 };
2043 
2044 //-------------------------------------------------------------------------
2045 /// Instruction operand types
2046 
2047 typedef uint8 mopt_t;
2048 const mopt_t
2049  mop_z = 0, ///< none
2050  mop_r = 1, ///< register (they exist until MMAT_LVARS)
2051  mop_n = 2, ///< immediate number constant
2052  mop_str = 3, ///< immediate string constant
2053  mop_d = 4, ///< result of another instruction
2054  mop_S = 5, ///< local stack variable (they exist until MMAT_LVARS)
2055  mop_v = 6, ///< global variable
2056  mop_b = 7, ///< micro basic block (mblock_t)
2057  mop_f = 8, ///< list of arguments
2058  mop_l = 9, ///< local variable
2059  mop_a = 10, ///< mop_addr_t: address of operand (mop_l, mop_v, mop_S, mop_r)
2060  mop_h = 11, ///< helper function
2061  mop_c = 12, ///< mcases
2062  mop_fn = 13, ///< floating point constant
2063  mop_p = 14, ///< operand pair
2064  mop_sc = 15; ///< scattered
2065 
2066 const int NOSIZE = -1; ///< wrong or unexisting operand size
2067 
2068 //-------------------------------------------------------------------------
2069 /// Reference to a local variable. Used by mop_l
2071 {
2072  /// Pointer to the parent mbl_array_t object.
2073  /// Since we need to access the 'mba->vars' array in order to retrieve
2074  /// the referenced variable, we keep a pointer to mbl_array_t here.
2075  /// Note: this means this class and consequently mop_t, minsn_t, mblock_t
2076  /// are specific to a mbl_array_t object and can not migrate between
2077  /// them. fortunately this is not something we need to do.
2078  /// second, lvar_ref_t's appear only after MMAT_LVARS.
2080  sval_t off; ///< offset from the beginning of the variable
2081  int idx; ///< index into mba->vars
2082  lvar_ref_t(mbl_array_t *m, int i, sval_t o=0) : mba(m), off(o), idx(i) {}
2083  lvar_ref_t(const lvar_ref_t &r) : mba(r.mba), off(r.off), idx(r.idx) {}
2084  lvar_ref_t &operator=(const lvar_ref_t &r)
2085  {
2086  off = r.off;
2087  idx = r.idx;
2088  return *this;
2089  }
2091  DEFINE_MEMORY_ALLOCATION_FUNCS()
2092  void swap(lvar_ref_t &r)
2093  {
2094  std::swap(off, r.off);
2095  std::swap(idx, r.idx);
2096  }
2097  lvar_t &hexapi var(void) const; ///< Retrieve the referenced variable
2098 };
2099 
2100 //-------------------------------------------------------------------------
2101 /// Reference to a stack variable. Used for mop_S
2103 {
2104  /// Pointer to the parent mbl_array_t object.
2105  /// We need it in order to retrieve the referenced stack variable.
2106  /// See notes for lvar_ref_t::mba.
2108 
2109  /// Offset to the stack variable from the bottom of the stack frame.
2110  /// It is called 'decompiler stkoff' and it is different from IDA stkoff.
2111  /// See a note and a picture about 'decompiler stkoff' below.
2112  sval_t off;
2113 
2114  stkvar_ref_t(mbl_array_t *m, sval_t o) : mba(m), off(o) {}
2116  DEFINE_MEMORY_ALLOCATION_FUNCS()
2117  void swap(stkvar_ref_t &r)
2118  {
2119  std::swap(off, r.off);
2120  }
2121  /// Retrieve the referenced stack variable.
2122  /// \param p_off if specified, will hold IDA stkoff after the call.
2123  /// \return pointer to the stack variable
2124  member_t *hexapi get_stkvar(uval_t *p_off=NULL) const;
2125 };
2126 
2127 //-------------------------------------------------------------------------
2128 /// Scattered operand info. Used for mop_sc
2129 struct scif_t : public vdloc_t
2130 {
2131  /// Pointer to the parent mbl_array_t object.
2132  /// Some operations may convert a scattered operand into something simpler,
2133  /// (a stack operand, for example). We will need to create stkvar_ref_t at
2134  /// that moment, this is why we need this pointer.
2135  /// See notes for lvar_ref_t::mba.
2137 
2138  /// Usually scattered operands are created from a function prototype,
2139  /// which has the name information. We preserve it and use it to name
2140  /// the corresponding local variable.
2141  qstring name;
2142 
2143  /// Scattered operands always have type info assigned to them
2144  /// because without it we won't be able to manipulte them.
2145  tinfo_t type;
2146 
2147  scif_t(mbl_array_t *_mba, qstring *n, tinfo_t *tif) : mba(_mba)
2148  {
2149  n->swap(name);
2150  tif->swap(type);
2151  }
2152  scif_t &operator =(const vdloc_t &loc)
2153  {
2154  *(vdloc_t *)this = loc;
2155  return *this;
2156  }
2157 };
2158 
2159 //-------------------------------------------------------------------------
2160 /// An integer constant. Used for mop_n
2161 /// We support 64-bit values but 128-bit values can be represented with mop_p
2163 {
2164  uint64 value;
2165  uint64 org_value; // original value before changing the operand size
2166  mnumber_t(uint64 v, ea_t _ea=BADADDR, int n=0)
2167  : operand_locator_t(_ea, n), value(v), org_value(v) {}
2168  DEFINE_MEMORY_ALLOCATION_FUNCS()
2170  {
2171  if ( value < r.value )
2172  return -1;
2173  if ( value > r.value )
2174  return -1;
2175  return 0;
2176  }
2177  // always use this function instead of manually modifying the 'value' field
2178  void update_value(uint64 val64)
2179  {
2180  value = val64;
2181  org_value = val64;
2182  }
2183 };
2184 
2185 //-------------------------------------------------------------------------
2186 /// Floating point constant. Used for mop_fn
2187 /// For more details, please see the ieee.h file from IDA SDK.
2189 {
2190  uint16 fnum[6]; ///< Internal representation of the number
2191  int nbytes; ///< Original size of the constant in bytes
2192  operator uint16 *(void) { return fnum; }
2193  operator const uint16 *(void) const { return fnum; }
2194  void hexapi print(qstring *vout) const;
2195  const char *hexapi dstr(void) const;
2196  DEFINE_MEMORY_ALLOCATION_FUNCS()
2198  {
2199  return ecmp(fnum, r.fnum);
2200  }
2201 };
2202 
2203 //-------------------------------------------------------------------------
2204 /// \defgroup SHINS_ Bits to control how we print instructions
2205 //@{
2206 #define SHINS_NUMADDR 0x01 ///< display definition addresses for numbers
2207 #define SHINS_VALNUM 0x02 ///< display value numbers
2208 #define SHINS_SHORT 0x04 ///< do not display use-def chains and other attrs
2209 #define SHINS_LDXEA 0x08 ///< display address of ldx expressions (not used)
2210 //@}
2211 
2212 //-------------------------------------------------------------------------
2213 /// How to handle side effect of change_size()
2214 /// Sometimes we need to create a temporary operand and change its size in order
2215 /// to check some hypothesis. If we revert our changes, we do not want that the
2216 /// database (global variables, stack frame, etc) changes in any manner.
2218 {
2219  NO_SIDEFF, ///< change operand size but ignore side effects
2220  ///< if you decide to keep the changed operand,
2221  ///< handle_new_size() must be called
2222  WITH_SIDEFF, ///< change operand size and handle side effects
2223  ONLY_SIDEFF, ///< only handle side effects
2224  ANY_REGSIZE = 0x80, ///< any register size is permitted
2225 };
2226 
2227 // Max size of simple operands.
2228 // Please note there are some exceptions: udts, floating point, xmm/ymm, etc
2229 const int MAX_OPSIZE = 2 * sizeof(ea_t);
2230 const int DOUBLE_OPSIZE = 2 * MAX_OPSIZE;
2231 //-------------------------------------------------------------------------
2232 /// An microinstruction operand.
2233 /// This is the smallest building block of our microcode.
2234 /// Later operands will be used in instructions, which are grouped into blocks.
2235 /// An array of basic blocks + some additional info will be the microcode.
2236 class mop_t
2237 {
2238  void hexapi copy(const mop_t &rop);
2239  mop_t &hexapi assign(const mop_t &rop);
2240 public:
2241  /// Operand type.
2242  mopt_t t;
2243 
2244  /// Operand properties.
2245  uint8 oprops;
2246 #define OPROP_IMPDONE 0x01 ///< imported operand (a pointer) has been dereferenced
2247 #define OPROP_UDT 0x02 ///< a struct or union
2248 #define OPROP_FLOAT 0x04 ///< possibly floating value
2249 #define OPROP_CCFLAGS 0x08 ///< condition codes register value
2250 #define OPROP_UDEFVAL 0x10 ///< uses undefined value
2251 
2252  /// Value number.
2253  /// Zero means unknown.
2254  /// Operands with the same value number are equal.
2255  uint16 valnum;
2256 
2257  /// Operand size.
2258  /// Usually it is 1,2,4,8 or NOSIZE but for UDTs other sizes are permitted
2259  int size;
2260 
2261  /// The following union holds additional details about the operand.
2262  /// Depending on the operand type different kinds of info are stored.
2263  /// You should access these fields only after verifying the operand type.
2264  /// All pointers are owned by the operand and are freed by its destructor.
2265  union
2266  {
2267  mreg_t r; // mop_r register number
2268  mnumber_t *nnn; // mop_n immediate value
2269  minsn_t *d; // mop_d result (destination) of another instruction
2270  stkvar_ref_t *s; // mop_S stack variable
2271  ea_t g; // mop_v global variable (its linear address)
2272  int b; // mop_b block number (used in jmp,call instructions)
2273  mcallinfo_t *f; // mop_f function call information
2274  lvar_ref_t *l; // mop_l local variable
2275  mop_addr_t *a; // mop_a variable whose address is taken
2276  char *helper; // mop_h helper function name
2277  char *cstr; // mop_str string constant
2278  mcases_t *c; // mop_c cases
2279  fnumber_t *fpc; // mop_fn floating point constant
2280  mop_pair_t *pair; // mop_p operand pair
2281  scif_t *scif; // mop_sc scattered operand info
2282  };
2283  // -- End of data fields, member function declarations follow:
2284 
2285  void set_impptr_done(void) { oprops |= OPROP_IMPDONE; }
2286  void set_udt(void) { oprops |= OPROP_UDT; }
2287  void set_undef_val(void) { oprops |= OPROP_UDEFVAL; }
2288  bool is_impptr_done(void) const { return (oprops & OPROP_IMPDONE) != 0; }
2289  bool is_udt(void) const { return (oprops & OPROP_UDT) != 0; }
2290  bool probably_floating(void) const { return (oprops & OPROP_FLOAT) != 0; }
2291  bool is_ccflags(void) const { return (oprops & OPROP_CCFLAGS) != 0; }
2292  bool is_undef_val(void) const { return (oprops & OPROP_UDEFVAL) != 0; }
2293 
2294  mop_t(void) { zero(); }
2295  mop_t(const mop_t &rop) { copy(rop); }
2296  mop_t(mreg_t _r, int _s) : t(mop_r), oprops(0), valnum(0), size(_s), r(_r) {}
2297  mop_t &operator=(const mop_t &rop) { return assign(rop); }
2298  ~mop_t(void)
2299  {
2300  erase();
2301  }
2302  DEFINE_MEMORY_ALLOCATION_FUNCS()
2303  void zero(void) { t = mop_z; oprops = 0; valnum = 0; size = NOSIZE; }
2304  void hexapi swap(mop_t &rop);
2305  void hexapi erase(void);
2306  void erase_but_keep_size(void) { int s2 = size; erase(); size = s2; }
2307 
2308  void hexapi print(qstring *vout, int shins_flags=SHINS_SHORT|SHINS_VALNUM) const;
2309  const char *hexapi dstr(void) const; // use this function for debugging
2310 
2311  //-----------------------------------------------------------------------
2312  // Operand creation
2313  //-----------------------------------------------------------------------
2314  /// Create operand from mlist_t.
2315  /// Example: if LST contains 4 bits for R0.4, our operand will be
2316  /// (t=mop_r, r=R0, size=4)
2317  /// \param mba pointer to microcode
2318  /// \param lst list of locations
2319  /// \param fullsize mba->fullsize
2320  /// \return success
2321  bool hexapi create_from_mlist(mbl_array_t *mba, const mlist_t &lst, sval_t fullsize);
2322 
2323  /// Create operand from ivlset_t.
2324  /// Example: if IVS contains [glbvar..glbvar+4), our operand will be
2325  /// (t=mop_v, g=&glbvar, size=4)
2326  /// \param mba pointer to microcode
2327  /// \param ivs set of memory intervals
2328  /// \param fullsize mba->fullsize
2329  /// \return success
2330  bool hexapi create_from_ivlset(mbl_array_t *mba, const ivlset_t &ivs, sval_t fullsize);
2331 
2332  /// Create operand from vdloc_t.
2333  /// Example: if LOC contains (type=ALOC_REG1, r=R0), our operand will be
2334  /// (t=mop_r, r=R0, size=_SIZE)
2335  /// \param mba pointer to microcode
2336  /// \param loc location
2337  /// \param fullsize mba->fullsize
2338  /// Note: this function can not handle scattered locations.
2339  /// \return success
2340  void hexapi create_from_vdloc(mbl_array_t *mba, const vdloc_t &loc, int _size);
2341 
2342  /// Create operand from scattered vdloc_t.
2343  /// Example: if LOC is (ALOC_DIST, {EAX.4, EDX.4}) and TYPE is _LARGE_INTEGER,
2344  /// our operand will be
2345  /// (t=mop_sc, scif={EAX.4, EDX.4})
2346  /// \param mba pointer to microcode
2347  /// \param name name of the operand, if available
2348  /// \param type type of the operand, must be present
2349  /// \param loc a scattered location
2350  /// \return success
2351  void hexapi create_from_scattered_vdloc(
2352  mbl_array_t *mba,
2353  const char *name,
2354  tinfo_t type,
2355  const vdloc_t &loc);
2356 
2357  /// Create operand from an instruction.
2358  /// This function creates a nested instruction that can be used as an operand.
2359  /// Example: if m="add x,y,z", our operand will be (t=mop_d,d=m).
2360  /// The destination operand of 'add' (z) is lost.
2361  /// \param m instruction to embed into operand. may not be NULL.
2362  void hexapi create_from_insn(const minsn_t *m);
2363 
2364  /// Create an integer constant operand.
2365  /// \param _value value to store in the operand
2366  /// \param _size size of the value in bytes (1,2,4,8)
2367  /// \param _ea address of the processor instruction that made the value
2368  /// \param opnum operand number of the processor instruction
2369  void hexapi make_number(uint64 _value, int _size, ea_t _ea=BADADDR, int opnum=0);
2370 
2371  /// Create a floating point constant operand.
2372  /// \param bytes pointer to the floating point value as used by the current
2373  /// processor (e.g. for x86 it must be in IEEE 754)
2374  /// \param _size number of bytes occupied by the constant.
2375  /// \return success
2376  bool hexapi make_fpnum(const void *bytes, size_t _size);
2377 
2378  /// Create a register operand without erasing previous data.
2379  /// \param reg micro register number
2380  /// Note: this function does not erase the previous contents of the operand;
2381  /// call erase() if necessary
2382  void _make_reg(mreg_t reg)
2383  {
2384  t = mop_r;
2385  r = reg;
2386  }
2387  void _make_reg(mreg_t reg, int _size)
2388  {
2389  t = mop_r;
2390  r = reg;
2391  size = _size;
2392  }
2393  /// Create a register operand.
2394  void make_reg(mreg_t reg) { erase(); _make_reg(reg); }
2395  void make_reg(mreg_t reg, int _size) { erase(); _make_reg(reg, _size); }
2396 
2397  /// Create a local variable operand.
2398  /// \param mba pointer to microcode
2399  /// \param idx index into mba->vars
2400  /// \param off offset from the beginning of the variable
2401  /// Note: this function does not erase the previous contents of the operand;
2402  /// call erase() if necessary
2403  void _make_lvar(mbl_array_t *mba, int idx, sval_t off=0)
2404  {
2405  t = mop_l;
2406  l = new lvar_ref_t(mba, idx, off);
2407  }
2408 
2409  /// Create a global variable operand without erasing previous data.
2410  /// \param ea address of the variable
2411  /// Note: this function does not erase the previous contents of the operand;
2412  /// call erase() if necessary
2413  void _make_gvar(ea_t ea)
2414  {
2415  t = mop_v;
2416  g = ea;
2417  }
2418  /// Create a global variable operand.
2419  void make_gvar(ea_t ea) { erase(); _make_gvar(ea); }
2420 
2421  /// Create a stack variable operand.
2422  /// \param mba pointer to microcode
2423  /// \param off decompiler stkoff
2424  /// Note: this function does not erase the previous contents of the operand;
2425  /// call erase() if necessary
2426  void _make_stkvar(mbl_array_t *mba, sval_t off)
2427  {
2428  t = mop_S;
2429  s = new stkvar_ref_t(mba, off);
2430  }
2431 
2432  /// Create pair of registers.
2433  /// \param loreg register holding the low part of the value
2434  /// \param hireg register holding the high part of the value
2435  /// \param halfsize the size of each of loreg/hireg
2436  void hexapi make_reg_pair(int loreg, int hireg, int halfsize);
2437 
2438  /// Create a nested instruction without erasing previous data.
2439  /// \param ea address of the nested instruction
2440  /// Note: this function does not erase the previous contents of the operand;
2441  /// call erase() if necessary
2442  /// See also create_from_insn, which is higher level
2443  void _make_insn(minsn_t *ins);
2444  /// Create a nested instruction.
2445  void make_insn(minsn_t *ins) { erase(); _make_insn(ins); }
2446 
2447  /// Create a block reference operand without erasing previous data.
2448  /// \param blknum block number
2449  /// Note: this function does not erase the previous contents of the operand;
2450  /// call erase() if necessary
2451  void _make_blkref(int blknum)
2452  {
2453  t = mop_b;
2454  b = blknum;
2455  }
2456  /// Create a global variable operand.
2457  void make_blkref(int blknum) { erase(); _make_blkref(blknum); }
2458 
2459  /// Create a helper operand.
2460  /// A helper operand usually keeps a built-in function name like "va_start"
2461  /// It is essentially just an arbitrary identifier without any additional info.
2462  void hexapi make_helper(const char *name);
2463 
2464  /// Create a constant string operand.
2465  void _make_strlit(const char *str)
2466  {
2467  t = mop_str;
2468  cstr = ::qstrdup(str);
2469  }
2470  void _make_strlit(qstring *str) // str is consumed
2471  {
2472  t = mop_str;
2473  cstr = str->extract();
2474  }
2475 
2476  /// Create a call info operand without erasing previous data.
2477  /// \param fi callinfo
2478  /// Note: this function does not erase the previous contents of the operand;
2479  /// call erase() if necessary
2481  {
2482  t = mop_f;
2483  f = fi;
2484  }
2485 
2486  /// Create a 'switch cases' operand without erasing previous data.
2487  /// Note: this function does not erase the previous contents of the operand;
2488  /// call erase() if necessary
2489  void _make_cases(mcases_t *_cases)
2490  {
2491  t = mop_c;
2492  c = _cases;
2493  }
2494 
2495  /// Create a pair operand without erasing previous data.
2496  /// Note: this function does not erase the previous contents of the operand;
2497  /// call erase() if necessary
2498  void _make_pair(mop_pair_t *_pair)
2499  {
2500  t = mop_p;
2501  pair = _pair;
2502  }
2503 
2504  //-----------------------------------------------------------------------
2505  // Various operand tests
2506  //-----------------------------------------------------------------------
2507  /// Is a register operand?
2508  bool is_reg(void) const { return t == mop_r; }
2509  /// Is the specified register?
2510  bool is_reg(mreg_t _r) const { return t == mop_r && r == _r; }
2511  /// Is the specified register of the specified size?
2512  bool is_reg(mreg_t _r, int _size) const { return t == mop_r && r == _r && size == _size; }
2513  /// Is a condition code?
2514  bool is_cc(void) const { return is_reg() && r >= mr_cf && r < mr_first; }
2515  /// Is a bit register?
2516  /// This includes condition codes and eventually other bit registers
2517  static bool hexapi is_bit_reg(mreg_t reg);
2518  bool is_bit_reg(void) const { return is_reg() && is_bit_reg(r); }
2519  /// Is a kernel register?
2520  bool is_kreg(void) const;
2521  /// Is a block reference to the specified block?
2522  bool is_mob(int serial) const { return t == mop_b && b == serial; }
2523  /// Is a scattered operand?
2524  bool is_scattered(void) const { return t == mop_sc; }
2525  /// Is address of a global memory cell?
2526  bool is_glbaddr() const;
2527  /// Is address of the specified global memory cell?
2528  bool is_glbaddr(ea_t ea) const;
2529  /// Is address of a stack variable?
2530  bool is_stkaddr() const;
2531  /// Is a sub-instruction?
2532  bool is_insn(void) const { return t == mop_d; }
2533  /// Is a sub-instruction with the specified opcode?
2534  bool is_insn(mcode_t code) const;
2535  /// Has any side effects?
2536  /// \param include_ldx consider ldx as having side effects?
2537  bool has_side_effects(bool include_ldx=false) const;
2538  /// Is it possible for the operand to use aliased memory?
2539  bool hexapi may_use_aliased_memory(void) const;
2540 
2541  /// Are the possible values of the operand only 0 and 1?
2542  /// This function returns true for 0/1 constants, bit registers,
2543  /// the result of 'set' insns, etc.
2544  bool hexapi is01(void) const;
2545 
2546  /// Does the high part of the operand consist of the sign bytes?
2547  /// \param nbytes number of bytes that were sign extended.
2548  /// the remaining size-nbytes high bytes must be sign bytes
2549  /// Example: is_sign_extended_from(xds.4(op.1), 1) -> true
2550  /// because the high 3 bytes are certainly sign bits
2551  bool hexapi is_sign_extended_from(int nbytes) const;
2552 
2553  /// Does the high part of the operand consist of zero bytes?
2554  /// \param nbytes number of bytes that were zero extended.
2555  /// the remaining size-nbytes high bytes must be zero
2556  /// Example: is_zero_extended_from(xdu.8(op.1), 2) -> true
2557  /// because the high 6 bytes are certainly zero
2558  bool hexapi is_zero_extended_from(int nbytes) const;
2559 
2560  /// Does the high part of the operand consist of zero or sign bytes?
2561  bool is_extended_from(int nbytes, bool is_signed) const
2562  {
2563  if ( is_signed )
2564  return is_sign_extended_from(nbytes);
2565  else
2566  return is_zero_extended_from(nbytes);
2567  }
2568 
2569  //-----------------------------------------------------------------------
2570  // Comparisons
2571  //-----------------------------------------------------------------------
2572  /// Compare operands.
2573  /// This is the main comparison function for operands.
2574  /// \param rop operand to compare with
2575  /// \param eqflags combination of \ref EQ_ bits
2576  bool hexapi equal_mops(const mop_t &rop, int eqflags) const;
2577  bool operator==(const mop_t &rop) const { return equal_mops(rop, 0); }
2578  bool operator!=(const mop_t &rop) const { return !equal_mops(rop, 0); }
2579 
2580  /// Lexographical operand comparison.
2581  /// It can be used to store mop_t in various containers, like std::set
2582  bool operator <(const mop_t &rop) const { return lexcompare(rop) < 0; }
2583  friend int lexcompare(const mop_t &a, const mop_t &b) { return a.lexcompare(b); }
2584  int hexapi lexcompare(const mop_t &rop) const;
2585 
2586  //-----------------------------------------------------------------------
2587  // Visiting operand parts
2588  //-----------------------------------------------------------------------
2589  /// Visit the operand and all its sub-operands.
2590  /// This function visits the current operand as well.
2591  /// \param mv visitor object
2592  /// \param type operand type
2593  /// \param is_target is a destination operand?
2594  int hexapi for_all_ops(
2595  mop_visitor_t &mv,
2596  const tinfo_t *type=NULL,
2597  bool is_target=false);
2598 
2599  /// Visit all sub-operands of a scattered operand.
2600  /// This function does not visit the current operand, only its sub-operands.
2601  /// All sub-operands are synthetic and are destroyed after the visitor.
2602  /// This function works only with scattered operands.
2603  /// \param sv visitor object
2604  int hexapi for_all_scattered_submops(scif_visitor_t &sv) const;
2605 
2606  //-----------------------------------------------------------------------
2607  // Working with mop_n operands
2608  //-----------------------------------------------------------------------
2609  /// Retrieve value of a constant integer operand.
2610  /// These functions can be called only for mop_n operands.
2611  /// See is_constant() that can be called on any operand.
2612  uint64 value(bool is_signed) const { return extend_sign(nnn->value, size, is_signed); }
2613  int64 signed_value(void) const { return value(true); }
2614  uint64 unsigned_value(void) const { return value(false); }
2615 
2616  /// Retrieve value of a constant integer operand.
2617  /// \param out pointer to the output buffer
2618  /// \param is_signed should treat the value as signed
2619  /// \return true if the operand is mop_n
2620  bool hexapi is_constant(uint64 *out=NULL, bool is_signed=true) const;
2621 
2622  bool is_equal_to(uint64 n, bool is_signed=true) const
2623  {
2624  uint64 v;
2625  return is_constant(&v, is_signed) && v == n;
2626  }
2627  bool is_zero(void) const { return is_equal_to(0, false); }
2628  bool is_one(void) const { return is_equal_to(1, false); }
2629  bool is_positive_constant(void) const
2630  {
2631  uint64 v;
2632  return is_constant(&v, true) && int64(v) > 0;
2633  }
2634  bool is_negative_constant(void) const
2635  {
2636  uint64 v;
2637  return is_constant(&v, true) && int64(v) < 0;
2638  }
2639 
2640  //-----------------------------------------------------------------------
2641  // Working with mop_S operands
2642  //-----------------------------------------------------------------------
2643  /// Retrieve the referenced stack variable.
2644  /// \param p_off if specified, will hold IDA stkoff after the call.
2645  /// \return pointer to the stack variable
2646  member_t *get_stkvar(uval_t *p_off) const { return s->get_stkvar(p_off); }
2647 
2648  /// Get the referenced stack offset.
2649  /// This function can also handle mop_sc if it is entirely mapped into
2650  /// a continuous stack region.
2651  /// \param p_off the output buffer
2652  /// \return success
2653  bool hexapi get_stkoff(sval_t *p_off) const;
2654 
2655  //-----------------------------------------------------------------------
2656  // Working with mop_d operands
2657  //-----------------------------------------------------------------------
2658  /// Get subinstruction of the operand.
2659  /// If the operand has a subinstruction with the specified opcode, return it.
2660  /// \param code desired opcode
2661  /// \return pointer to the instruction or NULL
2662  const minsn_t *get_insn(mcode_t code) const;
2663  minsn_t *get_insn(mcode_t code);
2664 
2665  //-----------------------------------------------------------------------
2666  // Transforming operands
2667  //-----------------------------------------------------------------------
2668  /// Make the low part of the operand.
2669  /// This function takes into account the memory endianness (byte sex)
2670  /// \param width the desired size of the operand part in bytes
2671  /// \return success
2672  bool hexapi make_low_half(int width);
2673 
2674  /// Make the high part of the operand.
2675  /// This function takes into account the memory endianness (byte sex)
2676  /// \param width the desired size of the operand part in bytes
2677  /// \return success
2678  bool hexapi make_high_half(int width);
2679 
2680  /// Make the first part of the operand.
2681  /// This function does not care about the memory endianness
2682  /// \param width the desired size of the operand part in bytes
2683  /// \return success
2684  bool hexapi make_first_half(int width);
2685 
2686  /// Make the second part of the operand.
2687  /// This function does not care about the memory endianness
2688  /// \param width the desired size of the operand part in bytes
2689  /// \return success
2690  bool hexapi make_second_half(int width);
2691 
2692  /// Shift the operand.
2693  /// This function shifts only the beginning of the operand.
2694  /// The operand size will be changed.
2695  /// Examples: shift_mop(AH.1, -1) -> AX.2
2696  /// shift_mop(qword_00000008.8, 4) -> dword_0000000C.4
2697  /// shift_mop(xdu.8(op.4), 4) -> #0.4
2698  /// shift_mop(#0x12345678.4, 3) -> #12.1
2699  /// \param offset shift count (the number of bytes to shift)
2700  /// \return success
2701  bool hexapi shift_mop(int offset);
2702 
2703  /// Change the operand size.
2704  /// Examples: change_size(AL.1, 2) -> AX.2
2705  /// change_size(qword_00000008.8, 4) -> dword_00000008.4
2706  /// change_size(xdu.8(op.4), 4) -> op.4
2707  /// change_size(#0x12345678.4, 1) -> #0x78.1
2708  /// \param nsize new operand size
2709  /// \param sideff may modify the database because of the size change?
2710  /// \return success
2711  bool hexapi change_size(int nsize, side_effect_t sideff=WITH_SIDEFF);
2712  bool double_size(side_effect_t sideff=WITH_SIDEFF) { return change_size(size*2, sideff); }
2713 
2714  /// Move subinstructions with side effects out of the operand.
2715  /// If we decide to delete an instruction operand, it is a good idea to
2716  /// call this function. Alternatively we should skip such operands
2717  /// by calling mop_t::has_side_effects()
2718  /// For example, if we transform: jnz x, x, @blk => goto @blk
2719  /// then we must call this function before deleting the X operands.
2720  /// \param blk current block
2721  /// \param top top level instruction that contains our operand
2722  /// \param moved_calls pointer to the boolean that will track if all side
2723  /// effects get handled correctly. must be false initially.
2724  /// \return false failed to preserve a side effect, it is not safe to
2725  /// delete the operand
2726  /// true no side effects or successfully preserved them
2727  bool hexapi preserve_side_effects(
2728  mblock_t *blk,
2729  minsn_t *top,
2730  bool *moved_calls=NULL);
2731 
2732  /// Apply a unary opcode to the operand.
2733  /// \param mcode opcode to apply. it must accept 'l' and 'd' operands
2734  /// but not 'r'. examples: m_low/m_high/m_xds/m_xdu
2735  /// \param ea value of minsn_t::ea for the newly created insruction
2736  /// \param newsize new operand size
2737  /// Example: apply_ld_mcode(m_low) will convert op => low(op)
2738  void hexapi apply_ld_mcode(mcode_t mcode, ea_t ea, int newsize);
2739  void apply_xdu(ea_t ea, int newsize) { apply_ld_mcode(m_xdu, ea, newsize); }
2740  void apply_xds(ea_t ea, int newsize) { apply_ld_mcode(m_xds, ea, newsize); }
2741 
2742 };
2743 DECLARE_TYPE_AS_MOVABLE(mop_t);
2744 
2745 /// Pair of operands
2747 {
2748 public:
2749  mop_t lop; ///< low operand
2750  mop_t hop; ///< high operand
2751  DEFINE_MEMORY_ALLOCATION_FUNCS()
2752 };
2753 
2754 /// Address of an operand (mop_l, mop_v, mop_S, mop_r)
2755 class mop_addr_t : public mop_t
2756 {
2757 public:
2758  int insize; // how many bytes of the pointed operand can be read
2759  int outsize; // how many bytes of the pointed operand can be written
2760 
2761  mop_addr_t(): insize(NOSIZE), outsize(NOSIZE) {}
2762  mop_addr_t(const mop_addr_t &ra)
2763  : mop_t(ra), insize(ra.insize), outsize(ra.outsize) {}
2764  mop_addr_t(const mop_t &ra, int isz, int osz)
2765  : mop_t(ra), insize(isz), outsize(osz) {}
2766 
2767  mop_addr_t &operator=(const mop_addr_t &rop)
2768  {
2769  *(mop_t *)this = mop_t(rop);
2770  insize = rop.insize;
2771  outsize = rop.outsize;
2772  return *this;
2773  }
2774  int lexcompare(const mop_addr_t &ra) const
2775  {
2776  int code = mop_t::lexcompare(ra);
2777  return code != 0 ? code
2778  : insize != ra.insize ? (insize-ra.insize)
2779  : outsize != ra.outsize ? (outsize-ra.outsize)
2780  : 0;
2781  }
2782 };
2783 
2784 /// A call argument
2785 class mcallarg_t : public mop_t // #callarg
2786 {
2787 public:
2788  ea_t ea; ///< address where the argument was initialized.
2789  ///< BADADDR means unknown.
2790  tinfo_t type; ///< formal argument type
2791  qstring name; ///< formal argument name
2792  argloc_t argloc; ///< ida argloc
2793 
2794  mcallarg_t(void) : ea(BADADDR) {}
2795  mcallarg_t(const mop_t &rarg) : mop_t(rarg), ea(BADADDR) {}
2796  void copy_mop(const mop_t &op) { *(mop_t *)this = op; }
2797  void hexapi print(qstring *vout, int shins_flags=SHINS_SHORT|SHINS_VALNUM) const;
2798  const char *hexapi dstr(void) const;
2799  void hexapi set_regarg(mreg_t mr, int sz, const tinfo_t &tif);
2800  void set_regarg(mreg_t mr, const tinfo_t &tif)
2801  {
2802  set_regarg(mr, tif.get_size(), tif);
2803  }
2804  void set_regarg(mreg_t mr, char dt, type_sign_t sign = type_unsigned)
2805  {
2806  int sz = get_dtype_size(dt);
2807  set_regarg(mr, sz, get_int_type_by_width_and_sign(sz, sign));
2808  }
2809  void make_int(int val, ea_t val_ea, int opno = 0)
2810  {
2811  type = tinfo_t(BTF_INT);
2812  make_number(val, inf.cc.size_i, val_ea, opno);
2813  }
2814  void make_uint(int val, ea_t val_ea, int opno = 0)
2815  {
2816  type = tinfo_t(BTF_UINT);
2817  make_number(val, inf.cc.size_i, val_ea, opno);
2818  }
2819 };
2820 DECLARE_TYPE_AS_MOVABLE(mcallarg_t);
2821 typedef qvector<mcallarg_t> mcallargs_t;
2822 
2823 /// Function roles.
2824 /// They are used to calculate use/def lists and to recognize functions
2825 /// without using string comparisons.
2827 {
2828  ROLE_UNK, ///< unknown function role
2829  ROLE_EMPTY, ///< empty, does not do anything (maybe spoils regs)
2830  ROLE_MEMSET, ///< memset(void *dst, uchar value, size_t count);
2831  ROLE_MEMSET32, ///< memset32(void *dst, uint32 value, size_t count);
2832  ROLE_MEMSET64, ///< memset32(void *dst, uint64 value, size_t count);
2833  ROLE_MEMCPY, ///< memcpy(void *dst, const void *src, size_t count);
2834  ROLE_STRCPY, ///< strcpy(char *dst, const char *src);
2835  ROLE_STRLEN, ///< strlen(const char *src);
2836  ROLE_STRCAT, ///< strcat(char *dst, const char *src);
2837  ROLE_TAIL, ///< char *tail(const char *str);
2838  ROLE_BUG, ///< BUG() helper macro: never returns, causes exception
2839  ROLE_ALLOCA, ///< alloca() function
2840  ROLE_BSWAP, ///< bswap() function (any size)
2841  ROLE_PRESENT, ///< present() function (used in patterns)
2842  ROLE_CONTAINING_RECORD, ///< CONTAINING_RECORD() macro
2843  ROLE_FASTFAIL, ///< __fastfail()
2844  ROLE_READFLAGS, ///< __readeflags, __readcallersflags
2845  ROLE_IS_MUL_OK, ///< is_mul_ok
2846  ROLE_SATURATED_MUL, ///< saturated_mul
2847  ROLE_BITTEST, ///< [lock] bt
2848  ROLE_BITTESTANDSET, ///< [lock] bts
2849  ROLE_BITTESTANDRESET, ///< [lock] btr
2850  ROLE_BITTESTANDCOMPLEMENT, ///< [lock] btc
2851  ROLE_VA_ARG, ///< va_arg() macro
2852  ROLE_VA_COPY, ///< va_copy() function
2853  ROLE_VA_START, ///< va_start() function
2854  ROLE_VA_END, ///< va_end() function
2855  ROLE_ROL, ///< rotate left
2856  ROLE_ROR, ///< rotate right
2857  ROLE_CFSUB3, ///< carry flag after subtract with carry
2858  ROLE_OFSUB3, ///< overflow flag after subtract with carry
2859  ROLE_ABS, ///< integer absolute value
2860 };
2861 
2862 /// \defgroup FUNC_NAME_ Well known function names
2863 //@{
2864 #define FUNC_NAME_MEMCPY "memcpy"
2865 #define FUNC_NAME_MEMSET "memset"
2866 #define FUNC_NAME_MEMSET32 "memset32"
2867 #define FUNC_NAME_MEMSET64 "memset64"
2868 #define FUNC_NAME_STRCPY "strcpy"
2869 #define FUNC_NAME_STRLEN "strlen"
2870 #define FUNC_NAME_STRCAT "strcat"
2871 #define FUNC_NAME_TAIL "tail"
2872 #define FUNC_NAME_VA_ARG "va_arg"
2873 #define FUNC_NAME_EMPTY "$empty"
2874 #define FUNC_NAME_PRESENT "$present"
2875 #define FUNC_NAME_CONTAINING_RECORD "CONTAINING_RECORD"
2876 //@}
2877 
2878 
2879 // the default 256 function arguments is too big, we use a lower value
2880 #undef MAX_FUNC_ARGS
2881 #define MAX_FUNC_ARGS 64
2882 
2883 /// Information about a call argument
2884 class mcallinfo_t // #callinfo
2885 {
2886 public:
2887  ea_t callee; ///< address of the called function, if known
2888  int solid_args; ///< number of solid args.
2889  ///< there may be variadic args in addtion
2890  int call_spd; ///< sp value at call insn
2891  int stkargs_top; ///< first offset past stack arguments
2892  cm_t cc; ///< calling convention
2893  mcallargs_t args; ///< call arguments
2894  mopvec_t retregs; ///< return register(s) (e.g., AX, AX:DX, etc.)
2895  ///< this vector is built from return_regs
2896  tinfo_t return_type; ///< type of the returned value
2897  argloc_t return_argloc; ///< location of the returned value
2898 
2899  mlist_t return_regs; ///< list of values returned by the function
2900  mlist_t spoiled; ///< list of spoiled locations (includes return_regs)
2901  mlist_t pass_regs; ///< passthrough registers: registers that depend on input
2902  ///< values (subset of spoiled)
2903  ivlset_t visible_memory; ///< what memory is visible to the call?
2904  mlist_t dead_regs; ///< registers defined by the function but never used.
2905  ///< upon propagation we do the following:
2906  ///< - dead_regs += return_regs
2907  ///< - retregs.clear() since the call is propagated
2908  int flags; ///< combination of \ref FCI_... bits
2909 /// \defgroup FCI_ Call properties
2910 //@{
2911 #define FCI_PROP 0x01 ///< call has been propagated
2912 #define FCI_DEAD 0x02 ///< some return registers were determined dead
2913 #define FCI_FINAL 0x04 ///< call type is final, should not be changed
2914 #define FCI_NORET 0x08 ///< call does not return
2915 #define FCI_PURE 0x10 ///< pure function
2916 #define FCI_NOSIDE 0x20 ///< call does not have side effects
2917 #define FCI_SPLOK 0x40 ///< spoiled/visible_memory lists have been
2918  ///< optimized. for some functions we can reduce them
2919  ///< as soon as information about the arguments becomes
2920  ///< available. in order not to try optimize them again
2921  ///< we use this bit.
2922 //@}
2923  funcrole_t role; ///< function role
2924 
2925  mcallinfo_t(ea_t _callee=BADADDR, int _sargs=0)
2926  : callee(_callee), solid_args(_sargs), call_spd(0), stkargs_top(0),
2927  cc(CM_CC_INVALID), flags(0), role(ROLE_UNK) {}
2928  DEFINE_MEMORY_ALLOCATION_FUNCS()
2929  int hexapi lexcompare(const mcallinfo_t &f) const;
2930  bool hexapi set_type(const tinfo_t &type);
2931  tinfo_t hexapi get_type(void) const;
2932  bool is_vararg(void) const { return is_vararg_cc(cc); }
2933  void hexapi print(qstring *vout, int size=-1, int shins_flags=SHINS_SHORT|SHINS_VALNUM) const;
2934  const char *hexapi dstr(void) const;
2935 };
2936 
2937 /// List of switch cases and targets
2938 class mcases_t // #cases
2939 {
2940 public:
2941  casevec_t values; ///< expression values for each target
2942  intvec_t targets; ///< target block numbers
2943 
2944  void swap(mcases_t &r) { values.swap(r.values); targets.swap(r.targets); }
2946  DEFINE_MEMORY_ALLOCATION_FUNCS()
2947  bool empty(void) const { return targets.empty(); }
2948  size_t size(void) const { return targets.size(); }
2949  void resize(int s) { values.resize(s); targets.resize(s); }
2950  void hexapi print(qstring *vout) const;
2951  const char *hexapi dstr(void) const;
2952 };
2953 
2954 //-------------------------------------------------------------------------
2955 /// Value offset (microregister number or stack offset)
2956 struct voff_t
2957 {
2958  sval_t off; ///< register number or stack offset
2959  mopt_t type; ///< mop_r - register, mop_S - stack, mop_z - undefined
2960 
2961  voff_t() : off(-1), type(mop_z) {}
2962  voff_t(mopt_t _type, sval_t _off) : off(_off), type(_type) {}
2963  voff_t(const mop_t &op) : off(-1), type(mop_z)
2964  {
2965  if ( op.is_reg() || op.t == mop_S )
2966  set(op.t, op.is_reg() ? op.r : op.s->off);
2967  }
2968 
2969  void set(mopt_t _type, sval_t _off) { type = _type; off = _off; }
2970  void set_stkoff(sval_t stkoff) { set(mop_S, stkoff); }
2971  void set_reg (mreg_t mreg) { set(mop_r, mreg); }
2972  void undef() { set(mop_z, -1); }
2973 
2974  bool defined() const { return type != mop_z; }
2975  bool is_reg() const { return type == mop_r; }
2976  bool is_stkoff() const { return type == mop_S; }
2977  mreg_t get_reg() const { QASSERT(51892, is_reg()); return off; }
2978  sval_t get_stkoff() const { QASSERT(51893, is_stkoff()); return off; }
2979 
2980  void inc(sval_t delta) { off += delta; }
2981  voff_t add(int width) const { return voff_t(type, off+width); }
2982  sval_t diff(const voff_t &r) const { QASSERT(51894, type == r.type); return off - r.off; }
2983 
2984 
2986  {
2987  int code = ::compare(type, r.type);
2988  return code != 0 ? code : ::compare(off, r.off);
2989  }
2990 };
2991 
2992 //-------------------------------------------------------------------------
2993 /// Value interval (register or stack range)
2994 struct vivl_t : voff_t
2995 {
2996  int size; ///< Interval size in bytes
2997 
2998  vivl_t(mopt_t _type = mop_z, sval_t _off = -1, int _size = 0)
2999  : voff_t(_type, _off), size(_size) {}
3000  vivl_t(const class chain_t &ch);
3001  vivl_t(const mop_t &op) : voff_t(op), size(op.size) {}
3002 
3003  // Make a value interval
3004  void set(mopt_t _type, sval_t _off, int _size = 0)
3005  { voff_t::set(_type, _off); size = _size; }
3006  void set(const voff_t &voff, int _size)
3007  { set(voff.type, voff.off, _size); }
3008  void set_stkoff(sval_t stkoff, int sz = 0) { set(mop_S, stkoff, sz); }
3009  void set_reg (mreg_t mreg, int sz = 0) { set(mop_r, mreg, sz); }
3010 
3011  /// Extend a value interval using another value interval of the same type
3012  /// \return success
3013  bool hexapi extend_to_cover(const vivl_t &r);
3014 
3015  /// Intersect value intervals the same type
3016  /// \return size of the resulting intersection
3017  uval_t hexapi intersect(const vivl_t &r);
3018 
3019  /// Do two value intervals overlap?
3020  bool overlap(const vivl_t &r) const
3021  {
3022  return type == r.type
3023  && interval::overlap(off, size, r.off, r.size);
3024  }
3025  /// Does our value interval include another?
3026  bool includes(const vivl_t &r) const
3027  {
3028  return type == r.type
3029  && interval::includes(off, size, r.off, r.size);
3030  }
3031 
3032  /// Does our value interval contain the specified value offset?
3033  bool contains(const voff_t &voff2) const
3034  {
3035  return type == voff2.type
3036  && interval::contains(off, size, voff2.off);
3037  }
3038 
3039  // Comparisons
3041  {
3042  int code = voff_t::compare(r);
3043  return code; //return code != 0 ? code : ::compare(size, r.size);
3044  }
3045  bool operator==(const mop_t &mop) const
3046  {
3047  return type == mop.t && off == (mop.is_reg() ? mop.r : mop.s->off);
3048  }
3049  void hexapi print(qstring *vout) const;
3050  const char *hexapi dstr(void) const;
3051 };
3052 
3053 //-------------------------------------------------------------------------
3054 /// ud (use->def) and du (def->use) chain.
3055 /// We store in chains only the block numbers, not individual instructions
3056 /// See https://en.wikipedia.org/wiki/Use-define_chain
3057 class chain_t : public intvec_t // sequence of block numbers
3058 {
3059  voff_t k; ///< Value offset of the chain.
3060  ///< (what variable is this chain about)
3061 
3062 public:
3063  int width; ///< size of the value in bytes
3064  int varnum; ///< allocated variable index (-1 - not allocated yet)
3065  uchar flags; ///< combination \ref CHF_ bits
3066 /// \defgroup CHF_ Chain properties
3067 //@{
3068 #define CHF_INITED 0x01 ///< is chain initialized? (valid only after lvar allocation)
3069 #define CHF_REPLACED 0x02 ///< chain operands have been replaced?
3070 #define CHF_OVER 0x04 ///< overlapped chain
3071 #define CHF_FAKE 0x08 ///< fake chain created by widen_chains()
3072 #define CHF_PASSTHRU 0x10 ///< pass-thru chain, must use the input variable to the block
3073 #define CHF_TERM 0x20 ///< terminating chain; the variable does not survive across the block
3074 //@}
3075  chain_t() : width(0), varnum(-1), flags(CHF_INITED) {}
3076  chain_t(mopt_t t, sval_t off, int w=1, int v=-1)
3077  : k(t, off), width(w), varnum(v), flags(CHF_INITED) {}
3078  chain_t(const voff_t &_k, int w=1)
3079  : k(_k), width(w), varnum(-1), flags(CHF_INITED) {}
3080  void set_value(const chain_t &r)
3081  { width = r.width; varnum = r.varnum; flags = r.flags; *(intvec_t *)this = (intvec_t &)r; }
3082  const voff_t &key() const { return k; }
3083  bool is_inited(void) const { return (flags & CHF_INITED) != 0; }
3084  bool is_reg(void) const { return k.is_reg(); }
3085  bool is_stkoff(void) const { return k.is_stkoff(); }
3086  bool is_replaced(void) const { return (flags & CHF_REPLACED) != 0; }
3087  bool is_overlapped(void) const { return (flags & CHF_OVER) != 0; }
3088  bool is_fake(void) const { return (flags & CHF_FAKE) != 0; }
3089  bool is_passreg(void) const { return (flags & CHF_PASSTHRU) != 0; }
3090  bool is_term(void) const { return (flags & CHF_TERM) != 0; }
3091  void set_inited(bool b) { setflag(flags, CHF_INITED, b); }
3092  void set_replaced(bool b) { setflag(flags, CHF_REPLACED, b); }
3093  void set_overlapped(bool b) { setflag(flags, CHF_OVER, b); }
3094  void set_term(bool b) { setflag(flags, CHF_TERM, b); }
3095  mreg_t get_reg() const { return k.get_reg(); }
3096  sval_t get_stkoff() const { return k.get_stkoff(); }
3097  bool overlap(const chain_t &r) const
3098  { return k.type == r.k.type && interval::overlap(k.off, width, r.k.off, r.width); }
3099  bool includes(const chain_t &r) const
3100  { return k.type == r.k.type && interval::includes(k.off, width, r.k.off, r.width); }
3101  const voff_t endoff() const { return k.add(width); }
3102 
3103  bool operator<(const chain_t &r) const { return key() < r.key(); }
3104 
3105  void hexapi print(qstring *vout) const;
3106  const char *hexapi dstr(void) const;
3107  /// Append the contents of the chain to the specified list of locations.
3108  void hexapi append_list(mlist_t *list) const;
3109  void clear_varnum(void) { varnum = -1; set_replaced(false); }
3110 };
3111 
3112 //-------------------------------------------------------------------------
3113 #if defined(__NT__)
3114 #define SIZEOF_BLOCK_CHAINS 24
3115 #elif defined(__MAC__)
3116 #define SIZEOF_BLOCK_CHAINS 32
3117 #else
3118 #define SIZEOF_BLOCK_CHAINS 56
3119 #endif
3120 /// Chains of one block.
3121 /// Please note that this class is based on std::map and it must be accessed
3122 /// using the block_chains_begin(), block_chains_find() and similar functions.
3123 /// This is required because different compilers use different implementations
3124 /// of std::map. However, since the size of std::map depends on the compilation
3125 /// options, we replace it with a byte array.
3127 {
3128  size_t body[SIZEOF_BLOCK_CHAINS/sizeof(size_t)]; // opaque std::set, uncopyable
3129 public:
3130 
3131  /// Get chain for the specified register
3132  /// \param reg register number
3133  /// \param width size of register in bytes
3134  const chain_t *get_reg_chain(mreg_t reg, int width=1) const
3135  { return get_chain((chain_t(mop_r, reg, width))); }
3136  chain_t *get_reg_chain(mreg_t reg, int width=1)
3137  { return get_chain((chain_t(mop_r, reg, width))); }
3138 
3139  /// Get chain for the specified stack offset
3140  /// \param off stack offset
3141  /// \param width size of stack value in bytes
3142  const chain_t *get_stk_chain(sval_t off, int width=1) const
3143  { return get_chain(chain_t(mop_S, off, width)); }
3144  chain_t *get_stk_chain(sval_t off, int width=1)
3145  { return get_chain(chain_t(mop_S, off, width)); }
3146 
3147  /// Get chain for the specified value offset.
3148  /// \param k value offset (register number or stack offset)
3149  /// \param width size of value in bytes
3150  const chain_t *get_chain(const voff_t &k, int width=1) const
3151  { return get_chain(chain_t(k, width)); }
3152  chain_t *get_chain(const voff_t &k, int width=1)
3153  { return (chain_t*)((const block_chains_t *)this)->get_chain(k, width); }
3154 
3155  /// Get chain similar to the specified chain
3156  /// \param ch chain to search for. only its 'k' and 'width' are used.
3157  const chain_t *hexapi get_chain(const chain_t &ch) const;
3158  chain_t *get_chain(const chain_t &ch)
3159  { return (chain_t*)((const block_chains_t *)this)->get_chain(ch); }
3160 
3161  void hexapi print(qstring *vout) const;
3162  const char *hexapi dstr(void) const;
3163  DEFINE_MEMORY_ALLOCATION_FUNCS()
3164 };
3165 //-------------------------------------------------------------------------
3166 /// Chain visitor class
3168 {
3169  block_chains_t *parent; ///< parent of the current chain
3170  chain_visitor_t(void) : parent(NULL) {}
3171  virtual int idaapi visit_chain(int nblock, chain_t &ch) = 0;
3172 };
3173 
3174 //-------------------------------------------------------------------------
3175 /// Graph chains.
3176 /// This class represents all ud and du chains of the decompiled function
3177 class graph_chains_t : public qvector<block_chains_t>
3178 {
3179  int lock; ///< are chained locked? (in-use)
3180 public:
3181  graph_chains_t(void) : lock(0) {}
3182  ~graph_chains_t(void) { QASSERT(50444, !lock); }
3183  /// Visit all chains
3184  /// \param cv chain visitor
3185  /// \param gca_flags combination of GCA_ bits
3186  int hexapi for_all_chains(chain_visitor_t &cv, int gca_flags);
3187  /// \defgroup GCA_ chain visitor flags
3188  //@{
3189 #define GCA_EMPTY 0x01 ///< include empty chains
3190 #define GCA_SPEC 0x02 ///< include chains for special registers
3191 #define GCA_ALLOC 0x04 ///< enumerate only allocated chains
3192 #define GCA_NALLOC 0x08 ///< enumerate only non-allocated chains
3193 #define GCA_OFIRST 0x10 ///< consider only chains of the first block
3194 #define GCA_OLAST 0x20 ///< consider only chains of the last block
3195  //@}
3196  /// Are the chains locked?
3197  /// It is a good idea to lock the chains before using them. This ensures
3198  /// that they won't be recalculated and reallocated during the use.
3199  /// See the \ref chain_keeper_t class for that.
3200  bool is_locked(void) const { return lock != 0; }
3201  /// Lock the chains
3202  void acquire(void) { lock++; }
3203  /// Unlock the chains
3204  void hexapi release(void);
3205  void swap(graph_chains_t &r)
3206  {
3207  qvector<block_chains_t>::swap(r);
3208  std::swap(lock, r.lock);
3209  }
3210 };
3211 //-------------------------------------------------------------------------
3212 /// Microinstruction class #insn
3213 class minsn_t
3214 {
3215  void hexapi init(ea_t _ea);
3216  void hexapi copy(const minsn_t &m);
3217 public:
3218  mcode_t opcode; ///< instruction opcode
3219  int iprops; ///< combination of \ref IPROP_ bits
3220  minsn_t *next; ///< next insn in doubly linked list. check also nexti()
3221  minsn_t *prev; ///< prev insn in doubly linked list. check also previ()
3222  ea_t ea; ///< instruction address
3223  mop_t l; ///< left operand
3224  mop_t r; ///< right operand
3225  mop_t d; ///< destination operand
3226 
3227  /// \defgroup IPROP_ instruction property bits
3228  //@{
3229  // bits to be used in patterns:
3230 #define IPROP_OPTIONAL 0x0001 ///< optional instruction
3231 #define IPROP_PERSIST 0x0002 ///< persistent insn; they are not destroyed
3232 #define IPROP_WILDMATCH 0x0004 ///< match multiple insns
3233 
3234  // instruction attributes:
3235 #define IPROP_CLNPOP 0x0008 ///< the purpose of the instruction is to clean stack
3236  ///< (e.g. "pop ecx" is often used for that)
3237 #define IPROP_FPINSN 0x0010 ///< floating point insn
3238 #define IPROP_FARCALL 0x0020 ///< call of a far function using push cs/call sequence
3239 #define IPROP_TAILCALL 0x0040 ///< tail call
3240 #define IPROP_ASSERT 0x0080 ///< assertion: usually mov #val, op.
3241  ///< assertions are used to help the optimizer.
3242  ///< assertions are ignored when generating ctree
3243 
3244  // instruction history:
3245 #define IPROP_SPLIT 0x0700 ///< the instruction has been split:
3246 #define IPROP_SPLIT1 0x0100 ///< into 1 byte
3247 #define IPROP_SPLIT2 0x0200 ///< into 2 bytes
3248 #define IPROP_SPLIT4 0x0300 ///< into 4 bytes
3249 #define IPROP_SPLIT8 0x0400 ///< into 8 bytes
3250 #define IPROP_COMBINED 0x0800 ///< insn has been modified because of a partial reference
3251 #define IPROP_EXTSTX 0x1000 ///< this is m_ext propagated into m_stx
3252 #define IPROP_IGNLOWSRC 0x2000 ///< low part of the instruction source operand
3253  ///< has been created artificially
3254  ///< (this bit is used only for 'and x, 80...')
3255 #define IPROP_INV_JX 0x4000 ///< inverted conditional jump
3256 #define IPROP_WAS_NORET 0x8000 ///< was noret icall
3257 #define IPROP_MULTI_MOV 0x10000 ///< the minsn was generated as part of insn that moves multiple registers
3258  ///< (example: STM on ARM may transfer multiple registers)
3259 
3260  ///< bits that can be set by plugins:
3261 #define IPROP_DONT_PROP 0x20000 ///< may not propagate
3262 #define IPROP_DONT_COMB 0x40000 ///< may not combine this instruction with others
3263  //@}
3264 
3265  bool is_optional(void) const { return (iprops & IPROP_OPTIONAL) != 0; }
3266  bool is_combined(void) const { return (iprops & IPROP_COMBINED) != 0; }
3267  bool is_farcall(void) const { return (iprops & IPROP_FARCALL) != 0; }
3268  bool is_cleaning_pop(void) const { return (iprops & IPROP_CLNPOP) != 0; }
3269  bool is_extstx(void) const { return (iprops & IPROP_EXTSTX) != 0; }
3270  bool is_tailcall(void) const { return (iprops & IPROP_TAILCALL) != 0; }
3271  bool is_fpinsn(void) const { return (iprops & IPROP_FPINSN) != 0; }
3272  bool is_assert(void) const { return (iprops & IPROP_ASSERT) != 0; }
3273  bool is_persistent(void) const { return (iprops & IPROP_PERSIST) != 0; }
3274  bool is_wild_match(void) const { return (iprops & IPROP_WILDMATCH) != 0; }
3275  bool is_propagatable(void) const { return (iprops & IPROP_DONT_PROP) == 0; }
3276  bool is_ignlowsrc(void) const { return (iprops & IPROP_IGNLOWSRC) != 0; }
3277  bool is_inverted_jx(void) const { return (iprops & IPROP_INV_JX) != 0; }
3278  bool was_noret_icall(void) const { return (iprops & IPROP_WAS_NORET) != 0; }
3279  bool is_multimov(void) const { return (iprops & IPROP_MULTI_MOV) != 0; }
3280  bool is_combinable(void) const { return (iprops & IPROP_DONT_COMB) == 0; }
3281  bool was_split(void) const { return (iprops & IPROP_SPLIT) != 0; }
3282 
3283  void set_optional(void) { iprops |= IPROP_OPTIONAL; }
3284  void set_combined(void);
3285  void clr_combined(void) { iprops &= ~IPROP_COMBINED; }
3286  void set_farcall(void) { iprops |= IPROP_FARCALL; }
3287  void set_cleaning_pop(void) { iprops |= IPROP_CLNPOP; }
3288  void set_extstx(void) { iprops |= IPROP_EXTSTX; }
3289  void set_tailcall(void) { iprops |= IPROP_TAILCALL; }
3290  void clr_tailcall(void) { iprops &= ~IPROP_TAILCALL; }
3291  void set_fpinsn(void) { iprops |= IPROP_FPINSN; }
3292  void clr_fpinsn(void) { iprops &= ~IPROP_FPINSN; }
3293  void set_assert(void) { iprops |= IPROP_ASSERT; }
3294  void clr_assert(void) { iprops &= ~IPROP_ASSERT; }
3295  void set_persistent(void) { iprops |= IPROP_PERSIST; }
3296  void set_wild_match(void) { iprops |= IPROP_WILDMATCH; }
3297  void clr_propagatable(void) { iprops |= IPROP_DONT_PROP; }
3298  void set_ignlowsrc(void) { iprops |= IPROP_IGNLOWSRC; }
3299  void clr_ignlowsrc(void) { iprops &= ~IPROP_IGNLOWSRC; }
3300  void set_inverted_jx(void) { iprops |= IPROP_INV_JX; }
3301  void set_noret_icall(void) { iprops |= IPROP_WAS_NORET; }
3302  void clr_noret_icall(void) { iprops &= ~IPROP_WAS_NORET; }
3303  void set_multimov(void) { iprops |= IPROP_MULTI_MOV; }
3304  void clr_multimov(void) { iprops &= ~IPROP_MULTI_MOV; }
3305  void set_combinable(void) { iprops &= ~IPROP_DONT_COMB; }
3306  void clr_combinable(void) { iprops |= IPROP_DONT_COMB; }
3307  void set_split_size(int s)
3308  { // s may be only 1,2,4,8. other values are ignored
3309  iprops &= ~IPROP_SPLIT;
3310  iprops |= (s == 1 ? IPROP_SPLIT1
3311  : s == 2 ? IPROP_SPLIT2
3312  : s == 4 ? IPROP_SPLIT4
3313  : s == 8 ? IPROP_SPLIT8 : 0);
3314  }
3315  int get_split_size(void) const
3316  {
3317  int cnt = (iprops & IPROP_SPLIT) >> 8;
3318  return cnt == 0 ? 0 : 1 << (cnt-1);
3319  }
3320 
3321  /// Constructor
3322  minsn_t(ea_t _ea) { init(_ea); }
3323  minsn_t(const minsn_t &m) { next = prev = NULL; copy(m); }
3324  DEFINE_MEMORY_ALLOCATION_FUNCS()
3325 
3326  /// Assignment operator. It does not copy prev/next fields.
3327  minsn_t &operator=(const minsn_t &m) { copy(m); return *this; }
3328 
3329  /// Swap two instructions.
3330  /// The prev/next fields are not modified by this function
3331  /// because it would corrupt the doubly linked list.
3332  void hexapi swap(minsn_t &m);
3333 
3334  /// Generate insn text into the buffer
3335  void hexapi print(qstring *vout, int shins_flags=SHINS_SHORT|SHINS_VALNUM) const;
3336 
3337  /// Get displayable text without tags in a static buffer
3338  const char *hexapi dstr(void) const;
3339 
3340  /// Change the instruction address.
3341  /// This function modifies subinstructions as well.
3342  void hexapi setaddr(ea_t new_ea);
3343 
3344  /// Optimize one instruction without context.
3345  /// This function does not have access to the instruction context (the
3346  /// previous and next instructions in the list, the block number, etc).
3347  /// It performs only basic optimizations that are available without this info.
3348  /// \param optflags combination of \ref OPTI_ bits
3349  /// \return number of changes, 0-unchanged
3350  /// See also mblock_t::optimize_insn()
3351  int optimize_solo(int optflags=0) { return optimize_subtree(NULL, NULL, NULL, NULL, optflags); }
3352  /// \defgroup OPTI_ optimization flags
3353  //@{
3354 #define OPTI_ADDREXPRS 0x0001 ///< optimize all address expressions (&x+N; &x-&y)
3355 #define OPTI_MINSTKREF 0x0002 ///< may update minstkref
3356 #define OPTI_COMBINSNS 0x0004 ///< may combine insns (only for optimize_insn)
3357  //@}
3358 
3359  /// Optimize instruction in its context.
3360  /// Do not use this function, use mblock_t::optimize()
3361  int hexapi optimize_subtree(
3362  mblock_t *blk,
3363  minsn_t *top,
3364  minsn_t *parent,
3365  minsn_t **converted_call,
3366  int optflags=OPTI_MINSTKREF);
3367 
3368  /// Visit all instruction operands.
3369  /// This function visits subinstruction operands as well.
3370  /// \param mv operand visitor
3371  /// \return non-zero value returned by mv.visit_mop() or zero
3372  int hexapi for_all_ops(mop_visitor_t &mv);
3373 
3374  /// Visit all instructions.
3375  /// This function visits the instruction itself and all its subinstructions.
3376  /// \param mv instruction visitor
3377  /// \return non-zero value returned by mv.visit_mop() or zero
3378  int hexapi for_all_insns(minsn_visitor_t &mv);
3379 
3380  /// Convert instruction to nop.
3381  /// This function erases all info but the prev/next fields.
3382  /// In most cases it is better to use mblock_t::make_nop(), which also
3383  /// marks the block lists as dirty.
3384  void hexapi _make_nop(void);
3385 
3386  /// Compare instructions.
3387  /// This is the main comparison function for instructions.
3388  /// \param m instruction to compare with
3389  /// \param eqflags combination of \ref EQ_ bits
3390  bool hexapi equal_insns(const minsn_t &m, int eqflags) const; // intelligent comparison
3391  /// \defgroup EQ_ comparison bits
3392  //@{
3393 #define EQ_IGNSIZE 0x0001 ///< ignore operand sizes
3394 #define EQ_IGNCODE 0x0002 ///< ignore instruction opcodes
3395 #define EQ_CMPDEST 0x0004 ///< compare instruction destinations
3396 #define EQ_OPTINSN 0x0008 ///< optimize mop_d operands
3397  //@}
3398 
3399  /// Lexographical comparison
3400  /// It can be used to store minsn_t in various containers, like std::set
3401  bool operator <(const minsn_t &ri) const { return lexcompare(ri) < 0; }
3402  int hexapi lexcompare(const minsn_t &ri) const;
3403 
3404  //-----------------------------------------------------------------------
3405  // Call instructions
3406  //-----------------------------------------------------------------------
3407  /// Is a non-returing call?
3408  /// \param ignore_noret_icall if set, indirect calls to noret functions will
3409  /// return false
3410  bool hexapi is_noret_call(bool ignore_noret_icall=false);
3411 
3412  /// Is an unknown call?
3413  /// Unknown calls are resolved by mbl_array_t::analyze_calls()
3414  /// They exist until the MMAT_CALLS maturity level.
3415  bool is_unknown_call(void) const { return is_mcode_call(opcode) && d.t == mop_z; }
3416 
3417  /// Is a helper call with the specified name?
3418  /// Helper calls usually have well-known function names (see \ref FUNC_NAME_)
3419  /// but they may have any other name. The decompiler does not assume any
3420  /// special meaning for non-well-known names.
3421  bool hexapi is_helper(const char *name) const;
3422 
3423  /// Find a call instruction.
3424  /// Check for the current instruction and its subinstructions.
3425  /// \param with_helpers consider helper calls as well?
3426  minsn_t *hexapi find_call(bool with_helpers=false) const;
3427 
3428  /// Does the instruction contain a call?
3429  bool contains_call(bool with_helpers=false) const { return find_call(with_helpers) != NULL; }
3430 
3431  /// Does the instruction have a side effect?
3432  /// \param include_ldx consider ldx as having side effects?
3433  /// stx is always considered as having side effects.
3434  /// Apart from ldx/std only call may have side effects.
3435  bool hexapi has_side_effects(bool include_ldx=false) const;
3436 
3437  /// Get the function role of a call
3438  funcrole_t get_role(void) const { return d.t == mop_f ? d.f->role : ROLE_UNK; }
3439  bool is_memcpy(void) const { return get_role() == ROLE_MEMCPY; }
3440  bool is_memset(void) const { return get_role() == ROLE_MEMSET; }
3441  bool is_alloca(void) const { return get_role() == ROLE_ALLOCA; }
3442  bool is_bswap (void) const { return get_role() == ROLE_BSWAP; }
3443  bool is_readflags (void) const { return get_role() == ROLE_READFLAGS; }
3444 
3445  //-----------------------------------------------------------------------
3446  // Misc
3447  //-----------------------------------------------------------------------
3448  /// Does the instruction have the specified opcode?
3449  /// This function searches subinstructions as well.
3450  /// \param mcode opcode to search for.
3451  bool contains_opcode(mcode_t mcode) const { return find_opcode(mcode) != NULL; }
3452 
3453  /// Find a (sub)insruction with the specified opcode.
3454  /// \param mcode opcode to search for.
3455  const minsn_t *find_opcode(mcode_t mcode) const { return (CONST_CAST(minsn_t*)(this))->find_opcode(mcode); }
3456  minsn_t *hexapi find_opcode(mcode_t mcode);
3457 
3458  /// Find an operand that is a subinsruction with the specified opcode.
3459  /// This function checks only the 'l' and 'r' operands of the current insn.
3460  /// \param[out] other pointer to the other operand
3461  /// (&r if we return &l and vice versa)
3462  /// \param op opcode to search for
3463  /// \return &l or &r or NULL
3464  const minsn_t *hexapi find_ins_op(const mop_t **other, mcode_t op=m_nop) const;
3465  minsn_t *find_ins_op(mop_t **other, mcode_t op=m_nop) { return CONST_CAST(minsn_t*)((CONST_CAST(const minsn_t*)(this))->find_ins_op((const mop_t**)other, op)); }
3466 
3467  /// Find a numeric operand of the current instruction.
3468  /// This function checks only the 'l' and 'r' operands of the current insn.
3469  /// \param[out] other pointer to the other operand
3470  /// (&r if we return &l and vice versa)
3471  /// \return &l or &r or NULL
3472  const mop_t *hexapi find_num_op(const mop_t **other) const;
3473  mop_t *find_num_op(mop_t **other) { return CONST_CAST(mop_t*)((CONST_CAST(const minsn_t*)(this))->find_num_op((const mop_t**)other)); }
3474 
3475  bool is_mov(void) const { return opcode == m_mov || (opcode == m_f2f && l.size == d.size); }
3476  bool is_like_move(void) const { return is_mov() || is_mcode_xdsu(opcode) || opcode == m_low; }
3477 
3478  /// Does the instruction modify its 'd' operand?
3479  /// Some instructions (e.g. m_stx) do not modify the 'd' operand.
3480  bool hexapi modifes_d(void) const;
3481  bool modifies_pair_mop(void) const { return d.t == mop_p && modifes_d(); }
3482 
3483  /// Is the instruction in the specified range of instructions?
3484  /// \param m1 beginning of the range in the doubly linked list
3485  /// \param m2 end of the range in the doubly linked list (excluded, may be NULL)
3486  /// This function assumes that m1 and m2 belong to the same basic block
3487  /// and they are top level instructions.
3488  bool hexapi is_between(const minsn_t *m1, const minsn_t *m2) const;
3489 
3490  /// Is the instruction after the specified one?
3491  /// \param m the instruction to compare against in the list
3492  bool is_after(const minsn_t *m) const { return m != NULL && is_between(m->next, NULL); }
3493 
3494  /// Is it possible for the instruction to use aliased memory?
3495  bool hexapi may_use_aliased_memory(void) const;
3496 };
3497 
3498 /// Skip assertions forward
3499 const minsn_t *hexapi getf_reginsn(const minsn_t *ins);
3500 /// Skip assertions backward
3501 const minsn_t *hexapi getb_reginsn(const minsn_t *ins);
3502 inline minsn_t *getf_reginsn(minsn_t *ins) { return CONST_CAST(minsn_t*)(getf_reginsn(CONST_CAST(const minsn_t *)(ins))); }
3503 inline minsn_t *getb_reginsn(minsn_t *ins) { return CONST_CAST(minsn_t*)(getb_reginsn(CONST_CAST(const minsn_t *)(ins))); }
3504 
3505 //-------------------------------------------------------------------------
3506 /// Basic block types
3508 {
3509  BLT_NONE = 0, ///< unknown block type
3510  BLT_STOP = 1, ///< stops execution regularly (must be the last block)
3511  BLT_0WAY = 2, ///< does not have successors (tail is a noret function)
3512  BLT_1WAY = 3, ///< passes execution to one block (regular or goto block)
3513  BLT_2WAY = 4, ///< passes execution to two blocks (conditional jump)
3514  BLT_NWAY = 5, ///< passes execution to many blocks (switch idiom)
3515  BLT_XTRN = 6, ///< external block (out of function address)
3516 };
3517 
3518 // Maximal bit range
3519 #define MAXRANGE bitrange_t(0, USHRT_MAX)
3520 
3521 //-------------------------------------------------------------------------
3522 /// Microcode of one basic block.
3523 /// All blocks are part of a doubly linked list as well as can be addressed
3524 /// by indexing the mba->natural array. A block contains a doubly linked list
3525 /// of instructions, various localtion lists that are used for data flow
3526 /// analysis and other attributes.
3528 {
3529  friend class codegen_t;
3530  DECLARE_UNCOPYABLE(mblock_t)
3531  void hexapi init(void);
3532 public:
3533  mblock_t *nextb; ///< next block in the doubly linked list
3534  mblock_t *prevb; ///< previous block in the doubly linked list
3535  uint32 flags; ///< combination of \ref MBL_ bits
3536  /// \defgroup MBL_ Basic block properties
3537  //@{
3538 #define MBL_PRIV 0x0001 ///< private block - no instructions except
3539  ///< the specified are accepted (used in patterns)
3540 #define MBL_NONFAKE 0x0000 ///< regular block
3541 #define MBL_FAKE 0x0002 ///< fake block (after a tail call)
3542 #define MBL_GOTO 0x0004 ///< this block is a goto target
3543 #define MBL_TCAL 0x0008 ///< aritifical call block for tail calls
3544 #define MBL_PUSH 0x0010 ///< needs "convert push/pop instructions"
3545 #define MBL_DMT64 0x0020 ///< needs "demote 64bits"
3546 #define MBL_COMB 0x0040 ///< needs "combine" pass
3547 #define MBL_PROP 0x0080 ///< needs 'propagation' pass
3548 #define MBL_DEAD 0x0100 ///< needs "eliminate deads" pass
3549 #define MBL_LIST 0x0200 ///< use/def lists are ready (not dirty)
3550 #define MBL_INCONST 0x0400 ///< inconsistent lists: we are building them
3551 #define MBL_CALL 0x0800 ///< call information has been built
3552 #define MBL_BACKPROP 0x1000 ///< performed backprop_cc
3553 #define MBL_NORET 0x2000 ///< dead end block: doesn't return execution control
3554 #define MBL_DSLOT 0x4000 ///< block for delay slot
3555 #define MBL_VALRANGES 0x8000 ///< should optimize using value ranges
3556  //@}
3557  ea_t start; ///< start address
3558  ea_t end; ///< end address
3559  ///< note: we can not rely on start/end addresses
3560  ///< very much because instructions are
3561  ///< propagated between blocks
3562  minsn_t *head; ///< pointer to the first instruction of the block
3563  minsn_t *tail; ///< pointer to the last instruction of the block
3564  mbl_array_t *mba; ///< the parent micro block array
3565  int serial; ///< block number
3566  mblock_type_t type; ///< block type (BLT_NONE - not computed yet)
3567 
3568  mlist_t dead_at_start; ///< data that is dead at the block entry
3569  mlist_t mustbuse; ///< data that must be used by the block
3570  mlist_t maybuse; ///< data that may be used by the block
3571  mlist_t mustbdef; ///< data that must be defined by the block
3572  mlist_t maybdef; ///< data that may be defined by the block
3573  mlist_t dnu; ///< data that is defined but not used in the block
3574 
3575  sval_t maxbsp; ///< maximal sp value in the block (0...stacksize)
3576  sval_t minbstkref; ///< lowest stack location accessible with indirect
3577  ///< addressing (offset from the stack bottom)
3578  ///< initially it is 0 (not computed)
3579  sval_t minbargref; ///< the same for arguments
3580 
3581  intvec_t predset; ///< control flow graph: list of our predecessors
3582  ///< use npred() and pred() to access it
3583  intvec_t succset; ///< control flow graph: list of our successors
3584  ///< use nsucc() and succ() to access it
3585 
3586  // the exact size of this class is not documented, they may be more fields
3587  char reserved[];
3588 
3589  void mark_lists_dirty(void) { flags &= ~MBL_LIST; request_propagation(); }
3590  void request_propagation(void) { flags |= MBL_PROP; }
3591  bool needs_propagation(void) const { return (flags & MBL_PROP) != 0; }
3592  void request_demote64(void) { flags |= MBL_DMT64; }
3593  bool lists_dirty(void) const { return (flags & MBL_LIST) == 0; }
3594  bool lists_ready(void) const { return (flags & (MBL_LIST|MBL_INCONST)) == MBL_LIST; }
3595  int make_lists_ready(void) // returns number of changes
3596  {
3597  if ( lists_ready() )
3598  return 0;
3599  return build_lists(false);
3600  }
3601 
3602  /// Get number of block predecessors
3603  int npred(void) const { return predset.size(); } // number of xrefs to the block
3604  /// Get number of block successors
3605  int nsucc(void) const { return succset.size(); } // number of xrefs from the block
3606  // Get predecessor number N
3607  int pred(int n) const { return predset[n]; }
3608  // Get successor number N
3609  int succ(int n) const { return succset[n]; }
3610 
3611  mblock_t(void) { init(); }
3612  virtual ~mblock_t(void);
3613  DEFINE_MEMORY_ALLOCATION_FUNCS()
3614  bool empty(void) const { return head == NULL; }
3615 
3616  /// Print block contents.
3617  /// \param vp print helpers class. it can be used to direct the printed
3618  /// info to any destination
3619  void hexapi print(vd_printer_t &vp) const;
3620 
3621  /// Dump block info.
3622  /// This function is useful for debugging, see mbl_array_t::dump for info
3623  void hexapi dump(void) const;
3624  AS_PRINTF(2, 0) void hexapi vdump_block(const char *title, va_list va) const;
3625  AS_PRINTF(2, 3) void dump_block(const char *title, ...) const
3626  {
3627  va_list va;
3628  va_start(va, title);
3629  vdump_block(title, va);
3630  va_end(va);
3631  }
3632 
3633  //-----------------------------------------------------------------------
3634  // Functions to insert/remove insns during the microcode optimization phase.
3635  // See codegen_t, microcode_filter_t, udcall_t classes for the initial
3636  // microcode generation.
3637  //-----------------------------------------------------------------------
3638  /// Insert instruction into the doubly linked list
3639  /// \param nm new instruction
3640  /// \param om existing instruction, part of the doubly linked list
3641  /// if NULL, then the instruction will be inserted at the beginning
3642  /// of the list
3643  /// NM will be inserted immediately after OM
3644  /// \return pointer to NM
3645  minsn_t *hexapi insert_into_block(minsn_t *nm, minsn_t *om);
3646 
3647  /// Remove instruction from the doubly linked list
3648  /// \param m instruction to remove
3649  /// The removed iinstruction is not deleted, the caller gets its ownership
3650  /// \return pointer to the next instruction
3651  minsn_t *hexapi remove_from_block(minsn_t *m);
3652 
3653  //-----------------------------------------------------------------------
3654  // Iterator over instructions and operands
3655  //-----------------------------------------------------------------------
3656  /// Visit all instructions.
3657  /// This function visits subinstructions too.
3658  /// \param mv instruction visitor
3659  /// \return zero or the value returned by mv.visit_insn()
3660  /// See also mbl_array_t::for_all_topinsns()
3661  int hexapi for_all_insns(minsn_visitor_t &mv);
3662 
3663  /// Visit all operands.
3664  /// This function visit subinstruction operands too.
3665  /// \param mv operand visitor
3666  /// \return zero or the value returned by mv.visit_mop()
3667  int hexapi for_all_ops(mop_visitor_t &mv);
3668 
3669  /// Visit all operands that use LIST.
3670  /// \param list ptr to the list of locations. it may be modified:
3671  /// parts that get redefined by the instructions in [i1,i2)
3672  /// will be deleted.
3673  /// \param i1 starting instruction. must be a top level insn.
3674  /// \param i2 ending instruction (excluded). must be a top level insn.
3675  /// \param mmv operand visitor
3676  /// \return zero or the value returned by mmv.visit_mop()
3677  int hexapi for_all_uses(
3678  mlist_t *list,
3679  minsn_t *i1,
3680  minsn_t *i2,
3681  mlist_mop_visitor_t &mmv);
3682 
3683  //-----------------------------------------------------------------------
3684  // Optimization functions
3685  //-----------------------------------------------------------------------
3686  /// Optimize one instruction in the context of the block.
3687  /// \param m pointer to a top level instruction
3688  /// \param optflags combination of \ref OPTI_ bits
3689  /// \return number of changes made to the block
3690  /// This function may change other instructions in the block too.
3691  /// However, it will not destroy top level instructions (it may convert them
3692  /// to nop's). See also minsn_t::optimize_solo()
3693  int hexapi optimize_insn(minsn_t *m, int optflags=OPTI_MINSTKREF|OPTI_COMBINSNS);
3694 
3695  /// Optimize a basic block.
3696  /// Usually there is no need to call this function explicitly because the
3697  /// decompiler will call it itself if optinsn_t::func or optblock_t::func
3698  /// return non-zero.
3699  /// \return number of changes made to the block
3700  int hexapi optimize_block(void);
3701 
3702  /// Build def-use lists and eliminate deads.
3703  /// \param kill_deads do delete dead instructions?
3704  /// \return the number of eliminated instructions
3705  /// Better mblock_t::call make_lists_ready() rather than this function.
3706  int hexapi build_lists(bool kill_deads);
3707 
3708  //-----------------------------------------------------------------------
3709  // Functions that build with use/def lists. These lists are used to
3710  // reprsent list of registers and stack locations that are either modified
3711  // or accessed by microinstructions.
3712  //-----------------------------------------------------------------------
3713  /// Append use-list of an operand.
3714  /// This function calculates list of locations that may or must be used
3715  /// by the operand and appends it to LIST.
3716  /// \param list ptr to the output buffer. we will append to it.
3717  /// \param op operand to calculate the use list of
3718  /// \param maymust should we calculate 'may-use' or 'must-use' list?
3719  /// see \ref maymust_t for more details.
3720  /// \param mask if only part of the operand should be considered,
3721  /// a bitmask can be used to specify which part.
3722  /// example: op=AX,mask=0xFF means that we will consider only AL.
3723  void hexapi append_use_list(
3724  mlist_t *list,
3725  const mop_t &op,
3726  maymust_t maymust,
3727  bitrange_t mask=MAXRANGE) const;
3728 
3729  /// Append def-list of an operand.
3730  /// This function calculates list of locations that may or must be modified
3731  /// by the operand and appends it to LIST.
3732  /// \param list ptr to the output buffer. we will append to it.
3733  /// \param op operand to calculate the def list of
3734  /// \param maymust should we calculate 'may-def' or 'must-def' list?
3735  /// see \ref maymust_t for more details.
3736  void hexapi append_def_list(
3737  mlist_t *list,
3738  const mop_t &op,
3739  maymust_t maymust) const;
3740 
3741  /// Build use-list of an instruction.
3742  /// This function calculates list of locations that may or must be used
3743  /// by the instruction. Examples:
3744  /// "ldx ds.2, eax.4, ebx.4", may-list: all aliasable memory
3745  /// "ldx ds.2, eax.4, ebx.4", must-list: empty
3746  /// Since LDX uses EAX for indirect access, it may access any aliasable
3747  /// memory. On the other hand, we can not tell for sure which memory cells
3748  /// will be accessed, this is why the must-list is empty.
3749  /// \param ins instruction to calculate the use list of
3750  /// \param maymust should we calculate 'may-use' or 'must-use' list?
3751  /// see \ref maymust_t for more details.
3752  /// \return the calculated use-list
3753  mlist_t hexapi build_use_list(const minsn_t &ins, maymust_t maymust) const;
3754 
3755  /// Build def-list of an instruction.
3756  /// This function calculates list of locations that may or must be modified
3757  /// by the instruction. Examples:
3758  /// "stx ebx.4, ds.2, eax.4", may-list: all aliasable memory
3759  /// "stx ebx.4, ds.2, eax.4", must-list: empty
3760  /// Since STX uses EAX for indirect access, it may modify any aliasable
3761  /// memory. On the other hand, we can not tell for sure which memory cells
3762  /// will be modified, this is why the must-list is empty.
3763  /// \param ins instruction to calculate the def list of
3764  /// \param maymust should we calculate 'may-def' or 'must-def' list?
3765  /// see \ref maymust_t for more details.
3766  /// \return the calculated def-list
3767  mlist_t hexapi build_def_list(const minsn_t &ins, maymust_t maymust) const;
3768 
3769  //-----------------------------------------------------------------------
3770  // The use/def lists can be used to search for interesting instructions
3771  //-----------------------------------------------------------------------
3772  /// Is the list used by the specified instruction range?
3773  /// \param list list of locations. LIST may be modified by the function:
3774  /// redefined locations will be removed from it.
3775  /// \param i1 starting instruction of the range (must be a top level insn)
3776  /// \param i2 end instruction of the range (must be a top level insn)
3777  /// i2 is excluded from the range. it can be specified as NULL.
3778  /// i1 and i2 must belong to the same block.
3779  /// \param maymust should we search in 'may-access' or 'must-access' mode?
3780  bool is_used(mlist_t *list, const minsn_t *i1, const minsn_t *i2, maymust_t maymust=MAY_ACCESS) const
3781  { return find_first_use(list, i1, i2, maymust) != NULL; }
3782 
3783  /// Find the first insn that uses the specified list in the insn range.
3784  /// \param list list of locations. LIST may be modified by the function:
3785  /// redefined locations will be removed from it.
3786  /// \param i1 starting instruction of the range (must be a top level insn)
3787  /// \param i2 end instruction of the range (must be a top level insn)
3788  /// i2 is excluded from the range. it can be specified as NULL.
3789  /// i1 and i2 must belong to the same block.
3790  /// \param maymust should we search in 'may-access' or 'must-access' mode?
3791  /// \return pointer to such instruction or NULL.
3792  /// Upon return LIST will contain only locations not redefined
3793  /// by insns [i1..result]
3794  const minsn_t *hexapi find_first_use(mlist_t *list, const minsn_t *i1, const minsn_t *i2, maymust_t maymust=MAY_ACCESS) const;
3795  minsn_t *find_first_use(mlist_t *list, minsn_t *i1, const minsn_t *i2, maymust_t maymust=MAY_ACCESS) const
3796  {
3797  return CONST_CAST(minsn_t*)(find_first_use(list,
3798  CONST_CAST(const minsn_t*)(i1),
3799  i2,
3800  maymust));
3801  }
3802 
3803  /// Is the list redefined by the specified instructions?
3804  /// \param list list of locations to check.
3805  /// \param i1 starting instruction of the range (must be a top level insn)
3806  /// \param i2 end instruction of the range (must be a top level insn)
3807  /// i2 is excluded from the range. it can be specified as NULL.
3808  /// i1 and i2 must belong to the same block.
3809  /// \param maymust should we search in 'may-access' or 'must-access' mode?
3811  const mlist_t &list,
3812  const minsn_t *i1,
3813  const minsn_t *i2,
3814  maymust_t maymust=MAY_ACCESS) const
3815  {
3816  return find_redefinition(list, i1, i2, maymust) != NULL;
3817  }
3818 
3819  /// Find the first insn that redefines any part of the list in the insn range.
3820  /// \param list list of locations to check.
3821  /// \param i1 starting instruction of the range (must be a top level insn)
3822  /// \param i2 end instruction of the range (must be a top level insn)
3823  /// i2 is excluded from the range. it can be specified as NULL.
3824  /// i1 and i2 must belong to the same block.
3825  /// \param maymust should we search in 'may-access' or 'must-access' mode?
3826  /// \return pointer to such instruction or NULL.
3827  const minsn_t *hexapi find_redefinition(
3828  const mlist_t &list,
3829  const minsn_t *i1,
3830  const minsn_t *i2,
3831  maymust_t maymust=MAY_ACCESS) const;
3832  minsn_t *find_redefinition(
3833  const mlist_t &list,
3834  minsn_t *i1,
3835  const minsn_t *i2,
3836  maymust_t maymust=MAY_ACCESS) const
3837  {
3838  return CONST_CAST(minsn_t*)(find_redefinition(list,
3839  CONST_CAST(const minsn_t*)(i1),
3840  i2,
3841  maymust));
3842  }
3843 
3844  /// Is the right hand side of the instruction redefined the insn range?
3845  /// "right hand side" corresponds to the source operands of the instruction.
3846  /// \param ins instruction to consider
3847  /// \param i1 starting instruction of the range (must be a top level insn)
3848  /// \param i2 end instruction of the range (must be a top level insn)
3849  /// i2 is excluded from the range. it can be specified as NULL.
3850  /// i1 and i2 must belong to the same block.
3851  bool hexapi is_rhs_redefined(minsn_t *ins, minsn_t *i1, minsn_t *i2);
3852 
3853  /// Find the instruction that accesses the specified operand.
3854  /// This function search inside one block.
3855  /// \param op operand to search for
3856  /// \param p_i1 ptr to ptr to a top level instruction.
3857  /// denotes the beginning of the search range.
3858  /// \param i2 end instruction of the range (must be a top level insn)
3859  /// i2 is excluded from the range. it can be specified as NULL.
3860  /// i1 and i2 must belong to the same block.
3861  /// \fdflags combination of \ref FD_ bits
3862  /// \return the instruction that accesses the operand. this instruction
3863  /// may be a sub-instruction. to find out the top level
3864  /// instruction, check out *p_i1.
3865  /// NULL means 'not found'.
3866  minsn_t *hexapi find_access(
3867  const mop_t &op,
3868  minsn_t **parent,
3869  const minsn_t *mend,
3870  int fdflags) const;
3871  /// \defgroup FD_ bits for mblock_t::find_access
3872  //@{
3873 #define FD_BACKWARD 0x0000 ///< search direction
3874 #define FD_FORWARD 0x0001 ///< search direction
3875 #define FD_USE 0x0000 ///< look for use
3876 #define FD_DEF 0x0002 ///< look for definition
3877 #define FD_DIRTY 0x0004 ///< ignore possible implicit definitions
3878  ///< by function calls and indirect memory access
3879  //@}
3880 
3881  // Convenience functions:
3882  minsn_t *find_def(
3883  const mop_t &op,
3884  minsn_t **p_i1,
3885  const minsn_t *i2,
3886  int fdflags)
3887  {
3888  return find_access(op, p_i1, i2, fdflags|FD_DEF);
3889  }
3890  minsn_t *find_use(
3891  const mop_t &op,
3892  minsn_t **p_i1,
3893  const minsn_t *i2,
3894  int fdflags)
3895  {
3896  return find_access(op, p_i1, i2, fdflags|FD_USE);
3897  }
3898 
3899  /// Find possible values.
3900  /// \param res set of value ranges
3901  /// \param key what to search for
3902  /// \param vrflags combination of \ref VR_ bits
3903  bool hexapi get_valranges(valrng_t *res, const vivl_t &vivl, int vrflags) const;
3904  /// \defgroup VR_ bits for get_valranges
3905  //@{
3906 #define VR_AT_START 0x0000 ///< get value ranges at the block start
3907 #define VR_AT_END 0x0001 ///< get value ranges at the block end, just before
3908  ///< the last instruction
3909 #define VR_EXACT 0x0002 ///< find exact match. if not set, the returned
3910  ///< valrng size will be >= vivl.size
3911  //@}
3912 
3913  /// Erase the instruction (convert it to nop) and mark the lists dirty.
3914  /// This is the recommended function to use because it also marks the block
3915  /// use-def lists dirty.
3916  void make_nop(minsn_t *m) { m->_make_nop(); mark_lists_dirty(); }
3917 };
3918 //-------------------------------------------------------------------------
3919 /// Warning ids
3921 {
3922  WARN_VARARG_REGS, ///< 0 can not handle register arguments in vararg function, discarded them
3923  WARN_ILL_PURGED, ///< 1 odd caller purged bytes %d, correcting
3924  WARN_ILL_FUNCTYPE, ///< 2 invalid function type has been ignored
3925  WARN_VARARG_TCAL, ///< 3 can not handle tail call to vararg
3926  WARN_VARARG_NOSTK, ///< 4 call vararg without local stack
3927  WARN_VARARG_MANY, ///< 5 too many varargs, some ignored
3928  WARN_ADDR_OUTARGS, ///< 6 can not handle address arithmetics in outgoing argument area of stack frame -- unused
3929  WARN_DEP_UNK_CALLS, ///< 7 found interdependent unknown calls
3930  WARN_ILL_ELLIPSIS, ///< 8 erroneously detected ellipsis type has been ignored
3931  WARN_GUESSED_TYPE, ///< 9 using guessed type %s;
3932  WARN_EXP_LINVAR, ///< 10 failed to expand a linear variable
3933  WARN_WIDEN_CHAINS, ///< 11 failed to widen chains
3934  WARN_BAD_PURGED, ///< 12 inconsistent function type and number of purged bytes
3935  WARN_CBUILD_LOOPS, ///< 13 too many cbuild loops
3936  WARN_NO_SAVE_REST, ///< 14 could not find valid save-restore pair for %s
3937  WARN_ODD_INPUT_REG, ///< 15 odd input register %s
3938  WARN_ODD_ADDR_USE, ///< 16 odd use of a variable address
3939  WARN_MUST_RET_FP, ///< 17 function return type is incorrect (must be floating point)
3940  WARN_ILL_FPU_STACK, ///< 18 inconsistent fpu stack
3941  WARN_SELFREF_PROP, ///< 19 self-referencing variable has been detected
3942  WARN_WOULD_OVERLAP, ///< 20 variables would overlap: %s
3943  WARN_ARRAY_INARG, ///< 21 array has been used for an input argument
3944  WARN_MAX_ARGS, ///< 22 too many input arguments, some ignored
3945  WARN_BAD_FIELD_TYPE,///< 23 incorrect structure member type for %s::%s, ignored
3946  WARN_WRITE_CONST, ///< 24 write access to const memory at %a has been detected
3947  WARN_BAD_RETVAR, ///< 25 wrong return variable
3948  WARN_FRAG_LVAR, ///< 26 fragmented variable at %s may be wrong
3949  WARN_HUGE_STKOFF, ///< 27 exceedingly huge offset into the stack frame
3950  WARN_UNINITED_REG, ///< 28 reference to an uninitialized register has been removed: %s
3951  WARN_FIXED_MACRO, ///< 29 fixed broken macro-insn
3952  WARN_WRONG_VA_OFF, ///< 30 wrong offset of va_list variable
3953  WARN_CR_NOFIELD, ///< 31 CONTAINING_RECORD: no field '%s' in struct '%s' at %d
3954  WARN_CR_BADOFF, ///< 32 CONTAINING_RECORD: too small offset %d for struct '%s'
3955  WARN_BAD_STROFF, ///< 33 user specified stroff has not been processed: %s
3956  WARN_BAD_VARSIZE, ///< 34 inconsistent variable size for '%s'
3957  WARN_UNSUPP_REG, ///< 35 unsupported processor register '%s'
3958  WARN_UNALIGNED_ARG, ///< 36 unaligned function argument '%s'
3959  WARN_BAD_STD_TYPE, ///< 37 corrupted or unexisting local type '%s'
3960  WARN_BAD_CALL_SP, ///< 38 bad sp value at call
3961  WARN_MISSED_SWITCH, ///< 39 wrong markup of switch jump, skipped it
3962  WARN_BAD_SP, ///< 40 positive sp value %a has been found
3963  WARN_BAD_STKPNT, ///< 41 wrong sp change point
3964  WARN_UNDEF_LVAR, ///< 42 variable '%s' is possibly undefined
3965  WARN_JUMPOUT, ///< 43 control flows out of bounds
3966 
3967  WARN_MAX,
3968 };
3969 
3970 /// Warning instances
3972 {
3973  ea_t ea; ///< Address where the warning occurred
3974  warnid_t id; ///< Warning id
3975  qstring text; ///< Fully formatted text of the warning
3977  {
3978  if ( ea < r.ea )
3979  return -1;
3980  if ( ea > r.ea )
3981  return 1;
3982  if ( id < r.id )
3983  return -1;
3984  if ( id > r.id )
3985  return 1;
3986  return strcmp(text.c_str(), r.text.c_str());
3987  }
3988 };
3989 DECLARE_TYPE_AS_MOVABLE(hexwarn_t);
3990 typedef qvector<hexwarn_t> hexwarns_t;
3991 
3992 //-------------------------------------------------------------------------
3993 /// Microcode maturity levels
3995 {
3996  MMAT_ZERO, ///< microcode does not exist
3997  MMAT_GENERATED, ///< generated microcode
3998  MMAT_PREOPTIMIZED, ///< preoptimized pass is complete
3999  MMAT_LOCOPT, ///< local optimization of each basic block is complete.
4000  ///< control flow graph is ready too.
4001  MMAT_CALLS, ///< detected call arguments
4002  MMAT_GLBOPT1, ///< performed the first pass of global optimization
4003  MMAT_GLBOPT2, ///< most global optimization passes are done
4004  MMAT_GLBOPT3, ///< completed all global optimization
4005  MMAT_LVARS, ///< allocated local variables
4006 };
4007 
4008 //-------------------------------------------------------------------------
4009 enum memreg_index_t ///< memory region types
4010 {
4011  MMIDX_GLBLOW, ///< global memory: low part
4012  MMIDX_LVARS, ///< stack: local variables
4013  MMIDX_RETADDR, ///< stack: return address
4014  MMIDX_SHADOW, ///< stack: shadow arguments
4015  MMIDX_ARGS, ///< stack: regular stack arguments
4016  MMIDX_GLBHIGH, ///< global memory: high part
4017 };
4018 
4019 //-------------------------------------------------------------------------
4020 /// Ranges to decompile. Either a function or an explicit vector of ranges.
4022 {
4023  func_t *pfn; ///< function to decompile
4024  rangevec_t ranges; ///< empty ? function_mode : snippet mode
4025  mba_ranges_t(func_t *_pfn=NULL) : pfn(_pfn) {}
4026  mba_ranges_t(const rangevec_t &r) : pfn(NULL), ranges(r) {}
4027  ea_t start(void) const { return (ranges.empty() ? *pfn : ranges[0]).start_ea; }
4028  bool empty(void) const { return pfn == NULL && ranges.empty(); }
4029  void clear(void) { pfn = NULL; ranges.clear(); }
4030  bool is_snippet(void) const { return !ranges.empty(); }
4031  bool range_contains(ea_t ea) const;
4032  bool is_fragmented(void) const { return ranges.empty() ? pfn->tailqty > 0 : ranges.size() > 1; }
4033 };
4034 
4035 /// Item iterator of arbitrary rangevec items
4037 {
4038  const rangevec_t *ranges;
4039  const range_t *rptr; // pointer into ranges
4040  ea_t cur; // current address
4041  range_item_iterator_t(void) : ranges(NULL), rptr(NULL), cur(BADADDR) {}
4042  bool set(const rangevec_t &r);
4043  bool next_code(void);
4044  ea_t current(void) const { return cur; }
4045 };
4046 
4047 /// Item iterator for mba_ranges_t
4049 {
4051  func_item_iterator_t fii; // this is used if rii.ranges==NULL
4052  bool is_snippet(void) const { return rii.ranges != NULL; }
4053  bool set(const mba_ranges_t &mbr)
4054  {
4055  if ( mbr.is_snippet() )
4056  return rii.set(mbr.ranges);
4057  else
4058  return fii.set(mbr.pfn);
4059  }
4060  bool next_code(void)
4061  {
4062  if ( is_snippet() )
4063  return rii.next_code();
4064  else
4065  return fii.next_code();
4066  }
4067  ea_t current(void) const
4068  {
4069  return is_snippet() ? rii.current() : fii.current();
4070  }
4071 };
4072 
4073 /// Chunk iterator of arbitrary rangevec items
4075 {
4076  const range_t *rptr; // pointer into ranges
4077  const range_t *rend;
4078  range_chunk_iterator_t(void) : rptr(NULL), rend(NULL) {}
4079  bool set(const rangevec_t &r) { rptr = r.begin(); rend = r.end(); return rptr != rend; }
4080  bool next(void) { return ++rptr != rend; }
4081  const range_t &chunk(void) const { return *rptr; }
4082 };
4083 
4084 /// Chunk iterator for mba_ranges_t
4086 {
4088  func_tail_iterator_t fii; // this is used if rii.rptr==NULL
4089  bool is_snippet(void) const { return rii.rptr != NULL; }
4090  bool set(const mba_ranges_t &mbr)
4091  {
4092  if ( mbr.is_snippet() )
4093  return rii.set(mbr.ranges);
4094  else
4095  return fii.set(mbr.pfn);
4096  }
4097  bool next(void)
4098  {
4099  if ( is_snippet() )
4100  return rii.next();
4101  else
4102  return fii.next();
4103  }
4104  const range_t &chunk(void) const
4105  {
4106  return is_snippet() ? rii.chunk() : fii.chunk();
4107  }
4108 };
4109 
4110 //-------------------------------------------------------------------------
4111 /// Array of micro blocks represents microcode for a decompiled function.
4112 /// The first micro block is the entry point, the last one if the exit point.
4113 /// The entry and exit blocks are always empty. The exit block is generated
4114 /// at MMAT_LOCOPT maturity level.
4115 class mbl_array_t
4116 {
4117  DECLARE_UNCOPYABLE(mbl_array_t)
4118  uint32 flags;
4119  uint32 flags2;
4120  // bits to describe the microcode, set by the decompiler
4121 #define MBA_PRCDEFS 0x00000001 ///< use precise defeas for chain-allocated lvars
4122 #define MBA_NOFUNC 0x00000002 ///< function is not present, addresses might be wrong
4123 #define MBA_PATTERN 0x00000004 ///< microcode pattern, callinfo is present
4124 #define MBA_LOADED 0x00000008 ///< loaded gdl, no instructions (debugging)
4125 #define MBA_RETFP 0x00000010 ///< function returns floating point value
4126 #define MBA_SPLINFO 0x00000020 ///< (final_type ? idb_spoiled : spoiled_regs) is valid
4127 #define MBA_PASSREGS 0x00000040 ///< has mcallinfo_t::pass_regs
4128 #define MBA_THUNK 0x00000080 ///< thunk function
4129 #define MBA_CMNSTK 0x00000100 ///< stkvars+stkargs should be considered as one area
4130 
4131  // bits to describe analysis stages and requests
4132 #define MBA_PREOPT 0x00000200 ///< preoptimization stage complete
4133 #define MBA_CMBBLK 0x00000400 ///< request to combine blocks
4134 #define MBA_ASRTOK 0x00000800 ///< assertions have been generated
4135 #define MBA_CALLS 0x00001000 ///< callinfo has been built
4136 #define MBA_ASRPROP 0x00002000 ///< assertion have been propagated
4137 #define MBA_SAVRST 0x00004000 ///< save-restore analysis has been performed
4138 #define MBA_RETREF 0x00008000 ///< return type has been refined
4139 #define MBA_GLBOPT 0x00010000 ///< microcode has been optimized globally
4140 #define MBA_OVERVAR 0x00020000 ///< an overlapped variable has been detected
4141 #define MBA_LVARS0 0x00040000 ///< lvar pre-allocation has been performed
4142 #define MBA_LVARS1 0x00080000 ///< lvar real allocation has been performed
4143 #define MBA_DELPAIRS 0x00100000 ///< pairs have been deleted once
4144 #define MBA_CHVARS 0x00200000 ///< can verify chain varnums
4145 
4146  // bits that can be set by the caller:
4147 #define MBA_SHORT 0x00400000 ///< use short display
4148 #define MBA_COLGDL 0x00800000 ///< display graph after each reduction
4149 #define MBA_INSGDL 0x01000000 ///< display instruction in graphs
4150 #define MBA_NICE 0x02000000 ///< apply transformations to c code
4151 #define MBA_REFINE 0x04000000 ///< may refine return value size
4152 #define MBA_DELASRT 0x08000000 ///< may delete assertions at the end of glbopt
4153 #define MBA_WINGR32 0x10000000 ///< use wingraph32
4154 #define MBA_NUMADDR 0x20000000 ///< display definition addresses for numbers
4155 #define MBA_VALNUM 0x40000000 ///< display value numbers
4156 
4157 #define MBA_INITIAL_FLAGS (MBA_INSGDL|MBA_NICE|MBA_CMBBLK|MBA_REFINE|MBA_DELASRT\
4158  |MBA_PRCDEFS|MBA_WINGR32|MBA_VALNUM)
4159 
4160 #define MBA2_LVARNAMES_OK 0x00000001 // may verify lvar_names?
4161 #define MBA2_LVARS_RENAMED 0x00000002 // accept empty names now?
4162 #define MBA2_OVER_CHAINS 0x00000004 // has overlapped chains?
4163 #define MBA2_VALRNG_DONE 0x00000008 // calculated valranges?
4164 #define MBA2_IS_CTR 0x00000010 // is constructor?
4165 #define MBA2_IS_DTR 0x00000020 // is destructor?
4166 
4167 #define MBA2_INITIAL_FLAGS (MBA2_LVARNAMES_OK|MBA2_LVARS_RENAMED)
4168 #define MBA2_ALL_FLAGS 0x0000003F
4169 
4170 public:
4171  bool precise_defeas(void) const { return (flags & MBA_PRCDEFS) != 0; }
4172  bool optimized(void) const { return (flags & MBA_GLBOPT) != 0; }
4173  bool short_display(void) const { return (flags & MBA_SHORT ) != 0; }
4174  bool show_reduction(void) const { return (flags & MBA_COLGDL) != 0; }
4175  bool graph_insns(void) const { return (flags & MBA_INSGDL) != 0; }
4176  bool loaded_gdl(void) const { return (flags & MBA_LOADED) != 0; }
4177  bool should_beautify(void)const { return (flags & MBA_NICE ) != 0; }
4178  bool rtype_refined(void) const { return (flags & MBA_RETREF) != 0; }
4179  bool may_refine_rettype(void) const { return (flags & MBA_REFINE) != 0; }
4180  bool may_del_asserts(void) const { return (flags & MBA_DELASRT) != 0; }
4181  bool use_wingraph32(void) const { return (flags & MBA_WINGR32) != 0; }
4182  bool display_numaddrs(void) const { return (flags & MBA_NUMADDR) != 0; }
4183  bool display_valnums(void) const { return (flags & MBA_VALNUM) != 0; }
4184  bool is_pattern(void) const { return (flags & MBA_PATTERN) != 0; }
4185  bool is_thunk(void) const { return (flags & MBA_THUNK) != 0; }
4186  bool saverest_done(void) const { return (flags & MBA_SAVRST) != 0; }
4187  bool callinfo_built(void) const { return (flags & MBA_CALLS) != 0; }
4188  bool has_overvars(void) const { return (flags & MBA_OVERVAR) != 0; }
4189  bool really_alloc(void) const { return (flags & MBA_LVARS0) != 0; }
4190  bool lvars_allocated(void)const { return (flags & MBA_LVARS1) != 0; }
4191  bool chain_varnums_ok(void)const { return (flags & MBA_CHVARS) != 0; }
4192  bool returns_fpval(void) const { return (flags & MBA_RETFP) != 0; }
4193  bool has_passregs(void) const { return (flags & MBA_PASSREGS) != 0; }
4194  bool generated_asserts(void) const { return (flags & MBA_ASRTOK) != 0; }
4195  bool propagated_asserts(void) const { return (flags & MBA_ASRPROP) != 0; }
4196  bool deleted_pairs(void) const { return (flags & MBA_DELPAIRS) != 0; }
4197  bool common_stkvars_stkargs(void) const { return (flags & MBA_CMNSTK) != 0; }
4198  bool lvar_names_ok(void) const { return (flags2 & MBA2_LVARNAMES_OK) != 0; }
4199  bool lvars_renamed(void) const { return (flags2 & MBA2_LVARS_RENAMED) != 0; }
4200  bool has_over_chains(void) const { return (flags2 & MBA2_OVER_CHAINS) != 0; }
4201  bool valranges_done(void) const { return (flags2 & MBA2_VALRNG_DONE) != 0; }
4202  bool is_ctr(void) const { return (flags2 & MBA2_IS_CTR) != 0; }
4203  bool is_dtr(void) const { return (flags2 & MBA2_IS_DTR) != 0; }
4204  bool is_cdtr(void) const { return (flags2 & (MBA2_IS_CTR|MBA2_IS_DTR)) != 0; }
4205  int get_mba_flags(void) const { return flags; }
4206  void set_mba_flags(int f) { flags |= f; }
4207  void clr_mba_flags(int f) { flags &= ~f; }
4208  void set_mba_flags2(int f) { flags2 |= f; }
4209  void clr_mba_flags2(int f) { flags2 &= ~f; }
4210  void clr_cdtr(void) { flags2 &= ~(MBA2_IS_CTR|MBA2_IS_DTR); }
4211  int calc_shins_flags(void) const
4212  {
4213  int shins_flags = 0;
4214  if ( short_display() )
4215  shins_flags |= SHINS_SHORT;
4216  if ( display_valnums() )
4217  shins_flags |= SHINS_VALNUM;
4218  if ( display_numaddrs() )
4219  shins_flags |= SHINS_NUMADDR;
4220  return shins_flags;
4221  }
4222 
4223 /*
4224  +-----------+ <- inargtop
4225  | prmN |
4226  | ... | <- minargref
4227  | prm0 |
4228  +-----------+ <- inargoff
4229  |shadow_args|
4230  +-----------+
4231  | retaddr |
4232  frsize+frregs +-----------+ <- initial esp |
4233  | frregs | |
4234  +frsize +-----------+ <- typical ebp |
4235  | | | |
4236  | | | fpd |
4237  | | | |
4238  | frsize | <- current ebp |
4239  | | |
4240  | | |
4241  | | | stacksize
4242  | | |
4243  | | |
4244  | | <- minstkref |
4245  stkvar base off 0 +---.. | | | current
4246  | | | | stack
4247  | | | | pointer
4248  | | | | range
4249  |tmpstk_size| | | (what getspd() returns)
4250  | | | |
4251  | | | |
4252  +-----------+ <- minimal sp | | offset 0 for the decompiler (vd)
4253 
4254  There is a detail that may add confusion when working with stack variables.
4255  The decompiler does not use the same stack offsets as IDA.
4256  The picture above should explain the difference:
4257  - IDA stkoffs are displayed on the left, decompiler stkoffs - on the right
4258  - Decompiler stkoffs are always >= 0
4259  - IDA stkoff==0 corresponds to stkoff==tmpstk_size in the decompiler
4260  - See stkoff_vd2ida and stkoff_ida2vd below to convert IDA stkoffs to vd stkoff
4261 
4262 */
4263 
4264  // convert a stack offset used in vd to a stack offset used in ida stack frame
4265  sval_t stkoff_vd2ida(sval_t off) const
4266  {
4267  return off - tmpstk_size;
4268  }
4269  // convert a ida stack frame offset to a stack offset used in vd
4270  sval_t stkoff_ida2vd(sval_t off) const
4271  {
4272  return off + tmpstk_size;
4273  }
4274  sval_t argbase() const
4275  {
4276  return retsize + stacksize;
4277  }
4278  static vdloc_t hexapi idaloc2vd(const argloc_t &loc, int width, sval_t spd);
4279  vdloc_t idaloc2vd(const argloc_t &loc, int width) const
4280  {
4281  return idaloc2vd(loc, width, argbase());
4282  }
4283  // helper for mvm.get_func_output_regs
4284  static vdloc_t idaloc2vd(const mbl_array_t *mba, const argloc_t &loc, int width)
4285  {
4286  return mbl_array_t::idaloc2vd(loc, width, mba == NULL ? 0 : mba->argbase());
4287  }
4288 
4289  static argloc_t hexapi vd2idaloc(const vdloc_t &loc, int width, sval_t spd);
4290  argloc_t vd2idaloc(const vdloc_t &loc, int width) const
4291  {
4292  return vd2idaloc(loc, width, argbase());
4293  }
4294 
4295  bool is_stkarg(const lvar_t &v) const
4296  {
4297  return v.location.is_stkoff() && v.location.stkoff() >= inargoff;
4298  }
4299  member_t *get_stkvar(sval_t vd_stkoff, uval_t *poff) const;
4300  // get lvar location
4301  argloc_t get_ida_argloc(const lvar_t &v) const
4302  {
4303  return vd2idaloc(v.location, v.width);
4304  }
4305  mba_ranges_t mbr;
4306  ea_t entry_ea;
4307  ea_t last_prolog_ea;
4308  ea_t first_epilog_ea;
4309  int qty; ///< number of basic blocks
4310  int npurged; ///< -1 - unknown
4311  cm_t cc; ///< calling convention
4312  sval_t tmpstk_size; ///< size of the temporary stack part
4313  ///< (which dynamically changes with push/pops)
4314  sval_t frsize; ///< size of local stkvars range in the stack frame
4315  sval_t frregs; ///< size of saved registers range in the stack frame
4316  sval_t fpd; ///< frame pointer delta
4317  int pfn_flags; ///< copy of func_t::flags
4318  int retsize; ///< size of return address in the stack frame
4319  int shadow_args; ///< size of shadow argument area
4320  sval_t fullsize; ///< Full stack size including incoming args
4321  sval_t stacksize; ///< The maximal size of the function stack including
4322  ///< bytes allocated for outgoing call arguments
4323  ///< (up to retaddr)
4324  sval_t inargoff; ///< offset of the first stack argument
4325  sval_t minstkref; ///< The lowest stack location whose address was taken
4326  ea_t minstkref_ea; ///< address with lowest minstkref (for debugging)
4327  sval_t minargref; ///< The lowest stack argument location whose address was taken
4328  ///< This location and locations above it can be aliased
4329  ///< It controls locations >= inargoff-shadow_args
4330  sval_t spd_adjust; ///< If sp>0, the max positive sp value
4331  ivl_t aliased_vars; ///< Aliased stkvar locations
4332  ivl_t aliased_args; ///< Aliased stkarg locations
4333  ivlset_t gotoff_stkvars; ///< stkvars that hold .got offsets. considered to be unaliasable
4334  ivlset_t restricted_memory;
4335  ivlset_t aliased_memory; ///< aliased_memory+restricted_memory=ALLMEM
4336  mlist_t nodel_memory; ///< global dead elimination may not delete references to this area
4337  rlist_t consumed_argregs; ///< registers converted into stack arguments, should not be used as arguments
4338 
4339  mba_maturity_t maturity; ///< current maturity level
4340  mba_maturity_t reqmat; ///< required maturity level
4341 
4342  bool final_type; ///< is the function type final? (specified by the user)
4343  tinfo_t idb_type; ///< function type as retrieved from the database
4344  reginfovec_t idb_spoiled; ///< MBL_SPLINFO && final_type: info in ida format
4345  mlist_t spoiled_list; ///< MBL_SPLINFO && !final_type: info in vd format
4346  int fti_flags; ///< FTI_... constants for the current function
4347 
4348  netnode idb_node;
4349 #define NALT_VD 2 ///< this index is not used by ida
4350 
4351  qstring label; ///< name of the function or pattern (colored)
4352  lvars_t vars; ///< local variables
4353  intvec_t argidx; ///< input arguments (indexes into 'vars')
4354  int retvaridx; ///< index of variable holding the return value
4355  ///< -1 means none
4356 
4357  ea_t error_ea; ///< during microcode generation holds ins.ea
4358  qstring error_strarg;
4359 
4360  mblock_t *blocks; ///< double linked list of blocks
4361  mblock_t **natural; ///< natural order of blocks
4362 
4363  ivl_with_name_t std_ivls[6]; ///< we treat memory as consisting of 6 parts
4364  ///< see \ref memreg_index_t
4365 
4366  mutable hexwarns_t notes;
4367  mutable uchar occurred_warns[32]; // occurred warning messages
4368  // (even disabled warnings are taken into account)
4369  bool write_to_const_detected(void) const
4370  {
4371  return test_bit(occurred_warns, WARN_WRITE_CONST);
4372  }
4373  bool bad_call_sp_detected(void) const
4374  {
4375  return test_bit(occurred_warns, WARN_BAD_CALL_SP);
4376  }
4377  bool regargs_is_not_aligned(void) const
4378  {
4379  return test_bit(occurred_warns, WARN_UNALIGNED_ARG);
4380  }
4381  bool has_bad_sp(void) const
4382  {
4383  return test_bit(occurred_warns, WARN_BAD_SP);
4384  }
4385 
4386  // the exact size of this class is not documented, they may be more fields
4387  char reserved[];
4388  mbl_array_t(void);
4389  ~mbl_array_t(void) { term(); }
4390  DEFINE_MEMORY_ALLOCATION_FUNCS()
4391  void hexapi term(void);
4392  func_t *get_curfunc(void) const { return mbr.pfn; }
4393  bool use_frame(void) const { return mbr.pfn != NULL; }
4394  bool range_contains(ea_t ea) const { return mbr.range_contains(ea); }
4395  bool is_snippet(void) const { return mbr.is_snippet(); }
4396  /// Optimize each basic block locally
4397  /// \param locopt_bits combination of \ref LOCOPT_ bits
4398  /// \return number of changes. 0 means nothing changed
4399  /// This function is called by the decompiler, usually there is no need to
4400  /// call it explicitly.
4401  int hexapi optimize_local(int locopt_bits);
4402  /// \defgroup LOCOPT_ Bits for optimize_local()
4403  //@{
4404 #define LOCOPT_ALL 0x0001 ///< redo optimization for all blocks. if this bit
4405  ///< is not set, only dirty blocks will be optimized
4406 #define LOCOPT_REFINE 0x0002 ///< refine return type, ok to fail
4407 #define LOCOPT_REFINE2 0x0004 ///< refine return type, try harder
4408  //@}
4409 
4410  /// Build control flow graph.
4411  /// This function may be called only once. It calculates the type of each
4412  /// basic block and the adjacency list. optimize_local() calls this function
4413  /// if necessary. You need to call this function only before MMAT_LOCOPT.
4414  /// \return error code
4415  merror_t hexapi build_graph(void);
4416 
4417  /// Get control graph.
4418  /// Call build_graph() if you need the graph before MMAT_LOCOPT.
4419  mbl_graph_t *hexapi get_graph(void);
4420 
4421  /// Analyze calls and determine calling conventions.
4422  /// \param acflags permitted actions that are necessary for successful detection
4423  /// of calling conventions. See \ref ACFL_
4424  /// \return number of calls. -1 means error.
4425  int hexapi analyze_calls(int acflags);
4426  /// \defgroup ACFL_ Bits for analyze_calls()
4427  //@{
4428 #define ACFL_LOCOPT 0x01 ///< perform local propagation (requires ACFL_BLKOPT)
4429 #define ACFL_BLKOPT 0x02 ///< perform interblock transformations
4430 #define ACFL_GLBPROP 0x04 ///< perform global propagation
4431 #define ACFL_GLBDEL 0x08 ///< perform dead code eliminition
4432 #define ACFL_GUESS 0x10 ///< may guess calling conventions
4433  //@}
4434 
4435  /// Optimize microcode globally.
4436  /// This function applies various optimization methods until we reach the
4437  /// fixed point. After that it preallocates lvars unless reqmat forbids it.
4438  /// \return error code
4439  merror_t hexapi optimize_global(void);
4440 
4441  /// Allocate local variables.
4442  /// Must be called only immediately after optimize_global(), with no
4443  /// modifications to the microcode. Converts registers,
4444  /// stack variables, and similar operands into mop_l. This call will not fail
4445  /// because all necessary checks were performed in optimize_global().
4446  /// After this call the microcode reaches its final state.
4447  void hexapi alloc_lvars(void);
4448 
4449  /// Dump microcode to a file.
4450  /// The file will be created in the directory pointed by IDA_DUMPDIR envvar.
4451  /// Dump will be created only if IDA is run under debugger.
4452  void hexapi dump(void) const;
4453  AS_PRINTF(3, 0) void hexapi vdump_mba(bool _verify, const char *title, va_list va) const;
4454  AS_PRINTF(3, 4) void dump_mba(bool _verify, const char *title, ...) const
4455  {
4456  va_list va;
4457  va_start(va, title);
4458  vdump_mba(_verify, title, va);
4459  va_end(va);
4460  }
4461 
4462  /// Print microcode to any destination.
4463  /// \param vp print sink
4464  void hexapi print(vd_printer_t &vp) const;
4465 
4466  /// Verify microcode consistency.
4467  /// \param always if false, the check will be performed only if ida runs
4468  /// under debugger
4469  /// If any inconsistency is discovered, an internal error will be generated.
4470  /// We strongly recommend you to call this function before returing control
4471  /// to the decompiler from your callbacks, in the case if you modified
4472  /// the microcode.
4473  void hexapi verify(bool always) const;
4474 
4475  /// Mark the microcode use-def chains dirty.
4476  /// Call this function is any inter-block data dependencies got changed
4477  /// because of your modifications to the microcode. Failing to do so may
4478  /// cause an internal error.
4479  void hexapi mark_chains_dirty(void);
4480 
4481  /// Get basic block by its serial number.
4482  const mblock_t *get_mblock(int n) const { return natural[n]; }
4483  mblock_t *get_mblock(int n) { return CONST_CAST(mblock_t*)((CONST_CAST(const mbl_array_t *)(this))->get_mblock(n)); }
4484 
4485  /// Insert a block in the middle of the mbl array.
4486  /// \param bblk he new block will be inserted before BBLK
4487  /// \return ptr to new block
4488  mblock_t *hexapi insert_block(int bblk);
4489 
4490  /// Delete a block.
4491  /// \param blk block to delete
4492  /// \return true if at least one of the other blocks became empty or unreachable
4493  bool hexapi remove_block(mblock_t *blk);
4494 
4495  /// Delete all empty blocks.
4496  bool hexapi remove_empty_blocks(void);
4497 
4498  /// Combine blocks.
4499  /// This function merges blocks constituting linear flow.
4500  /// It calls remove_empty_blocks() as well.
4501  /// \return true if changed any blocks
4502  bool hexapi combine_blocks(void);
4503 
4504  /// Visit all operands of all instructions.
4505  /// \param mv operand visitor
4506  /// \return non-zero value returned by mv.visit_mop() or zero
4507  int hexapi for_all_ops(mop_visitor_t &mv);
4508 
4509  /// Visit all instructions.
4510  /// This function visits all instruction and subinstructions.
4511  /// \param mv instruction visitor
4512  /// \return non-zero value returned by mv.visit_mop() or zero
4513  int hexapi for_all_insns(minsn_visitor_t &mv);
4514 
4515  /// Visit all top level instructions.
4516  /// \param mv instruction visitor
4517  /// \return non-zero value returned by mv.visit_mop() or zero
4518  int hexapi for_all_topinsns(minsn_visitor_t &mv);
4519 
4520  /// Find an operand in the microcode.
4521  /// This function tries to find the operand that matches LIST.
4522  /// Any operand that overlaps with LIST is considered as a match.
4523  /// \param[out] ctx context information for the result
4524  /// \param ea desired address of the operand
4525  /// \param is_dest search for destination operand? this argument may be
4526  /// ignored if the exact match could not be found
4527  /// \param list list of locations the correspond to the operand
4528  /// \return pointer to the operand or NULL.
4529  mop_t *hexapi find_mop(op_parent_info_t *ctx, ea_t ea, bool is_dest, const mlist_t &list);
4530 
4531  /// Get input argument of the decompiled function.
4532  /// \param n argument number (0..nargs-1)
4533  lvar_t &hexapi arg(int n);
4534  const lvar_t &arg(int n) const { return CONST_CAST(mbl_array_t*)(this)->arg(n); }
4535 
4536  /// Get information about various memory regions.
4537  /// We map the stack frame to the global memory, to some unused range.
4538  const ivl_t &get_std_region(memreg_index_t idx) const;
4539  const ivl_t &get_lvars_region(void) const;
4540  const ivl_t &get_shadow_region(void) const;
4541  const ivl_t &get_args_region(void) const;
4542  ivl_t get_stack_region(void) const; // get entire stack region
4543 
4544  /// Serialize mbl array into a sequence of bytes.
4545  void hexapi serialize(bytevec_t &b) const;
4546 
4547  /// Deserialize a byte sequence into mbl array.
4548  /// \param bytes pointer to the beginning of the byte sequence.
4549  /// \param nbytes number of bytes in the byte sequence.
4550  /// \return new mbl array
4551  static mbl_array_t *hexapi deserialize(const uchar *bytes, size_t nbytes);
4552 
4553 };
4554 //-------------------------------------------------------------------------
4555 /// Convenience class to release graph chains automatically.
4556 /// Use this class instead of using graph_chains_t directly.
4558 {
4559  graph_chains_t *gc;
4560  chain_keeper_t &operator=(const chain_keeper_t &); // not defined
4561 public:
4562  chain_keeper_t(graph_chains_t *_gc) : gc(_gc) { QASSERT(50446, gc != NULL); gc->acquire(); }
4563  ~chain_keeper_t(void)
4564  {
4565  gc->release();
4566  }
4567  block_chains_t &operator[](size_t idx) { return (*gc)[idx]; }
4568  block_chains_t &front(void) { return gc->front(); }
4569  block_chains_t &back(void) { return gc->back(); }
4570  operator graph_chains_t &(void) { return *gc; }
4571  int for_all_chains(chain_visitor_t &cv, int gca) { return gc->for_all_chains(cv, gca); }
4572  DEFINE_MEMORY_ALLOCATION_FUNCS()
4573 };
4574 
4575 //-------------------------------------------------------------------------
4576 /// Kind of use-def and def-use chains
4578 {
4579  GC_REGS_AND_STKVARS, ///< registers and stkvars (restricted memory only)
4580  GC_ASR, ///< all the above and assertions
4581  GC_XDSU, ///< only registers calculated with FULL_XDSU
4582  GC_END, ///< number of chain types
4583  GC_DIRTY_ALL = (1 << (2*GC_END))-1, ///< bitmask to represent all chains
4584 };
4585 
4586 //-------------------------------------------------------------------------
4587 /// Control flow graph of microcode.
4589 {
4590  mbl_array_t *mba; ///< pointer to the mbl array
4591  int dirty; ///< what kinds of use-def chains are dirty?
4592  int chain_stamp; ///< we increment this counter each time chains are recalculated
4593  graph_chains_t gcs[2*GC_END]; ///< cached use-def chains
4594 
4595  /// Is LIST accessed between two instructions?
4596  /// This function can analyze all path between the specified instructions
4597  /// and find if the specified list is used in any of them. The instructions
4598  /// may be located in different basic blocks. This function does not use
4599  /// use-def chains but use the graph for analysis. It may be slow in some
4600  /// cases but its advantage is that is does not require building the use-def
4601  /// chains.
4602  /// \param list list to verify
4603  /// \param b1 starting block
4604  /// \param b2 ending block. may be -1, it means all possible paths from b1
4605  /// \param m1 starting instruction (in b1)
4606  /// \param m2 ending instruction (in b2). excluded. may be NULL.
4607  /// \param access_type read or write access?
4608  /// \param maymust may access or must access?
4609  /// \return true if found an access to the list
4610  bool hexapi is_accessed_globally(
4611  const mlist_t &list, // list to verify
4612  int b1, // starting block
4613  int b2, // ending block
4614  const minsn_t *m1, // starting instruction (in b1)
4615  const minsn_t *m2, // ending instruction (in b2)
4616  access_type_t access_type,
4617  maymust_t maymust) const;
4618  int get_ud_gc_idx(gctype_t gctype) const { return (gctype << 1); }
4619  int get_du_gc_idx(gctype_t gctype) const { return (gctype << 1)+1; }
4620  int get_ud_dirty_bit(gctype_t gctype) { return 1 << get_ud_gc_idx(gctype); }
4621  int get_du_dirty_bit(gctype_t gctype) { return 1 << get_du_gc_idx(gctype); }
4622 
4623 public:
4624  /// Is the use-def chain of the specified kind dirty?
4626  {
4627  int bit = get_ud_dirty_bit(gctype);
4628  return (dirty & bit) != 0;
4629  }
4630 
4631  /// Is the def-use chain of the specified kind dirty?
4633  {
4634  int bit = get_du_dirty_bit(gctype);
4635  return (dirty & bit) != 0;
4636  }
4637  int get_chain_stamp(void) const { return chain_stamp; }
4638 
4639  /// Get use-def chains.
4640  graph_chains_t *hexapi get_ud(gctype_t gctype);
4641 
4642  /// Get def-use chains.
4643  graph_chains_t *hexapi get_du(gctype_t gctype);
4644 
4645  /// Is LIST redefined in the graph?
4646  bool is_redefined_globally(const mlist_t &list, int b1, int b2, const minsn_t *m1, const minsn_t *m2, maymust_t maymust=MAY_ACCESS) const
4647  { return is_accessed_globally(list, b1, b2, m1, m2, WRITE_ACCESS, maymust); }
4648 
4649  /// Is LIST used in the graph?
4650  bool is_used_globally(const mlist_t &list, int b1, int b2, const minsn_t *m1, const minsn_t *m2, maymust_t maymust=MAY_ACCESS) const
4651  { return is_accessed_globally(list, b1, b2, m1, m2, READ_ACCESS, maymust); }
4652 
4653  mblock_t *get_mblock(int n) const { return mba->get_mblock(n); }
4654 };
4655 
4656 //-------------------------------------------------------------------------
4657 /// Helper class to generate the initial microcode
4659 {
4660 public:
4661  mbl_array_t *mba; // ptr to mbl array
4662  mblock_t *mb; // current basic block
4663  insn_t insn; // instruction to generate microcode for
4664  char ignore_micro; // value of get_ignore_micro() for the insn
4665 
4667  : mba(m), mb(NULL), ignore_micro(IM_NONE) {}
4668  virtual ~codegen_t(void)
4669  {
4670  }
4671 
4672  /// Analyze prolog/epilog of the function to decompile.
4673  /// If prolog is found, allocate and fill 'mba->pi' structure.
4674  /// \param fc flow chart
4675  /// \param reachable bitmap of reachable blocks
4676  /// \return error code
4677  virtual merror_t idaapi analyze_prolog(
4678  const class qflow_chart_t &fc,
4679  const class bitset_t &reachable) = 0;
4680 
4681  /// Generate microcode for one instruction.
4682  /// The instruction is in INSN
4683  /// \return MERR_OK - all ok
4684  /// MERR_BLOCK - all ok, need to switch to new block
4685  /// MERR_BADBLK - delete current block and continue
4686  /// other error codes are fatal
4687  virtual merror_t idaapi gen_micro() = 0;
4688 
4689  /// Generate microcode to load one operand.
4690  virtual mreg_t idaapi load_operand(int opnum) = 0;
4691 
4692  /// Emit one microinstruction.
4693  /// See explanations for emit().
4694  virtual minsn_t *idaapi emit_micro_mvm(
4695  mcode_t code,
4696  op_dtype_t dtype,
4697  uval_t l,
4698  uval_t r,
4699  uval_t d,
4700  int offsize)
4701  {
4702  return emit(code, get_dtype_size(dtype), l, r, d, offsize);
4703  }
4704 
4705  /// Emit one microinstruction.
4706  /// The L, R, D arguments usually mean the register number. However, they depend
4707  /// on CODE. For example:
4708  /// - for m_goto and m_jcnd L is the target address
4709  /// - for m_ldc L is the constant value to load
4710  /// \param code instruction opcode
4711  /// \param width operand size in bytes
4712  /// \param l left operand
4713  /// \param r right operand
4714  /// \param d destination operand
4715  /// \param offsize for ldx/stx, the size of the offset operand.
4716  /// for ldc, operand number of the constant value
4717  /// \return created microinstruction. can be NULL if the instruction got
4718  /// immediately optimized away.
4719  minsn_t *hexapi emit(mcode_t code, int width, uval_t l, uval_t r, uval_t d, int offsize);
4720 
4721  /// Emit one microinstruction.
4722  /// This variant accepts pointers to operands. It is more difficult to use
4723  /// but permits to create virtually any instruction. Operands may be NULL
4724  /// when it makes sense.
4725  minsn_t *hexapi emit(mcode_t code, const mop_t *l, const mop_t *r, const mop_t *d);
4726 
4727 };
4728 
4729 //-------------------------------------------------------------------------
4730 /// Is a kernel register?
4731 bool hexapi is_kreg(mreg_t r);
4732 
4733 /// Get list of temporary registers.
4734 /// Tempregs are temporary registers that are used during code generation.
4735 /// They do not map to regular processor registers. They are used only to
4736 /// store temporary values during execution of one instruction.
4737 /// Tempregs may not be used to pass a value from one block to another.
4738 /// In other words, at the end of a block all tempregs must be dead.
4739 const mlist_t &hexapi get_temp_regs();
4740 
4741 inline void mop_t::_make_insn(minsn_t *ins)
4742 {
4743  t = mop_d;
4744  d = ins;
4745 }
4746 
4747 inline bool mop_t::has_side_effects(bool include_ldx) const
4748 {
4749  return is_insn() && d->has_side_effects(include_ldx);
4750 }
4751 
4752 inline bool mop_t::is_kreg(void) const
4753 {
4754  return t == mop_r && ::is_kreg(r);
4755 }
4756 
4757 inline minsn_t *mop_t::get_insn(mcode_t code)
4758 {
4759  return is_insn(code) ? d : NULL;
4760 }
4761 inline const minsn_t *mop_t::get_insn(mcode_t code) const
4762 {
4763  return is_insn(code) ? d : NULL;
4764 }
4765 
4766 inline bool mop_t::is_insn(mcode_t code) const
4767 {
4768  return is_insn() && d->opcode == code;
4769 }
4770 
4771 inline bool mop_t::is_glbaddr() const
4772 {
4773  return t == mop_a && a->t == mop_v;
4774 }
4775 
4776 inline bool mop_t::is_glbaddr(ea_t ea) const
4777 {
4778  return is_glbaddr() && a->g == ea;
4779 }
4780 
4781 inline bool mop_t::is_stkaddr() const
4782 {
4783  return t == mop_a && a->t == mop_S;
4784 }
4785 
4786 inline vivl_t::vivl_t(const chain_t &ch)
4787  : voff_t(ch.key().type, ch.is_reg() ? ch.get_reg() : ch.get_stkoff()),
4788  size(ch.width)
4789 {
4790 }
4791 
4792 // The following memory regions exist
4793 // start length
4794 // ------------------------ ---------
4795 // lvars spbase stacksize
4796 // retaddr spbase+stacksize retsize
4797 // shadow spbase+stacksize+retsize shadow_args
4798 // args inargoff MAX_FUNC_ARGS*sp_width-shadow_args
4799 // globals data_segment sizeof_data_segment
4800 // heap everything else?
4801 
4803 {
4804  return std_ivls[idx].ivl;
4805 }
4806 
4807 inline const ivl_t &mbl_array_t::get_lvars_region(void) const
4808 {
4809  return get_std_region(MMIDX_LVARS);
4810 }
4811 
4812 inline const ivl_t &mbl_array_t::get_shadow_region(void) const
4813 {
4814  return get_std_region(MMIDX_SHADOW);
4815 }
4816 
4817 inline const ivl_t &mbl_array_t::get_args_region(void) const
4818 {
4819  return get_std_region(MMIDX_ARGS);
4820 }
4821 
4822 inline ivl_t mbl_array_t::get_stack_region(void) const
4823 {
4824  return ivl_t(std_ivls[MMIDX_LVARS].ivl.off, fullsize);
4825 }
4826 
4827 //-------------------------------------------------------------------------
4828 /// Get decompiler version.
4829 /// The returned string is of the form <major>.<minor>.<revision>.<build-date>
4830 /// \return pointer to version string. For example: "2.0.0.140605"
4831 
4832 const char *hexapi get_hexrays_version(void);
4833 
4834 
4835 /// Open pseudocode window.
4836 /// The specified function is decompiled and the pseudocode window is opened.
4837 /// \param ea function to decompile
4838 /// \param new_window 0:reuse existing window; 1:open new window;
4839 /// -1: reuse existing window if the current view is pseudocode
4840 /// \return false if failed
4841 
4842 vdui_t *hexapi open_pseudocode(ea_t ea, int new_window);
4843 
4844 
4845 /// Close pseudocode window.
4846 /// \param f pointer to window
4847 /// \return false if failed
4848 
4850 
4851 
4852 /// Get the vdui_t instance associated to the TWidget
4853 /// \param f pointer to window
4854 /// \return a vdui_t *, or NULL
4855 
4857 
4858 
4859 /// \defgroup VDRUN_ Batch decompilation bits
4860 //@{
4861 #define VDRUN_NEWFILE 0x0000 ///< Create a new file or overwrite existing file
4862 #define VDRUN_APPEND 0x0001 ///< Create a new file or append to existing file
4863 #define VDRUN_ONLYNEW 0x0002 ///< Fail if output file already exists
4864 #define VDRUN_SILENT 0x0004 ///< Silent decompilation
4865 #define VDRUN_SENDIDB 0x0008 ///< Send problematic databases to hex-rays.com
4866 #define VDRUN_MAYSTOP 0x0010 ///< the user can cancel decompilation
4867 #define VDRUN_CMDLINE 0x0020 ///< called from ida's command line
4868 #define VDRUN_STATS 0x0040 ///< print statistics into vd_stats.txt
4869 //@}
4870 
4871 /// Batch decompilation.
4872 /// Decompile all or the specified functions
4873 /// \return true if no internal error occurred and the user has not cancelled decompilation
4874 /// \param outfile name of the output file
4875 /// \param funcaddrs list of functions to decompile.
4876 /// If NULL or empty, then decompile all nonlib functions
4877 /// \param flags \ref VDRUN_
4878 
4879 bool hexapi decompile_many(const char *outfile, eavec_t *funcaddrs, int flags);
4880 
4881 
4882 /// Exception object: decompiler failure information
4884 {
4885  merror_t code; ///< \ref MERR_
4886  ea_t errea; ///< associated address
4887  qstring str; ///< string information
4888  hexrays_failure_t(void) : code(MERR_OK), errea(BADADDR) {}
4889  hexrays_failure_t(merror_t c, ea_t ea, const char *buf=NULL) : code(c), errea(ea), str(buf) {}
4890  hexrays_failure_t(merror_t c, ea_t ea, const qstring &buf) : code(c), errea(ea), str(buf) {}
4891  qstring hexapi desc(void) const;
4892  DEFINE_MEMORY_ALLOCATION_FUNCS()
4893 };
4894 
4895 /// Exception object: decompiler exception
4896 struct vd_failure_t : public std::exception
4897 {
4898  hexrays_failure_t hf;
4899  vd_failure_t(void) {}
4900  vd_failure_t(merror_t code, ea_t ea, const char *buf=NULL) : hf(code, ea, buf) {}
4901  vd_failure_t(merror_t code, ea_t ea, const qstring &buf) : hf(code, ea, buf) {}
4902  vd_failure_t(const hexrays_failure_t &_hf) : hf(_hf) {}
4903  qstring desc(void) const { return hf.desc(); }
4904 #ifdef __GNUC__
4905  ~vd_failure_t(void) throw() {}
4906 #endif
4907  DEFINE_MEMORY_ALLOCATION_FUNCS()
4908 };
4909 
4910 /// Exception object: decompiler internal error
4911 struct vd_interr_t : public vd_failure_t
4912 {
4913  vd_interr_t(ea_t ea, const qstring &buf) : vd_failure_t(MERR_INTERR, ea, buf) {}
4914  vd_interr_t(ea_t ea, const char *buf) : vd_failure_t(MERR_INTERR, ea, buf) {}
4915 };
4916 
4917 /// Send the database to Hex-Rays.
4918 /// This function sends the current database to the Hex-Rays server.
4919 /// The database is sent in the compressed form over an encrypted (SSL) connection.
4920 /// \param err failure description object. Empty hexrays_failure_t object can
4921 /// be used if error information is not available.
4922 /// \param silent if false, a dialog box will be displayed before sending the database.
4923 
4924 void hexapi send_database(const hexrays_failure_t &err, bool silent);
4925 
4926 
4927 /// Result of get_current_operand()
4929 {
4930  qstring name; ///< register or stkvar name
4931  union
4932  {
4933  sval_t stkoff; ///< if stkvar, stack offset
4934  int regnum; ///< if register, the register id
4935  };
4936  int size; ///< operand size
4937  int flags;
4938 #define GCO_STK 0x0000 ///< a stack variable
4939 #define GCO_REG 0x0001 ///< is register? otherwise a stack variable
4940 #define GCO_USE 0x0002 ///< is source operand?
4941 #define GCO_DEF 0x0004 ///< is destination operand?
4942  bool is_reg(void) const { return (flags & GCO_REG) != 0; }
4943  bool is_use(void) const { return (flags & GCO_USE) != 0; }
4944  bool is_def(void) const { return (flags & GCO_DEF) != 0; }
4945 
4946  /// Append operand info to LIST.
4947  /// This function converts IDA register number or stack offset to
4948  /// a decompiler list.
4949  /// \param list list to append to
4950  /// \param mba microcode object
4951  bool hexapi append_to_list(mlist_t *list, const mbl_array_t *mba) const;
4952 };
4953 
4954 /// Get the instruction operand under the cursor.
4955 /// This function determines the operand that is under the cursor in the active
4956 /// disassembly listing. If the operand refers to a register or stack variable,
4957 /// it return true.
4958 /// \param out[out] output buffer
4960 
4961 void hexapi remitem(const citem_t *e);
4962 //-------------------------------------------------------------------------
4963 /// Ctree element type. At the beginning of this list there are expression
4964 /// elements (cot_...), followed by statement elements (cit_...).
4966 {
4967  cot_empty = 0,
4968  cot_comma = 1, ///< x, y
4969  cot_asg = 2, ///< x = y
4970  cot_asgbor = 3, ///< x |= y
4971  cot_asgxor = 4, ///< x ^= y
4972  cot_asgband = 5, ///< x &= y
4973  cot_asgadd = 6, ///< x += y
4974  cot_asgsub = 7, ///< x -= y
4975  cot_asgmul = 8, ///< x *= y
4976  cot_asgsshr = 9, ///< x >>= y signed
4977  cot_asgushr = 10, ///< x >>= y unsigned
4978  cot_asgshl = 11, ///< x <<= y
4979  cot_asgsdiv = 12, ///< x /= y signed
4980  cot_asgudiv = 13, ///< x /= y unsigned
4981  cot_asgsmod = 14, ///< x %= y signed
4982  cot_asgumod = 15, ///< x %= y unsigned
4983  cot_tern = 16, ///< x ? y : z
4984  cot_lor = 17, ///< x || y
4985  cot_land = 18, ///< x && y
4986  cot_bor = 19, ///< x | y
4987  cot_xor = 20, ///< x ^ y
4988  cot_band = 21, ///< x & y
4989  cot_eq = 22, ///< x == y int or fpu (see EXFL_FPOP)
4990  cot_ne = 23, ///< x != y int or fpu (see EXFL_FPOP)
4991  cot_sge = 24, ///< x >= y signed or fpu (see EXFL_FPOP)
4992  cot_uge = 25, ///< x >= y unsigned
4993  cot_sle = 26, ///< x <= y signed or fpu (see EXFL_FPOP)
4994  cot_ule = 27, ///< x <= y unsigned
4995  cot_sgt = 28, ///< x > y signed or fpu (see EXFL_FPOP)
4996  cot_ugt = 29, ///< x > y unsigned
4997  cot_slt = 30, ///< x < y signed or fpu (see EXFL_FPOP)
4998  cot_ult = 31, ///< x < y unsigned
4999  cot_sshr = 32, ///< x >> y signed
5000  cot_ushr = 33, ///< x >> y unsigned