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