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