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