5 * This work is licensed under the terms of 3-clause BSD license.
6 * See COPYING file in the top-level directory.
14 #include "my_assert.h"
18 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
19 #define IS(w, y) !strcmp(w, y)
20 #define IS_START(w, y) !strncmp(w, y, strlen(y))
22 #include "protoparse.h"
24 static const char *asmfn;
28 #define anote(fmt, ...) \
29 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
30 #define awarn(fmt, ...) \
31 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
32 #define aerr(fmt, ...) do { \
33 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
38 #include "masm_tools.h"
41 OPF_RMD = (1 << 0), /* removed from code generation */
42 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
43 OPF_FLAGS = (1 << 2), /* sets flags */
44 OPF_JMP = (1 << 3), /* branch, call */
45 OPF_CJMP = (1 << 4), /* cond. branch (cc or jecxz/loop) */
46 OPF_CC = (1 << 5), /* uses flags */
47 OPF_TAIL = (1 << 6), /* ret or tail call */
48 OPF_RSAVE = (1 << 7), /* push/pop is local reg save/load */
49 OPF_REP = (1 << 8), /* prefixed by rep */
50 OPF_REPZ = (1 << 9), /* rep is repe/repz */
51 OPF_REPNZ = (1 << 10), /* rep is repne/repnz */
52 OPF_FARG = (1 << 11), /* push collected as func arg */
53 OPF_FARGNR = (1 << 12), /* push collected as func arg (no reuse) */
54 OPF_EBP_S = (1 << 13), /* ebp used as scratch here, not BP */
55 OPF_DF = (1 << 14), /* DF flag set */
56 OPF_ATAIL = (1 << 15), /* tail call with reused arg frame */
57 OPF_32BIT = (1 << 16), /* 32bit division */
58 OPF_LOCK = (1 << 17), /* op has lock prefix */
59 OPF_VAPUSH = (1 << 18), /* vararg ptr push (as call arg) */
60 OPF_DONE = (1 << 19), /* already fully handled by analysis */
61 OPF_PPUSH = (1 << 20), /* part of complex push-pop graph */
134 // must be sorted (larger len must be further in enum)
143 #define MAX_EXITS 128
145 #define MAX_OPERANDS 3
150 enum opr_lenmod lmod;
151 unsigned int is_ptr:1; // pointer in C
152 unsigned int is_array:1; // array in C
153 unsigned int type_from_var:1; // .. in header, sometimes wrong
154 unsigned int size_mismatch:1; // type override differs from C
155 unsigned int size_lt:1; // type override is larger than C
156 unsigned int had_ds:1; // had ds: prefix
157 const struct parsed_proto *pp; // for OPT_LABEL
165 struct parsed_opr operand[MAX_OPERANDS];
168 unsigned char pfo_inv;
169 unsigned char operand_cnt;
170 unsigned char p_argnum; // arg push: altered before call arg #
171 unsigned char p_arggrp; // arg push: arg group # for above
172 unsigned char p_argpass;// arg push: arg of host func
173 short p_argnext;// arg push: same arg pushed elsewhere or -1
174 int regmask_src; // all referensed regs
176 int pfomask; // flagop: parsed_flag_op that can't be delayed
177 int cc_scratch; // scratch storage during analysis
178 int bt_i; // branch target for branches
179 struct parsed_data *btj;// branch targets for jumptables
180 struct parsed_proto *pp;// parsed_proto for OP_CALL
186 // OP_CALL - parser proto hint (str)
187 // (OPF_CC) - points to one of (OPF_FLAGS) that affects cc op
188 // OP_PUSH - points to OP_POP in complex push/pop graph
189 // OP_POP - points to OP_PUSH in simple push/pop pair
193 enum opr_lenmod lmod;
200 enum opr_lenmod lmod;
214 struct label_ref *next;
218 IDAFA_BP_FRAME = (1 << 0),
219 IDAFA_LIB_FUNC = (1 << 1),
220 IDAFA_STATIC = (1 << 2),
221 IDAFA_NORETURN = (1 << 3),
222 IDAFA_THUNK = (1 << 4),
223 IDAFA_FPD = (1 << 5),
226 // note: limited to 32k due to p_argnext
228 #define MAX_ARG_GRP 2
230 static struct parsed_op ops[MAX_OPS];
231 static struct parsed_equ *g_eqs;
233 static char *g_labels[MAX_OPS];
234 static struct label_ref g_label_refs[MAX_OPS];
235 static const struct parsed_proto *g_func_pp;
236 static struct parsed_data *g_func_pd;
237 static int g_func_pd_cnt;
238 static char g_func[256];
239 static char g_comment[256];
240 static int g_bp_frame;
241 static int g_sp_frame;
242 static int g_stack_frame_used;
243 static int g_stack_fsz;
244 static int g_ida_func_attr;
245 static int g_skip_func;
246 static int g_allow_regfunc;
247 static int g_quiet_pp;
248 static int g_header_mode;
250 #define ferr(op_, fmt, ...) do { \
251 printf("%s:%d: error %u: [%s] '%s': " fmt, asmfn, (op_)->asmln, \
252 __LINE__, g_func, dump_op(op_), ##__VA_ARGS__); \
256 #define fnote(op_, fmt, ...) \
257 printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
258 dump_op(op_), ##__VA_ARGS__)
260 #define ferr_assert(op_, cond) do { \
261 if (!(cond)) ferr(op_, "assertion '%s' failed\n", #cond); \
264 const char *regs_r32[] = {
265 "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
266 // not r32, but list here for easy parsing and printing
267 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
269 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
270 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
271 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
273 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
275 // possible basic comparison types (without inversion)
276 enum parsed_flag_op {
280 PFO_BE, // 6 CF=1||ZF=1
284 PFO_LE, // e ZF=1||SF!=OF
287 #define PFOB_O (1 << PFO_O)
288 #define PFOB_C (1 << PFO_C)
289 #define PFOB_Z (1 << PFO_Z)
290 #define PFOB_S (1 << PFO_S)
292 static const char *parsed_flag_op_names[] = {
293 "o", "c", "z", "be", "s", "p", "l", "le"
296 static int char_array_i(const char *array[], size_t len, const char *s)
300 for (i = 0; i < len; i++)
307 static void printf_number(char *buf, size_t buf_size,
308 unsigned long number)
310 // output in C-friendly form
311 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
314 static int check_segment_prefix(const char *s)
316 if (s[0] == 0 || s[1] != 's' || s[2] != ':')
330 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
334 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
336 *reg_lmod = OPLM_QWORD;
340 *reg_lmod = OPLM_DWORD;
343 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
345 *reg_lmod = OPLM_WORD;
348 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
350 *reg_lmod = OPLM_BYTE;
353 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
355 *reg_lmod = OPLM_BYTE;
362 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
364 enum opr_lenmod lmod;
377 while (my_isblank(*s))
379 for (; my_issep(*s); d++, s++)
381 while (my_isblank(*s))
385 // skip '?s:' prefixes
386 if (check_segment_prefix(s))
389 s = next_idt(w, sizeof(w), s);
394 reg = parse_reg(&lmod, w);
396 *regmask |= 1 << reg;
400 if ('0' <= w[0] && w[0] <= '9') {
401 number = parse_number(w);
402 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
406 // probably some label/identifier - pass
409 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
413 strcpy(name, cvtbuf);
418 static int is_reg_in_str(const char *s)
422 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
425 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
426 if (!strncmp(s, regs_r32[i], 3))
432 static const char *parse_stack_el(const char *name, char *extra_reg,
435 const char *p, *p2, *s;
441 if (g_bp_frame || early_try)
444 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
446 if (extra_reg != NULL) {
447 strncpy(extra_reg, name, 3);
452 if (IS_START(p, "ebp+")) {
456 if (p2 != NULL && is_reg_in_str(p)) {
457 if (extra_reg != NULL) {
458 strncpy(extra_reg, p, p2 - p);
459 extra_reg[p2 - p] = 0;
464 if (!('0' <= *p && *p <= '9'))
471 if (!IS_START(name, "esp+"))
477 if (is_reg_in_str(s)) {
478 if (extra_reg != NULL) {
479 strncpy(extra_reg, s, p - s);
480 extra_reg[p - s] = 0;
485 aerr("%s IDA stackvar not set?\n", __func__);
487 if (!('0' <= *s && *s <= '9')) {
488 aerr("%s IDA stackvar offset not set?\n", __func__);
491 if (s[0] == '0' && s[1] == 'x')
494 if (len < sizeof(buf) - 1) {
495 strncpy(buf, s, len);
497 val = strtol(buf, &endp, 16);
498 if (val == 0 || *endp != 0) {
499 aerr("%s num parse fail for '%s'\n", __func__, buf);
508 if ('0' <= *p && *p <= '9')
514 static int guess_lmod_from_name(struct parsed_opr *opr)
516 if (IS_START(opr->name, "dword_") || IS_START(opr->name, "off_")) {
517 opr->lmod = OPLM_DWORD;
520 if (IS_START(opr->name, "word_")) {
521 opr->lmod = OPLM_WORD;
524 if (IS_START(opr->name, "byte_")) {
525 opr->lmod = OPLM_BYTE;
528 if (IS_START(opr->name, "qword_")) {
529 opr->lmod = OPLM_QWORD;
535 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
536 const struct parsed_type *c_type)
538 static const char *dword_types[] = {
539 "uint32_t", "int", "_DWORD", "UINT_PTR", "DWORD",
540 "WPARAM", "LPARAM", "UINT", "__int32",
541 "LONG", "HIMC", "BOOL", "size_t",
544 static const char *word_types[] = {
545 "uint16_t", "int16_t", "_WORD", "WORD",
546 "unsigned __int16", "__int16",
548 static const char *byte_types[] = {
549 "uint8_t", "int8_t", "char",
550 "unsigned __int8", "__int8", "BYTE", "_BYTE",
552 // structures.. deal the same as with _UNKNOWN for now
558 if (c_type->is_ptr) {
563 n = skip_type_mod(c_type->name);
565 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
566 if (IS(n, dword_types[i])) {
572 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
573 if (IS(n, word_types[i])) {
579 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
580 if (IS(n, byte_types[i])) {
589 static char *default_cast_to(char *buf, size_t buf_size,
590 struct parsed_opr *opr)
596 if (opr->pp == NULL || opr->pp->type.name == NULL
599 snprintf(buf, buf_size, "%s", "(void *)");
603 snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
607 static enum opr_type lmod_from_directive(const char *d)
611 else if (IS(d, "dw"))
613 else if (IS(d, "db"))
616 aerr("unhandled directive: '%s'\n", d);
620 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
626 *regmask |= 1 << reg;
629 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
632 static int parse_operand(struct parsed_opr *opr,
633 int *regmask, int *regmask_indirect,
634 char words[16][256], int wordc, int w, unsigned int op_flags)
636 const struct parsed_proto *pp = NULL;
637 enum opr_lenmod tmplmod;
638 unsigned long number;
646 aerr("parse_operand w %d, wordc %d\n", w, wordc);
650 for (i = w; i < wordc; i++) {
651 len = strlen(words[i]);
652 if (words[i][len - 1] == ',') {
653 words[i][len - 1] = 0;
659 wordc_in = wordc - w;
661 if ((op_flags & OPF_JMP) && wordc_in > 0
662 && !('0' <= words[w][0] && words[w][0] <= '9'))
664 const char *label = NULL;
666 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
667 && IS(words[w + 1], "ptr"))
668 label = words[w + 2];
669 else if (wordc_in == 2 && IS(words[w], "short"))
670 label = words[w + 1];
671 else if (wordc_in == 1
672 && strchr(words[w], '[') == NULL
673 && parse_reg(&tmplmod, words[w]) < 0)
677 opr->type = OPT_LABEL;
678 ret = check_segment_prefix(label);
681 aerr("fs/gs used\n");
685 strcpy(opr->name, label);
691 if (IS(words[w + 1], "ptr")) {
692 if (IS(words[w], "dword"))
693 opr->lmod = OPLM_DWORD;
694 else if (IS(words[w], "word"))
695 opr->lmod = OPLM_WORD;
696 else if (IS(words[w], "byte"))
697 opr->lmod = OPLM_BYTE;
698 else if (IS(words[w], "qword"))
699 opr->lmod = OPLM_QWORD;
701 aerr("type parsing failed\n");
703 wordc_in = wordc - w;
708 if (IS(words[w], "offset")) {
709 opr->type = OPT_OFFSET;
710 opr->lmod = OPLM_DWORD;
711 strcpy(opr->name, words[w + 1]);
712 pp = proto_parse(g_fhdr, opr->name, 1);
715 if (IS(words[w], "(offset")) {
716 p = strchr(words[w + 1], ')');
718 aerr("parse of bracketed offset failed\n");
720 opr->type = OPT_OFFSET;
721 strcpy(opr->name, words[w + 1]);
727 aerr("parse_operand 1 word expected\n");
729 ret = check_segment_prefix(words[w]);
732 aerr("fs/gs used\n");
734 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
736 strcpy(opr->name, words[w]);
738 if (words[w][0] == '[') {
739 opr->type = OPT_REGMEM;
740 ret = sscanf(words[w], "[%[^]]]", opr->name);
742 aerr("[] parse failure\n");
744 parse_indmode(opr->name, regmask_indirect, 1);
745 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
748 struct parsed_equ *eq =
749 equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
751 opr->lmod = eq->lmod;
755 else if (strchr(words[w], '[')) {
757 p = strchr(words[w], '[');
758 opr->type = OPT_REGMEM;
759 parse_indmode(p, regmask_indirect, 0);
760 strncpy(buf, words[w], p - words[w]);
761 buf[p - words[w]] = 0;
762 pp = proto_parse(g_fhdr, buf, 1);
765 else if (('0' <= words[w][0] && words[w][0] <= '9')
766 || words[w][0] == '-')
768 number = parse_number(words[w]);
769 opr->type = OPT_CONST;
771 printf_number(opr->name, sizeof(opr->name), number);
775 ret = parse_reg(&tmplmod, opr->name);
777 setup_reg_opr(opr, ret, tmplmod, regmask);
781 // most likely var in data segment
782 opr->type = OPT_LABEL;
783 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
787 if (pp->is_fptr || pp->is_func) {
788 opr->lmod = OPLM_DWORD;
792 tmplmod = OPLM_UNSPEC;
793 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
794 anote("unhandled C type '%s' for '%s'\n",
795 pp->type.name, opr->name);
797 if (opr->lmod == OPLM_UNSPEC) {
799 opr->type_from_var = 1;
801 else if (opr->lmod != tmplmod) {
802 opr->size_mismatch = 1;
803 if (tmplmod < opr->lmod)
806 opr->is_ptr = pp->type.is_ptr;
808 opr->is_array = pp->type.is_array;
812 if (opr->lmod == OPLM_UNSPEC)
813 guess_lmod_from_name(opr);
817 static const struct {
822 { "repe", OPF_REP|OPF_REPZ },
823 { "repz", OPF_REP|OPF_REPZ },
824 { "repne", OPF_REP|OPF_REPNZ },
825 { "repnz", OPF_REP|OPF_REPNZ },
826 { "lock", OPF_LOCK }, // ignored for now..
829 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
831 static const struct {
834 unsigned short minopr;
835 unsigned short maxopr;
838 unsigned char pfo_inv;
840 { "nop", OP_NOP, 0, 0, 0 },
841 { "push", OP_PUSH, 1, 1, 0 },
842 { "pop", OP_POP, 1, 1, OPF_DATA },
843 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
844 { "mov" , OP_MOV, 2, 2, OPF_DATA },
845 { "lea", OP_LEA, 2, 2, OPF_DATA },
846 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
847 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
848 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
849 { "not", OP_NOT, 1, 1, OPF_DATA },
850 { "xlat", OP_XLAT, 0, 0, OPF_DATA },
851 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
852 { "lodsb",OP_LODS, 0, 0, OPF_DATA },
853 { "lodsw",OP_LODS, 0, 0, OPF_DATA },
854 { "lodsd",OP_LODS, 0, 0, OPF_DATA },
855 { "stosb",OP_STOS, 0, 0, OPF_DATA },
856 { "stosw",OP_STOS, 0, 0, OPF_DATA },
857 { "stosd",OP_STOS, 0, 0, OPF_DATA },
858 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
859 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
860 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
861 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
862 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
863 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
864 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
865 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
866 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
867 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
868 { "cld", OP_CLD, 0, 0, OPF_DATA },
869 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
870 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
871 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
872 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
873 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
874 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
875 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
876 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
877 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
878 { "shld", OP_SHLD, 3, 3, OPF_DATA|OPF_FLAGS },
879 { "shrd", OP_SHRD, 3, 3, OPF_DATA|OPF_FLAGS },
880 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
881 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
882 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
883 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
884 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
885 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
886 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
887 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
888 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
889 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
890 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
891 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
892 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
893 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
894 { "test", OP_TEST, 2, 2, OPF_FLAGS },
895 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
896 { "retn", OP_RET, 0, 1, OPF_TAIL },
897 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
898 { "jmp", OP_JMP, 1, 1, OPF_JMP },
899 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
900 { "loop", OP_LOOP, 1, 1, OPF_JMP|OPF_CJMP|OPF_DATA },
901 { "jo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 0 }, // 70 OF=1
902 { "jno", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 1 }, // 71 OF=0
903 { "jc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72 CF=1
904 { "jb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72
905 { "jnc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73 CF=0
906 { "jnb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
907 { "jae", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
908 { "jz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74 ZF=1
909 { "je", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74
910 { "jnz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75 ZF=0
911 { "jne", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75
912 { "jbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
913 { "jna", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
914 { "ja", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
915 { "jnbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
916 { "js", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 0 }, // 78 SF=1
917 { "jns", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 1 }, // 79 SF=0
918 { "jp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a PF=1
919 { "jpe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a
920 { "jnp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b PF=0
921 { "jpo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b
922 { "jl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c SF!=OF
923 { "jnge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c
924 { "jge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d SF=OF
925 { "jnl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d
926 { "jle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
927 { "jng", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
928 { "jg", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
929 { "jnle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
930 { "seto", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 0 },
931 { "setno", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 1 },
932 { "setc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
933 { "setb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
934 { "setnc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
935 { "setae", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
936 { "setnb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
937 { "setz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
938 { "sete", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
939 { "setnz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
940 { "setne", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
941 { "setbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
942 { "setna", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
943 { "seta", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
944 { "setnbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
945 { "sets", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 0 },
946 { "setns", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 1 },
947 { "setp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
948 { "setpe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
949 { "setnp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
950 { "setpo", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
951 { "setl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
952 { "setnge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
953 { "setge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
954 { "setnl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
955 { "setle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
956 { "setng", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
957 { "setg", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
958 { "setnle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
961 { "emms", OP_EMMS, 0, 0, OPF_DATA },
962 { "movq", OP_MOV, 2, 2, OPF_DATA },
967 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
969 enum opr_lenmod lmod = OPLM_UNSPEC;
970 int prefix_flags = 0;
978 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
979 if (IS(words[w], pref_table[i].name)) {
980 prefix_flags = pref_table[i].flags;
987 aerr("lone prefix: '%s'\n", words[0]);
992 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
993 if (IS(words[w], op_table[i].name))
997 if (i == ARRAY_SIZE(op_table)) {
999 aerr("unhandled op: '%s'\n", words[0]);
1004 op->op = op_table[i].op;
1005 op->flags = op_table[i].flags | prefix_flags;
1006 op->pfo = op_table[i].pfo;
1007 op->pfo_inv = op_table[i].pfo_inv;
1008 op->regmask_src = op->regmask_dst = 0;
1011 if (op->op == OP_UD2)
1014 for (opr = 0; opr < op_table[i].maxopr; opr++) {
1015 if (opr >= op_table[i].minopr && w >= wordc)
1018 regmask = regmask_ind = 0;
1019 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
1020 words, wordc, w, op->flags);
1022 if (opr == 0 && (op->flags & OPF_DATA))
1023 op->regmask_dst = regmask;
1025 op->regmask_src |= regmask;
1026 op->regmask_src |= regmask_ind;
1030 aerr("parse_op %s incomplete: %d/%d\n",
1031 words[0], w, wordc);
1034 op->operand_cnt = opr;
1035 if (!strncmp(op_table[i].name, "set", 3))
1036 op->operand[0].lmod = OPLM_BYTE;
1039 // first operand is not dst
1042 op->regmask_src |= op->regmask_dst;
1043 op->regmask_dst = 0;
1046 // first operand is src too
1058 op->regmask_src |= op->regmask_dst;
1063 op->regmask_src |= op->regmask_dst;
1064 op->regmask_dst |= op->regmask_src;
1070 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1071 && op->operand[0].lmod == op->operand[1].lmod
1072 && op->operand[0].reg == op->operand[1].reg
1073 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1075 op->regmask_src = 0;
1078 op->regmask_src |= op->regmask_dst;
1081 // ops with implicit argumets
1083 op->operand_cnt = 2;
1084 setup_reg_opr(&op->operand[0], xAX, OPLM_BYTE, &op->regmask_src);
1085 op->regmask_dst = op->regmask_src;
1086 setup_reg_opr(&op->operand[1], xDX, OPLM_DWORD, &op->regmask_src);
1090 op->operand_cnt = 2;
1091 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1092 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1098 if (op->operand_cnt != 0)
1100 if (words[op_w][4] == 'b')
1102 else if (words[op_w][4] == 'w')
1104 else if (words[op_w][4] == 'd')
1106 op->operand_cnt = 3;
1107 setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1108 lmod, &op->regmask_src);
1109 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1110 op->regmask_dst = op->regmask_src;
1111 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1112 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1117 if (op->operand_cnt != 0)
1119 if (words[op_w][4] == 'b')
1121 else if (words[op_w][4] == 'w')
1123 else if (words[op_w][4] == 'd')
1125 op->operand_cnt = 3;
1126 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1127 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1128 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1129 op->regmask_dst = op->regmask_src;
1133 op->regmask_dst = 1 << xCX;
1136 op->operand_cnt = 2;
1137 op->regmask_src = 1 << xCX;
1138 op->operand[1].type = OPT_REG;
1139 op->operand[1].reg = xCX;
1140 op->operand[1].lmod = OPLM_DWORD;
1144 if (op->operand_cnt != 1)
1149 op->regmask_src |= op->regmask_dst;
1150 op->regmask_dst = (1 << xDX) | (1 << xAX);
1151 if (op->operand[0].lmod == OPLM_UNSPEC)
1152 op->operand[0].lmod = OPLM_DWORD;
1157 // we could set up operands for edx:eax, but there is no real need to
1158 // (see is_opr_modified())
1159 op->regmask_src |= op->regmask_dst;
1160 op->regmask_dst = (1 << xDX) | (1 << xAX);
1161 if (op->operand[0].lmod == OPLM_UNSPEC)
1162 op->operand[0].lmod = OPLM_DWORD;
1170 op->regmask_src |= op->regmask_dst;
1171 if (op->operand[1].lmod == OPLM_UNSPEC)
1172 op->operand[1].lmod = OPLM_BYTE;
1176 op->regmask_src |= op->regmask_dst;
1177 if (op->operand[2].lmod == OPLM_UNSPEC)
1178 op->operand[2].lmod = OPLM_BYTE;
1182 op->regmask_src |= op->regmask_dst;
1183 op->regmask_dst = 0;
1184 if (op->operand[0].lmod == OPLM_UNSPEC
1185 && (op->operand[0].type == OPT_CONST
1186 || op->operand[0].type == OPT_OFFSET
1187 || op->operand[0].type == OPT_LABEL))
1188 op->operand[0].lmod = OPLM_DWORD;
1194 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1195 && op->operand[0].lmod == op->operand[1].lmod
1196 && op->operand[0].reg == op->operand[1].reg
1197 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1199 op->flags |= OPF_RMD | OPF_DONE;
1200 op->regmask_src = op->regmask_dst = 0;
1205 if (op->operand[0].type == OPT_REG
1206 && op->operand[1].type == OPT_REGMEM)
1209 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1210 if (IS(buf, op->operand[1].name))
1211 op->flags |= OPF_RMD | OPF_DONE;
1216 // trashed regs must be explicitly detected later
1217 op->regmask_dst = 0;
1221 op->regmask_dst = (1 << xBP) | (1 << xSP);
1222 op->regmask_src = 1 << xBP;
1229 if (op->operand[0].type == OPT_REG
1230 && op->operand[0].lmod == OPLM_DWORD
1231 && op->operand[1].type == OPT_CONST)
1233 if ((op->op == OP_AND && op->operand[1].val == 0)
1234 || (op->op == OP_OR && op->operand[1].val == ~0))
1236 op->regmask_src = 0;
1241 static const char *op_name(struct parsed_op *po)
1243 static char buf[16];
1247 if (po->op == OP_JCC || po->op == OP_SCC) {
1249 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1252 strcpy(p, parsed_flag_op_names[po->pfo]);
1256 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1257 if (op_table[i].op == po->op)
1258 return op_table[i].name;
1264 static const char *dump_op(struct parsed_op *po)
1266 static char out[128];
1273 snprintf(out, sizeof(out), "%s", op_name(po));
1274 for (i = 0; i < po->operand_cnt; i++) {
1278 snprintf(p, sizeof(out) - (p - out),
1279 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1280 po->operand[i].name);
1286 static const char *lmod_type_u(struct parsed_op *po,
1287 enum opr_lenmod lmod)
1299 ferr(po, "invalid lmod: %d\n", lmod);
1300 return "(_invalid_)";
1304 static const char *lmod_cast_u(struct parsed_op *po,
1305 enum opr_lenmod lmod)
1317 ferr(po, "invalid lmod: %d\n", lmod);
1318 return "(_invalid_)";
1322 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1323 enum opr_lenmod lmod)
1335 ferr(po, "invalid lmod: %d\n", lmod);
1336 return "(_invalid_)";
1340 static const char *lmod_cast_s(struct parsed_op *po,
1341 enum opr_lenmod lmod)
1353 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1354 return "(_invalid_)";
1358 static const char *lmod_cast(struct parsed_op *po,
1359 enum opr_lenmod lmod, int is_signed)
1362 lmod_cast_s(po, lmod) :
1363 lmod_cast_u(po, lmod);
1366 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1378 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1383 static const char *opr_name(struct parsed_op *po, int opr_num)
1385 if (opr_num >= po->operand_cnt)
1386 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1387 return po->operand[opr_num].name;
1390 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1392 if (opr_num >= po->operand_cnt)
1393 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1394 if (po->operand[opr_num].type != OPT_CONST)
1395 ferr(po, "opr %d: const expected\n", opr_num);
1396 return po->operand[opr_num].val;
1399 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1401 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1402 ferr(po, "invalid reg: %d\n", popr->reg);
1403 return regs_r32[popr->reg];
1406 // cast1 is the "final" cast
1407 static const char *simplify_cast(const char *cast1, const char *cast2)
1409 static char buf[256];
1415 if (IS(cast1, cast2))
1417 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1419 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1421 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1423 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1425 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1428 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1432 static const char *simplify_cast_num(const char *cast, unsigned int val)
1434 if (IS(cast, "(u8)") && val < 0x100)
1436 if (IS(cast, "(s8)") && val < 0x80)
1438 if (IS(cast, "(u16)") && val < 0x10000)
1440 if (IS(cast, "(s16)") && val < 0x8000)
1442 if (IS(cast, "(s32)") && val < 0x80000000)
1448 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1457 namelen = strlen(name);
1459 p = strchr(name, '+');
1463 ferr(po, "equ parse failed for '%s'\n", name);
1465 if (IS_START(p, "0x"))
1467 *extra_offs = strtol(p, &endp, 16);
1469 ferr(po, "equ parse failed for '%s'\n", name);
1472 for (i = 0; i < g_eqcnt; i++)
1473 if (strncmp(g_eqs[i].name, name, namelen) == 0
1474 && g_eqs[i].name[namelen] == 0)
1478 ferr(po, "unresolved equ name: '%s'\n", name);
1485 static int is_stack_access(struct parsed_op *po,
1486 const struct parsed_opr *popr)
1488 return (parse_stack_el(popr->name, NULL, 0)
1489 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1490 && IS_START(popr->name, "ebp")));
1493 static void parse_stack_access(struct parsed_op *po,
1494 const char *name, char *ofs_reg, int *offset_out,
1495 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1497 const char *bp_arg = "";
1498 const char *p = NULL;
1499 struct parsed_equ *eq;
1506 if (IS_START(name, "ebp-")
1507 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1510 if (IS_START(p, "0x"))
1512 offset = strtoul(p, &endp, 16);
1516 ferr(po, "ebp- parse of '%s' failed\n", name);
1519 bp_arg = parse_stack_el(name, ofs_reg, 0);
1520 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1521 eq = equ_find(po, bp_arg, &offset);
1523 ferr(po, "detected but missing eq\n");
1524 offset += eq->offset;
1527 if (!strncmp(name, "ebp", 3))
1530 // yes it sometimes LEAs ra for compares..
1531 if (!is_lea && ofs_reg[0] == 0
1532 && stack_ra <= offset && offset < stack_ra + 4)
1534 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1537 *offset_out = offset;
1538 *stack_ra_out = stack_ra;
1540 *bp_arg_out = bp_arg;
1543 static int stack_frame_access(struct parsed_op *po,
1544 struct parsed_opr *popr, char *buf, size_t buf_size,
1545 const char *name, const char *cast, int is_src, int is_lea)
1547 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1548 const char *prefix = "";
1549 const char *bp_arg = NULL;
1550 char ofs_reg[16] = { 0, };
1551 int i, arg_i, arg_s;
1559 if (po->flags & OPF_EBP_S)
1560 ferr(po, "stack_frame_access while ebp is scratch\n");
1562 parse_stack_access(po, name, ofs_reg, &offset,
1563 &stack_ra, &bp_arg, is_lea);
1565 if (offset > stack_ra)
1567 arg_i = (offset - stack_ra - 4) / 4;
1568 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1570 if (g_func_pp->is_vararg
1571 && arg_i == g_func_pp->argc_stack && is_lea)
1573 // should be va_list
1576 snprintf(buf, buf_size, "%sap", cast);
1579 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1580 offset, bp_arg, arg_i);
1582 if (ofs_reg[0] != 0)
1583 ferr(po, "offset reg on arg access?\n");
1585 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1586 if (g_func_pp->arg[i].reg != NULL)
1592 if (i == g_func_pp->argc)
1593 ferr(po, "arg %d not in prototype?\n", arg_i);
1595 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1602 ferr(po, "lea/byte to arg?\n");
1603 if (is_src && (offset & 3) == 0)
1604 snprintf(buf, buf_size, "%sa%d",
1605 simplify_cast(cast, "(u8)"), i + 1);
1607 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1608 cast, offset & 3, i + 1);
1613 ferr(po, "lea/word to arg?\n");
1618 ferr(po, "problematic arg store\n");
1619 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1620 simplify_cast(cast, "*(u16 *)"), i + 1);
1623 ferr(po, "unaligned arg word load\n");
1625 else if (is_src && (offset & 2) == 0)
1626 snprintf(buf, buf_size, "%sa%d",
1627 simplify_cast(cast, "(u16)"), i + 1);
1629 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1630 cast, (offset & 2) ? "HI" : "LO", i + 1);
1642 snprintf(buf, buf_size, "(u32)&a%d + %d",
1645 ferr(po, "unaligned arg store\n");
1647 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1648 snprintf(buf, buf_size, "%s(a%d >> %d)",
1649 prefix, i + 1, (offset & 3) * 8);
1653 snprintf(buf, buf_size, "%s%sa%d",
1654 prefix, is_lea ? "&" : "", i + 1);
1659 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1663 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1666 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1667 if (tmp_lmod != OPLM_DWORD
1668 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1669 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1671 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1672 i + 1, offset, g_func_pp->arg[i].type.name);
1674 // can't check this because msvc likes to reuse
1675 // arg space for scratch..
1676 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1677 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1681 if (g_stack_fsz == 0)
1682 ferr(po, "stack var access without stackframe\n");
1683 g_stack_frame_used = 1;
1685 sf_ofs = g_stack_fsz + offset;
1686 lim = (ofs_reg[0] != 0) ? -4 : 0;
1687 if (offset > 0 || sf_ofs < lim)
1688 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1698 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1699 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1703 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1704 // known unaligned or possibly unaligned
1705 strcat(g_comment, " unaligned");
1707 prefix = "*(u16 *)&";
1708 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1709 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1712 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1716 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1717 // known unaligned or possibly unaligned
1718 strcat(g_comment, " unaligned");
1720 prefix = "*(u32 *)&";
1721 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1722 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1725 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1729 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1736 static void check_func_pp(struct parsed_op *po,
1737 const struct parsed_proto *pp, const char *pfx)
1739 enum opr_lenmod tmp_lmod;
1743 if (pp->argc_reg != 0) {
1744 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1745 pp_print(buf, sizeof(buf), pp);
1746 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1748 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1749 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1750 pfx, pp->argc_reg, pp->argc_stack);
1753 // fptrs must use 32bit args, callsite might have no information and
1754 // lack a cast to smaller types, which results in incorrectly masked
1755 // args passed (callee may assume masked args, it does on ARM)
1756 if (!pp->is_osinc) {
1757 for (i = 0; i < pp->argc; i++) {
1758 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1759 if (ret && tmp_lmod != OPLM_DWORD)
1760 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1761 i + 1, pp->arg[i].type.name);
1766 static const char *check_label_read_ref(struct parsed_op *po,
1769 const struct parsed_proto *pp;
1771 pp = proto_parse(g_fhdr, name, 0);
1773 ferr(po, "proto_parse failed for ref '%s'\n", name);
1776 check_func_pp(po, pp, "ref");
1781 static char *out_src_opr(char *buf, size_t buf_size,
1782 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1785 char tmp1[256], tmp2[256];
1794 switch (popr->type) {
1797 ferr(po, "lea from reg?\n");
1799 switch (popr->lmod) {
1801 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1804 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1807 snprintf(buf, buf_size, "%s%s",
1808 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1811 if (popr->name[1] == 'h') // XXX..
1812 snprintf(buf, buf_size, "%s(%s >> 8)",
1813 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1815 snprintf(buf, buf_size, "%s%s",
1816 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1819 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1824 if (is_stack_access(po, popr)) {
1825 stack_frame_access(po, popr, buf, buf_size,
1826 popr->name, cast, 1, is_lea);
1830 strcpy(expr, popr->name);
1831 if (strchr(expr, '[')) {
1832 // special case: '[' can only be left for label[reg] form
1833 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1835 ferr(po, "parse failure for '%s'\n", expr);
1836 if (tmp1[0] == '(') {
1837 // (off_4FFF50+3)[eax]
1838 p = strchr(tmp1 + 1, ')');
1839 if (p == NULL || p[1] != 0)
1840 ferr(po, "parse failure (2) for '%s'\n", expr);
1842 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1844 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1847 // XXX: do we need more parsing?
1849 snprintf(buf, buf_size, "%s", expr);
1853 snprintf(buf, buf_size, "%s(%s)",
1854 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1858 name = check_label_read_ref(po, popr->name);
1859 if (cast[0] == 0 && popr->is_ptr)
1863 snprintf(buf, buf_size, "(u32)&%s", name);
1864 else if (popr->size_lt)
1865 snprintf(buf, buf_size, "%s%s%s%s", cast,
1866 lmod_cast_u_ptr(po, popr->lmod),
1867 popr->is_array ? "" : "&", name);
1869 snprintf(buf, buf_size, "%s%s%s", cast, name,
1870 popr->is_array ? "[0]" : "");
1874 name = check_label_read_ref(po, popr->name);
1878 ferr(po, "lea an offset?\n");
1879 snprintf(buf, buf_size, "%s&%s", cast, name);
1884 ferr(po, "lea from const?\n");
1886 printf_number(tmp1, sizeof(tmp1), popr->val);
1887 if (popr->val == 0 && strchr(cast, '*'))
1888 snprintf(buf, buf_size, "NULL");
1890 snprintf(buf, buf_size, "%s%s",
1891 simplify_cast_num(cast, popr->val), tmp1);
1895 ferr(po, "invalid src type: %d\n", popr->type);
1901 // note: may set is_ptr (we find that out late for ebp frame..)
1902 static char *out_dst_opr(char *buf, size_t buf_size,
1903 struct parsed_op *po, struct parsed_opr *popr)
1905 switch (popr->type) {
1907 switch (popr->lmod) {
1909 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1912 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1916 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1920 if (popr->name[1] == 'h') // XXX..
1921 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1923 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1926 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1931 if (is_stack_access(po, popr)) {
1932 stack_frame_access(po, popr, buf, buf_size,
1933 popr->name, "", 0, 0);
1937 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1940 if (popr->size_mismatch)
1941 snprintf(buf, buf_size, "%s%s%s",
1942 lmod_cast_u_ptr(po, popr->lmod),
1943 popr->is_array ? "" : "&", popr->name);
1945 snprintf(buf, buf_size, "%s%s", popr->name,
1946 popr->is_array ? "[0]" : "");
1950 ferr(po, "invalid dst type: %d\n", popr->type);
1956 static char *out_src_opr_u32(char *buf, size_t buf_size,
1957 struct parsed_op *po, struct parsed_opr *popr)
1959 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1962 static void out_test_for_cc(char *buf, size_t buf_size,
1963 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1964 enum opr_lenmod lmod, const char *expr)
1966 const char *cast, *scast;
1968 cast = lmod_cast_u(po, lmod);
1969 scast = lmod_cast_s(po, lmod);
1973 case PFO_BE: // CF=1||ZF=1; CF=0
1974 snprintf(buf, buf_size, "(%s%s %s 0)",
1975 cast, expr, is_inv ? "!=" : "==");
1979 case PFO_L: // SF!=OF; OF=0
1980 snprintf(buf, buf_size, "(%s%s %s 0)",
1981 scast, expr, is_inv ? ">=" : "<");
1984 case PFO_LE: // ZF=1||SF!=OF; OF=0
1985 snprintf(buf, buf_size, "(%s%s %s 0)",
1986 scast, expr, is_inv ? ">" : "<=");
1990 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1994 static void out_cmp_for_cc(char *buf, size_t buf_size,
1995 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1997 const char *cast, *scast, *cast_use;
1998 char buf1[256], buf2[256];
1999 enum opr_lenmod lmod;
2001 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
2002 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
2003 po->operand[0].lmod, po->operand[1].lmod);
2004 lmod = po->operand[0].lmod;
2006 cast = lmod_cast_u(po, lmod);
2007 scast = lmod_cast_s(po, lmod);
2023 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
2026 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
2027 if (po->op == OP_DEC)
2028 snprintf(buf2, sizeof(buf2), "1");
2030 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
2034 // note: must be unsigned compare
2035 snprintf(buf, buf_size, "(%s %s %s)",
2036 buf1, is_inv ? ">=" : "<", buf2);
2040 snprintf(buf, buf_size, "(%s %s %s)",
2041 buf1, is_inv ? "!=" : "==", buf2);
2045 // note: must be unsigned compare
2046 snprintf(buf, buf_size, "(%s %s %s)",
2047 buf1, is_inv ? ">" : "<=", buf2);
2050 if (is_inv && lmod == OPLM_BYTE
2051 && po->operand[1].type == OPT_CONST
2052 && po->operand[1].val == 0xff)
2054 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2055 snprintf(buf, buf_size, "(0)");
2059 // note: must be signed compare
2061 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
2062 scast, buf1, buf2, is_inv ? ">=" : "<");
2066 snprintf(buf, buf_size, "(%s %s %s)",
2067 buf1, is_inv ? ">=" : "<", buf2);
2071 snprintf(buf, buf_size, "(%s %s %s)",
2072 buf1, is_inv ? ">" : "<=", buf2);
2080 static void out_cmp_test(char *buf, size_t buf_size,
2081 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2083 char buf1[256], buf2[256], buf3[256];
2085 if (po->op == OP_TEST) {
2086 if (IS(opr_name(po, 0), opr_name(po, 1))) {
2087 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
2090 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2091 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
2092 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2094 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
2095 po->operand[0].lmod, buf3);
2097 else if (po->op == OP_CMP) {
2098 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2101 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2104 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2105 struct parsed_opr *popr2)
2107 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2108 ferr(po, "missing lmod for both operands\n");
2110 if (popr1->lmod == OPLM_UNSPEC)
2111 popr1->lmod = popr2->lmod;
2112 else if (popr2->lmod == OPLM_UNSPEC)
2113 popr2->lmod = popr1->lmod;
2114 else if (popr1->lmod != popr2->lmod) {
2115 if (popr1->type_from_var) {
2116 popr1->size_mismatch = 1;
2117 if (popr1->lmod < popr2->lmod)
2119 popr1->lmod = popr2->lmod;
2121 else if (popr2->type_from_var) {
2122 popr2->size_mismatch = 1;
2123 if (popr2->lmod < popr1->lmod)
2125 popr2->lmod = popr1->lmod;
2128 ferr(po, "conflicting lmods: %d vs %d\n",
2129 popr1->lmod, popr2->lmod);
2133 static const char *op_to_c(struct parsed_op *po)
2157 ferr(po, "op_to_c was supplied with %d\n", po->op);
2161 static void op_set_clear_flag(struct parsed_op *po,
2162 enum op_flags flag_set, enum op_flags flag_clear)
2164 po->flags |= flag_set;
2165 po->flags &= ~flag_clear;
2168 // last op in stream - unconditional branch or ret
2169 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2170 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2171 && ops[_i].op != OP_CALL))
2173 #define check_i(po, i) \
2175 ferr(po, "bad " #i ": %d\n", i)
2177 // note: this skips over calls and rm'd stuff assuming they're handled
2178 // so it's intended to use at one of final passes
2179 static int scan_for_pop(int i, int opcnt, int magic, int reg,
2180 int depth, int *maxdepth, int do_flags)
2182 const struct parsed_proto *pp;
2183 struct parsed_op *po;
2188 for (; i < opcnt; i++) {
2190 if (po->cc_scratch == magic)
2191 break; // already checked
2192 po->cc_scratch = magic;
2194 if (po->flags & OPF_TAIL) {
2195 if (po->op == OP_CALL) {
2196 pp = proto_parse(g_fhdr, po->operand[0].name, g_quiet_pp);
2197 if (pp != NULL && pp->is_noreturn)
2198 // no stack cleanup for noreturn
2201 return -1; // deadend
2204 if (po->flags & (OPF_RMD|OPF_DONE|OPF_FARG))
2207 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2208 if (po->btj != NULL) {
2210 for (j = 0; j < po->btj->count; j++) {
2211 check_i(po, po->btj->d[j].bt_i);
2212 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, magic, reg,
2213 depth, maxdepth, do_flags);
2215 return ret; // dead end
2220 check_i(po, po->bt_i);
2221 if (po->flags & OPF_CJMP) {
2222 ret |= scan_for_pop(po->bt_i, opcnt, magic, reg,
2223 depth, maxdepth, do_flags);
2225 return ret; // dead end
2234 if ((po->op == OP_POP || po->op == OP_PUSH)
2235 && po->operand[0].type == OPT_REG && po->operand[0].reg == reg)
2240 if (po->op == OP_PUSH) {
2243 if (depth > *maxdepth)
2246 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2249 else if (po->op == OP_POP) {
2251 if (relevant && do_flags)
2252 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2257 if (depth < 0) // should not happen
2258 ferr(po, "fail with depth\n");
2260 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2268 // scan for 'reg' pop backwards starting from i
2269 // intended to use for register restore search, so other reg
2270 // references are considered an error
2271 static int scan_for_rsave_pop_reg(int i, int magic, int reg, int set_flags)
2273 struct parsed_op *po;
2274 struct label_ref *lr;
2277 ops[i].cc_scratch = magic;
2281 if (g_labels[i] != NULL) {
2282 lr = &g_label_refs[i];
2283 for (; lr != NULL; lr = lr->next) {
2284 check_i(&ops[i], lr->i);
2285 ret |= scan_for_rsave_pop_reg(lr->i, magic, reg, set_flags);
2289 if (i > 0 && LAST_OP(i - 1))
2297 if (ops[i].cc_scratch == magic)
2299 ops[i].cc_scratch = magic;
2302 if (po->op == OP_POP && po->operand[0].reg == reg) {
2303 if (po->flags & (OPF_RMD|OPF_DONE))
2306 po->flags |= set_flags;
2310 // this also covers the case where we reach corresponding push
2311 if ((po->regmask_dst | po->regmask_src) & (1 << reg))
2315 // nothing interesting on this path
2319 static void find_reachable_exits(int i, int opcnt, int magic,
2320 int *exits, int *exit_count)
2322 struct parsed_op *po;
2325 for (; i < opcnt; i++)
2328 if (po->cc_scratch == magic)
2330 po->cc_scratch = magic;
2332 if (po->flags & OPF_TAIL) {
2333 ferr_assert(po, *exit_count < MAX_EXITS);
2334 exits[*exit_count] = i;
2339 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2340 if (po->flags & OPF_RMD)
2343 if (po->btj != NULL) {
2344 for (j = 0; j < po->btj->count; j++) {
2345 check_i(po, po->btj->d[j].bt_i);
2346 find_reachable_exits(po->btj->d[j].bt_i, opcnt, magic,
2352 check_i(po, po->bt_i);
2353 if (po->flags & OPF_CJMP)
2354 find_reachable_exits(po->bt_i, opcnt, magic, exits, exit_count);
2362 // scan for 'reg' pop backwards starting from exits (all paths)
2363 static int scan_for_pop_ret(int i, int opcnt, int reg, int set_flags)
2365 static int exits[MAX_EXITS];
2366 static int exit_count;
2371 find_reachable_exits(i, opcnt, i + opcnt * 15, exits,
2373 ferr_assert(&ops[i], exit_count > 0);
2376 for (j = 0; j < exit_count; j++) {
2377 ret = scan_for_rsave_pop_reg(exits[j], i + opcnt * 16 + set_flags,
2386 // scan for one or more pop of push <const>
2387 static int scan_for_pop_const_r(int i, int opcnt, int magic,
2388 int push_i, int is_probe)
2390 struct parsed_op *po;
2391 struct label_ref *lr;
2395 for (; i < opcnt; i++)
2398 if (po->cc_scratch == magic)
2399 return ret; // already checked
2400 po->cc_scratch = magic;
2402 if (po->flags & OPF_JMP) {
2403 if (po->flags & OPF_RMD)
2405 if (po->op == OP_CALL)
2408 if (po->btj != NULL) {
2409 for (j = 0; j < po->btj->count; j++) {
2410 check_i(po, po->btj->d[j].bt_i);
2411 ret |= scan_for_pop_const_r(po->btj->d[j].bt_i, opcnt, magic,
2419 check_i(po, po->bt_i);
2420 if (po->flags & OPF_CJMP) {
2421 ret |= scan_for_pop_const_r(po->bt_i, opcnt, magic, push_i,
2432 if ((po->flags & (OPF_TAIL|OPF_RSAVE)) || po->op == OP_PUSH)
2435 if (g_labels[i] != NULL) {
2436 // all refs must be visited
2437 lr = &g_label_refs[i];
2438 for (; lr != NULL; lr = lr->next) {
2440 if (ops[lr->i].cc_scratch != magic)
2443 if (i > 0 && !LAST_OP(i - 1) && ops[i - 1].cc_scratch != magic)
2447 if (po->op == OP_POP)
2449 if (po->flags & (OPF_RMD|OPF_DONE))
2453 po->flags |= OPF_DONE;
2454 po->datap = &ops[push_i];
2463 static void scan_for_pop_const(int i, int opcnt, int magic)
2467 ret = scan_for_pop_const_r(i + 1, opcnt, magic, i, 1);
2469 ops[i].flags |= OPF_RMD | OPF_DONE;
2470 scan_for_pop_const_r(i + 1, opcnt, magic + 1, i, 0);
2474 // check if all branch targets within a marked path are also marked
2475 // note: the path checked must not be empty or end with a branch
2476 static int check_path_branches(int opcnt, int magic)
2478 struct parsed_op *po;
2481 for (i = 0; i < opcnt; i++) {
2483 if (po->cc_scratch != magic)
2486 if (po->flags & OPF_JMP) {
2487 if ((po->flags & OPF_RMD) || po->op == OP_CALL)
2490 if (po->btj != NULL) {
2491 for (j = 0; j < po->btj->count; j++) {
2492 check_i(po, po->btj->d[j].bt_i);
2493 if (ops[po->btj->d[j].bt_i].cc_scratch != magic)
2498 check_i(po, po->bt_i);
2499 if (ops[po->bt_i].cc_scratch != magic)
2501 if ((po->flags & OPF_CJMP) && ops[i + 1].cc_scratch != magic)
2509 // scan for multiple pushes for given pop
2510 static int scan_pushes_for_pop_r(int i, int magic, int pop_i,
2513 int reg = ops[pop_i].operand[0].reg;
2514 struct parsed_op *po;
2515 struct label_ref *lr;
2518 ops[i].cc_scratch = magic;
2522 if (g_labels[i] != NULL) {
2523 lr = &g_label_refs[i];
2524 for (; lr != NULL; lr = lr->next) {
2525 check_i(&ops[i], lr->i);
2526 ret |= scan_pushes_for_pop_r(lr->i, magic, pop_i, is_probe);
2530 if (i > 0 && LAST_OP(i - 1))
2538 if (ops[i].cc_scratch == magic)
2540 ops[i].cc_scratch = magic;
2543 if (po->op == OP_CALL)
2545 if ((po->flags & (OPF_TAIL|OPF_RSAVE)) || po->op == OP_POP)
2548 if (po->op == OP_PUSH)
2550 if (po->datap != NULL)
2552 if (po->operand[0].type == OPT_REG && po->operand[0].reg == reg)
2553 // leave this case for reg save/restore handlers
2557 po->flags |= OPF_PPUSH | OPF_DONE;
2558 po->datap = &ops[pop_i];
2567 static void scan_pushes_for_pop(int i, int opcnt, int *regmask_pp)
2569 int magic = i + opcnt * 14;
2572 ret = scan_pushes_for_pop_r(i, magic, i, 1);
2574 ret = check_path_branches(opcnt, magic);
2576 ops[i].flags |= OPF_PPUSH | OPF_DONE;
2577 *regmask_pp |= 1 << ops[i].operand[0].reg;
2578 scan_pushes_for_pop_r(i, magic + 1, i, 0);
2583 static void scan_propagate_df(int i, int opcnt)
2585 struct parsed_op *po = &ops[i];
2588 for (; i < opcnt; i++) {
2590 if (po->flags & OPF_DF)
2591 return; // already resolved
2592 po->flags |= OPF_DF;
2594 if (po->op == OP_CALL)
2595 ferr(po, "call with DF set?\n");
2597 if (po->flags & OPF_JMP) {
2598 if (po->btj != NULL) {
2600 for (j = 0; j < po->btj->count; j++) {
2601 check_i(po, po->btj->d[j].bt_i);
2602 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2607 check_i(po, po->bt_i);
2608 if (po->flags & OPF_CJMP)
2609 scan_propagate_df(po->bt_i, opcnt);
2615 if (po->flags & OPF_TAIL)
2618 if (po->op == OP_CLD) {
2619 po->flags |= OPF_RMD | OPF_DONE;
2624 ferr(po, "missing DF clear?\n");
2627 // is operand 'opr' referenced by parsed_op 'po'?
2628 static int is_opr_referenced(const struct parsed_opr *opr,
2629 const struct parsed_op *po)
2633 if (opr->type == OPT_REG) {
2634 mask = po->regmask_dst | po->regmask_src;
2635 if (po->op == OP_CALL)
2636 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2637 if ((1 << opr->reg) & mask)
2643 for (i = 0; i < po->operand_cnt; i++)
2644 if (IS(po->operand[0].name, opr->name))
2650 // is operand 'opr' read by parsed_op 'po'?
2651 static int is_opr_read(const struct parsed_opr *opr,
2652 const struct parsed_op *po)
2656 if (opr->type == OPT_REG) {
2657 mask = po->regmask_src;
2658 if (po->op == OP_CALL)
2659 // assume worst case
2660 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2661 if ((1 << opr->reg) & mask)
2671 // is operand 'opr' modified by parsed_op 'po'?
2672 static int is_opr_modified(const struct parsed_opr *opr,
2673 const struct parsed_op *po)
2677 if (!(po->flags & OPF_DATA))
2680 if (opr->type == OPT_REG) {
2681 if (po->op == OP_CALL) {
2682 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2683 if ((1 << opr->reg) & mask)
2689 if (po->operand[0].type == OPT_REG) {
2690 if (po->regmask_dst & (1 << opr->reg))
2697 return IS(po->operand[0].name, opr->name);
2700 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2701 static int is_any_opr_modified(const struct parsed_op *po_test,
2702 const struct parsed_op *po, int c_mode)
2707 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2710 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2713 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2716 // in reality, it can wreck any register, but in decompiled C
2717 // version it can only overwrite eax or edx:eax
2718 mask = (1 << xAX) | (1 << xDX);
2722 if (po->op == OP_CALL
2723 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2726 for (i = 0; i < po_test->operand_cnt; i++)
2727 if (IS(po_test->operand[i].name, po->operand[0].name))
2733 // scan for any po_test operand modification in range given
2734 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2737 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2740 for (; i < opcnt; i++) {
2741 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2748 // scan for po_test operand[0] modification in range given
2749 static int scan_for_mod_opr0(struct parsed_op *po_test,
2752 for (; i < opcnt; i++) {
2753 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2760 static int scan_for_flag_set(int i, int magic, int *branched,
2761 int *setters, int *setter_cnt)
2763 struct label_ref *lr;
2767 if (ops[i].cc_scratch == magic) {
2768 // is this a problem?
2769 //ferr(&ops[i], "%s looped\n", __func__);
2772 ops[i].cc_scratch = magic;
2774 if (g_labels[i] != NULL) {
2777 lr = &g_label_refs[i];
2778 for (; lr->next; lr = lr->next) {
2779 check_i(&ops[i], lr->i);
2780 ret = scan_for_flag_set(lr->i, magic,
2781 branched, setters, setter_cnt);
2786 check_i(&ops[i], lr->i);
2787 if (i > 0 && LAST_OP(i - 1)) {
2791 ret = scan_for_flag_set(lr->i, magic,
2792 branched, setters, setter_cnt);
2798 if (ops[i].flags & OPF_FLAGS) {
2799 setters[*setter_cnt] = i;
2804 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2811 // scan back for cdq, if anything modifies edx, fail
2812 static int scan_for_cdq_edx(int i)
2815 if (g_labels[i] != NULL) {
2816 if (g_label_refs[i].next != NULL)
2818 if (i > 0 && LAST_OP(i - 1)) {
2819 i = g_label_refs[i].i;
2826 if (ops[i].op == OP_CDQ)
2829 if (ops[i].regmask_dst & (1 << xDX))
2836 static int scan_for_reg_clear(int i, int reg)
2839 if (g_labels[i] != NULL) {
2840 if (g_label_refs[i].next != NULL)
2842 if (i > 0 && LAST_OP(i - 1)) {
2843 i = g_label_refs[i].i;
2850 if (ops[i].op == OP_XOR
2851 && ops[i].operand[0].lmod == OPLM_DWORD
2852 && ops[i].operand[0].reg == ops[i].operand[1].reg
2853 && ops[i].operand[0].reg == reg)
2856 if (ops[i].regmask_dst & (1 << reg))
2863 static void patch_esp_adjust(struct parsed_op *po, int adj)
2865 ferr_assert(po, po->op == OP_ADD);
2866 ferr_assert(po, IS(opr_name(po, 0), "esp"));
2867 ferr_assert(po, po->operand[1].type == OPT_CONST);
2869 // this is a bit of a hack, but deals with use of
2870 // single adj for multiple calls
2871 po->operand[1].val -= adj;
2872 po->flags |= OPF_RMD;
2873 if (po->operand[1].val == 0)
2874 po->flags |= OPF_DONE;
2875 ferr_assert(po, (int)po->operand[1].val >= 0);
2878 // scan for positive, constant esp adjust
2879 // multipath case is preliminary
2880 static int scan_for_esp_adjust(int i, int opcnt,
2881 int adj_expect, int *adj, int *is_multipath, int do_update)
2883 int adj_expect_unknown = 0;
2884 struct parsed_op *po;
2888 *adj = *is_multipath = 0;
2889 if (adj_expect < 0) {
2890 adj_expect_unknown = 1;
2891 adj_expect = 32 * 4; // enough?
2894 for (; i < opcnt && *adj < adj_expect; i++) {
2895 if (g_labels[i] != NULL)
2899 if (po->flags & OPF_DONE)
2902 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2903 if (po->operand[1].type != OPT_CONST)
2904 ferr(&ops[i], "non-const esp adjust?\n");
2905 *adj += po->operand[1].val;
2907 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2910 patch_esp_adjust(po, adj_expect);
2912 po->flags |= OPF_RMD;
2916 else if (po->op == OP_PUSH) {
2917 //if (first_pop == -1)
2918 // first_pop = -2; // none
2919 *adj -= lmod_bytes(po, po->operand[0].lmod);
2921 else if (po->op == OP_POP) {
2922 if (!(po->flags & OPF_DONE)) {
2923 // seems like msvc only uses 'pop ecx' for stack realignment..
2924 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2926 if (first_pop == -1 && *adj >= 0)
2929 if (do_update && *adj >= 0) {
2930 po->flags |= OPF_RMD;
2932 po->flags |= OPF_DONE;
2935 *adj += lmod_bytes(po, po->operand[0].lmod);
2936 if (*adj > adj_best)
2939 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2940 if (po->op == OP_JMP && po->btj == NULL) {
2946 if (po->op != OP_CALL)
2948 if (po->operand[0].type != OPT_LABEL)
2950 if (po->pp != NULL && po->pp->is_stdcall)
2952 if (adj_expect_unknown && first_pop >= 0)
2954 // assume it's another cdecl call
2958 if (first_pop >= 0) {
2959 // probably only 'pop ecx' was used
2967 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2969 struct parsed_op *po;
2973 ferr(ops, "%s: followed bad branch?\n", __func__);
2975 for (; i < opcnt; i++) {
2977 if (po->cc_scratch == magic)
2979 po->cc_scratch = magic;
2982 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2983 if (po->btj != NULL) {
2985 for (j = 0; j < po->btj->count; j++)
2986 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2990 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2991 if (!(po->flags & OPF_CJMP))
2994 if (po->flags & OPF_TAIL)
2999 static const struct parsed_proto *try_recover_pp(
3000 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
3002 const struct parsed_proto *pp = NULL;
3006 // maybe an arg of g_func?
3007 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
3009 char ofs_reg[16] = { 0, };
3010 int arg, arg_s, arg_i;
3017 parse_stack_access(po, opr->name, ofs_reg,
3018 &offset, &stack_ra, NULL, 0);
3019 if (ofs_reg[0] != 0)
3020 ferr(po, "offset reg on arg access?\n");
3021 if (offset <= stack_ra) {
3022 // search who set the stack var instead
3023 if (search_instead != NULL)
3024 *search_instead = 1;
3028 arg_i = (offset - stack_ra - 4) / 4;
3029 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
3030 if (g_func_pp->arg[arg].reg != NULL)
3036 if (arg == g_func_pp->argc)
3037 ferr(po, "stack arg %d not in prototype?\n", arg_i);
3039 pp = g_func_pp->arg[arg].fptr;
3041 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
3042 check_func_pp(po, pp, "icall arg");
3044 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
3046 p = strchr(opr->name + 1, '[');
3047 memcpy(buf, opr->name, p - opr->name);
3048 buf[p - opr->name] = 0;
3049 pp = proto_parse(g_fhdr, buf, g_quiet_pp);
3051 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
3052 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
3055 ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
3058 check_func_pp(po, pp, "reg-fptr ref");
3064 static void scan_for_call_type(int i, const struct parsed_opr *opr,
3065 int magic, const struct parsed_proto **pp_found, int *pp_i,
3068 const struct parsed_proto *pp = NULL;
3069 struct parsed_op *po;
3070 struct label_ref *lr;
3072 ops[i].cc_scratch = magic;
3075 if (g_labels[i] != NULL) {
3076 lr = &g_label_refs[i];
3077 for (; lr != NULL; lr = lr->next) {
3078 check_i(&ops[i], lr->i);
3079 scan_for_call_type(lr->i, opr, magic, pp_found, pp_i, multi);
3081 if (i > 0 && LAST_OP(i - 1))
3089 if (ops[i].cc_scratch == magic)
3091 ops[i].cc_scratch = magic;
3093 if (!(ops[i].flags & OPF_DATA))
3095 if (!is_opr_modified(opr, &ops[i]))
3097 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
3098 // most probably trashed by some processing
3103 opr = &ops[i].operand[1];
3104 if (opr->type != OPT_REG)
3108 po = (i >= 0) ? &ops[i] : ops;
3111 // reached the top - can only be an arg-reg
3112 if (opr->type != OPT_REG || g_func_pp == NULL)
3115 for (i = 0; i < g_func_pp->argc; i++) {
3116 if (g_func_pp->arg[i].reg == NULL)
3118 if (IS(opr->name, g_func_pp->arg[i].reg))
3121 if (i == g_func_pp->argc)
3123 pp = g_func_pp->arg[i].fptr;
3125 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
3126 i + 1, g_func_pp->arg[i].reg);
3127 check_func_pp(po, pp, "icall reg-arg");
3130 pp = try_recover_pp(po, opr, NULL);
3132 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
3133 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
3134 || (*pp_found)->is_stdcall != pp->is_stdcall
3135 || (*pp_found)->is_fptr != pp->is_fptr
3136 || (*pp_found)->argc != pp->argc
3137 || (*pp_found)->argc_reg != pp->argc_reg
3138 || (*pp_found)->argc_stack != pp->argc_stack)
3140 ferr(po, "icall: parsed_proto mismatch\n");
3150 static void add_label_ref(struct label_ref *lr, int op_i)
3152 struct label_ref *lr_new;
3159 lr_new = calloc(1, sizeof(*lr_new));
3161 lr_new->next = lr->next;
3165 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
3167 struct parsed_op *po = &ops[i];
3168 struct parsed_data *pd;
3169 char label[NAMELEN], *p;
3172 p = strchr(po->operand[0].name, '[');
3176 len = p - po->operand[0].name;
3177 strncpy(label, po->operand[0].name, len);
3180 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3181 if (IS(g_func_pd[j].label, label)) {
3187 //ferr(po, "label '%s' not parsed?\n", label);
3190 if (pd->type != OPT_OFFSET)
3191 ferr(po, "label '%s' with non-offset data?\n", label);
3193 // find all labels, link
3194 for (j = 0; j < pd->count; j++) {
3195 for (l = 0; l < opcnt; l++) {
3196 if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
3197 add_label_ref(&g_label_refs[l], i);
3207 static void clear_labels(int count)
3211 for (i = 0; i < count; i++) {
3212 if (g_labels[i] != NULL) {
3219 static void resolve_branches_parse_calls(int opcnt)
3221 const struct parsed_proto *pp_c;
3222 struct parsed_proto *pp;
3223 struct parsed_data *pd;
3224 struct parsed_op *po;
3225 const char *tmpname;
3228 for (i = 0; i < opcnt; i++)
3234 if (po->op == OP_CALL) {
3237 if (po->operand[0].type == OPT_LABEL) {
3238 tmpname = opr_name(po, 0);
3239 if (IS_START(tmpname, "loc_"))
3240 ferr(po, "call to loc_*\n");
3241 pp_c = proto_parse(g_fhdr, tmpname, g_header_mode);
3242 if (!g_header_mode && pp_c == NULL)
3243 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3246 pp = proto_clone(pp_c);
3247 my_assert_not(pp, NULL);
3250 else if (po->datap != NULL) {
3251 pp = calloc(1, sizeof(*pp));
3252 my_assert_not(pp, NULL);
3254 ret = parse_protostr(po->datap, pp);
3256 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3263 check_func_pp(po, pp, "fptr var call");
3264 if (pp->is_noreturn)
3265 po->flags |= OPF_TAIL;
3271 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3274 if (po->operand[0].type == OPT_REGMEM) {
3275 pd = try_resolve_jumptab(i, opcnt);
3283 for (l = 0; l < opcnt; l++) {
3284 if (g_labels[l] != NULL
3285 && IS(po->operand[0].name, g_labels[l]))
3287 if (l == i + 1 && po->op == OP_JMP) {
3288 // yet another alignment type..
3289 po->flags |= OPF_RMD|OPF_DONE;
3292 add_label_ref(&g_label_refs[l], i);
3298 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3301 if (po->operand[0].type == OPT_LABEL)
3305 ferr(po, "unhandled branch\n");
3309 po->flags |= OPF_TAIL;
3310 if (i > 0 && ops[i - 1].op == OP_POP)
3311 po->flags |= OPF_ATAIL;
3316 static void scan_prologue_epilogue(int opcnt)
3318 int ecx_push = 0, esp_sub = 0;
3322 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
3323 && ops[1].op == OP_MOV
3324 && IS(opr_name(&ops[1], 0), "ebp")
3325 && IS(opr_name(&ops[1], 1), "esp"))
3328 ops[0].flags |= OPF_RMD | OPF_DONE;
3329 ops[1].flags |= OPF_RMD | OPF_DONE;
3332 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
3333 g_stack_fsz = opr_const(&ops[2], 1);
3334 ops[2].flags |= OPF_RMD | OPF_DONE;
3338 // another way msvc builds stack frame..
3340 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3342 ops[i].flags |= OPF_RMD | OPF_DONE;
3346 // and another way..
3347 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3348 && ops[i].operand[1].type == OPT_CONST
3349 && ops[i + 1].op == OP_CALL
3350 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3352 g_stack_fsz += ops[i].operand[1].val;
3353 ops[i].flags |= OPF_RMD | OPF_DONE;
3355 ops[i].flags |= OPF_RMD | OPF_DONE;
3362 for (; i < opcnt; i++)
3363 if (ops[i].flags & OPF_TAIL)
3366 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3367 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3373 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3374 || ops[j].op == OP_LEAVE)
3376 ops[j].flags |= OPF_RMD | OPF_DONE;
3378 else if (ops[i].op == OP_CALL && ops[i].pp != NULL
3379 && ops[i].pp->is_noreturn)
3381 // on noreturn, msvc sometimes cleans stack, sometimes not
3386 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3387 ferr(&ops[j], "'pop ebp' expected\n");
3389 if (g_stack_fsz != 0) {
3390 if (ops[j].op == OP_LEAVE)
3392 else if (ops[j].op == OP_POP
3393 && ops[j - 1].op == OP_MOV
3394 && IS(opr_name(&ops[j - 1], 0), "esp")
3395 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3397 ops[j - 1].flags |= OPF_RMD | OPF_DONE;
3400 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3402 ferr(&ops[j], "esp restore expected\n");
3405 if (ecx_push && j >= 0 && ops[j].op == OP_POP
3406 && IS(opr_name(&ops[j], 0), "ecx"))
3408 ferr(&ops[j], "unexpected ecx pop\n");
3414 } while (i < opcnt);
3417 ferr(ops, "missing ebp epilogue\n");
3423 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3424 ops[i].flags |= OPF_RMD | OPF_DONE;
3430 for (; i < opcnt; i++) {
3431 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3433 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3434 && ops[i].operand[1].type == OPT_CONST)
3436 g_stack_fsz = ops[i].operand[1].val;
3437 ops[i].flags |= OPF_RMD | OPF_DONE;
3443 if (ecx_push && !esp_sub) {
3444 // could actually be args for a call..
3445 for (; i < opcnt; i++)
3446 if (ops[i].op != OP_PUSH)
3449 if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
3450 const struct parsed_proto *pp;
3451 pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
3452 j = pp ? pp->argc_stack : 0;
3453 while (i > 0 && j > 0) {
3455 if (ops[i].op == OP_PUSH) {
3456 ops[i].flags &= ~(OPF_RMD | OPF_DONE);
3461 ferr(&ops[i], "unhandled prologue\n");
3464 i = g_stack_fsz = ecx_push = 0;
3465 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3466 if (!(ops[i].flags & OPF_RMD))
3476 if (ecx_push || esp_sub)
3482 for (; i < opcnt; i++)
3483 if (ops[i].flags & OPF_TAIL)
3486 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3487 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3494 for (l = 0; l < ecx_push; l++) {
3495 if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
3497 else if (ops[j].op == OP_ADD
3498 && IS(opr_name(&ops[j], 0), "esp")
3499 && ops[j].operand[1].type == OPT_CONST)
3502 l += ops[j].operand[1].val / 4 - 1;
3505 ferr(&ops[j], "'pop ecx' expected\n");
3507 ops[j].flags |= OPF_RMD | OPF_DONE;
3511 ferr(&ops[j], "epilogue scan failed\n");
3517 if (ops[j].op != OP_ADD
3518 || !IS(opr_name(&ops[j], 0), "esp")
3519 || ops[j].operand[1].type != OPT_CONST
3520 || ops[j].operand[1].val != g_stack_fsz)
3521 ferr(&ops[j], "'add esp' expected\n");
3523 ops[j].flags |= OPF_RMD | OPF_DONE;
3524 ops[j].operand[1].val = 0; // hack for stack arg scanner
3529 } while (i < opcnt);
3532 ferr(ops, "missing esp epilogue\n");
3536 static const struct parsed_proto *resolve_icall(int i, int opcnt,
3537 int *pp_i, int *multi_src)
3539 const struct parsed_proto *pp = NULL;
3540 int search_advice = 0;
3545 switch (ops[i].operand[0].type) {
3549 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3554 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3562 // find an instruction that changed opr before i op
3563 // *op_i must be set to -1 by the caller
3564 // *entry is set to 1 if one source is determined to be the caller
3565 // returns 1 if found, *op_i is then set to origin
3566 static int resolve_origin(int i, const struct parsed_opr *opr,
3567 int magic, int *op_i, int *is_caller)
3569 struct label_ref *lr;
3572 if (ops[i].cc_scratch == magic)
3574 ops[i].cc_scratch = magic;
3577 if (g_labels[i] != NULL) {
3578 lr = &g_label_refs[i];
3579 for (; lr != NULL; lr = lr->next) {
3580 check_i(&ops[i], lr->i);
3581 ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3583 if (i > 0 && LAST_OP(i - 1))
3589 if (is_caller != NULL)
3594 if (ops[i].cc_scratch == magic)
3596 ops[i].cc_scratch = magic;
3598 if (!(ops[i].flags & OPF_DATA))
3600 if (!is_opr_modified(opr, &ops[i]))
3607 // XXX: could check if the other op does the same
3616 // find an instruction that previously referenced opr
3617 // if multiple results are found - fail
3618 // *op_i must be set to -1 by the caller
3619 // returns 1 if found, *op_i is then set to referencer insn
3620 static int resolve_last_ref(int i, const struct parsed_opr *opr,
3621 int magic, int *op_i)
3623 struct label_ref *lr;
3626 if (ops[i].cc_scratch == magic)
3628 ops[i].cc_scratch = magic;
3631 if (g_labels[i] != NULL) {
3632 lr = &g_label_refs[i];
3633 for (; lr != NULL; lr = lr->next) {
3634 check_i(&ops[i], lr->i);
3635 ret |= resolve_last_ref(lr->i, opr, magic, op_i);
3637 if (i > 0 && LAST_OP(i - 1))
3645 if (ops[i].cc_scratch == magic)
3647 ops[i].cc_scratch = magic;
3649 if (!is_opr_referenced(opr, &ops[i]))
3660 // find next instruction that reads opr
3661 // if multiple results are found - fail
3662 // *op_i must be set to -1 by the caller
3663 // returns 1 if found, *op_i is then set to referencer insn
3664 static int find_next_read(int i, int opcnt,
3665 const struct parsed_opr *opr, int magic, int *op_i)
3667 struct parsed_op *po;
3670 for (; i < opcnt; i++)
3672 if (ops[i].cc_scratch == magic)
3674 ops[i].cc_scratch = magic;
3677 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
3678 if (po->btj != NULL) {
3680 for (j = 0; j < po->btj->count; j++) {
3681 check_i(po, po->btj->d[j].bt_i);
3682 ret |= find_next_read(po->btj->d[j].bt_i, opcnt, opr,
3688 if (po->flags & OPF_RMD)
3690 check_i(po, po->bt_i);
3691 if (po->flags & OPF_CJMP) {
3692 ret = find_next_read(po->bt_i, opcnt, opr, magic, op_i);
3701 if (!is_opr_read(opr, po)) {
3702 if (is_opr_modified(opr, po))
3705 if (po->flags & OPF_TAIL)
3720 static int try_resolve_const(int i, const struct parsed_opr *opr,
3721 int magic, unsigned int *val)
3726 ret = resolve_origin(i, opr, magic, &s_i, NULL);
3729 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3732 *val = ops[i].operand[1].val;
3739 static struct parsed_proto *process_call_early(int i, int opcnt,
3742 struct parsed_op *po = &ops[i];
3743 struct parsed_proto *pp;
3749 if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3753 // look for and make use of esp adjust
3755 if (!pp->is_stdcall && pp->argc_stack > 0)
3756 ret = scan_for_esp_adjust(i + 1, opcnt,
3757 pp->argc_stack * 4, &adj, &multipath, 0);
3759 if (pp->argc_stack > adj / 4)
3763 if (ops[ret].op == OP_POP) {
3764 for (j = 1; j < adj / 4; j++) {
3765 if (ops[ret + j].op != OP_POP
3766 || ops[ret + j].operand[0].reg != xCX)
3778 static struct parsed_proto *process_call(int i, int opcnt)
3780 struct parsed_op *po = &ops[i];
3781 const struct parsed_proto *pp_c;
3782 struct parsed_proto *pp;
3783 const char *tmpname;
3784 int call_i = -1, ref_i = -1;
3785 int adj = 0, multipath = 0;
3788 tmpname = opr_name(po, 0);
3793 pp_c = resolve_icall(i, opcnt, &call_i, &multipath);
3795 if (!pp_c->is_func && !pp_c->is_fptr)
3796 ferr(po, "call to non-func: %s\n", pp_c->name);
3797 pp = proto_clone(pp_c);
3798 my_assert_not(pp, NULL);
3800 // not resolved just to single func
3803 switch (po->operand[0].type) {
3805 // we resolved this call and no longer need the register
3806 po->regmask_src &= ~(1 << po->operand[0].reg);
3808 if (!multipath && i != call_i && ops[call_i].op == OP_MOV
3809 && ops[call_i].operand[1].type == OPT_LABEL)
3811 // no other source users?
3812 ret = resolve_last_ref(i, &po->operand[0], i + opcnt * 10,
3814 if (ret == 1 && call_i == ref_i) {
3815 // and nothing uses it after us?
3817 ret = find_next_read(i + 1, opcnt, &po->operand[0],
3818 i + opcnt * 11, &ref_i);
3820 // then also don't need the source mov
3821 ops[call_i].flags |= OPF_RMD;
3833 pp = calloc(1, sizeof(*pp));
3834 my_assert_not(pp, NULL);
3837 ret = scan_for_esp_adjust(i + 1, opcnt,
3838 -1, &adj, &multipath, 0);
3839 if (ret < 0 || adj < 0) {
3840 if (!g_allow_regfunc)
3841 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3842 pp->is_unresolved = 1;
3846 if (adj > ARRAY_SIZE(pp->arg))
3847 ferr(po, "esp adjust too large: %d\n", adj);
3848 pp->ret_type.name = strdup("int");
3849 pp->argc = pp->argc_stack = adj;
3850 for (arg = 0; arg < pp->argc; arg++)
3851 pp->arg[arg].type.name = strdup("int");
3856 // look for and make use of esp adjust
3859 if (!pp->is_stdcall && pp->argc_stack > 0) {
3860 int adj_expect = pp->is_vararg ? -1 : pp->argc_stack * 4;
3861 ret = scan_for_esp_adjust(i + 1, opcnt,
3862 adj_expect, &adj, &multipath, 0);
3865 if (pp->is_vararg) {
3866 if (adj / 4 < pp->argc_stack) {
3867 fnote(po, "(this call)\n");
3868 ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3869 adj, pp->argc_stack * 4);
3871 // modify pp to make it have varargs as normal args
3873 pp->argc += adj / 4 - pp->argc_stack;
3874 for (; arg < pp->argc; arg++) {
3875 pp->arg[arg].type.name = strdup("int");
3878 if (pp->argc > ARRAY_SIZE(pp->arg))
3879 ferr(po, "too many args for '%s'\n", tmpname);
3881 if (pp->argc_stack > adj / 4) {
3882 fnote(po, "(this call)\n");
3883 ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3884 tmpname, pp->argc_stack * 4, adj);
3887 scan_for_esp_adjust(i + 1, opcnt,
3888 pp->argc_stack * 4, &adj, &multipath, 1);
3890 else if (pp->is_vararg)
3891 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3897 static int collect_call_args_early(struct parsed_op *po, int i,
3898 struct parsed_proto *pp, int *regmask)
3903 for (arg = 0; arg < pp->argc; arg++)
3904 if (pp->arg[arg].reg == NULL)
3907 // first see if it can be easily done
3908 for (j = i; j > 0 && arg < pp->argc; )
3910 if (g_labels[j] != NULL)
3914 if (ops[j].op == OP_CALL)
3916 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3918 else if (ops[j].op == OP_POP)
3920 else if (ops[j].flags & OPF_CJMP)
3922 else if (ops[j].op == OP_PUSH) {
3923 if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3925 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3929 if (pp->arg[arg].type.is_va_list)
3933 for (arg++; arg < pp->argc; arg++)
3934 if (pp->arg[arg].reg == NULL)
3943 for (arg = 0; arg < pp->argc; arg++)
3944 if (pp->arg[arg].reg == NULL)
3947 for (j = i; j > 0 && arg < pp->argc; )
3951 if (ops[j].op == OP_PUSH)
3953 ops[j].p_argnext = -1;
3954 ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3955 pp->arg[arg].datap = &ops[j];
3957 if (ops[j].operand[0].type == OPT_REG)
3958 *regmask |= 1 << ops[j].operand[0].reg;
3960 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
3961 ops[j].flags &= ~OPF_RSAVE;
3964 for (arg++; arg < pp->argc; arg++)
3965 if (pp->arg[arg].reg == NULL)
3973 static int collect_call_args_r(struct parsed_op *po, int i,
3974 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3975 int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
3977 struct parsed_proto *pp_tmp;
3978 struct parsed_op *po_tmp;
3979 struct label_ref *lr;
3980 int need_to_save_current;
3981 int arg_grp_current = 0;
3982 int save_args_seen = 0;
3990 ferr(po, "dead label encountered\n");
3994 for (; arg < pp->argc; arg++)
3995 if (pp->arg[arg].reg == NULL)
3997 magic = (magic & 0xffffff) | (arg << 24);
3999 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
4001 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
4002 if (ops[j].cc_scratch != magic) {
4003 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
4007 // ok: have already been here
4010 ops[j].cc_scratch = magic;
4012 if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
4013 lr = &g_label_refs[j];
4014 if (lr->next != NULL)
4016 for (; lr->next; lr = lr->next) {
4017 check_i(&ops[j], lr->i);
4018 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
4020 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
4021 arg_grp, arg, magic, need_op_saving, may_reuse);
4026 check_i(&ops[j], lr->i);
4027 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
4029 if (j > 0 && LAST_OP(j - 1)) {
4030 // follow last branch in reverse
4035 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
4036 arg_grp, arg, magic, need_op_saving, may_reuse);
4042 if (ops[j].op == OP_CALL)
4044 if (pp->is_unresolved)
4049 ferr(po, "arg collect hit unparsed call '%s'\n",
4050 ops[j].operand[0].name);
4051 if (may_reuse && pp_tmp->argc_stack > 0)
4052 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
4053 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
4055 // esp adjust of 0 means we collected it before
4056 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
4057 && (ops[j].operand[1].type != OPT_CONST
4058 || ops[j].operand[1].val != 0))
4060 if (pp->is_unresolved)
4063 fnote(po, "(this call)\n");
4064 ferr(&ops[j], "arg collect %d/%d hit esp adjust of %d\n",
4065 arg, pp->argc, ops[j].operand[1].val);
4067 else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
4069 if (pp->is_unresolved)
4072 fnote(po, "(this call)\n");
4073 ferr(&ops[j], "arg collect %d/%d hit pop\n", arg, pp->argc);
4075 else if (ops[j].flags & OPF_CJMP)
4077 if (pp->is_unresolved)
4082 else if (ops[j].op == OP_PUSH
4083 && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
4085 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
4088 ops[j].p_argnext = -1;
4089 po_tmp = pp->arg[arg].datap;
4091 ops[j].p_argnext = po_tmp - ops;
4092 pp->arg[arg].datap = &ops[j];
4094 need_to_save_current = 0;
4097 if (ops[j].operand[0].type == OPT_REG)
4098 reg = ops[j].operand[0].reg;
4100 if (!need_op_saving) {
4101 ret = scan_for_mod(&ops[j], j + 1, i, 1);
4102 need_to_save_current = (ret >= 0);
4104 if (need_op_saving || need_to_save_current) {
4105 // mark this push as one that needs operand saving
4106 ops[j].flags &= ~OPF_RMD;
4107 if (ops[j].p_argnum == 0) {
4108 ops[j].p_argnum = arg + 1;
4109 save_args |= 1 << arg;
4111 else if (ops[j].p_argnum < arg + 1) {
4112 // XXX: might kill valid var..
4113 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
4114 ops[j].p_argnum = arg + 1;
4115 save_args |= 1 << arg;
4118 if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
4121 if (arg_grp_current >= MAX_ARG_GRP)
4122 ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
4123 ops[j].p_argnum, pp->name);
4126 else if (ops[j].p_argnum == 0)
4127 ops[j].flags |= OPF_RMD;
4129 // some PUSHes are reused by different calls on other branches,
4130 // but that can't happen if we didn't branch, so they
4131 // can be removed from future searches (handles nested calls)
4133 ops[j].flags |= OPF_FARGNR;
4135 ops[j].flags |= OPF_FARG;
4136 ops[j].flags &= ~OPF_RSAVE;
4138 // check for __VALIST
4139 if (!pp->is_unresolved && g_func_pp != NULL
4140 && pp->arg[arg].type.is_va_list)
4143 ret = resolve_origin(j, &ops[j].operand[0],
4144 magic + 1, &k, NULL);
4145 if (ret == 1 && k >= 0)
4147 if (ops[k].op == OP_LEA) {
4148 snprintf(buf, sizeof(buf), "arg_%X",
4149 g_func_pp->argc_stack * 4);
4150 if (!g_func_pp->is_vararg
4151 || strstr(ops[k].operand[1].name, buf))
4153 ops[k].flags |= OPF_RMD | OPF_DONE;
4154 ops[j].flags |= OPF_RMD | OPF_VAPUSH;
4155 save_args &= ~(1 << arg);
4159 ferr(&ops[j], "lea va_list used, but no vararg?\n");
4161 // check for va_list from g_func_pp arg too
4162 else if (ops[k].op == OP_MOV
4163 && is_stack_access(&ops[k], &ops[k].operand[1]))
4165 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
4166 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
4168 ops[k].flags |= OPF_RMD | OPF_DONE;
4169 ops[j].flags |= OPF_RMD;
4170 ops[j].p_argpass = ret + 1;
4171 save_args &= ~(1 << arg);
4178 *save_arg_vars |= save_args;
4180 // tracking reg usage
4182 *regmask |= 1 << reg;
4185 if (!pp->is_unresolved) {
4187 for (; arg < pp->argc; arg++)
4188 if (pp->arg[arg].reg == NULL)
4191 magic = (magic & 0xffffff) | (arg << 24);
4194 if (ops[j].p_arggrp > arg_grp_current) {
4196 arg_grp_current = ops[j].p_arggrp;
4198 if (ops[j].p_argnum > 0)
4199 save_args_seen |= 1 << (ops[j].p_argnum - 1);
4202 if (arg < pp->argc) {
4203 ferr(po, "arg collect failed for '%s': %d/%d\n",
4204 pp->name, arg, pp->argc);
4208 if (arg_grp_current > *arg_grp)
4209 *arg_grp = arg_grp_current;
4214 static int collect_call_args(struct parsed_op *po, int i,
4215 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
4218 // arg group is for cases when pushes for
4219 // multiple funcs are going on
4220 struct parsed_op *po_tmp;
4221 int save_arg_vars_current = 0;
4226 ret = collect_call_args_r(po, i, pp, regmask,
4227 &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
4232 // propagate arg_grp
4233 for (a = 0; a < pp->argc; a++) {
4234 if (pp->arg[a].reg != NULL)
4237 po_tmp = pp->arg[a].datap;
4238 while (po_tmp != NULL) {
4239 po_tmp->p_arggrp = arg_grp;
4240 if (po_tmp->p_argnext > 0)
4241 po_tmp = &ops[po_tmp->p_argnext];
4247 save_arg_vars[arg_grp] |= save_arg_vars_current;
4249 if (pp->is_unresolved) {
4251 pp->argc_stack += ret;
4252 for (a = 0; a < pp->argc; a++)
4253 if (pp->arg[a].type.name == NULL)
4254 pp->arg[a].type.name = strdup("int");
4260 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
4264 for (i = 0; i < pp->argc; i++)
4265 if (pp->arg[i].reg == NULL)
4269 memmove(&pp->arg[i + 1], &pp->arg[i],
4270 sizeof(pp->arg[0]) * pp->argc_stack);
4271 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
4272 pp->arg[i].reg = strdup(reg);
4273 pp->arg[i].type.name = strdup("int");
4278 static void output_std_flags(FILE *fout, struct parsed_op *po,
4279 int *pfomask, const char *dst_opr_text)
4281 if (*pfomask & (1 << PFO_Z)) {
4282 fprintf(fout, "\n cond_z = (%s%s == 0);",
4283 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
4284 *pfomask &= ~(1 << PFO_Z);
4286 if (*pfomask & (1 << PFO_S)) {
4287 fprintf(fout, "\n cond_s = (%s%s < 0);",
4288 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
4289 *pfomask &= ~(1 << PFO_S);
4294 OPP_FORCE_NORETURN = (1 << 0),
4295 OPP_SIMPLE_ARGS = (1 << 1),
4296 OPP_ALIGN = (1 << 2),
4299 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
4302 const char *cconv = "";
4304 if (pp->is_fastcall)
4305 cconv = "__fastcall ";
4306 else if (pp->is_stdcall && pp->argc_reg == 0)
4307 cconv = "__stdcall ";
4309 fprintf(fout, (flags & OPP_ALIGN) ? "%-16s" : "%s", cconv);
4311 if (pp->is_noreturn || (flags & OPP_FORCE_NORETURN))
4312 fprintf(fout, "noreturn ");
4315 static void output_pp(FILE *fout, const struct parsed_proto *pp,
4320 fprintf(fout, (flags & OPP_ALIGN) ? "%-5s" : "%s ",
4324 output_pp_attrs(fout, pp, flags);
4327 fprintf(fout, "%s", pp->name);
4332 for (i = 0; i < pp->argc; i++) {
4334 fprintf(fout, ", ");
4335 if (pp->arg[i].fptr != NULL && !(flags & OPP_SIMPLE_ARGS)) {
4337 output_pp(fout, pp->arg[i].fptr, 0);
4339 else if (pp->arg[i].type.is_retreg) {
4340 fprintf(fout, "u32 *r_%s", pp->arg[i].reg);
4343 fprintf(fout, "%s", pp->arg[i].type.name);
4345 fprintf(fout, " a%d", i + 1);
4348 if (pp->is_vararg) {
4350 fprintf(fout, ", ");
4351 fprintf(fout, "...");
4356 static int get_pp_arg_regmask(const struct parsed_proto *pp)
4361 for (i = 0; i < pp->argc; i++) {
4362 if (pp->arg[i].reg != NULL) {
4363 reg = char_array_i(regs_r32,
4364 ARRAY_SIZE(regs_r32), pp->arg[i].reg);
4366 ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
4367 pp->arg[i].reg, pp->name);
4368 regmask |= 1 << reg;
4375 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
4381 snprintf(buf1, sizeof(buf1), "%d", grp);
4382 snprintf(buf, buf_size, "s%s_a%d", buf1, num);
4387 static void gen_x_cleanup(int opcnt);
4389 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
4391 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
4392 struct parsed_opr *last_arith_dst = NULL;
4393 char buf1[256], buf2[256], buf3[256], cast[64];
4394 struct parsed_proto *pp, *pp_tmp;
4395 struct parsed_data *pd;
4397 int save_arg_vars[MAX_ARG_GRP] = { 0, };
4399 int need_tmp_var = 0;
4402 int label_pending = 0;
4403 int regmask_save = 0; // regs saved/restored in this func
4404 int regmask_arg = 0; // regs carrying function args (fastcall, etc)
4405 int regmask_now; // temp
4406 int regmask_init = 0; // regs that need zero initialization
4407 int regmask_pp = 0; // regs used in complex push-pop graph
4408 int regmask = 0; // used regs
4418 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
4419 g_stack_frame_used = 0;
4421 g_func_pp = proto_parse(fhdr, funcn, 0);
4422 if (g_func_pp == NULL)
4423 ferr(ops, "proto_parse failed for '%s'\n", funcn);
4425 regmask_arg = get_pp_arg_regmask(g_func_pp);
4428 // - resolve all branches
4429 // - parse calls with labels
4430 resolve_branches_parse_calls(opcnt);
4433 // - handle ebp/esp frame, remove ops related to it
4434 scan_prologue_epilogue(opcnt);
4437 // - remove dead labels
4438 for (i = 0; i < opcnt; i++)
4440 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
4447 // - process trivial calls
4448 for (i = 0; i < opcnt; i++)
4451 if (po->flags & (OPF_RMD|OPF_DONE))
4454 if (po->op == OP_CALL)
4456 pp = process_call_early(i, opcnt, &j);
4458 if (!(po->flags & OPF_ATAIL))
4459 // since we know the args, try to collect them
4460 if (collect_call_args_early(po, i, pp, ®mask) != 0)
4466 // commit esp adjust
4467 if (ops[j].op != OP_POP)
4468 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
4470 for (l = 0; l < pp->argc_stack; l++)
4471 ops[j + l].flags |= OPF_DONE | OPF_RMD;
4475 if (strstr(pp->ret_type.name, "int64"))
4478 po->flags |= OPF_DONE;
4485 // - handle push <const>/pop pairs
4486 for (i = 0; i < opcnt; i++)
4489 if (po->flags & (OPF_RMD|OPF_DONE))
4492 if (po->op == OP_CALL && !(po->flags & OPF_DONE))
4494 pp = process_call(i, opcnt);
4496 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
4497 // since we know the args, collect them
4498 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4502 if (strstr(pp->ret_type.name, "int64"))
4505 else if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4506 && !(po->flags & OPF_RSAVE) && po->operand[0].type == OPT_CONST)
4508 scan_for_pop_const(i, opcnt, i + opcnt * 12);
4510 else if (po->op == OP_POP)
4511 scan_pushes_for_pop(i, opcnt, ®mask_pp);
4515 // - find POPs for PUSHes, rm both
4516 // - scan for STD/CLD, propagate DF
4517 // - scan for all used registers
4518 // - find flag set ops for their users
4519 // - do unreselved calls
4520 // - declare indirect functions
4521 for (i = 0; i < opcnt; i++)
4524 if (po->flags & (OPF_RMD|OPF_DONE))
4527 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4528 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
4530 if (po->operand[0].type == OPT_REG)
4532 reg = po->operand[0].reg;
4534 ferr(po, "reg not set for push?\n");
4536 // FIXME: OPF_RSAVE, regmask_save
4538 ret = scan_for_pop(i + 1, opcnt, i + opcnt * 3,
4539 po->operand[0].reg, 0, &depth, 0);
4542 ferr(po, "too much depth: %d\n", depth);
4544 po->flags |= OPF_RMD;
4545 scan_for_pop(i + 1, opcnt, i + opcnt * 4,
4546 po->operand[0].reg, 0, &depth, 1);
4549 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, 0);
4552 if (regmask & (1 << reg)) {
4553 if (regmask_save & (1 << reg))
4554 ferr(po, "%s already saved?\n", po->operand[0].name);
4555 // arg = OPF_RSAVE; // FIXME
4558 scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, arg);
4564 if (po->op == OP_STD) {
4565 po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
4566 scan_propagate_df(i + 1, opcnt);
4569 regmask_now = po->regmask_src | po->regmask_dst;
4570 if (regmask_now & (1 << xBP)) {
4571 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4572 if (po->regmask_dst & (1 << xBP))
4573 // compiler decided to drop bp frame and use ebp as scratch
4574 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
4576 regmask_now &= ~(1 << xBP);
4580 regmask |= regmask_now;
4582 if (po->flags & OPF_CC)
4584 int setters[16], cnt = 0, branched = 0;
4586 ret = scan_for_flag_set(i, i + opcnt * 6,
4587 &branched, setters, &cnt);
4588 if (ret < 0 || cnt <= 0)
4589 ferr(po, "unable to trace flag setter(s)\n");
4590 if (cnt > ARRAY_SIZE(setters))
4591 ferr(po, "too many flag setters\n");
4593 for (j = 0; j < cnt; j++)
4595 tmp_op = &ops[setters[j]]; // flag setter
4598 // to get nicer code, we try to delay test and cmp;
4599 // if we can't because of operand modification, or if we
4600 // have arith op, or branch, make it calculate flags explicitly
4601 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4603 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4604 pfomask = 1 << po->pfo;
4606 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4607 pfomask = 1 << po->pfo;
4610 // see if we'll be able to handle based on op result
4611 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4612 && po->pfo != PFO_Z && po->pfo != PFO_S
4613 && po->pfo != PFO_P)
4615 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4617 pfomask = 1 << po->pfo;
4620 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4621 propagate_lmod(tmp_op, &tmp_op->operand[0],
4622 &tmp_op->operand[1]);
4623 if (tmp_op->operand[0].lmod == OPLM_DWORD)
4628 tmp_op->pfomask |= pfomask;
4629 cond_vars |= pfomask;
4631 // note: may overwrite, currently not a problem
4635 if (po->op == OP_RCL || po->op == OP_RCR
4636 || po->op == OP_ADC || po->op == OP_SBB)
4637 cond_vars |= 1 << PFO_C;
4640 if (po->op == OP_CMPS || po->op == OP_SCAS) {
4641 cond_vars |= 1 << PFO_Z;
4643 else if (po->op == OP_MUL
4644 || (po->op == OP_IMUL && po->operand_cnt == 1))
4646 if (po->operand[0].lmod == OPLM_DWORD)
4649 else if (po->op == OP_CALL) {
4650 // note: resolved non-reg calls are OPF_DONE already
4653 ferr(po, "NULL pp\n");
4655 if (pp->is_unresolved) {
4656 int regmask_stack = 0;
4657 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4660 // this is pretty rough guess:
4661 // see ecx and edx were pushed (and not their saved versions)
4662 for (arg = 0; arg < pp->argc; arg++) {
4663 if (pp->arg[arg].reg != NULL)
4666 tmp_op = pp->arg[arg].datap;
4668 ferr(po, "parsed_op missing for arg%d\n", arg);
4669 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4670 regmask_stack |= 1 << tmp_op->operand[0].reg;
4673 if (!((regmask_stack & (1 << xCX))
4674 && (regmask_stack & (1 << xDX))))
4676 if (pp->argc_stack != 0
4677 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4679 pp_insert_reg_arg(pp, "ecx");
4680 pp->is_fastcall = 1;
4681 regmask_init |= 1 << xCX;
4682 regmask |= 1 << xCX;
4684 if (pp->argc_stack != 0
4685 || ((regmask | regmask_arg) & (1 << xDX)))
4687 pp_insert_reg_arg(pp, "edx");
4688 regmask_init |= 1 << xDX;
4689 regmask |= 1 << xDX;
4693 // note: __cdecl doesn't fall into is_unresolved category
4694 if (pp->argc_stack > 0)
4698 for (arg = 0; arg < pp->argc; arg++) {
4699 if (pp->arg[arg].reg != NULL) {
4700 reg = char_array_i(regs_r32,
4701 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
4703 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
4704 if (!(regmask & (1 << reg))) {
4705 regmask_init |= 1 << reg;
4706 regmask |= 1 << reg;
4711 else if (po->op == OP_MOV && po->operand[0].pp != NULL
4712 && po->operand[1].pp != NULL)
4714 // <var> = offset <something>
4715 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4716 && !IS_START(po->operand[1].name, "off_"))
4718 if (!po->operand[0].pp->is_fptr)
4719 ferr(po, "%s not declared as fptr when it should be\n",
4720 po->operand[0].name);
4721 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4722 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4723 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4724 fnote(po, "var: %s\n", buf1);
4725 fnote(po, "func: %s\n", buf2);
4726 ferr(po, "^ mismatch\n");
4730 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
4731 regmask |= 1 << xAX;
4732 else if (po->op == OP_DIV || po->op == OP_IDIV) {
4733 // 32bit division is common, look for it
4734 if (po->op == OP_DIV)
4735 ret = scan_for_reg_clear(i, xDX);
4737 ret = scan_for_cdq_edx(i);
4739 po->flags |= OPF_32BIT;
4743 else if (po->op == OP_CLD)
4744 po->flags |= OPF_RMD | OPF_DONE;
4746 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4752 // - confirm regmask_save, it might have been reduced
4753 if (regmask_save != 0)
4756 for (i = 0; i < opcnt; i++) {
4758 if (po->flags & OPF_RMD)
4761 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
4762 regmask_save |= 1 << po->operand[0].reg;
4766 // output starts here
4768 // define userstack size
4769 if (g_func_pp->is_userstack) {
4770 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4771 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4772 fprintf(fout, "#endif\n");
4775 // the function itself
4776 ferr_assert(ops, !g_func_pp->is_fptr);
4777 output_pp(fout, g_func_pp,
4778 (g_ida_func_attr & IDAFA_NORETURN) ? OPP_FORCE_NORETURN : 0);
4779 fprintf(fout, "\n{\n");
4781 // declare indirect functions
4782 for (i = 0; i < opcnt; i++) {
4784 if (po->flags & OPF_RMD)
4787 if (po->op == OP_CALL) {
4790 ferr(po, "NULL pp\n");
4792 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4793 if (pp->name[0] != 0) {
4794 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4795 memcpy(pp->name, "i_", 2);
4797 // might be declared already
4799 for (j = 0; j < i; j++) {
4800 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4801 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4811 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4814 output_pp(fout, pp, OPP_SIMPLE_ARGS);
4815 fprintf(fout, ";\n");
4820 // output LUTs/jumptables
4821 for (i = 0; i < g_func_pd_cnt; i++) {
4823 fprintf(fout, " static const ");
4824 if (pd->type == OPT_OFFSET) {
4825 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
4827 for (j = 0; j < pd->count; j++) {
4829 fprintf(fout, ", ");
4830 fprintf(fout, "&&%s", pd->d[j].u.label);
4834 fprintf(fout, "%s %s[] =\n { ",
4835 lmod_type_u(ops, pd->lmod), pd->label);
4837 for (j = 0; j < pd->count; j++) {
4839 fprintf(fout, ", ");
4840 fprintf(fout, "%u", pd->d[j].u.val);
4843 fprintf(fout, " };\n");
4847 // declare stack frame, va_arg
4849 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
4850 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
4854 if (g_func_pp->is_userstack) {
4855 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4856 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
4860 if (g_func_pp->is_vararg) {
4861 fprintf(fout, " va_list ap;\n");
4865 // declare arg-registers
4866 for (i = 0; i < g_func_pp->argc; i++) {
4867 if (g_func_pp->arg[i].reg != NULL) {
4868 reg = char_array_i(regs_r32,
4869 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
4870 if (regmask & (1 << reg)) {
4871 if (g_func_pp->arg[i].type.is_retreg)
4872 fprintf(fout, " u32 %s = *r_%s;\n",
4873 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4875 fprintf(fout, " u32 %s = (u32)a%d;\n",
4876 g_func_pp->arg[i].reg, i + 1);
4879 if (g_func_pp->arg[i].type.is_retreg)
4880 ferr(ops, "retreg '%s' is unused?\n",
4881 g_func_pp->arg[i].reg);
4882 fprintf(fout, " // %s = a%d; // unused\n",
4883 g_func_pp->arg[i].reg, i + 1);
4889 // declare normal registers
4890 regmask_now = regmask & ~regmask_arg;
4891 regmask_now &= ~(1 << xSP);
4892 if (regmask_now & 0x00ff) {
4893 for (reg = 0; reg < 8; reg++) {
4894 if (regmask_now & (1 << reg)) {
4895 fprintf(fout, " u32 %s", regs_r32[reg]);
4896 if (regmask_init & (1 << reg))
4897 fprintf(fout, " = 0");
4898 fprintf(fout, ";\n");
4903 if (regmask_now & 0xff00) {
4904 for (reg = 8; reg < 16; reg++) {
4905 if (regmask_now & (1 << reg)) {
4906 fprintf(fout, " mmxr %s", regs_r32[reg]);
4907 if (regmask_init & (1 << reg))
4908 fprintf(fout, " = { 0, }");
4909 fprintf(fout, ";\n");
4916 for (reg = 0; reg < 8; reg++) {
4917 if (regmask_save & (1 << reg)) {
4918 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
4924 for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
4925 if (save_arg_vars[i] == 0)
4927 for (reg = 0; reg < 32; reg++) {
4928 if (save_arg_vars[i] & (1 << reg)) {
4929 fprintf(fout, " u32 %s;\n",
4930 saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
4936 // declare push-pop temporaries
4938 for (reg = 0; reg < 8; reg++) {
4939 if (regmask_pp & (1 << reg)) {
4940 fprintf(fout, " u32 pp_%s;\n", regs_r32[reg]);
4947 for (i = 0; i < 8; i++) {
4948 if (cond_vars & (1 << i)) {
4949 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
4956 fprintf(fout, " u32 tmp;\n");
4961 fprintf(fout, " u64 tmp64;\n");
4966 fprintf(fout, "\n");
4968 if (g_func_pp->is_vararg) {
4969 if (g_func_pp->argc_stack == 0)
4970 ferr(ops, "vararg func without stack args?\n");
4971 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
4975 for (i = 0; i < opcnt; i++)
4977 if (g_labels[i] != NULL) {
4978 fprintf(fout, "\n%s:\n", g_labels[i]);
4981 delayed_flag_op = NULL;
4982 last_arith_dst = NULL;
4986 if (po->flags & OPF_RMD)
4991 #define assert_operand_cnt(n_) \
4992 if (po->operand_cnt != n_) \
4993 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4995 // conditional/flag using op?
4996 if (po->flags & OPF_CC)
5002 // we go through all this trouble to avoid using parsed_flag_op,
5003 // which makes generated code much nicer
5004 if (delayed_flag_op != NULL)
5006 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
5007 po->pfo, po->pfo_inv);
5010 else if (last_arith_dst != NULL
5011 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
5012 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
5015 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
5016 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
5017 last_arith_dst->lmod, buf3);
5020 else if (tmp_op != NULL) {
5021 // use preprocessed flag calc results
5022 if (!(tmp_op->pfomask & (1 << po->pfo)))
5023 ferr(po, "not prepared for pfo %d\n", po->pfo);
5025 // note: pfo_inv was not yet applied
5026 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
5027 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
5030 ferr(po, "all methods of finding comparison failed\n");
5033 if (po->flags & OPF_JMP) {
5034 fprintf(fout, " if %s", buf1);
5036 else if (po->op == OP_RCL || po->op == OP_RCR
5037 || po->op == OP_ADC || po->op == OP_SBB)
5040 fprintf(fout, " cond_%s = %s;\n",
5041 parsed_flag_op_names[po->pfo], buf1);
5043 else if (po->flags & OPF_DATA) { // SETcc
5044 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
5045 fprintf(fout, " %s = %s;", buf2, buf1);
5048 ferr(po, "unhandled conditional op\n");
5052 pfomask = po->pfomask;
5054 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
5055 struct parsed_opr opr = {0,};
5058 opr.lmod = OPLM_DWORD;
5059 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
5061 if (ret != 1 || uval == 0) {
5062 // we need initial flags for ecx=0 case..
5063 if (i > 0 && ops[i - 1].op == OP_XOR
5064 && IS(ops[i - 1].operand[0].name,
5065 ops[i - 1].operand[1].name))
5067 fprintf(fout, " cond_z = ");
5068 if (pfomask & (1 << PFO_C))
5069 fprintf(fout, "cond_c = ");
5070 fprintf(fout, "0;\n");
5072 else if (last_arith_dst != NULL) {
5073 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
5074 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
5075 last_arith_dst->lmod, buf3);
5076 fprintf(fout, " cond_z = %s;\n", buf1);
5079 ferr(po, "missing initial ZF\n");
5086 assert_operand_cnt(2);
5087 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5088 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5089 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
5090 fprintf(fout, " %s = %s;", buf1,
5091 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5096 assert_operand_cnt(2);
5097 po->operand[1].lmod = OPLM_DWORD; // always
5098 fprintf(fout, " %s = %s;",
5099 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5100 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5105 assert_operand_cnt(2);
5106 fprintf(fout, " %s = %s;",
5107 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5108 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5112 assert_operand_cnt(2);
5113 switch (po->operand[1].lmod) {
5115 strcpy(buf3, "(s8)");
5118 strcpy(buf3, "(s16)");
5121 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
5123 fprintf(fout, " %s = %s;",
5124 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5125 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5130 assert_operand_cnt(2);
5131 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5132 fprintf(fout, " tmp = %s;",
5133 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
5134 fprintf(fout, " %s = %s;",
5135 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5136 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5137 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5138 fprintf(fout, " %s = %stmp;",
5139 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
5140 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
5141 snprintf(g_comment, sizeof(g_comment), "xchg");
5145 assert_operand_cnt(1);
5146 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5147 fprintf(fout, " %s = ~%s;", buf1, buf1);
5151 assert_operand_cnt(2);
5152 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5153 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5154 fprintf(fout, " %s = *(u8 *)(%s + %s);", buf1, buf2, buf1);
5155 strcpy(g_comment, "xlat");
5159 assert_operand_cnt(2);
5160 fprintf(fout, " %s = (s32)%s >> 31;",
5161 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5162 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5163 strcpy(g_comment, "cdq");
5167 assert_operand_cnt(3);
5168 if (po->flags & OPF_REP) {
5173 fprintf(fout, " eax = %sesi; esi %c= %d;",
5174 lmod_cast_u_ptr(po, po->operand[0].lmod),
5175 (po->flags & OPF_DF) ? '-' : '+',
5176 lmod_bytes(po, po->operand[0].lmod));
5177 strcpy(g_comment, "lods");
5182 assert_operand_cnt(3);
5183 if (po->flags & OPF_REP) {
5184 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
5185 (po->flags & OPF_DF) ? '-' : '+',
5186 lmod_bytes(po, po->operand[0].lmod));
5187 fprintf(fout, " %sedi = eax;",
5188 lmod_cast_u_ptr(po, po->operand[0].lmod));
5189 strcpy(g_comment, "rep stos");
5192 fprintf(fout, " %sedi = eax; edi %c= %d;",
5193 lmod_cast_u_ptr(po, po->operand[0].lmod),
5194 (po->flags & OPF_DF) ? '-' : '+',
5195 lmod_bytes(po, po->operand[0].lmod));
5196 strcpy(g_comment, "stos");
5201 assert_operand_cnt(3);
5202 j = lmod_bytes(po, po->operand[0].lmod);
5203 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
5204 l = (po->flags & OPF_DF) ? '-' : '+';
5205 if (po->flags & OPF_REP) {
5207 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
5210 " %sedi = %sesi;", buf1, buf1);
5211 strcpy(g_comment, "rep movs");
5214 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
5215 buf1, buf1, l, j, l, j);
5216 strcpy(g_comment, "movs");
5221 // repe ~ repeat while ZF=1
5222 assert_operand_cnt(3);
5223 j = lmod_bytes(po, po->operand[0].lmod);
5224 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
5225 l = (po->flags & OPF_DF) ? '-' : '+';
5226 if (po->flags & OPF_REP) {
5228 " for (; ecx != 0; ecx--) {\n");
5229 if (pfomask & (1 << PFO_C)) {
5232 " cond_c = %sesi < %sedi;\n", buf1, buf1);
5233 pfomask &= ~(1 << PFO_C);
5236 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
5237 buf1, buf1, l, j, l, j);
5239 " if (cond_z %s 0) break;\n",
5240 (po->flags & OPF_REPZ) ? "==" : "!=");
5243 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
5244 (po->flags & OPF_REPZ) ? "e" : "ne");
5248 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
5249 buf1, buf1, l, j, l, j);
5250 strcpy(g_comment, "cmps");
5252 pfomask &= ~(1 << PFO_Z);
5253 last_arith_dst = NULL;
5254 delayed_flag_op = NULL;
5258 // only does ZF (for now)
5259 // repe ~ repeat while ZF=1
5260 assert_operand_cnt(3);
5261 j = lmod_bytes(po, po->operand[0].lmod);
5262 l = (po->flags & OPF_DF) ? '-' : '+';
5263 if (po->flags & OPF_REP) {
5265 " for (; ecx != 0; ecx--) {\n");
5267 " cond_z = (%seax == %sedi); edi %c= %d;\n",
5268 lmod_cast_u(po, po->operand[0].lmod),
5269 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5271 " if (cond_z %s 0) break;\n",
5272 (po->flags & OPF_REPZ) ? "==" : "!=");
5275 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
5276 (po->flags & OPF_REPZ) ? "e" : "ne");
5279 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
5280 lmod_cast_u(po, po->operand[0].lmod),
5281 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5282 strcpy(g_comment, "scas");
5284 pfomask &= ~(1 << PFO_Z);
5285 last_arith_dst = NULL;
5286 delayed_flag_op = NULL;
5289 // arithmetic w/flags
5291 if (po->operand[1].type == OPT_CONST && !po->operand[1].val)
5292 goto dualop_arith_const;
5293 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5297 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5298 if (po->operand[1].type == OPT_CONST) {
5299 j = lmod_bytes(po, po->operand[0].lmod);
5300 if (((1ull << j * 8) - 1) == po->operand[1].val)
5301 goto dualop_arith_const;
5306 assert_operand_cnt(2);
5307 fprintf(fout, " %s %s= %s;",
5308 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5310 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5311 output_std_flags(fout, po, &pfomask, buf1);
5312 last_arith_dst = &po->operand[0];
5313 delayed_flag_op = NULL;
5317 // and 0, or ~0 used instead mov
5318 assert_operand_cnt(2);
5319 fprintf(fout, " %s = %s;",
5320 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5321 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5322 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5323 output_std_flags(fout, po, &pfomask, buf1);
5324 last_arith_dst = &po->operand[0];
5325 delayed_flag_op = NULL;
5330 assert_operand_cnt(2);
5331 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5332 if (pfomask & (1 << PFO_C)) {
5333 if (po->operand[1].type == OPT_CONST) {
5334 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5335 j = po->operand[1].val;
5338 if (po->op == OP_SHL)
5342 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
5346 ferr(po, "zero shift?\n");
5350 pfomask &= ~(1 << PFO_C);
5352 fprintf(fout, " %s %s= %s", buf1, op_to_c(po),
5353 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5354 if (po->operand[1].type != OPT_CONST)
5355 fprintf(fout, " & 0x1f");
5357 output_std_flags(fout, po, &pfomask, buf1);
5358 last_arith_dst = &po->operand[0];
5359 delayed_flag_op = NULL;
5363 assert_operand_cnt(2);
5364 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5365 fprintf(fout, " %s = %s%s >> %s;", buf1,
5366 lmod_cast_s(po, po->operand[0].lmod), buf1,
5367 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5368 output_std_flags(fout, po, &pfomask, buf1);
5369 last_arith_dst = &po->operand[0];
5370 delayed_flag_op = NULL;
5375 assert_operand_cnt(3);
5376 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5377 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5378 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5379 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5380 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
5381 if (po->operand[2].type != OPT_CONST)
5382 ferr(po, "TODO: masking\n");
5383 if (po->op == OP_SHLD) {
5384 fprintf(fout, " %s <<= %s; %s |= %s >> (%d - %s);",
5385 buf1, buf3, buf1, buf2, l, buf3);
5386 strcpy(g_comment, "shld");
5389 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
5390 buf1, buf3, buf1, buf2, l, buf3);
5391 strcpy(g_comment, "shrd");
5393 output_std_flags(fout, po, &pfomask, buf1);
5394 last_arith_dst = &po->operand[0];
5395 delayed_flag_op = NULL;
5400 assert_operand_cnt(2);
5401 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5402 if (po->operand[1].type == OPT_CONST) {
5403 j = po->operand[1].val;
5404 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
5405 fprintf(fout, po->op == OP_ROL ?
5406 " %s = (%s << %d) | (%s >> %d);" :
5407 " %s = (%s >> %d) | (%s << %d);",
5408 buf1, buf1, j, buf1,
5409 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
5413 output_std_flags(fout, po, &pfomask, buf1);
5414 last_arith_dst = &po->operand[0];
5415 delayed_flag_op = NULL;
5420 assert_operand_cnt(2);
5421 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5422 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5423 if (po->operand[1].type == OPT_CONST) {
5424 j = po->operand[1].val % l;
5426 ferr(po, "zero rotate\n");
5427 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
5428 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
5429 if (po->op == OP_RCL) {
5431 " %s = (%s << %d) | (cond_c << %d)",
5432 buf1, buf1, j, j - 1);
5434 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
5438 " %s = (%s >> %d) | (cond_c << %d)",
5439 buf1, buf1, j, l - j);
5441 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
5443 fprintf(fout, ";\n");
5444 fprintf(fout, " cond_c = tmp;");
5448 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
5449 output_std_flags(fout, po, &pfomask, buf1);
5450 last_arith_dst = &po->operand[0];
5451 delayed_flag_op = NULL;
5455 assert_operand_cnt(2);
5456 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5457 if (IS(opr_name(po, 0), opr_name(po, 1))) {
5458 // special case for XOR
5459 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
5460 fprintf(fout, " cond_be = 1;\n");
5461 pfomask &= ~(1 << PFO_BE);
5463 fprintf(fout, " %s = 0;",
5464 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5465 last_arith_dst = &po->operand[0];
5466 delayed_flag_op = NULL;
5472 assert_operand_cnt(2);
5473 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5474 if (pfomask & (1 << PFO_C)) {
5475 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5476 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5477 if (po->operand[0].lmod == OPLM_DWORD) {
5478 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
5479 fprintf(fout, " cond_c = tmp64 >> 32;\n");
5480 fprintf(fout, " %s = (u32)tmp64;",
5481 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5482 strcat(g_comment, "add64");
5485 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
5486 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
5487 fprintf(fout, " %s += %s;",
5488 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5491 pfomask &= ~(1 << PFO_C);
5492 output_std_flags(fout, po, &pfomask, buf1);
5493 last_arith_dst = &po->operand[0];
5494 delayed_flag_op = NULL;
5500 assert_operand_cnt(2);
5501 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5502 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
5503 for (j = 0; j <= PFO_LE; j++) {
5504 if (!(pfomask & (1 << j)))
5506 if (j == PFO_Z || j == PFO_S)
5509 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5510 fprintf(fout, " cond_%s = %s;\n",
5511 parsed_flag_op_names[j], buf1);
5512 pfomask &= ~(1 << j);
5519 assert_operand_cnt(2);
5520 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5521 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5522 if (po->op == OP_SBB
5523 && IS(po->operand[0].name, po->operand[1].name))
5525 // avoid use of unitialized var
5526 fprintf(fout, " %s = -cond_c;", buf1);
5527 // carry remains what it was
5528 pfomask &= ~(1 << PFO_C);
5531 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
5532 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5534 output_std_flags(fout, po, &pfomask, buf1);
5535 last_arith_dst = &po->operand[0];
5536 delayed_flag_op = NULL;
5540 assert_operand_cnt(2);
5541 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5542 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
5543 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5545 output_std_flags(fout, po, &pfomask, buf1);
5546 last_arith_dst = &po->operand[0];
5547 delayed_flag_op = NULL;
5548 strcat(g_comment, "bsf");
5552 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
5553 for (j = 0; j <= PFO_LE; j++) {
5554 if (!(pfomask & (1 << j)))
5556 if (j == PFO_Z || j == PFO_S || j == PFO_C)
5559 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5560 fprintf(fout, " cond_%s = %s;\n",
5561 parsed_flag_op_names[j], buf1);
5562 pfomask &= ~(1 << j);
5568 if (pfomask & (1 << PFO_C))
5569 // carry is unaffected by inc/dec.. wtf?
5570 ferr(po, "carry propagation needed\n");
5572 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5573 if (po->operand[0].type == OPT_REG) {
5574 strcpy(buf2, po->op == OP_INC ? "++" : "--");
5575 fprintf(fout, " %s%s;", buf1, buf2);
5578 strcpy(buf2, po->op == OP_INC ? "+" : "-");
5579 fprintf(fout, " %s %s= 1;", buf1, buf2);
5581 output_std_flags(fout, po, &pfomask, buf1);
5582 last_arith_dst = &po->operand[0];
5583 delayed_flag_op = NULL;
5587 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5588 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5589 fprintf(fout, " %s = -%s%s;", buf1,
5590 lmod_cast_s(po, po->operand[0].lmod), buf2);
5591 last_arith_dst = &po->operand[0];
5592 delayed_flag_op = NULL;
5593 if (pfomask & (1 << PFO_C)) {
5594 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
5595 pfomask &= ~(1 << PFO_C);
5600 if (po->operand_cnt == 2) {
5601 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5604 if (po->operand_cnt == 3)
5605 ferr(po, "TODO imul3\n");
5608 assert_operand_cnt(1);
5609 switch (po->operand[0].lmod) {
5611 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5612 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
5613 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5614 fprintf(fout, " edx = tmp64 >> 32;\n");
5615 fprintf(fout, " eax = tmp64;");
5618 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5619 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
5620 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5624 ferr(po, "TODO: unhandled mul type\n");
5627 last_arith_dst = NULL;
5628 delayed_flag_op = NULL;
5633 assert_operand_cnt(1);
5634 if (po->operand[0].lmod != OPLM_DWORD)
5635 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5637 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5638 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5639 po->op == OP_IDIV));
5640 switch (po->operand[0].lmod) {
5642 if (po->flags & OPF_32BIT)
5643 snprintf(buf3, sizeof(buf3), "%seax", buf2);
5645 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
5646 snprintf(buf3, sizeof(buf3), "%stmp64",
5647 (po->op == OP_IDIV) ? "(s64)" : "");
5649 if (po->operand[0].type == OPT_REG
5650 && po->operand[0].reg == xDX)
5652 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5653 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5656 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5657 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5661 ferr(po, "unhandled division type\n");
5663 last_arith_dst = NULL;
5664 delayed_flag_op = NULL;
5669 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5671 for (j = 0; j < 8; j++) {
5672 if (pfomask & (1 << j)) {
5673 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5674 fprintf(fout, " cond_%s = %s;",
5675 parsed_flag_op_names[j], buf1);
5682 last_arith_dst = NULL;
5683 delayed_flag_op = po;
5687 // SETcc - should already be handled
5690 // note: we reuse OP_Jcc for SETcc, only flags differ
5692 fprintf(fout, "\n goto %s;", po->operand[0].name);
5696 fprintf(fout, " if (ecx == 0)\n");
5697 fprintf(fout, " goto %s;", po->operand[0].name);
5698 strcat(g_comment, "jecxz");
5702 fprintf(fout, " if (--ecx == 0)\n");
5703 fprintf(fout, " goto %s;", po->operand[0].name);
5704 strcat(g_comment, "loop");
5708 assert_operand_cnt(1);
5709 last_arith_dst = NULL;
5710 delayed_flag_op = NULL;
5712 if (po->operand[0].type == OPT_REGMEM) {
5713 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5716 ferr(po, "parse failure for jmp '%s'\n",
5717 po->operand[0].name);
5718 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
5721 else if (po->operand[0].type != OPT_LABEL)
5722 ferr(po, "unhandled jmp type\n");
5724 fprintf(fout, " goto %s;", po->operand[0].name);
5728 assert_operand_cnt(1);
5730 my_assert_not(pp, NULL);
5733 if (po->flags & OPF_CC) {
5734 // we treat conditional branch to another func
5735 // (yes such code exists..) as conditional tailcall
5737 fprintf(fout, " {\n");
5740 if (pp->is_fptr && !pp->is_arg) {
5741 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5742 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5744 if (pp->is_unresolved)
5745 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5746 buf3, asmfn, po->asmln, pp->name);
5749 fprintf(fout, "%s", buf3);
5750 if (strstr(pp->ret_type.name, "int64")) {
5751 if (po->flags & OPF_TAIL)
5752 ferr(po, "int64 and tail?\n");
5753 fprintf(fout, "tmp64 = ");
5755 else if (!IS(pp->ret_type.name, "void")) {
5756 if (po->flags & OPF_TAIL) {
5757 if (!IS(g_func_pp->ret_type.name, "void")) {
5758 fprintf(fout, "return ");
5759 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5760 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5763 else if (regmask & (1 << xAX)) {
5764 fprintf(fout, "eax = ");
5765 if (pp->ret_type.is_ptr)
5766 fprintf(fout, "(u32)");
5770 if (pp->name[0] == 0)
5771 ferr(po, "missing pp->name\n");
5772 fprintf(fout, "%s%s(", pp->name,
5773 pp->has_structarg ? "_sa" : "");
5775 if (po->flags & OPF_ATAIL) {
5776 if (pp->argc_stack != g_func_pp->argc_stack
5777 || (pp->argc_stack > 0
5778 && pp->is_stdcall != g_func_pp->is_stdcall))
5779 ferr(po, "incompatible tailcall\n");
5780 if (g_func_pp->has_retreg)
5781 ferr(po, "TODO: retreg+tailcall\n");
5783 for (arg = j = 0; arg < pp->argc; arg++) {
5785 fprintf(fout, ", ");
5788 if (pp->arg[arg].type.is_ptr)
5789 snprintf(cast, sizeof(cast), "(%s)",
5790 pp->arg[arg].type.name);
5792 if (pp->arg[arg].reg != NULL) {
5793 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5797 for (; j < g_func_pp->argc; j++)
5798 if (g_func_pp->arg[j].reg == NULL)
5800 fprintf(fout, "%sa%d", cast, j + 1);
5805 for (arg = 0; arg < pp->argc; arg++) {
5807 fprintf(fout, ", ");
5810 if (pp->arg[arg].type.is_ptr)
5811 snprintf(cast, sizeof(cast), "(%s)",
5812 pp->arg[arg].type.name);
5814 if (pp->arg[arg].reg != NULL) {
5815 if (pp->arg[arg].type.is_retreg)
5816 fprintf(fout, "&%s", pp->arg[arg].reg);
5818 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5823 tmp_op = pp->arg[arg].datap;
5825 ferr(po, "parsed_op missing for arg%d\n", arg);
5827 if (tmp_op->flags & OPF_VAPUSH) {
5828 fprintf(fout, "ap");
5830 else if (tmp_op->p_argpass != 0) {
5831 fprintf(fout, "a%d", tmp_op->p_argpass);
5833 else if (tmp_op->p_argnum != 0) {
5834 fprintf(fout, "%s%s", cast,
5835 saved_arg_name(buf1, sizeof(buf1),
5836 tmp_op->p_arggrp, tmp_op->p_argnum));
5840 out_src_opr(buf1, sizeof(buf1),
5841 tmp_op, &tmp_op->operand[0], cast, 0));
5845 fprintf(fout, ");");
5847 if (strstr(pp->ret_type.name, "int64")) {
5848 fprintf(fout, "\n");
5849 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5850 fprintf(fout, "%seax = tmp64;", buf3);
5853 if (pp->is_unresolved) {
5854 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
5856 strcat(g_comment, buf2);
5859 if (po->flags & OPF_TAIL) {
5861 if (i == opcnt - 1 || pp->is_noreturn)
5863 else if (IS(pp->ret_type.name, "void"))
5865 else if (IS(g_func_pp->ret_type.name, "void"))
5867 // else already handled as 'return f()'
5870 if (!IS(g_func_pp->ret_type.name, "void")) {
5871 ferr(po, "int func -> void func tailcall?\n");
5874 fprintf(fout, "\n%sreturn;", buf3);
5875 strcat(g_comment, " ^ tailcall");
5879 strcat(g_comment, " tailcall");
5881 if (pp->is_noreturn)
5882 strcat(g_comment, " noreturn");
5883 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5884 strcat(g_comment, " argframe");
5885 if (po->flags & OPF_CC)
5886 strcat(g_comment, " cond");
5888 if (po->flags & OPF_CC)
5889 fprintf(fout, "\n }");
5891 delayed_flag_op = NULL;
5892 last_arith_dst = NULL;
5896 if (g_func_pp->is_vararg)
5897 fprintf(fout, " va_end(ap);\n");
5898 if (g_func_pp->has_retreg) {
5899 for (arg = 0; arg < g_func_pp->argc; arg++)
5900 if (g_func_pp->arg[arg].type.is_retreg)
5901 fprintf(fout, " *r_%s = %s;\n",
5902 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
5905 if (IS(g_func_pp->ret_type.name, "void")) {
5906 if (i != opcnt - 1 || label_pending)
5907 fprintf(fout, " return;");
5909 else if (g_func_pp->ret_type.is_ptr) {
5910 fprintf(fout, " return (%s)eax;",
5911 g_func_pp->ret_type.name);
5913 else if (IS(g_func_pp->ret_type.name, "__int64"))
5914 fprintf(fout, " return ((u64)edx << 32) | eax;");
5916 fprintf(fout, " return eax;");
5918 last_arith_dst = NULL;
5919 delayed_flag_op = NULL;
5923 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5924 if (po->p_argnum != 0) {
5925 // special case - saved func arg
5926 fprintf(fout, " %s = %s;",
5927 saved_arg_name(buf2, sizeof(buf2),
5928 po->p_arggrp, po->p_argnum), buf1);
5931 else if (po->flags & OPF_RSAVE) {
5932 fprintf(fout, " s_%s = %s;", buf1, buf1);
5935 else if (po->flags & OPF_PPUSH) {
5937 ferr_assert(po, tmp_op != NULL);
5938 out_dst_opr(buf2, sizeof(buf2), po, &tmp_op->operand[0]);
5939 fprintf(fout, " pp_%s = %s;", buf2, buf1);
5942 else if (g_func_pp->is_userstack) {
5943 fprintf(fout, " *(--esp) = %s;", buf1);
5946 if (!(g_ida_func_attr & IDAFA_NORETURN))
5947 ferr(po, "stray push encountered\n");
5952 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5953 if (po->flags & OPF_RSAVE) {
5954 fprintf(fout, " %s = s_%s;", buf1, buf1);
5957 else if (po->flags & OPF_PPUSH) {
5958 // push/pop graph / non-const
5959 ferr_assert(po, po->datap == NULL);
5960 fprintf(fout, " %s = pp_%s;", buf1, buf1);
5963 else if (po->datap != NULL) {
5966 fprintf(fout, " %s = %s;", buf1,
5967 out_src_opr(buf2, sizeof(buf2),
5968 tmp_op, &tmp_op->operand[0],
5969 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5972 else if (g_func_pp->is_userstack) {
5973 fprintf(fout, " %s = *esp++;", buf1);
5977 ferr(po, "stray pop encountered\n");
5986 strcpy(g_comment, "(emms)");
5991 ferr(po, "unhandled op type %d, flags %x\n",
5996 if (g_comment[0] != 0) {
5997 char *p = g_comment;
5998 while (my_isblank(*p))
6000 fprintf(fout, " // %s", p);
6005 fprintf(fout, "\n");
6007 // some sanity checking
6008 if (po->flags & OPF_REP) {
6009 if (po->op != OP_STOS && po->op != OP_MOVS
6010 && po->op != OP_CMPS && po->op != OP_SCAS)
6011 ferr(po, "unexpected rep\n");
6012 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
6013 && (po->op == OP_CMPS || po->op == OP_SCAS))
6014 ferr(po, "cmps/scas with plain rep\n");
6016 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
6017 && po->op != OP_CMPS && po->op != OP_SCAS)
6018 ferr(po, "unexpected repz/repnz\n");
6021 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
6023 // see is delayed flag stuff is still valid
6024 if (delayed_flag_op != NULL && delayed_flag_op != po) {
6025 if (is_any_opr_modified(delayed_flag_op, po, 0))
6026 delayed_flag_op = NULL;
6029 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
6030 if (is_opr_modified(last_arith_dst, po))
6031 last_arith_dst = NULL;
6037 if (g_stack_fsz && !g_stack_frame_used)
6038 fprintf(fout, " (void)sf;\n");
6040 fprintf(fout, "}\n\n");
6042 gen_x_cleanup(opcnt);
6045 static void gen_x_cleanup(int opcnt)
6049 for (i = 0; i < opcnt; i++) {
6050 struct label_ref *lr, *lr_del;
6052 lr = g_label_refs[i].next;
6053 while (lr != NULL) {
6058 g_label_refs[i].i = -1;
6059 g_label_refs[i].next = NULL;
6061 if (ops[i].op == OP_CALL) {
6063 proto_release(ops[i].pp);
6069 struct func_proto_dep;
6071 struct func_prototype {
6076 int has_ret:3; // -1, 0, 1: unresolved, no, yes
6077 unsigned int dep_resolved:1;
6078 unsigned int is_stdcall:1;
6079 struct func_proto_dep *dep_func;
6081 const struct parsed_proto *pp; // seed pp, if any
6084 struct func_proto_dep {
6086 struct func_prototype *proto;
6087 int regmask_live; // .. at the time of call
6088 unsigned int ret_dep:1; // return from this is caller's return
6091 static struct func_prototype *hg_fp;
6092 static int hg_fp_cnt;
6094 static struct scanned_var {
6096 enum opr_lenmod lmod;
6097 unsigned int is_seeded:1;
6098 unsigned int is_c_str:1;
6099 const struct parsed_proto *pp; // seed pp, if any
6101 static int hg_var_cnt;
6103 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6106 struct func_prototype *hg_fp_add(const char *funcn)
6108 struct func_prototype *fp;
6110 if ((hg_fp_cnt & 0xff) == 0) {
6111 hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
6112 my_assert_not(hg_fp, NULL);
6113 memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
6116 fp = &hg_fp[hg_fp_cnt];
6117 snprintf(fp->name, sizeof(fp->name), "%s", funcn);
6119 fp->argc_stack = -1;
6125 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
6130 for (i = 0; i < fp->dep_func_cnt; i++)
6131 if (IS(fp->dep_func[i].name, name))
6132 return &fp->dep_func[i];
6137 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
6140 if (hg_fp_find_dep(fp, name))
6143 if ((fp->dep_func_cnt & 0xff) == 0) {
6144 fp->dep_func = realloc(fp->dep_func,
6145 sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
6146 my_assert_not(fp->dep_func, NULL);
6147 memset(&fp->dep_func[fp->dep_func_cnt], 0,
6148 sizeof(fp->dep_func[0]) * 0x100);
6150 fp->dep_func[fp->dep_func_cnt].name = strdup(name);
6154 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
6156 const struct func_prototype *p1 = p1_, *p2 = p2_;
6157 return strcmp(p1->name, p2->name);
6161 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
6163 const struct func_prototype *p1 = p1_, *p2 = p2_;
6164 return p1->id - p2->id;
6168 // recursive register dep pass
6169 // - track saved regs (part 2)
6170 // - try to figure out arg-regs
6171 // - calculate reg deps
6172 static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
6173 struct func_prototype *fp, int regmask_save, int regmask_dst,
6174 int *regmask_dep, int *has_ret)
6176 struct func_proto_dep *dep;
6177 struct parsed_op *po;
6178 int from_caller = 0;
6184 for (; i < opcnt; i++)
6186 if (cbits[i >> 3] & (1 << (i & 7)))
6188 cbits[i >> 3] |= (1 << (i & 7));
6192 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
6193 if (po->flags & OPF_RMD)
6196 if (po->btj != NULL) {
6198 for (j = 0; j < po->btj->count; j++) {
6199 check_i(po, po->btj->d[j].bt_i);
6200 gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
6201 regmask_save, regmask_dst, regmask_dep, has_ret);
6206 check_i(po, po->bt_i);
6207 if (po->flags & OPF_CJMP) {
6208 gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
6209 regmask_save, regmask_dst, regmask_dep, has_ret);
6217 if (po->flags & OPF_FARG)
6218 /* (just calculate register deps) */;
6219 else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
6221 reg = po->operand[0].reg;
6223 ferr(po, "reg not set for push?\n");
6225 if (po->flags & OPF_RSAVE) {
6226 regmask_save |= 1 << reg;
6229 if (po->flags & OPF_DONE)
6233 ret = scan_for_pop(i + 1, opcnt, i + opcnt * 2,
6234 po->operand[0].reg, 0, &depth, 0);
6236 regmask_save |= 1 << reg;
6237 po->flags |= OPF_RMD;
6238 scan_for_pop(i + 1, opcnt, i + opcnt * 3,
6239 po->operand[0].reg, 0, &depth, 1);
6243 else if (po->flags & OPF_RMD)
6245 else if (po->op == OP_CALL) {
6246 po->regmask_dst |= 1 << xAX;
6248 dep = hg_fp_find_dep(fp, po->operand[0].name);
6250 dep->regmask_live = regmask_save | regmask_dst;
6252 else if (po->op == OP_RET) {
6253 if (po->operand_cnt > 0) {
6255 if (fp->argc_stack >= 0
6256 && fp->argc_stack != po->operand[0].val / 4)
6257 ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
6258 fp->argc_stack = po->operand[0].val / 4;
6262 // if has_ret is 0, there is uninitialized eax path,
6263 // which means it's most likely void func
6264 if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
6265 if (po->op == OP_CALL) {
6270 struct parsed_opr opr = { 0, };
6275 ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
6278 if (ret != 1 && from_caller) {
6279 // unresolved eax - probably void func
6283 if (j >= 0 && ops[j].op == OP_CALL) {
6284 dep = hg_fp_find_dep(fp, ops[j].operand[0].name);
6295 l = regmask_save | regmask_dst;
6296 if (g_bp_frame && !(po->flags & OPF_EBP_S))
6299 l = po->regmask_src & ~l;
6302 fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
6303 l, regmask_dst, regmask_save, po->flags);
6306 regmask_dst |= po->regmask_dst;
6308 if (po->flags & OPF_TAIL)
6313 static void gen_hdr(const char *funcn, int opcnt)
6315 int save_arg_vars[MAX_ARG_GRP] = { 0, };
6316 unsigned char cbits[MAX_OPS / 8];
6317 const struct parsed_proto *pp_c;
6318 struct parsed_proto *pp;
6319 struct func_prototype *fp;
6320 struct parsed_op *po;
6321 int regmask_dummy = 0;
6323 int max_bp_offset = 0;
6328 pp_c = proto_parse(g_fhdr, funcn, 1);
6330 // already in seed, will add to hg_fp later
6333 fp = hg_fp_add(funcn);
6335 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
6336 g_stack_frame_used = 0;
6339 // - resolve all branches
6340 // - parse calls with labels
6341 resolve_branches_parse_calls(opcnt);
6344 // - handle ebp/esp frame, remove ops related to it
6345 scan_prologue_epilogue(opcnt);
6348 // - remove dead labels
6350 for (i = 0; i < opcnt; i++)
6352 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6358 if (po->flags & (OPF_RMD|OPF_DONE))
6361 if (po->op == OP_CALL) {
6362 if (po->operand[0].type == OPT_LABEL)
6363 hg_fp_add_dep(fp, opr_name(po, 0));
6364 else if (po->pp != NULL)
6365 hg_fp_add_dep(fp, po->pp->name);
6370 // - remove dead labels
6371 // - handle push <const>/pop pairs
6372 for (i = 0; i < opcnt; i++)
6374 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6380 if (po->flags & (OPF_RMD|OPF_DONE))
6383 if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
6384 scan_for_pop_const(i, opcnt, i + opcnt * 13);
6388 // - process trivial calls
6389 for (i = 0; i < opcnt; i++)
6392 if (po->flags & (OPF_RMD|OPF_DONE))
6395 if (po->op == OP_CALL)
6397 pp = process_call_early(i, opcnt, &j);
6399 if (!(po->flags & OPF_ATAIL))
6400 // since we know the args, try to collect them
6401 if (collect_call_args_early(po, i, pp, ®mask_dummy) != 0)
6407 // commit esp adjust
6408 if (ops[j].op != OP_POP)
6409 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
6411 for (l = 0; l < pp->argc_stack; l++)
6412 ops[j + l].flags |= OPF_DONE | OPF_RMD;
6416 po->flags |= OPF_DONE;
6422 // - track saved regs (simple)
6424 for (i = 0; i < opcnt; i++)
6427 if (po->flags & (OPF_RMD|OPF_DONE))
6430 if (po->op == OP_PUSH && po->operand[0].type == OPT_REG
6431 && po->operand[0].reg != xCX)
6433 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, 0);
6435 // regmask_save |= 1 << po->operand[0].reg; // do it later
6436 po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
6437 scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, OPF_RMD);
6440 else if (po->op == OP_CALL)
6442 pp = process_call(i, opcnt);
6444 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
6445 // since we know the args, collect them
6446 ret = collect_call_args(po, i, pp, ®mask_dummy, save_arg_vars,
6453 memset(cbits, 0, sizeof(cbits));
6457 gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, ®mask_dep, &has_ret);
6459 // find unreachable code - must be fixed in IDA
6460 for (i = 0; i < opcnt; i++)
6462 if (cbits[i >> 3] & (1 << (i & 7)))
6465 if (g_labels[i] == NULL && i > 0 && ops[i - 1].op == OP_CALL
6466 && ops[i - 1].pp != NULL && ops[i - 1].pp->is_osinc)
6468 // the compiler sometimes still generates code after
6469 // noreturn OS functions
6472 if (ops[i].op != OP_NOP)
6473 ferr(&ops[i], "unreachable code\n");
6476 for (i = 0; i < g_eqcnt; i++) {
6477 if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
6478 max_bp_offset = g_eqs[i].offset;
6481 if (fp->argc_stack < 0) {
6482 max_bp_offset = (max_bp_offset + 3) & ~3;
6483 fp->argc_stack = max_bp_offset / 4;
6484 if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
6488 fp->regmask_dep = regmask_dep & ~(1 << xSP);
6489 fp->has_ret = has_ret;
6491 printf("// has_ret %d, regmask_dep %x\n",
6492 fp->has_ret, fp->regmask_dep);
6493 output_hdr_fp(stdout, fp, 1);
6494 if (IS(funcn, "sub_10007F72")) exit(1);
6497 gen_x_cleanup(opcnt);
6500 static void hg_fp_resolve_deps(struct func_prototype *fp)
6502 struct func_prototype fp_s;
6506 // this thing is recursive, so mark first..
6507 fp->dep_resolved = 1;
6509 for (i = 0; i < fp->dep_func_cnt; i++) {
6510 strcpy(fp_s.name, fp->dep_func[i].name);
6511 fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
6512 sizeof(hg_fp[0]), hg_fp_cmp_name);
6513 if (fp->dep_func[i].proto != NULL) {
6514 if (!fp->dep_func[i].proto->dep_resolved)
6515 hg_fp_resolve_deps(fp->dep_func[i].proto);
6517 dep = ~fp->dep_func[i].regmask_live
6518 & fp->dep_func[i].proto->regmask_dep;
6519 fp->regmask_dep |= dep;
6520 // printf("dep %s %s |= %x\n", fp->name,
6521 // fp->dep_func[i].name, dep);
6523 if (fp->has_ret == -1 && fp->dep_func[i].ret_dep)
6524 fp->has_ret = fp->dep_func[i].proto->has_ret;
6529 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6532 const struct parsed_proto *pp;
6533 char *p, namebuf[NAMELEN];
6539 for (; count > 0; count--, fp++) {
6540 if (fp->has_ret == -1)
6541 fprintf(fout, "// ret unresolved\n");
6543 fprintf(fout, "// dep:");
6544 for (j = 0; j < fp->dep_func_cnt; j++) {
6545 fprintf(fout, " %s/", fp->dep_func[j].name);
6546 if (fp->dep_func[j].proto != NULL)
6547 fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6548 fp->dep_func[j].proto->has_ret);
6550 fprintf(fout, "\n");
6553 p = strchr(fp->name, '@');
6555 memcpy(namebuf, fp->name, p - fp->name);
6556 namebuf[p - fp->name] = 0;
6564 pp = proto_parse(g_fhdr, name, 1);
6565 if (pp != NULL && pp->is_include)
6568 if (fp->pp != NULL) {
6569 // part of seed, output later
6573 regmask_dep = fp->regmask_dep;
6574 argc_stack = fp->argc_stack;
6576 fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6577 (fp->has_ret ? "int" : "void"));
6578 if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6579 && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6581 fprintf(fout, " __fastcall ");
6582 if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6588 else if (regmask_dep && !fp->is_stdcall) {
6589 fprintf(fout, "/*__usercall*/ ");
6591 else if (regmask_dep) {
6592 fprintf(fout, "/*__userpurge*/ ");
6594 else if (fp->is_stdcall)
6595 fprintf(fout, " __stdcall ");
6597 fprintf(fout, " __cdecl ");
6599 fprintf(fout, "%s(", name);
6602 for (j = 0; j < xSP; j++) {
6603 if (regmask_dep & (1 << j)) {
6606 fprintf(fout, ", ");
6608 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6610 fprintf(fout, "int");
6611 fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
6615 for (j = 0; j < argc_stack; j++) {
6618 fprintf(fout, ", ");
6619 if (fp->pp != NULL) {
6620 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6621 if (!fp->pp->arg[arg - 1].type.is_ptr)
6625 fprintf(fout, "int ");
6626 fprintf(fout, "a%d", arg);
6629 fprintf(fout, ");\n");
6633 static void output_hdr(FILE *fout)
6635 static const char *lmod_c_names[] = {
6636 [OPLM_UNSPEC] = "???",
6637 [OPLM_BYTE] = "uint8_t",
6638 [OPLM_WORD] = "uint16_t",
6639 [OPLM_DWORD] = "uint32_t",
6640 [OPLM_QWORD] = "uint64_t",
6642 const struct scanned_var *var;
6643 struct func_prototype *fp;
6644 char line[256] = { 0, };
6648 // add stuff from headers
6649 for (i = 0; i < pp_cache_size; i++) {
6650 if (pp_cache[i].is_cinc && !pp_cache[i].is_stdcall)
6651 snprintf(name, sizeof(name), "_%s", pp_cache[i].name);
6653 snprintf(name, sizeof(name), "%s", pp_cache[i].name);
6654 fp = hg_fp_add(name);
6655 fp->pp = &pp_cache[i];
6656 fp->argc_stack = fp->pp->argc_stack;
6657 fp->is_stdcall = fp->pp->is_stdcall;
6658 fp->regmask_dep = get_pp_arg_regmask(fp->pp);
6659 fp->has_ret = !IS(fp->pp->ret_type.name, "void");
6663 qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6664 for (i = 0; i < hg_fp_cnt; i++)
6665 hg_fp_resolve_deps(&hg_fp[i]);
6667 // note: messes up .proto ptr, don't use
6668 //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6671 for (i = 0; i < hg_var_cnt; i++) {
6674 if (var->pp != NULL)
6677 else if (var->is_c_str)
6678 fprintf(fout, "extern %-8s %s[];", "char", var->name);
6680 fprintf(fout, "extern %-8s %s;",
6681 lmod_c_names[var->lmod], var->name);
6684 fprintf(fout, " // seeded");
6685 fprintf(fout, "\n");
6688 fprintf(fout, "\n");
6690 // output function prototypes
6691 output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6694 fprintf(fout, "\n// - seed -\n");
6697 while (fgets(line, sizeof(line), g_fhdr))
6698 fwrite(line, 1, strlen(line), fout);
6701 // '=' needs special treatment
6703 static char *next_word_s(char *w, size_t wsize, char *s)
6712 for (i = 1; i < wsize - 1; i++) {
6714 printf("warning: missing closing quote: \"%s\"\n", s);
6723 for (; i < wsize - 1; i++) {
6724 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6730 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6731 printf("warning: '%s' truncated\n", w);
6736 static void scan_variables(FILE *fasm)
6738 struct scanned_var *var;
6739 char line[256] = { 0, };
6747 // skip to next data section
6748 while (my_fgets(line, sizeof(line), fasm))
6753 if (*p == 0 || *p == ';')
6756 p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6757 if (*p == 0 || *p == ';')
6760 if (*p != 's' || !IS_START(p, "segment para public"))
6766 if (p == NULL || !IS_START(p, "segment para public"))
6770 if (!IS_START(p, "'DATA'"))
6774 while (my_fgets(line, sizeof(line), fasm))
6783 if (*p == 0 || *p == ';')
6786 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6787 words[wordc][0] = 0;
6788 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6789 if (*p == 0 || *p == ';') {
6795 if (wordc == 2 && IS(words[1], "ends"))
6800 if (IS_START(words[0], "__IMPORT_DESCRIPTOR_")) {
6801 // when this starts, we don't need anything from this section
6805 if ((hg_var_cnt & 0xff) == 0) {
6806 hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6807 * (hg_var_cnt + 0x100));
6808 my_assert_not(hg_vars, NULL);
6809 memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6812 var = &hg_vars[hg_var_cnt++];
6813 snprintf(var->name, sizeof(var->name), "%s", words[0]);
6815 // maybe already in seed header?
6816 var->pp = proto_parse(g_fhdr, var->name, 1);
6817 if (var->pp != NULL) {
6818 if (var->pp->is_fptr) {
6819 var->lmod = OPLM_DWORD;
6822 else if (var->pp->is_func)
6824 else if (!guess_lmod_from_c_type(&var->lmod, &var->pp->type))
6825 aerr("unhandled C type '%s' for '%s'\n",
6826 var->pp->type.name, var->name);
6832 if (IS(words[1], "dd"))
6833 var->lmod = OPLM_DWORD;
6834 else if (IS(words[1], "dw"))
6835 var->lmod = OPLM_WORD;
6836 else if (IS(words[1], "db")) {
6837 var->lmod = OPLM_BYTE;
6838 if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6839 if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6843 else if (IS(words[1], "dq"))
6844 var->lmod = OPLM_QWORD;
6845 //else if (IS(words[1], "dt"))
6847 aerr("type '%s' not known\n", words[1]);
6855 static void set_label(int i, const char *name)
6861 p = strchr(name, ':');
6865 if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6866 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6867 g_labels[i] = realloc(g_labels[i], len + 1);
6868 my_assert_not(g_labels[i], NULL);
6869 memcpy(g_labels[i], name, len);
6870 g_labels[i][len] = 0;
6879 static struct chunk_item *func_chunks;
6880 static int func_chunk_cnt;
6881 static int func_chunk_alloc;
6883 static void add_func_chunk(FILE *fasm, const char *name, int line)
6885 if (func_chunk_cnt >= func_chunk_alloc) {
6886 func_chunk_alloc *= 2;
6887 func_chunks = realloc(func_chunks,
6888 func_chunk_alloc * sizeof(func_chunks[0]));
6889 my_assert_not(func_chunks, NULL);
6891 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6892 func_chunks[func_chunk_cnt].name = strdup(name);
6893 func_chunks[func_chunk_cnt].asmln = line;
6897 static int cmp_chunks(const void *p1, const void *p2)
6899 const struct chunk_item *c1 = p1, *c2 = p2;
6900 return strcmp(c1->name, c2->name);
6903 static int cmpstringp(const void *p1, const void *p2)
6905 return strcmp(*(char * const *)p1, *(char * const *)p2);
6908 static void scan_ahead(FILE *fasm)
6918 oldpos = ftell(fasm);
6921 while (my_fgets(line, sizeof(line), fasm))
6932 // get rid of random tabs
6933 for (i = 0; line[i] != 0; i++)
6934 if (line[i] == '\t')
6937 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6940 next_word(words[0], sizeof(words[0]), p);
6941 if (words[0][0] == 0)
6942 aerr("missing name for func chunk?\n");
6944 add_func_chunk(fasm, words[0], asmln);
6946 else if (IS_START(p, "; sctend"))
6952 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6953 words[wordc][0] = 0;
6954 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6955 if (*p == 0 || *p == ';') {
6961 if (wordc == 2 && IS(words[1], "ends"))
6965 fseek(fasm, oldpos, SEEK_SET);
6969 int main(int argc, char *argv[])
6971 FILE *fout, *fasm, *frlist;
6972 struct parsed_data *pd = NULL;
6974 char **rlist = NULL;
6976 int rlist_alloc = 0;
6977 int func_chunks_used = 0;
6978 int func_chunks_sorted = 0;
6979 int func_chunk_i = -1;
6980 long func_chunk_ret = 0;
6981 int func_chunk_ret_ln = 0;
6982 int scanned_ahead = 0;
6984 char words[20][256];
6985 enum opr_lenmod lmod;
6986 char *sctproto = NULL;
6988 int pending_endp = 0;
6990 int skip_warned = 0;
7003 for (arg = 1; arg < argc; arg++) {
7004 if (IS(argv[arg], "-v"))
7006 else if (IS(argv[arg], "-rf"))
7007 g_allow_regfunc = 1;
7008 else if (IS(argv[arg], "-m"))
7010 else if (IS(argv[arg], "-hdr"))
7011 g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
7016 if (argc < arg + 3) {
7017 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdr.h> [rlist]*\n"
7018 "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n"
7020 " -hdr - header generation mode\n"
7021 " -rf - allow unannotated indirect calls\n"
7022 " -m - allow multiple .text sections\n"
7023 "[rlist] is a file with function names to skip,"
7031 asmfn = argv[arg++];
7032 fasm = fopen(asmfn, "r");
7033 my_assert_not(fasm, NULL);
7035 hdrfn = argv[arg++];
7036 g_fhdr = fopen(hdrfn, "r");
7037 my_assert_not(g_fhdr, NULL);
7040 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
7041 my_assert_not(rlist, NULL);
7042 // needs special handling..
7043 rlist[rlist_len++] = "__alloca_probe";
7045 func_chunk_alloc = 32;
7046 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
7047 my_assert_not(func_chunks, NULL);
7049 memset(words, 0, sizeof(words));
7051 for (; arg < argc; arg++) {
7052 frlist = fopen(argv[arg], "r");
7053 my_assert_not(frlist, NULL);
7055 while (my_fgets(line, sizeof(line), frlist)) {
7057 if (*p == 0 || *p == ';')
7060 if (IS_START(p, "#if 0")
7061 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
7065 else if (IS_START(p, "#endif"))
7072 p = next_word(words[0], sizeof(words[0]), p);
7073 if (words[0][0] == 0)
7076 if (rlist_len >= rlist_alloc) {
7077 rlist_alloc = rlist_alloc * 2 + 64;
7078 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
7079 my_assert_not(rlist, NULL);
7081 rlist[rlist_len++] = strdup(words[0]);
7090 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
7092 fout = fopen(argv[arg_out], "w");
7093 my_assert_not(fout, NULL);
7096 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
7097 my_assert_not(g_eqs, NULL);
7099 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
7100 g_label_refs[i].i = -1;
7101 g_label_refs[i].next = NULL;
7105 scan_variables(fasm);
7107 while (my_fgets(line, sizeof(line), fasm))
7116 // get rid of random tabs
7117 for (i = 0; line[i] != 0; i++)
7118 if (line[i] == '\t')
7123 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
7124 goto do_pending_endp; // eww..
7126 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
7128 static const char *attrs[] = {
7137 // parse IDA's attribute-list comment
7138 g_ida_func_attr = 0;
7141 for (; *p != 0; p = sskip(p)) {
7142 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
7143 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
7144 g_ida_func_attr |= 1 << i;
7145 p += strlen(attrs[i]);
7149 if (i == ARRAY_SIZE(attrs)) {
7150 anote("unparsed IDA attr: %s\n", p);
7153 if (IS(attrs[i], "fpd=")) {
7154 p = next_word(words[0], sizeof(words[0]), p);
7159 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
7162 next_word(words[0], sizeof(words[0]), p);
7163 if (words[0][0] == 0)
7164 aerr("missing name for func chunk?\n");
7166 if (!scanned_ahead) {
7167 add_func_chunk(fasm, words[0], asmln);
7168 func_chunks_sorted = 0;
7171 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
7173 if (func_chunk_i >= 0) {
7174 if (func_chunk_i < func_chunk_cnt
7175 && IS(func_chunks[func_chunk_i].name, g_func))
7177 // move on to next chunk
7178 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7180 aerr("seek failed for '%s' chunk #%d\n",
7181 g_func, func_chunk_i);
7182 asmln = func_chunks[func_chunk_i].asmln;
7186 if (func_chunk_ret == 0)
7187 aerr("no return from chunk?\n");
7188 fseek(fasm, func_chunk_ret, SEEK_SET);
7189 asmln = func_chunk_ret_ln;
7195 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
7196 func_chunks_used = 1;
7198 if (IS_START(g_func, "sub_")) {
7199 unsigned long addr = strtoul(p, NULL, 16);
7200 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
7201 if (addr > f_addr && !scanned_ahead) {
7202 anote("scan_ahead caused by '%s', addr %lx\n",
7206 func_chunks_sorted = 0;
7214 for (i = wordc; i < ARRAY_SIZE(words); i++)
7216 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
7217 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
7218 if (*p == 0 || *p == ';') {
7223 if (*p != 0 && *p != ';')
7224 aerr("too many words\n");
7226 // alow asm patches in comments
7228 if (IS_START(p, "; sctpatch:")) {
7230 if (*p == 0 || *p == ';')
7232 goto parse_words; // lame
7234 if (IS_START(p, "; sctproto:")) {
7235 sctproto = strdup(p + 11);
7237 else if (IS_START(p, "; sctend")) {
7246 awarn("wordc == 0?\n");
7250 // don't care about this:
7251 if (words[0][0] == '.'
7252 || IS(words[0], "include")
7253 || IS(words[0], "assume") || IS(words[1], "segment")
7254 || IS(words[0], "align"))
7260 // do delayed endp processing to collect switch jumptables
7262 if (in_func && !g_skip_func && !end && wordc >= 2
7263 && ((words[0][0] == 'd' && words[0][2] == 0)
7264 || (words[1][0] == 'd' && words[1][2] == 0)))
7267 if (words[1][0] == 'd' && words[1][2] == 0) {
7269 if (g_func_pd_cnt >= pd_alloc) {
7270 pd_alloc = pd_alloc * 2 + 16;
7271 g_func_pd = realloc(g_func_pd,
7272 sizeof(g_func_pd[0]) * pd_alloc);
7273 my_assert_not(g_func_pd, NULL);
7275 pd = &g_func_pd[g_func_pd_cnt];
7277 memset(pd, 0, sizeof(*pd));
7278 strcpy(pd->label, words[0]);
7279 pd->type = OPT_CONST;
7280 pd->lmod = lmod_from_directive(words[1]);
7286 anote("skipping alignment byte?\n");
7289 lmod = lmod_from_directive(words[0]);
7290 if (lmod != pd->lmod)
7291 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
7294 if (pd->count_alloc < pd->count + wordc) {
7295 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
7296 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
7297 my_assert_not(pd->d, NULL);
7299 for (; i < wordc; i++) {
7300 if (IS(words[i], "offset")) {
7301 pd->type = OPT_OFFSET;
7304 p = strchr(words[i], ',');
7307 if (pd->type == OPT_OFFSET)
7308 pd->d[pd->count].u.label = strdup(words[i]);
7310 pd->d[pd->count].u.val = parse_number(words[i]);
7311 pd->d[pd->count].bt_i = -1;
7317 if (in_func && !g_skip_func) {
7319 gen_hdr(g_func, pi);
7321 gen_func(fout, g_fhdr, g_func, pi);
7326 g_ida_func_attr = 0;
7330 func_chunks_used = 0;
7333 memset(&ops, 0, pi * sizeof(ops[0]));
7338 for (i = 0; i < g_func_pd_cnt; i++) {
7340 if (pd->type == OPT_OFFSET) {
7341 for (j = 0; j < pd->count; j++)
7342 free(pd->d[j].u.label);
7356 if (IS(words[1], "proc")) {
7358 aerr("proc '%s' while in_func '%s'?\n",
7361 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
7363 strcpy(g_func, words[0]);
7364 set_label(0, words[0]);
7369 if (IS(words[1], "endp"))
7372 aerr("endp '%s' while not in_func?\n", words[0]);
7373 if (!IS(g_func, words[0]))
7374 aerr("endp '%s' while in_func '%s'?\n",
7377 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
7378 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
7384 if (!g_skip_func && func_chunks_used) {
7385 // start processing chunks
7386 struct chunk_item *ci, key = { g_func, 0 };
7388 func_chunk_ret = ftell(fasm);
7389 func_chunk_ret_ln = asmln;
7390 if (!func_chunks_sorted) {
7391 qsort(func_chunks, func_chunk_cnt,
7392 sizeof(func_chunks[0]), cmp_chunks);
7393 func_chunks_sorted = 1;
7395 ci = bsearch(&key, func_chunks, func_chunk_cnt,
7396 sizeof(func_chunks[0]), cmp_chunks);
7398 aerr("'%s' needs chunks, but none found\n", g_func);
7399 func_chunk_i = ci - func_chunks;
7400 for (; func_chunk_i > 0; func_chunk_i--)
7401 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
7404 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7406 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
7407 asmln = func_chunks[func_chunk_i].asmln;
7415 if (wordc == 2 && IS(words[1], "ends")) {
7419 goto do_pending_endp;
7423 // scan for next text segment
7424 while (my_fgets(line, sizeof(line), fasm)) {
7427 if (*p == 0 || *p == ';')
7430 if (strstr(p, "segment para public 'CODE' use32"))
7437 p = strchr(words[0], ':');
7439 set_label(pi, words[0]);
7443 if (!in_func || g_skip_func) {
7444 if (!skip_warned && !g_skip_func && g_labels[pi] != NULL) {
7446 anote("skipping from '%s'\n", g_labels[pi]);
7450 g_labels[pi] = NULL;
7454 if (wordc > 1 && IS(words[1], "="))
7457 aerr("unhandled equ, wc=%d\n", wordc);
7458 if (g_eqcnt >= eq_alloc) {
7460 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
7461 my_assert_not(g_eqs, NULL);
7464 len = strlen(words[0]);
7465 if (len > sizeof(g_eqs[0].name) - 1)
7466 aerr("equ name too long: %d\n", len);
7467 strcpy(g_eqs[g_eqcnt].name, words[0]);
7469 if (!IS(words[3], "ptr"))
7470 aerr("unhandled equ\n");
7471 if (IS(words[2], "dword"))
7472 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
7473 else if (IS(words[2], "word"))
7474 g_eqs[g_eqcnt].lmod = OPLM_WORD;
7475 else if (IS(words[2], "byte"))
7476 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
7477 else if (IS(words[2], "qword"))
7478 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
7480 aerr("bad lmod: '%s'\n", words[2]);
7482 g_eqs[g_eqcnt].offset = parse_number(words[4]);
7487 if (pi >= ARRAY_SIZE(ops))
7488 aerr("too many ops\n");
7490 parse_op(&ops[pi], words, wordc);
7492 if (sctproto != NULL) {
7493 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
7494 ops[pi].datap = sctproto;
7510 // vim:ts=2:shiftwidth=2:expandtab