9 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
10 #define IS(w, y) !strcmp(w, y)
11 #define IS_START(w, y) !strncmp(w, y, strlen(y))
13 #include "protoparse.h"
15 static const char *asmfn;
19 #define anote(fmt, ...) \
20 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
21 #define awarn(fmt, ...) \
22 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
23 #define aerr(fmt, ...) do { \
24 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
30 OPF_RMD = (1 << 0), /* removed or optimized out */
31 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
32 OPF_FLAGS = (1 << 2), /* sets flags */
33 OPF_JMP = (1 << 3), /* branches, ret and call */
34 OPF_CC = (1 << 4), /* uses flags */
35 OPF_TAIL = (1 << 5), /* ret or tail call */
36 OPF_RSAVE = (1 << 6), /* push/pop is local reg save/load */
37 OPF_REP = (1 << 7), /* prefixed by rep */
38 OPF_REPZ = (1 << 8), /* rep is repe/repz */
39 OPF_REPNZ = (1 << 9), /* rep is repne/repnz */
40 OPF_FARG = (1 << 10), /* push collected as func arg (no reuse) */
41 OPF_EBP_S = (1 << 11), /* ebp used as scratch, not BP */
109 // must be sorted (larger len must be further in enum)
117 #define MAX_OPERANDS 3
121 enum opr_lenmod lmod;
122 unsigned int is_ptr:1; // pointer in C
123 unsigned int is_array:1; // array in C
124 unsigned int type_from_var:1; // .. in header, sometimes wrong
125 unsigned int size_mismatch:1; // type override differs from C
126 unsigned int size_lt:1; // type override is larger than C
134 struct parsed_opr operand[MAX_OPERANDS];
137 int regmask_src; // all referensed regs
139 int pfomask; // flagop: parsed_flag_op that can't be delayed
140 int argnum; // push: altered before call arg #
141 int cc_scratch; // scratch storage during analysis
142 int bt_i; // branch target for branches
143 struct parsed_data *btj;// branch targets for jumptables
148 // OP_CALL - ptr to parsed_proto
149 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
153 enum opr_lenmod lmod;
160 enum opr_lenmod lmod;
174 struct label_ref *next;
178 IDAFA_BP_FRAME = (1 << 0),
179 IDAFA_LIB_FUNC = (1 << 1),
180 IDAFA_STATIC = (1 << 2),
181 IDAFA_NORETURN = (1 << 3),
182 IDAFA_THUNK = (1 << 4),
183 IDAFA_FPD = (1 << 5),
188 static struct parsed_op ops[MAX_OPS];
189 static struct parsed_equ *g_eqs;
191 static char g_labels[MAX_OPS][32];
192 static struct label_ref g_label_refs[MAX_OPS];
193 static const struct parsed_proto *g_func_pp;
194 static struct parsed_data *g_func_pd;
195 static int g_func_pd_cnt;
196 static char g_func[256];
197 static char g_comment[256];
198 static int g_bp_frame;
199 static int g_sp_frame;
200 static int g_stack_frame_used;
201 static int g_stack_fsz;
202 static int g_ida_func_attr;
203 #define ferr(op_, fmt, ...) do { \
204 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
205 dump_op(op_), ##__VA_ARGS__); \
209 #define fnote(op_, fmt, ...) \
210 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
211 dump_op(op_), ##__VA_ARGS__)
215 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
216 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
217 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
218 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
220 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
222 // possible basic comparison types (without inversion)
223 enum parsed_flag_op {
227 PFO_BE, // 6 CF=1||ZF=1
231 PFO_LE, // e ZF=1||SF!=OF
234 static const char *parsed_flag_op_names[] = {
235 "o", "c", "z", "be", "s", "p", "l", "le"
238 static int char_array_i(const char *array[], size_t len, const char *s)
242 for (i = 0; i < len; i++)
249 static void printf_number(char *buf, size_t buf_size,
250 unsigned long number)
252 // output in C-friendly form
253 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
256 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
260 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
262 *reg_lmod = OPLM_DWORD;
265 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
267 *reg_lmod = OPLM_WORD;
270 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
272 *reg_lmod = OPLM_BYTE;
275 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
277 *reg_lmod = OPLM_BYTE;
284 static unsigned long parse_number(const char *number)
286 int len = strlen(number);
287 const char *p = number;
297 if (len > 1 && *p == '0')
299 if (number[len - 1] == 'h') {
300 ret = strtoul(p, &endp, 16);
301 bad = (*endp != 'h');
304 ret = strtoul(p, &endp, 10);
308 aerr("number parsing failed\n");
314 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
316 enum opr_lenmod lmod;
329 while (my_isblank(*s))
331 for (; my_issep(*s); d++, s++)
333 while (my_isblank(*s))
338 if (IS_START(s, "ds:"))
341 s = next_idt(w, sizeof(w), s);
346 reg = parse_reg(&lmod, w);
348 *regmask |= 1 << reg;
352 if ('0' <= w[0] && w[0] <= '9') {
353 number = parse_number(w);
354 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
358 // probably some label/identifier - pass
361 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
365 strcpy(name, cvtbuf);
370 static int is_reg_in_str(const char *s)
374 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
377 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
378 if (!strncmp(s, regs_r32[i], 3))
384 static const char *parse_stack_el(const char *name, char *extra_reg)
386 const char *p, *p2, *s;
393 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
395 if (extra_reg != NULL) {
396 strncpy(extra_reg, name, 3);
401 if (IS_START(p, "ebp+")) {
405 if (p2 != NULL && is_reg_in_str(p)) {
406 if (extra_reg != NULL) {
407 strncpy(extra_reg, p, p2 - p);
408 extra_reg[p2 - p] = 0;
413 if (!('0' <= *p && *p <= '9'))
419 if (!IS_START(name, "esp+"))
422 p = strchr(name + 4, '+');
424 // must be a number after esp+, already converted to 0x..
426 if (!('0' <= *s && *s <= '9')) {
427 aerr("%s nan?\n", __func__);
430 if (s[0] == '0' && s[1] == 'x')
433 if (len < sizeof(buf) - 1) {
434 strncpy(buf, s, len);
436 val = strtol(buf, &endp, 16);
437 if (val == 0 || *endp != 0) {
438 aerr("%s num parse fail for '%s'\n", __func__, buf);
447 if ('0' <= *p && *p <= '9')
453 static int guess_lmod_from_name(struct parsed_opr *opr)
455 if (!strncmp(opr->name, "dword_", 6)) {
456 opr->lmod = OPLM_DWORD;
459 if (!strncmp(opr->name, "word_", 5)) {
460 opr->lmod = OPLM_WORD;
463 if (!strncmp(opr->name, "byte_", 5)) {
464 opr->lmod = OPLM_BYTE;
470 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
471 const struct parsed_type *c_type)
473 static const char *dword_types[] = {
474 "int", "_DWORD", "UINT_PTR",
475 "DWORD", "HANDLE", "HWND", "HMODULE",
476 "WPARAM", "LPARAM", "UINT",
478 static const char *word_types[] = {
479 "uint16_t", "int16_t",
480 "unsigned __int16", "__int16",
482 static const char *byte_types[] = {
483 "uint8_t", "int8_t", "char",
484 "unsigned __int8", "__int8", "BYTE",
490 if (c_type->is_ptr) {
495 n = skip_type_mod(c_type->name);
497 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
498 if (IS(n, dword_types[i])) {
504 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
505 if (IS(n, word_types[i])) {
511 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
512 if (IS(n, byte_types[i])) {
521 static enum opr_type lmod_from_directive(const char *d)
525 else if (IS(d, "dw"))
527 else if (IS(d, "db"))
530 aerr("unhandled directive: '%s'\n", d);
534 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
540 *regmask |= 1 << reg;
543 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
546 static int parse_operand(struct parsed_opr *opr,
547 int *regmask, int *regmask_indirect,
548 char words[16][256], int wordc, int w, unsigned int op_flags)
550 const struct parsed_proto *pp;
551 enum opr_lenmod tmplmod;
552 unsigned long number;
559 aerr("parse_operand w %d, wordc %d\n", w, wordc);
563 for (i = w; i < wordc; i++) {
564 len = strlen(words[i]);
565 if (words[i][len - 1] == ',') {
566 words[i][len - 1] = 0;
572 wordc_in = wordc - w;
574 if ((op_flags & OPF_JMP) && wordc_in > 0
575 && !('0' <= words[w][0] && words[w][0] <= '9'))
577 const char *label = NULL;
579 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
580 && IS(words[w + 1], "ptr"))
581 label = words[w + 2];
582 else if (wordc_in == 2 && IS(words[w], "short"))
583 label = words[w + 1];
584 else if (wordc_in == 1
585 && strchr(words[w], '[') == NULL
586 && parse_reg(&tmplmod, words[w]) < 0)
590 opr->type = OPT_LABEL;
591 if (IS_START(label, "ds:"))
593 strcpy(opr->name, label);
599 if (IS(words[w + 1], "ptr")) {
600 if (IS(words[w], "dword"))
601 opr->lmod = OPLM_DWORD;
602 else if (IS(words[w], "word"))
603 opr->lmod = OPLM_WORD;
604 else if (IS(words[w], "byte"))
605 opr->lmod = OPLM_BYTE;
607 aerr("type parsing failed\n");
609 wordc_in = wordc - w;
614 if (IS(words[w], "offset")) {
615 opr->type = OPT_OFFSET;
616 strcpy(opr->name, words[w + 1]);
619 if (IS(words[w], "(offset")) {
620 char *p = strchr(words[w + 1], ')');
622 aerr("parse of bracketed offset failed\n");
624 opr->type = OPT_OFFSET;
625 strcpy(opr->name, words[w + 1]);
631 aerr("parse_operand 1 word expected\n");
634 if (IS_START(tmp, "ds:"))
636 strcpy(opr->name, tmp);
638 if (words[w][0] == '[') {
639 opr->type = OPT_REGMEM;
640 ret = sscanf(words[w], "[%[^]]]", opr->name);
642 aerr("[] parse failure\n");
644 parse_indmode(opr->name, regmask_indirect, 1);
645 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
647 struct parsed_equ *eq =
648 equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
650 opr->lmod = eq->lmod;
654 else if (strchr(words[w], '[')) {
656 opr->type = OPT_REGMEM;
657 if (opr->lmod == OPLM_UNSPEC)
658 guess_lmod_from_name(opr);
659 parse_indmode(strchr(words[w], '['), regmask_indirect, 0);
662 else if (('0' <= words[w][0] && words[w][0] <= '9')
663 || words[w][0] == '-')
665 number = parse_number(words[w]);
666 opr->type = OPT_CONST;
668 printf_number(opr->name, sizeof(opr->name), number);
672 ret = parse_reg(&tmplmod, opr->name);
674 setup_reg_opr(opr, ret, tmplmod, regmask);
678 // most likely var in data segment
679 opr->type = OPT_LABEL;
681 pp = proto_parse(g_fhdr, opr->name);
683 if (pp->is_fptr || pp->is_func) {
684 opr->lmod = OPLM_DWORD;
688 tmplmod = OPLM_UNSPEC;
689 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
690 anote("unhandled C type '%s' for '%s'\n",
691 pp->type.name, opr->name);
693 if (opr->lmod == OPLM_UNSPEC) {
695 opr->type_from_var = 1;
697 else if (opr->lmod != tmplmod) {
698 opr->size_mismatch = 1;
699 if (tmplmod < opr->lmod)
702 opr->is_ptr = pp->type.is_ptr;
704 opr->is_array = pp->type.is_array;
707 if (opr->lmod == OPLM_UNSPEC)
708 guess_lmod_from_name(opr);
712 static const struct {
717 { "repe", OPF_REP|OPF_REPZ },
718 { "repz", OPF_REP|OPF_REPZ },
719 { "repne", OPF_REP|OPF_REPNZ },
720 { "repnz", OPF_REP|OPF_REPNZ },
723 static const struct {
730 { "nop", OP_NOP, 0, 0, 0 },
731 { "push", OP_PUSH, 1, 1, 0 },
732 { "pop", OP_POP, 1, 1, OPF_DATA },
733 { "mov" , OP_MOV, 2, 2, OPF_DATA },
734 { "lea", OP_LEA, 2, 2, OPF_DATA },
735 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
736 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
737 { "not", OP_NOT, 1, 1, OPF_DATA },
738 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
739 { "stosb",OP_STOS, 0, 0, OPF_DATA },
740 { "stosw",OP_STOS, 0, 0, OPF_DATA },
741 { "stosd",OP_STOS, 0, 0, OPF_DATA },
742 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
743 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
744 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
745 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
746 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
747 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
748 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
749 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
750 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
751 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
752 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
753 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
754 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
755 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
756 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
757 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
758 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
759 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
760 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
761 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
762 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
763 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
764 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
765 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
766 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
767 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
768 { "test", OP_TEST, 2, 2, OPF_FLAGS },
769 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
770 { "retn", OP_RET, 0, 1, OPF_TAIL },
771 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
772 { "jmp", OP_JMP, 1, 1, OPF_JMP },
773 { "jo", OP_JO, 1, 1, OPF_JMP|OPF_CC }, // 70 OF=1
774 { "jno", OP_JNO, 1, 1, OPF_JMP|OPF_CC }, // 71 OF=0
775 { "jc", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72 CF=1
776 { "jb", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72
777 { "jnc", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73 CF=0
778 { "jnb", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
779 { "jae", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
780 { "jz", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74 ZF=1
781 { "je", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74
782 { "jnz", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75 ZF=0
783 { "jne", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75
784 { "jbe", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76 CF=1 || ZF=1
785 { "jna", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76
786 { "ja", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77 CF=0 && ZF=0
787 { "jnbe", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77
788 { "js", OP_JS, 1, 1, OPF_JMP|OPF_CC }, // 78 SF=1
789 { "jns", OP_JNS, 1, 1, OPF_JMP|OPF_CC }, // 79 SF=0
790 { "jp", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a PF=1
791 { "jpe", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a
792 { "jnp", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b PF=0
793 { "jpo", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b
794 { "jl", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c SF!=OF
795 { "jnge", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c
796 { "jge", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d SF=OF
797 { "jnl", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d
798 { "jle", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e ZF=1 || SF!=OF
799 { "jng", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e
800 { "jg", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f ZF=0 && SF=OF
801 { "jnle", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f
802 { "seto", OP_JO, 1, 1, OPF_DATA|OPF_CC },
803 { "setno", OP_JNO, 1, 1, OPF_DATA|OPF_CC },
804 { "setc", OP_JC, 1, 1, OPF_DATA|OPF_CC },
805 { "setb", OP_JC, 1, 1, OPF_DATA|OPF_CC },
806 { "setnc", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
807 { "setae", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
808 { "setz", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
809 { "sete", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
810 { "setnz", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
811 { "setne", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
812 { "setbe", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
813 { "setna", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
814 { "seta", OP_JA, 1, 1, OPF_DATA|OPF_CC },
815 { "setnbe", OP_JA, 1, 1, OPF_DATA|OPF_CC },
816 { "sets", OP_JS, 1, 1, OPF_DATA|OPF_CC },
817 { "setns", OP_JNS, 1, 1, OPF_DATA|OPF_CC },
818 { "setp", OP_JP, 1, 1, OPF_DATA|OPF_CC },
819 { "setpe", OP_JP, 1, 1, OPF_DATA|OPF_CC },
820 { "setnp", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
821 { "setpo", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
822 { "setl", OP_JL, 1, 1, OPF_DATA|OPF_CC },
823 { "setnge", OP_JL, 1, 1, OPF_DATA|OPF_CC },
824 { "setge", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
825 { "setnl", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
826 { "setle", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
827 { "setng", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
828 { "setg", OP_JG, 1, 1, OPF_DATA|OPF_CC },
829 { "setnle", OP_JG, 1, 1, OPF_DATA|OPF_CC },
832 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
834 enum opr_lenmod lmod = OPLM_UNSPEC;
835 int prefix_flags = 0;
843 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
844 if (IS(words[w], pref_table[i].name)) {
845 prefix_flags = pref_table[i].flags;
852 aerr("lone prefix: '%s'\n", words[0]);
857 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
858 if (IS(words[w], op_table[i].name))
862 if (i == ARRAY_SIZE(op_table))
863 aerr("unhandled op: '%s'\n", words[0]);
866 op->op = op_table[i].op;
867 op->flags = op_table[i].flags | prefix_flags;
868 op->regmask_src = op->regmask_dst = 0;
870 for (opr = 0; opr < op_table[i].minopr; opr++) {
871 regmask = regmask_ind = 0;
872 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
873 words, wordc, w, op->flags);
875 if (opr == 0 && (op->flags & OPF_DATA))
876 op->regmask_dst = regmask;
877 // for now, mark dst as src too
878 op->regmask_src |= regmask | regmask_ind;
881 for (; w < wordc && opr < op_table[i].maxopr; opr++) {
882 w = parse_operand(&op->operand[opr],
883 &op->regmask_src, &op->regmask_src,
884 words, wordc, w, op->flags);
888 aerr("parse_op %s incomplete: %d/%d\n",
892 op->operand_cnt = opr;
893 if (!strncmp(op_table[i].name, "set", 3))
894 op->operand[0].lmod = OPLM_BYTE;
896 // ops with implicit argumets
900 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
901 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
905 if (op->operand_cnt != 0)
907 if (IS(words[op_w], "stosb"))
909 else if (IS(words[op_w], "stosw"))
911 else if (IS(words[op_w], "stosd"))
914 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
915 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
916 op->regmask_dst = op->regmask_src;
917 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
922 if (op->operand_cnt != 0)
924 if (words[op_w][4] == 'b')
926 else if (words[op_w][4] == 'w')
928 else if (words[op_w][4] == 'd')
931 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
932 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
933 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
934 op->regmask_dst = op->regmask_src;
938 if (op->operand_cnt != 1)
943 op->regmask_dst = (1 << xDX) | (1 << xAX);
944 op->regmask_src |= (1 << xAX);
945 if (op->operand[0].lmod == OPLM_UNSPEC)
946 op->operand[0].lmod = OPLM_DWORD;
951 // we could set up operands for edx:eax, but there is no real need to
952 // (see is_opr_modified())
953 regmask = (1 << xDX) | (1 << xAX);
954 op->regmask_dst = regmask;
955 op->regmask_src |= regmask;
956 if (op->operand[0].lmod == OPLM_UNSPEC)
957 op->operand[0].lmod = OPLM_DWORD;
965 if (op->operand[1].lmod == OPLM_UNSPEC)
966 op->operand[1].lmod = OPLM_BYTE;
970 if (op->operand[0].lmod == OPLM_UNSPEC
971 && (op->operand[0].type == OPT_CONST
972 || op->operand[0].type == OPT_OFFSET
973 || op->operand[0].type == OPT_LABEL))
974 op->operand[0].lmod = OPLM_DWORD;
979 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
980 && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
982 op->flags |= OPF_RMD;
987 if (op->operand[0].type == OPT_REG
988 && op->operand[1].type == OPT_REGMEM)
991 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
992 if (IS(buf, op->operand[1].name))
993 op->flags |= OPF_RMD;
1002 static const char *op_name(enum op_op op)
1006 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1007 if (op_table[i].op == op)
1008 return op_table[i].name;
1014 static const char *dump_op(struct parsed_op *po)
1016 static char out[128];
1023 snprintf(out, sizeof(out), "%s", op_name(po->op));
1024 for (i = 0; i < po->operand_cnt; i++) {
1028 snprintf(p, sizeof(out) - (p - out),
1029 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1030 po->operand[i].name);
1036 static const char *lmod_type_u(struct parsed_op *po,
1037 enum opr_lenmod lmod)
1047 ferr(po, "invalid lmod: %d\n", lmod);
1048 return "(_invalid_)";
1052 static const char *lmod_cast_u(struct parsed_op *po,
1053 enum opr_lenmod lmod)
1063 ferr(po, "invalid lmod: %d\n", lmod);
1064 return "(_invalid_)";
1068 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1069 enum opr_lenmod lmod)
1079 ferr(po, "invalid lmod: %d\n", lmod);
1080 return "(_invalid_)";
1084 static const char *lmod_cast_s(struct parsed_op *po,
1085 enum opr_lenmod lmod)
1095 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1096 return "(_invalid_)";
1100 static const char *lmod_cast(struct parsed_op *po,
1101 enum opr_lenmod lmod, int is_signed)
1104 lmod_cast_s(po, lmod) :
1105 lmod_cast_u(po, lmod);
1108 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1118 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1123 static const char *opr_name(struct parsed_op *po, int opr_num)
1125 if (opr_num >= po->operand_cnt)
1126 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1127 return po->operand[opr_num].name;
1130 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1132 if (opr_num >= po->operand_cnt)
1133 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1134 if (po->operand[opr_num].type != OPT_CONST)
1135 ferr(po, "opr %d: const expected\n", opr_num);
1136 return po->operand[opr_num].val;
1139 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1141 if ((unsigned int)popr->reg >= MAX_REGS)
1142 ferr(po, "invalid reg: %d\n", popr->reg);
1143 return regs_r32[popr->reg];
1146 // cast1 is the "final" cast
1147 static const char *simplify_cast(const char *cast1, const char *cast2)
1149 static char buf[256];
1155 if (IS(cast1, cast2))
1157 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1159 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1161 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1163 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1165 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1168 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1172 static const char *simplify_cast_num(const char *cast, unsigned int val)
1174 if (IS(cast, "(u8)") && val < 0x100)
1176 if (IS(cast, "(s8)") && val < 0x80)
1178 if (IS(cast, "(u16)") && val < 0x10000)
1180 if (IS(cast, "(s16)") && val < 0x8000)
1182 if (IS(cast, "(s32)") && val < 0x80000000)
1188 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1197 namelen = strlen(name);
1199 p = strchr(name, '+');
1203 ferr(po, "equ parse failed for '%s'\n", name);
1205 if (IS_START(p, "0x"))
1207 *extra_offs = strtol(p, &endp, 16);
1209 ferr(po, "equ parse failed for '%s'\n", name);
1212 for (i = 0; i < g_eqcnt; i++)
1213 if (strncmp(g_eqs[i].name, name, namelen) == 0
1214 && g_eqs[i].name[namelen] == 0)
1218 ferr(po, "unresolved equ name: '%s'\n", name);
1225 static int is_stack_access(struct parsed_op *po,
1226 const struct parsed_opr *popr)
1228 return (parse_stack_el(popr->name, NULL)
1229 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1230 && IS_START(popr->name, "ebp")));
1233 static void parse_stack_access(struct parsed_op *po,
1234 const char *name, char *ofs_reg, int *offset_out,
1235 int *stack_ra_out, const char **bp_arg_out)
1237 const char *bp_arg = "";
1238 const char *p = NULL;
1239 struct parsed_equ *eq;
1246 if (IS_START(name, "ebp-")
1247 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1250 if (IS_START(p, "0x"))
1252 offset = strtoul(p, &endp, 16);
1256 ferr(po, "ebp- parse of '%s' failed\n", name);
1259 bp_arg = parse_stack_el(name, ofs_reg);
1260 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1261 eq = equ_find(po, bp_arg, &offset);
1263 ferr(po, "detected but missing eq\n");
1264 offset += eq->offset;
1267 if (!strncmp(name, "ebp", 3))
1270 if (ofs_reg[0] == 0 && stack_ra <= offset && offset < stack_ra + 4)
1271 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1273 *offset_out = offset;
1274 *stack_ra_out = stack_ra;
1276 *bp_arg_out = bp_arg;
1279 static void stack_frame_access(struct parsed_op *po,
1280 struct parsed_opr *popr, char *buf, size_t buf_size,
1281 const char *name, const char *cast, int is_src, int is_lea)
1283 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1284 const char *prefix = "";
1285 const char *bp_arg = NULL;
1286 char ofs_reg[16] = { 0, };
1287 int i, arg_i, arg_s;
1294 if (po->flags & OPF_EBP_S)
1295 ferr(po, "stack_frame_access while ebp is scratch\n");
1297 parse_stack_access(po, name, ofs_reg, &offset, &stack_ra, &bp_arg);
1299 if (offset > stack_ra)
1301 arg_i = (offset - stack_ra - 4) / 4;
1302 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1304 if (g_func_pp->is_vararg
1305 && arg_i == g_func_pp->argc_stack && is_lea)
1307 // should be va_list
1310 snprintf(buf, buf_size, "%sap", cast);
1313 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1314 offset, bp_arg, arg_i);
1316 if (ofs_reg[0] != 0)
1317 ferr(po, "offset reg on arg access?\n");
1319 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1320 if (g_func_pp->arg[i].reg != NULL)
1326 if (i == g_func_pp->argc)
1327 ferr(po, "arg %d not in prototype?\n", arg_i);
1329 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1335 ferr(po, "lea/byte to arg?\n");
1336 if (is_src && (offset & 3) == 0)
1337 snprintf(buf, buf_size, "%sa%d",
1338 simplify_cast(cast, "(u8)"), i + 1);
1340 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1341 cast, offset & 3, i + 1);
1346 ferr(po, "lea/word to arg?\n");
1351 ferr(po, "problematic arg store\n");
1352 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1353 simplify_cast(cast, "*(u16 *)"), i + 1);
1356 ferr(po, "unaligned arg word load\n");
1358 else if (is_src && (offset & 2) == 0)
1359 snprintf(buf, buf_size, "%sa%d",
1360 simplify_cast(cast, "(u16)"), i + 1);
1362 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1363 cast, (offset & 2) ? "HI" : "LO", i + 1);
1375 snprintf(buf, buf_size, "(u32)&a%d + %d",
1378 ferr(po, "unaligned arg store\n");
1380 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1381 snprintf(buf, buf_size, "%s(a%d >> %d)",
1382 prefix, i + 1, (offset & 3) * 8);
1386 snprintf(buf, buf_size, "%s%sa%d",
1387 prefix, is_lea ? "&" : "", i + 1);
1392 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1396 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1399 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1400 if (tmp_lmod != OPLM_DWORD
1401 && (unaligned || (!is_src && tmp_lmod < popr->lmod)))
1403 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1404 i + 1, offset, g_func_pp->arg[i].type.name);
1406 if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1407 ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1411 if (g_stack_fsz == 0)
1412 ferr(po, "stack var access without stackframe\n");
1413 g_stack_frame_used = 1;
1415 sf_ofs = g_stack_fsz + offset;
1416 lim = (ofs_reg[0] != 0) ? -4 : 0;
1417 if (offset > 0 || sf_ofs < lim)
1418 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1428 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1429 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1433 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1434 // known unaligned or possibly unaligned
1435 strcat(g_comment, " unaligned");
1437 prefix = "*(u16 *)&";
1438 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1439 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1442 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1446 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1447 // known unaligned or possibly unaligned
1448 strcat(g_comment, " unaligned");
1450 prefix = "*(u32 *)&";
1451 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1452 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1455 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1459 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1464 static void check_label_read_ref(struct parsed_op *po, const char *name)
1466 const struct parsed_proto *pp;
1468 pp = proto_parse(g_fhdr, name);
1470 ferr(po, "proto_parse failed for ref '%s'\n", name);
1472 // currently we can take __cdecl and __stdcall
1473 if (pp->is_func && pp->argc_reg != 0)
1474 ferr(po, "reg-arg func reference?\n");
1477 static char *out_src_opr(char *buf, size_t buf_size,
1478 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1481 char tmp1[256], tmp2[256];
1489 switch (popr->type) {
1492 ferr(po, "lea from reg?\n");
1494 switch (popr->lmod) {
1496 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1499 snprintf(buf, buf_size, "%s%s",
1500 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1503 if (popr->name[1] == 'h') // XXX..
1504 snprintf(buf, buf_size, "%s(%s >> 8)",
1505 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1507 snprintf(buf, buf_size, "%s%s",
1508 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1511 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1516 if (is_stack_access(po, popr)) {
1517 stack_frame_access(po, popr, buf, buf_size,
1518 popr->name, cast, 1, is_lea);
1522 strcpy(expr, popr->name);
1523 if (strchr(expr, '[')) {
1524 // special case: '[' can only be left for label[reg] form
1525 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1527 ferr(po, "parse failure for '%s'\n", expr);
1528 if (tmp1[0] == '(') {
1529 // (off_4FFF50+3)[eax]
1530 p = strchr(tmp1 + 1, ')');
1531 if (p == NULL || p[1] != 0)
1532 ferr(po, "parse failure (2) for '%s'\n", expr);
1534 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1536 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1539 // XXX: do we need more parsing?
1541 snprintf(buf, buf_size, "%s", expr);
1545 snprintf(buf, buf_size, "%s(%s)",
1546 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1550 check_label_read_ref(po, popr->name);
1551 if (cast[0] == 0 && popr->is_ptr)
1555 snprintf(buf, buf_size, "(u32)&%s", popr->name);
1556 else if (popr->size_lt)
1557 snprintf(buf, buf_size, "%s%s%s%s", cast,
1558 lmod_cast_u_ptr(po, popr->lmod),
1559 popr->is_array ? "" : "&",
1562 snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1563 popr->is_array ? "[0]" : "");
1567 check_label_read_ref(po, popr->name);
1571 ferr(po, "lea an offset?\n");
1572 snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1577 ferr(po, "lea from const?\n");
1579 printf_number(tmp1, sizeof(tmp1), popr->val);
1580 snprintf(buf, buf_size, "%s%s",
1581 simplify_cast_num(cast, popr->val), tmp1);
1585 ferr(po, "invalid src type: %d\n", popr->type);
1591 // note: may set is_ptr (we find that out late for ebp frame..)
1592 static char *out_dst_opr(char *buf, size_t buf_size,
1593 struct parsed_op *po, struct parsed_opr *popr)
1595 switch (popr->type) {
1597 switch (popr->lmod) {
1599 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1603 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1607 if (popr->name[1] == 'h') // XXX..
1608 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1610 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1613 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1618 if (is_stack_access(po, popr)) {
1619 stack_frame_access(po, popr, buf, buf_size,
1620 popr->name, "", 0, 0);
1624 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1627 if (popr->size_mismatch)
1628 snprintf(buf, buf_size, "%s%s%s",
1629 lmod_cast_u_ptr(po, popr->lmod),
1630 popr->is_array ? "" : "&", popr->name);
1632 snprintf(buf, buf_size, "%s%s", popr->name,
1633 popr->is_array ? "[0]" : "");
1637 ferr(po, "invalid dst type: %d\n", popr->type);
1643 static char *out_src_opr_u32(char *buf, size_t buf_size,
1644 struct parsed_op *po, struct parsed_opr *popr)
1646 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1649 static enum parsed_flag_op split_cond(struct parsed_op *po,
1650 enum op_op op, int *is_inv)
1702 ferr(po, "split_cond: bad op %d\n", op);
1707 static void out_test_for_cc(char *buf, size_t buf_size,
1708 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1709 enum opr_lenmod lmod, const char *expr)
1711 const char *cast, *scast;
1713 cast = lmod_cast_u(po, lmod);
1714 scast = lmod_cast_s(po, lmod);
1718 case PFO_BE: // CF=1||ZF=1; CF=0
1719 snprintf(buf, buf_size, "(%s%s %s 0)",
1720 cast, expr, is_inv ? "!=" : "==");
1724 case PFO_L: // SF!=OF; OF=0
1725 snprintf(buf, buf_size, "(%s%s %s 0)",
1726 scast, expr, is_inv ? ">=" : "<");
1729 case PFO_LE: // ZF=1||SF!=OF; OF=0
1730 snprintf(buf, buf_size, "(%s%s %s 0)",
1731 scast, expr, is_inv ? ">" : "<=");
1735 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1739 static void out_cmp_for_cc(char *buf, size_t buf_size,
1740 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1742 const char *cast, *scast, *cast_use;
1743 char buf1[256], buf2[256];
1744 enum opr_lenmod lmod;
1746 if (po->operand[0].lmod != po->operand[1].lmod)
1747 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1748 po->operand[0].lmod, po->operand[1].lmod);
1749 lmod = po->operand[0].lmod;
1751 cast = lmod_cast_u(po, lmod);
1752 scast = lmod_cast_s(po, lmod);
1768 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1771 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1772 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1776 // note: must be unsigned compare
1777 snprintf(buf, buf_size, "(%s %s %s)",
1778 buf1, is_inv ? ">=" : "<", buf2);
1782 snprintf(buf, buf_size, "(%s %s %s)",
1783 buf1, is_inv ? "!=" : "==", buf2);
1787 // note: must be unsigned compare
1788 snprintf(buf, buf_size, "(%s %s %s)",
1789 buf1, is_inv ? ">" : "<=", buf2);
1792 if (is_inv && lmod == OPLM_BYTE
1793 && po->operand[1].type == OPT_CONST
1794 && po->operand[1].val == 0xff)
1796 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1797 snprintf(buf, buf_size, "(0)");
1801 // note: must be signed compare
1803 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1804 scast, buf1, buf2, is_inv ? ">=" : "<");
1808 snprintf(buf, buf_size, "(%s %s %s)",
1809 buf1, is_inv ? ">=" : "<", buf2);
1813 snprintf(buf, buf_size, "(%s %s %s)",
1814 buf1, is_inv ? ">" : "<=", buf2);
1822 static void out_cmp_test(char *buf, size_t buf_size,
1823 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1825 char buf1[256], buf2[256], buf3[256];
1827 if (po->op == OP_TEST) {
1828 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1829 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1832 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1833 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1834 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1836 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1837 po->operand[0].lmod, buf3);
1839 else if (po->op == OP_CMP) {
1840 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1843 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1846 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1847 struct parsed_opr *popr2)
1849 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1850 ferr(po, "missing lmod for both operands\n");
1852 if (popr1->lmod == OPLM_UNSPEC)
1853 popr1->lmod = popr2->lmod;
1854 else if (popr2->lmod == OPLM_UNSPEC)
1855 popr2->lmod = popr1->lmod;
1856 else if (popr1->lmod != popr2->lmod) {
1857 if (popr1->type_from_var) {
1858 popr1->size_mismatch = 1;
1859 if (popr1->lmod < popr2->lmod)
1861 popr1->lmod = popr2->lmod;
1863 else if (popr2->type_from_var) {
1864 popr2->size_mismatch = 1;
1865 if (popr2->lmod < popr1->lmod)
1867 popr2->lmod = popr1->lmod;
1870 ferr(po, "conflicting lmods: %d vs %d\n",
1871 popr1->lmod, popr2->lmod);
1875 static const char *op_to_c(struct parsed_op *po)
1899 ferr(po, "op_to_c was supplied with %d\n", po->op);
1903 static void op_set_clear_flag(struct parsed_op *po,
1904 enum op_flags flag_set, enum op_flags flag_clear)
1906 po->flags |= flag_set;
1907 po->flags &= ~flag_clear;
1910 // last op in stream - unconditional branch or ret
1911 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1912 || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1914 static int scan_for_pop(int i, int opcnt, const char *reg,
1915 int magic, int depth, int *maxdepth, int do_flags)
1917 struct parsed_op *po;
1921 for (; i < opcnt; i++) {
1923 if (po->cc_scratch == magic)
1924 break; // already checked
1925 po->cc_scratch = magic;
1927 if (po->flags & OPF_TAIL)
1928 return -1; // deadend
1930 if ((po->flags & OPF_RMD)
1931 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1934 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1935 if (po->btj != NULL) {
1937 for (j = 0; j < po->btj->count - 1; j++) {
1938 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1939 depth, maxdepth, do_flags);
1941 return ret; // dead end
1943 // follow last jumptable entry
1944 i = po->btj->d[j].bt_i - 1;
1949 ferr(po, "dead branch\n");
1953 if (po->flags & OPF_CC) {
1954 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1955 depth, maxdepth, do_flags);
1957 return ret; // dead end
1965 if ((po->op == OP_POP || po->op == OP_PUSH)
1966 && po->operand[0].type == OPT_REG
1967 && IS(po->operand[0].name, reg))
1969 if (po->op == OP_PUSH) {
1971 if (depth > *maxdepth)
1974 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1976 else if (depth == 0) {
1978 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1983 if (depth < 0) // should not happen
1984 ferr(po, "fail with depth\n");
1986 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1994 // scan for pop starting from 'ret' op (all paths)
1995 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2001 for (; i < opcnt; i++) {
2002 if (!(ops[i].flags & OPF_TAIL))
2005 for (j = i - 1; j >= 0; j--) {
2006 if (ops[j].flags & OPF_RMD)
2008 if (ops[j].flags & OPF_JMP)
2011 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2012 && IS(ops[j].operand[0].name, reg))
2015 ops[j].flags |= flag_set;
2019 if (g_labels[j][0] != 0)
2024 return found ? 0 : -1;
2027 // is operand 'opr' modified by parsed_op 'po'?
2028 static int is_opr_modified(const struct parsed_opr *opr,
2029 const struct parsed_op *po)
2031 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2034 if (opr->type == OPT_REG && po->operand[0].type == OPT_REG) {
2035 if (po->regmask_dst & (1 << opr->reg))
2041 return IS(po->operand[0].name, opr->name);
2044 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2045 static int is_any_opr_modified(const struct parsed_op *po_test,
2046 const struct parsed_op *po)
2050 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2053 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2056 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2059 // in reality, it can wreck any register, but in decompiled C
2060 // version it can only overwrite eax or edx:eax
2061 if (po->op == OP_CALL
2062 && ((po_test->regmask_src | po_test->regmask_dst)
2063 & ((1 << xAX)|(1 << xDX))))
2066 for (i = 0; i < po_test->operand_cnt; i++)
2067 if (IS(po_test->operand[i].name, po->operand[0].name))
2073 // scan for any po_test operand modification in range given
2074 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt)
2076 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2079 for (; i < opcnt; i++) {
2080 if (is_any_opr_modified(po_test, &ops[i]))
2087 // scan for po_test operand[0] modification in range given
2088 static int scan_for_mod_opr0(struct parsed_op *po_test,
2091 for (; i < opcnt; i++) {
2092 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2099 static int scan_for_flag_set(int i, int magic, int *branched,
2100 int *setters, int *setter_cnt)
2102 struct label_ref *lr;
2106 if (ops[i].cc_scratch == magic) {
2107 ferr(&ops[i], "%s looped\n", __func__);
2110 ops[i].cc_scratch = magic;
2112 if (g_labels[i][0] != 0) {
2115 lr = &g_label_refs[i];
2116 for (; lr->next; lr = lr->next) {
2117 ret = scan_for_flag_set(lr->i, magic,
2118 branched, setters, setter_cnt);
2123 if (i > 0 && LAST_OP(i - 1)) {
2127 ret = scan_for_flag_set(lr->i, magic,
2128 branched, setters, setter_cnt);
2134 if (ops[i].flags & OPF_FLAGS) {
2135 setters[*setter_cnt] = i;
2140 if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2147 // scan back for cdq, if anything modifies edx, fail
2148 static int scan_for_cdq_edx(int i)
2151 if (g_labels[i][0] != 0) {
2152 if (g_label_refs[i].next != NULL)
2154 if (i > 0 && LAST_OP(i - 1)) {
2155 i = g_label_refs[i].i;
2162 if (ops[i].op == OP_CDQ)
2165 if (ops[i].regmask_dst & (1 << xDX))
2167 if (g_labels[i][0] != 0)
2174 static int scan_for_reg_clear(int i, int reg)
2177 if (g_labels[i][0] != 0) {
2178 if (g_label_refs[i].next != NULL)
2180 if (i > 0 && LAST_OP(i - 1)) {
2181 i = g_label_refs[i].i;
2188 if (ops[i].op == OP_XOR
2189 && ops[i].operand[0].lmod == OPLM_DWORD
2190 && ops[i].operand[0].reg == ops[i].operand[1].reg
2191 && ops[i].operand[0].reg == reg)
2194 if (ops[i].regmask_dst & (1 << reg))
2196 if (g_labels[i][0] != 0)
2203 // scan for positive, constant esp adjust
2204 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2206 struct parsed_op *po;
2210 for (; i < opcnt; i++) {
2213 if (g_labels[i][0] != 0)
2216 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2217 if (po->operand[1].type != OPT_CONST)
2218 ferr(&ops[i], "non-const esp adjust?\n");
2219 *adj += po->operand[1].val;
2221 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2224 else if (po->op == OP_PUSH) {
2225 if (first_pop == -1)
2226 first_pop = -2; // none
2227 *adj -= lmod_bytes(po, po->operand[0].lmod);
2229 else if (po->op == OP_POP) {
2230 if (first_pop == -1)
2232 *adj += lmod_bytes(po, po->operand[0].lmod);
2234 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2235 if (po->op != OP_CALL)
2237 if (po->operand[0].type != OPT_LABEL)
2239 // TODO: should only allow combining __cdecl calls..
2243 if (*adj == 4 && first_pop >= 0 && ops[first_pop].op == OP_POP
2244 && ops[first_pop].operand[0].type == OPT_REG
2245 && ops[first_pop].operand[0].reg == xCX)
2247 // probably 'pop ecx' was used..
2254 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2256 struct parsed_op *po;
2260 ferr(ops, "%s: followed bad branch?\n", __func__);
2262 for (; i < opcnt; i++) {
2264 if (po->cc_scratch == magic)
2266 po->cc_scratch = magic;
2269 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2270 if (po->btj != NULL) {
2272 for (j = 0; j < po->btj->count; j++)
2273 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2277 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2278 if (!(po->flags & OPF_CC))
2281 if (po->flags & OPF_TAIL)
2286 static const struct parsed_proto *try_recover_pp(
2287 struct parsed_op *po, const struct parsed_opr *opr)
2289 const struct parsed_proto *pp = NULL;
2291 // maybe an arg of g_func?
2292 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2294 char ofs_reg[16] = { 0, };
2295 int arg, arg_s, arg_i;
2299 parse_stack_access(po, opr->name, ofs_reg,
2300 &offset, &stack_ra, NULL);
2301 if (ofs_reg[0] != 0)
2302 ferr(po, "offset reg on arg access?\n");
2303 if (offset <= stack_ra)
2304 ferr(po, "stack var call unhandled yet\n");
2306 arg_i = (offset - stack_ra - 4) / 4;
2307 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2308 if (g_func_pp->arg[arg].reg != NULL)
2314 if (arg == g_func_pp->argc)
2315 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2317 pp = g_func_pp->arg[arg].fptr;
2319 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2320 if (pp->argc_reg != 0)
2321 ferr(po, "icall sa: reg arg in arg-call unhandled yet\n");
2323 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2324 pp = proto_parse(g_fhdr, opr->name);
2326 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2327 if (pp->argc_reg != 0)
2328 ferr(po, "arg-call unhandled yet for '%s'\n", opr->name);
2334 static void scan_for_call_type(int i, struct parsed_opr *opr,
2335 int magic, const struct parsed_proto **pp_found)
2337 const struct parsed_proto *pp = NULL;
2338 struct parsed_op *po;
2339 struct label_ref *lr;
2342 if (ops[i].cc_scratch == magic)
2344 ops[i].cc_scratch = magic;
2346 if (g_labels[i][0] != 0) {
2347 lr = &g_label_refs[i];
2348 for (; lr != NULL; lr = lr->next)
2349 scan_for_call_type(lr->i, opr, magic, pp_found);
2350 if (i > 0 && LAST_OP(i - 1))
2355 if (!(ops[i].flags & OPF_DATA))
2357 if (!is_opr_modified(opr, &ops[i]))
2359 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2360 // most probably trashed by some processing
2365 opr = &ops[i].operand[1];
2366 if (opr->type != OPT_REG)
2370 po = (i >= 0) ? &ops[i] : ops;
2373 // reached the top - can only be an arg-reg
2374 if (opr->type != OPT_REG)
2377 for (i = 0; i < g_func_pp->argc; i++) {
2378 if (g_func_pp->arg[i].reg == NULL)
2380 if (IS(opr->name, g_func_pp->arg[i].reg))
2383 if (i == g_func_pp->argc)
2385 pp = g_func_pp->arg[i].fptr;
2387 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2388 i + 1, g_func_pp->arg[i].reg);
2389 if (pp->argc_reg != 0)
2390 ferr(po, "icall: reg arg in arg-call unhandled yet\n");
2393 pp = try_recover_pp(po, opr);
2395 if (*pp_found != NULL && pp != NULL) {
2396 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2397 || (*pp_found)->is_stdcall != pp->is_stdcall
2398 || (*pp_found)->argc != pp->argc
2399 || (*pp_found)->argc_reg != pp->argc_reg
2400 || (*pp_found)->argc_stack != pp->argc_stack)
2402 ferr(po, "icall: parsed_proto mismatch\n");
2409 static const struct parsed_proto *resolve_call(int i, int opcnt)
2411 const struct parsed_proto *pp = NULL;
2413 switch (ops[i].operand[0].type) {
2417 pp = try_recover_pp(&ops[i], &ops[i].operand[0]);
2420 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp);
2427 static int collect_call_args(struct parsed_op *po, int i,
2428 struct parsed_proto *pp, int *save_arg_vars, int arg,
2429 int magic, int need_op_saving, int may_reuse)
2431 struct parsed_proto *pp_tmp;
2432 struct label_ref *lr;
2433 int need_to_save_current;
2438 ferr(po, "dead label encountered\n");
2442 for (; arg < pp->argc; arg++)
2443 if (pp->arg[arg].reg == NULL)
2445 magic = (magic & 0xffffff) | (arg << 24);
2447 for (j = i; j >= 0 && arg < pp->argc; )
2449 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2450 if (ops[j].cc_scratch != magic) {
2451 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2455 // ok: have already been here
2458 ops[j].cc_scratch = magic;
2460 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2461 lr = &g_label_refs[j];
2462 if (lr->next != NULL)
2464 for (; lr->next; lr = lr->next) {
2465 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2467 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2468 arg, magic, need_op_saving, may_reuse);
2473 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2475 if (j > 0 && LAST_OP(j - 1)) {
2476 // follow last branch in reverse
2481 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2482 arg, magic, need_op_saving, may_reuse);
2488 if (ops[j].op == OP_CALL)
2490 pp_tmp = ops[j].datap;
2492 ferr(po, "arg collect hit unparsed call '%s'\n",
2493 ops[j].operand[0].name);
2494 if (may_reuse && pp_tmp->argc_stack > 0)
2495 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2496 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2498 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2499 ferr(po, "arg collect %d/%d hit esp adjust\n",
2502 else if (ops[j].op == OP_POP) {
2503 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2505 else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2509 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2511 pp->arg[arg].datap = &ops[j];
2512 need_to_save_current = 0;
2513 if (!need_op_saving) {
2514 ret = scan_for_mod(&ops[j], j + 1, i);
2515 need_to_save_current = (ret >= 0);
2517 if (need_op_saving || need_to_save_current) {
2518 // mark this push as one that needs operand saving
2519 ops[j].flags &= ~OPF_RMD;
2520 if (ops[j].argnum == 0) {
2521 ops[j].argnum = arg + 1;
2522 *save_arg_vars |= 1 << arg;
2524 else if (ops[j].argnum < arg + 1)
2525 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2526 ops[j].argnum, arg + 1, pp->name);
2528 else if (ops[j].argnum == 0)
2529 ops[j].flags |= OPF_RMD;
2531 // some PUSHes are reused by different calls on other branches,
2532 // but that can't happen if we didn't branch, so they
2533 // can be removed from future searches (handles nested calls)
2535 ops[j].flags |= OPF_FARG;
2538 for (arg++; arg < pp->argc; arg++)
2539 if (pp->arg[arg].reg == NULL)
2541 magic = (magic & 0xffffff) | (arg << 24);
2545 if (arg < pp->argc) {
2546 ferr(po, "arg collect failed for '%s': %d/%d\n",
2547 pp->name, arg, pp->argc);
2553 static void add_label_ref(struct label_ref *lr, int op_i)
2555 struct label_ref *lr_new;
2562 lr_new = calloc(1, sizeof(*lr_new));
2564 lr_new->next = lr->next;
2568 static void output_std_flags(FILE *fout, struct parsed_op *po,
2569 int *pfomask, const char *dst_opr_text)
2571 if (*pfomask & (1 << PFO_Z)) {
2572 fprintf(fout, "\n cond_z = (%s%s == 0);",
2573 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2574 *pfomask &= ~(1 << PFO_Z);
2576 if (*pfomask & (1 << PFO_S)) {
2577 fprintf(fout, "\n cond_s = (%s%s < 0);",
2578 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2579 *pfomask &= ~(1 << PFO_S);
2583 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2585 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2586 struct parsed_opr *last_arith_dst = NULL;
2587 char buf1[256], buf2[256], buf3[256], cast[64];
2588 const struct parsed_proto *pp_c;
2589 struct parsed_proto *pp, *pp_tmp;
2590 struct parsed_data *pd;
2591 const char *tmpname;
2592 enum parsed_flag_op pfo;
2593 int save_arg_vars = 0;
2594 int cmp_result_vars = 0;
2595 int need_mul_var = 0;
2596 int have_func_ret = 0;
2597 int have_normal_ret = 0;
2599 int label_pending = 0;
2600 int regmask_save = 0;
2601 int regmask_arg = 0;
2602 int regmask_now = 0;
2614 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2615 g_stack_frame_used = 0;
2617 g_func_pp = proto_parse(fhdr, funcn);
2618 if (g_func_pp == NULL)
2619 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2621 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2622 if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2623 fprintf(fout, "__stdcall ");
2624 if (g_ida_func_attr & IDAFA_NORETURN)
2625 fprintf(fout, "noreturn ");
2626 fprintf(fout, "%s(", funcn);
2628 for (i = 0; i < g_func_pp->argc; i++) {
2630 fprintf(fout, ", ");
2631 if (g_func_pp->arg[i].fptr != NULL) {
2633 pp = g_func_pp->arg[i].fptr;
2634 fprintf(fout, "%s (", pp->ret_type.name);
2635 if (pp->is_stdcall && pp->argc_reg == 0)
2636 fprintf(fout, "__stdcall ");
2637 fprintf(fout, "*a%d)(", i + 1);
2638 for (j = 0; j < pp->argc; j++) {
2640 fprintf(fout, ", ");
2641 if (pp->arg[j].fptr)
2642 ferr(ops, "nested fptr\n");
2643 fprintf(fout, "%s", pp->arg[j].type.name);
2648 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2651 if (g_func_pp->is_vararg) {
2653 fprintf(fout, ", ");
2654 fprintf(fout, "...");
2657 fprintf(fout, ")\n{\n");
2660 // - handle ebp/esp frame, remove ops related to it
2661 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2662 && ops[1].op == OP_MOV
2663 && IS(opr_name(&ops[1], 0), "ebp")
2664 && IS(opr_name(&ops[1], 1), "esp"))
2669 ops[0].flags |= OPF_RMD;
2670 ops[1].flags |= OPF_RMD;
2673 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2674 g_stack_fsz = opr_const(&ops[2], 1);
2675 ops[2].flags |= OPF_RMD;
2679 // another way msvc builds stack frame..
2681 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2683 ops[i].flags |= OPF_RMD;
2687 // and another way..
2688 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2689 && ops[i].operand[1].type == OPT_CONST
2690 && ops[i + 1].op == OP_CALL
2691 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2693 g_stack_fsz += ops[i].operand[1].val;
2694 ops[i].flags |= OPF_RMD;
2696 ops[i].flags |= OPF_RMD;
2703 for (; i < opcnt; i++)
2704 if (ops[i].op == OP_RET)
2706 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2709 if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2710 ops[i - 1].flags |= OPF_RMD;
2711 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2712 ferr(&ops[i - 1], "'pop ebp' expected\n");
2714 if (g_stack_fsz != 0) {
2715 if (ops[i - 2].op == OP_MOV
2716 && IS(opr_name(&ops[i - 2], 0), "esp")
2717 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2719 ops[i - 2].flags |= OPF_RMD;
2721 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2722 ferr(&ops[i - 2], "esp restore expected\n");
2724 if (ecx_push && ops[i - 3].op == OP_POP
2725 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2727 ferr(&ops[i - 3], "unexpected ecx pop\n");
2733 } while (i < opcnt);
2736 for (i = 0; i < opcnt; i++) {
2737 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2739 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2740 && ops[i].operand[1].type == OPT_CONST)
2749 g_stack_fsz = ops[i].operand[1].val;
2750 ops[i].flags |= OPF_RMD;
2754 for (; i < opcnt; i++)
2755 if (ops[i].op == OP_RET)
2757 if (ops[i - 1].op != OP_ADD
2758 || !IS(opr_name(&ops[i - 1], 0), "esp")
2759 || ops[i - 1].operand[1].type != OPT_CONST
2760 || ops[i - 1].operand[1].val != g_stack_fsz)
2761 ferr(&ops[i - 1], "'add esp' expected\n");
2762 ops[i - 1].flags |= OPF_RMD;
2765 } while (i < opcnt);
2770 // - parse calls with labels
2771 // - resolve all branches
2772 for (i = 0; i < opcnt; i++)
2778 if (po->flags & OPF_RMD)
2781 if (po->op == OP_CALL) {
2782 if (po->operand[0].type == OPT_LABEL) {
2783 tmpname = opr_name(po, 0);
2784 if (IS_START(tmpname, "loc_"))
2785 ferr(po, "call to loc_*\n");
2786 pp_c = proto_parse(fhdr, tmpname);
2788 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2789 if (pp_c->is_fptr && pp_c->argc_reg != 0)
2790 ferr(po, "fptr call with reg arg\n");
2791 pp = proto_clone(pp_c);
2792 my_assert_not(pp, NULL);
2798 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2801 if (po->operand[0].type == OPT_REGMEM) {
2802 char *p = strchr(po->operand[0].name, '[');
2804 ferr(po, "unhandled indirect branch\n");
2805 ret = p - po->operand[0].name;
2806 strncpy(buf1, po->operand[0].name, ret);
2809 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2810 if (IS(g_func_pd[j].label, buf1)) {
2816 //ferr(po, "label '%s' not parsed?\n", buf1);
2818 if (pd->type != OPT_OFFSET)
2819 ferr(po, "label '%s' with non-offset data?\n", buf1);
2821 // find all labels, link
2822 for (j = 0; j < pd->count; j++) {
2823 for (l = 0; l < opcnt; l++) {
2824 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2825 add_label_ref(&g_label_refs[l], i);
2836 for (l = 0; l < opcnt; l++) {
2837 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2838 add_label_ref(&g_label_refs[l], i);
2847 if (po->operand[0].type == OPT_LABEL)
2851 ferr(po, "unhandled branch\n");
2855 po->flags |= OPF_TAIL;
2860 // - remove dead labels
2862 for (i = 0; i < opcnt; i++)
2864 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
2868 if (po->flags & OPF_RMD)
2871 if (po->op == OP_CALL)
2873 tmpname = opr_name(po, 0);
2878 pp_c = resolve_call(i, opcnt);
2880 pp = proto_clone(pp_c);
2882 pp = calloc(1, sizeof(*pp));
2883 my_assert_not(pp, NULL);
2884 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2886 ferr(po, "non-__cdecl indirect call unhandled yet\n");
2888 if (j > ARRAY_SIZE(pp->arg))
2889 ferr(po, "esp adjust too large?\n");
2890 pp->ret_type.name = strdup("int");
2891 pp->argc = pp->argc_stack = j;
2892 for (arg = 0; arg < pp->argc; arg++)
2893 pp->arg[arg].type.name = strdup("int");
2898 // look for and make use of esp adjust
2900 if (!pp->is_stdcall && pp->argc_stack > 0)
2901 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2903 if (pp->is_vararg) {
2904 if (j / 4 < pp->argc_stack)
2905 ferr(po, "esp adjust is too small: %x < %x\n",
2906 j, pp->argc_stack * 4);
2907 // modify pp to make it have varargs as normal args
2909 pp->argc += j / 4 - pp->argc_stack;
2910 for (; arg < pp->argc; arg++) {
2911 pp->arg[arg].type.name = strdup("int");
2914 if (pp->argc > ARRAY_SIZE(pp->arg))
2915 ferr(po, "too many args for '%s'\n", tmpname);
2917 if (pp->argc_stack != j / 4)
2918 ferr(po, "stack tracking failed for '%s': %x %x\n",
2919 tmpname, pp->argc_stack * 4, j);
2921 ops[ret].flags |= OPF_RMD;
2922 // a bit of a hack, but deals with use of
2923 // single adj for multiple calls
2924 ops[ret].operand[1].val -= j;
2926 else if (pp->is_vararg)
2927 ferr(po, "missing esp_adjust for vararg func '%s'\n",
2930 // can't call functions with non-__cdecl callbacks yet
2931 for (arg = 0; arg < pp->argc; arg++) {
2932 if (pp->arg[arg].fptr != NULL) {
2933 pp_tmp = pp->arg[arg].fptr;
2934 if (pp_tmp->argc_reg != 0)
2935 ferr(po, "'%s' has a callback with reg-args\n", tmpname);
2939 collect_call_args(po, i, pp, &save_arg_vars,
2940 0, i + opcnt * 2, 0, 0);
2942 if (strstr(pp->ret_type.name, "int64"))
2944 if (!(po->flags & OPF_TAIL) && !IS(pp->ret_type.name, "void"))
2950 // - find POPs for PUSHes, rm both
2951 // - scan for all used registers
2952 // - find flag set ops for their users
2953 // - declare indirect functions
2954 for (i = 0; i < opcnt; i++) {
2956 if (po->flags & OPF_RMD)
2959 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
2960 reg = po->operand[0].reg;
2961 if (!(regmask & (1 << reg)))
2962 // not a reg save after all, rerun scan_for_pop
2963 po->flags &= ~OPF_RSAVE;
2965 regmask_save |= 1 << reg;
2968 if (po->op == OP_PUSH
2969 && po->argnum == 0 && !(po->flags & OPF_RSAVE)
2970 && po->operand[0].type == OPT_REG)
2972 reg = po->operand[0].reg;
2974 ferr(po, "reg not set for push?\n");
2977 ret = scan_for_pop(i + 1, opcnt,
2978 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
2981 ferr(po, "too much depth: %d\n", depth);
2983 po->flags |= OPF_RMD;
2984 scan_for_pop(i + 1, opcnt, po->operand[0].name,
2985 i + opcnt * 4, 0, &depth, 1);
2988 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
2991 if (regmask & (1 << reg)) {
2992 if (regmask_save & (1 << reg))
2993 ferr(po, "%s already saved?\n", po->operand[0].name);
2997 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3002 regmask_now = po->regmask_src | po->regmask_dst;
3003 if (regmask_now & (1 << xBP)) {
3004 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3005 if (po->regmask_dst & (1 << xBP))
3006 // compiler decided to drop bp frame and use ebp as scratch
3007 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
3009 regmask_now &= ~(1 << xBP);
3013 regmask |= regmask_now;
3015 if (po->flags & OPF_CC)
3017 int setters[16], cnt = 0, branched = 0;
3019 ret = scan_for_flag_set(i, i + opcnt * 6,
3020 &branched, setters, &cnt);
3021 if (ret < 0 || cnt <= 0)
3022 ferr(po, "unable to trace flag setter(s)\n");
3023 if (cnt > ARRAY_SIZE(setters))
3024 ferr(po, "too many flag setters\n");
3026 pfo = split_cond(po, po->op, &dummy);
3027 for (j = 0; j < cnt; j++)
3029 tmp_op = &ops[setters[j]]; // flag setter
3032 // to get nicer code, we try to delay test and cmp;
3033 // if we can't because of operand modification, or if we
3034 // have math op, or branch, make it calculate flags explicitly
3035 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
3036 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i) >= 0)
3039 else if (tmp_op->op == OP_CMPS) {
3040 pfomask = 1 << PFO_Z;
3043 // see if we'll be able to handle based on op result
3044 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3045 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3047 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3051 tmp_op->pfomask |= pfomask;
3052 cmp_result_vars |= pfomask;
3054 // note: may overwrite, currently not a problem
3058 if (po->op == OP_ADC || po->op == OP_SBB)
3059 cmp_result_vars |= 1 << PFO_C;
3061 else if (po->op == OP_MUL
3062 || (po->op == OP_IMUL && po->operand_cnt == 1))
3066 else if (po->op == OP_CALL && po->operand[0].type != OPT_LABEL) {
3068 my_assert_not(pp, NULL);
3069 fprintf(fout, " %s (", pp->ret_type.name);
3070 if (pp->is_stdcall && pp->argc_reg == 0)
3071 fprintf(fout, "__stdcall ");
3072 fprintf(fout, "*icall%d)(", i);
3073 for (j = 0; j < pp->argc; j++) {
3075 fprintf(fout, ", ");
3076 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3078 fprintf(fout, ");\n");
3080 else if (po->op == OP_RET)
3081 have_normal_ret = 1;
3084 // output LUTs/jumptables
3085 for (i = 0; i < g_func_pd_cnt; i++) {
3087 fprintf(fout, " static const ");
3088 if (pd->type == OPT_OFFSET) {
3089 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3091 for (j = 0; j < pd->count; j++) {
3093 fprintf(fout, ", ");
3094 fprintf(fout, "&&%s", pd->d[j].u.label);
3098 fprintf(fout, "%s %s[] =\n { ",
3099 lmod_type_u(ops, pd->lmod), pd->label);
3101 for (j = 0; j < pd->count; j++) {
3103 fprintf(fout, ", ");
3104 fprintf(fout, "%u", pd->d[j].u.val);
3107 fprintf(fout, " };\n");
3110 // declare stack frame, va_arg
3112 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3113 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3115 if (g_func_pp->is_vararg)
3116 fprintf(fout, " va_list ap;\n");
3118 // declare arg-registers
3119 for (i = 0; i < g_func_pp->argc; i++) {
3120 if (g_func_pp->arg[i].reg != NULL) {
3121 reg = char_array_i(regs_r32,
3122 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3124 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
3126 regmask_arg |= 1 << reg;
3127 fprintf(fout, " u32 %s = (u32)a%d;\n",
3128 g_func_pp->arg[i].reg, i + 1);
3133 // declare other regs - special case for eax
3134 if (!((regmask | regmask_arg) & 1)
3135 && (have_func_ret || have_normal_ret)
3136 && !IS(g_func_pp->ret_type.name, "void"))
3138 fprintf(fout, " u32 eax = 0;\n");
3142 regmask &= ~regmask_arg;
3143 regmask &= ~(1 << xSP);
3145 for (reg = 0; reg < 8; reg++) {
3146 if (regmask & (1 << reg)) {
3147 fprintf(fout, " u32 %s;\n", regs_r32[reg]);
3154 for (reg = 0; reg < 8; reg++) {
3155 if (regmask_save & (1 << reg)) {
3156 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3162 if (save_arg_vars) {
3163 for (reg = 0; reg < 32; reg++) {
3164 if (save_arg_vars & (1 << reg)) {
3165 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3171 if (cmp_result_vars) {
3172 for (i = 0; i < 8; i++) {
3173 if (cmp_result_vars & (1 << i)) {
3174 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3181 fprintf(fout, " u64 mul_tmp;\n");
3186 fprintf(fout, "\n");
3188 if (g_func_pp->is_vararg) {
3189 if (g_func_pp->argc_stack == 0)
3190 ferr(ops, "vararg func without stack args?\n");
3191 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3195 for (i = 0; i < opcnt; i++)
3197 if (g_labels[i][0] != 0) {
3198 fprintf(fout, "\n%s:\n", g_labels[i]);
3201 delayed_flag_op = NULL;
3202 last_arith_dst = NULL;
3206 if (po->flags & OPF_RMD)
3211 #define assert_operand_cnt(n_) \
3212 if (po->operand_cnt != n_) \
3213 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3215 // conditional/flag using op?
3216 if (po->flags & OPF_CC)
3221 pfo = split_cond(po, po->op, &is_inv);
3224 // we go through all this trouble to avoid using parsed_flag_op,
3225 // which makes generated code much nicer
3226 if (delayed_flag_op != NULL)
3228 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3231 else if (last_arith_dst != NULL
3232 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3233 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3236 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3237 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3238 last_arith_dst->lmod, buf3);
3241 else if (tmp_op != NULL) {
3242 // use preprocessed flag calc results
3243 if (!(tmp_op->pfomask & (1 << pfo)))
3244 ferr(po, "not prepared for pfo %d\n", pfo);
3246 // note: is_inv was not yet applied
3247 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3248 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3251 ferr(po, "all methods of finding comparison failed\n");
3254 if (po->flags & OPF_JMP) {
3255 fprintf(fout, " if %s\n", buf1);
3257 else if (po->op == OP_ADC || po->op == OP_SBB) {
3259 fprintf(fout, " cond_%s = %s;\n",
3260 parsed_flag_op_names[pfo], buf1);
3262 else if (po->flags & OPF_DATA) { // SETcc
3263 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3264 fprintf(fout, " %s = %s;", buf2, buf1);
3267 ferr(po, "unhandled conditional op\n");
3271 pfomask = po->pfomask;
3276 assert_operand_cnt(2);
3277 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3278 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3279 fprintf(fout, " %s = %s;", buf1,
3280 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3281 po->operand[0].is_ptr ? "(void *)" : "", 0));
3285 assert_operand_cnt(2);
3286 po->operand[1].lmod = OPLM_DWORD; // always
3287 fprintf(fout, " %s = %s;",
3288 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3289 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3294 assert_operand_cnt(2);
3295 fprintf(fout, " %s = %s;",
3296 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3297 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3301 assert_operand_cnt(2);
3302 switch (po->operand[1].lmod) {
3304 strcpy(buf3, "(s8)");
3307 strcpy(buf3, "(s16)");
3310 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3312 fprintf(fout, " %s = %s;",
3313 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3314 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3319 assert_operand_cnt(1);
3320 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3321 fprintf(fout, " %s = ~%s;", buf1, buf1);
3325 assert_operand_cnt(2);
3326 fprintf(fout, " %s = (s32)%s >> 31;",
3327 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3328 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3329 strcpy(g_comment, "cdq");
3334 assert_operand_cnt(3);
3335 if (po->flags & OPF_REP) {
3336 fprintf(fout, " for (; ecx != 0; ecx--, edi += %d)\n",
3337 lmod_bytes(po, po->operand[0].lmod));
3338 fprintf(fout, " %sedi = eax;",
3339 lmod_cast_u_ptr(po, po->operand[0].lmod));
3340 strcpy(g_comment, "rep stos");
3343 fprintf(fout, " %sedi = eax; edi += %d;",
3344 lmod_cast_u_ptr(po, po->operand[0].lmod),
3345 lmod_bytes(po, po->operand[0].lmod));
3346 strcpy(g_comment, "stos");
3352 assert_operand_cnt(3);
3353 j = lmod_bytes(po, po->operand[0].lmod);
3354 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3355 if (po->flags & OPF_REP) {
3357 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3360 " %sedi = %sesi;", buf1, buf1);
3361 strcpy(g_comment, "rep movs");
3364 fprintf(fout, " %sedi = %sesi; edi += %d; esi += %d;",
3366 strcpy(g_comment, "movs");
3372 // repe ~ repeat while ZF=1
3373 assert_operand_cnt(3);
3374 j = lmod_bytes(po, po->operand[0].lmod);
3375 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3376 if (po->flags & OPF_REP) {
3378 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3381 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3382 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3385 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3386 (po->flags & OPF_REPZ) ? "e" : "ne");
3390 " cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3392 strcpy(g_comment, "cmps");
3394 pfomask &= ~(1 << PFO_Z);
3395 last_arith_dst = NULL;
3396 delayed_flag_op = NULL;
3399 // arithmetic w/flags
3404 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3407 assert_operand_cnt(2);
3408 fprintf(fout, " %s %s= %s;",
3409 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3411 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3412 output_std_flags(fout, po, &pfomask, buf1);
3413 last_arith_dst = &po->operand[0];
3414 delayed_flag_op = NULL;
3419 assert_operand_cnt(2);
3420 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3421 if (pfomask & (1 << PFO_C)) {
3422 if (po->operand[1].type == OPT_CONST) {
3423 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3424 j = po->operand[1].val;
3427 if (po->op == OP_SHL)
3431 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3435 ferr(po, "zero shift?\n");
3439 pfomask &= ~(1 << PFO_C);
3441 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3442 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3443 output_std_flags(fout, po, &pfomask, buf1);
3444 last_arith_dst = &po->operand[0];
3445 delayed_flag_op = NULL;
3449 assert_operand_cnt(2);
3450 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3451 fprintf(fout, " %s = %s%s >> %s;", buf1,
3452 lmod_cast_s(po, po->operand[0].lmod), buf1,
3453 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3454 output_std_flags(fout, po, &pfomask, buf1);
3455 last_arith_dst = &po->operand[0];
3456 delayed_flag_op = NULL;
3461 assert_operand_cnt(2);
3462 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3463 if (po->operand[1].type == OPT_CONST) {
3464 j = po->operand[1].val;
3465 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3466 fprintf(fout, po->op == OP_ROL ?
3467 " %s = (%s << %d) | (%s >> %d);" :
3468 " %s = (%s >> %d) | (%s << %d);",
3469 buf1, buf1, j, buf1,
3470 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3474 output_std_flags(fout, po, &pfomask, buf1);
3475 last_arith_dst = &po->operand[0];
3476 delayed_flag_op = NULL;
3480 assert_operand_cnt(2);
3481 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3482 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3483 // special case for XOR
3484 fprintf(fout, " %s = 0;",
3485 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3486 last_arith_dst = &po->operand[0];
3487 delayed_flag_op = NULL;
3494 assert_operand_cnt(2);
3495 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3496 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3497 if (po->op == OP_SBB
3498 && IS(po->operand[0].name, po->operand[1].name))
3500 // avoid use of unitialized var
3501 fprintf(fout, " %s = -cond_c;", buf1);
3502 // carry remains what it was
3503 pfomask &= ~(1 << PFO_C);
3506 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3507 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3509 output_std_flags(fout, po, &pfomask, buf1);
3510 last_arith_dst = &po->operand[0];
3511 delayed_flag_op = NULL;
3516 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3517 if (po->operand[0].type == OPT_REG) {
3518 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3519 fprintf(fout, " %s%s;", buf1, buf2);
3522 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3523 fprintf(fout, " %s %s= 1;", buf1, buf2);
3525 output_std_flags(fout, po, &pfomask, buf1);
3526 last_arith_dst = &po->operand[0];
3527 delayed_flag_op = NULL;
3531 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3532 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3533 fprintf(fout, " %s = -%s%s;", buf1,
3534 lmod_cast_s(po, po->operand[0].lmod), buf2);
3535 last_arith_dst = &po->operand[0];
3536 delayed_flag_op = NULL;
3537 if (pfomask & (1 << PFO_C)) {
3538 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3539 pfomask &= ~(1 << PFO_C);
3544 if (po->operand_cnt == 2) {
3545 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3548 if (po->operand_cnt == 3)
3549 ferr(po, "TODO imul3\n");
3552 assert_operand_cnt(1);
3553 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3554 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3555 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3556 fprintf(fout, " edx = mul_tmp >> 32;\n");
3557 fprintf(fout, " eax = mul_tmp;");
3558 last_arith_dst = NULL;
3559 delayed_flag_op = NULL;
3564 assert_operand_cnt(1);
3565 if (po->operand[0].lmod != OPLM_DWORD)
3566 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3568 // 32bit division is common, look for it
3569 if (po->op == OP_DIV)
3570 ret = scan_for_reg_clear(i, xDX);
3572 ret = scan_for_cdq_edx(i);
3574 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3575 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3576 po->op == OP_IDIV));
3577 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3578 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3581 ferr(po, "TODO 64bit divident\n");
3582 last_arith_dst = NULL;
3583 delayed_flag_op = NULL;
3588 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3590 for (j = 0; j < 8; j++) {
3591 if (pfomask & (1 << j)) {
3592 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3593 fprintf(fout, " cond_%s = %s;",
3594 parsed_flag_op_names[j], buf1);
3601 last_arith_dst = NULL;
3602 delayed_flag_op = po;
3605 // note: we reuse OP_Jcc for SETcc, only flags differ
3606 case OP_JO ... OP_JG:
3607 if (po->flags & OPF_JMP)
3608 fprintf(fout, " goto %s;", po->operand[0].name);
3609 // else SETcc - should already be handled
3613 assert_operand_cnt(1);
3614 last_arith_dst = NULL;
3615 delayed_flag_op = NULL;
3617 if (po->operand[0].type == OPT_REGMEM) {
3618 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3621 ferr(po, "parse failure for jmp '%s'\n",
3622 po->operand[0].name);
3623 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
3626 else if (po->operand[0].type != OPT_LABEL)
3627 ferr(po, "unhandled jmp type\n");
3629 fprintf(fout, " goto %s;", po->operand[0].name);
3633 assert_operand_cnt(1);
3636 ferr(po, "NULL pp\n");
3638 if (po->operand[0].type != OPT_LABEL)
3639 fprintf(fout, " icall%d = %s;\n", i,
3640 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
3644 if (strstr(pp->ret_type.name, "int64")) {
3645 if (po->flags & OPF_TAIL)
3646 ferr(po, "int64 and tail?\n");
3647 fprintf(fout, "mul_tmp = ");
3649 else if (!IS(pp->ret_type.name, "void")) {
3650 if (po->flags & OPF_TAIL) {
3651 if (!IS(g_func_pp->ret_type.name, "void")) {
3652 fprintf(fout, "return ");
3653 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3654 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3658 fprintf(fout, "eax = ");
3659 if (pp->ret_type.is_ptr)
3660 fprintf(fout, "(u32)");
3664 if (po->operand[0].type != OPT_LABEL) {
3665 fprintf(fout, "icall%d(", i);
3668 if (pp->name[0] == 0)
3669 ferr(po, "missing pp->name\n");
3670 fprintf(fout, "%s%s(", pp->name,
3671 pp->has_structarg ? "_sa" : "");
3674 for (arg = 0; arg < pp->argc; arg++) {
3676 fprintf(fout, ", ");
3679 if (pp->arg[arg].type.is_ptr)
3680 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3682 if (pp->arg[arg].reg != NULL) {
3683 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3688 tmp_op = pp->arg[arg].datap;
3690 ferr(po, "parsed_op missing for arg%d\n", arg);
3691 if (tmp_op->argnum != 0) {
3692 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3696 out_src_opr(buf1, sizeof(buf1),
3697 tmp_op, &tmp_op->operand[0], cast, 0));
3700 fprintf(fout, ");");
3702 if (strstr(pp->ret_type.name, "int64")) {
3703 fprintf(fout, "\n");
3704 fprintf(fout, " edx = mul_tmp >> 32;\n");
3705 fprintf(fout, " eax = mul_tmp;");
3708 if (po->flags & OPF_TAIL) {
3709 strcpy(g_comment, "tailcall");
3713 else if (IS(pp->ret_type.name, "void"))
3715 else if (IS(g_func_pp->ret_type.name, "void"))
3717 // else already handled as 'return f()'
3720 if (!IS(g_func_pp->ret_type.name, "void"))
3721 ferr(po, "int func -> void func tailcall?\n");
3722 fprintf(fout, "\n return;");
3723 strcpy(g_comment, "^ tailcall");
3726 delayed_flag_op = NULL;
3727 last_arith_dst = NULL;
3731 if (g_func_pp->is_vararg)
3732 fprintf(fout, " va_end(ap);\n");
3734 if (IS(g_func_pp->ret_type.name, "void")) {
3735 if (i != opcnt - 1 || label_pending)
3736 fprintf(fout, " return;");
3738 else if (g_func_pp->ret_type.is_ptr) {
3739 fprintf(fout, " return (%s)eax;",
3740 g_func_pp->ret_type.name);
3743 fprintf(fout, " return eax;");
3745 last_arith_dst = NULL;
3746 delayed_flag_op = NULL;
3750 if (po->argnum != 0) {
3751 // special case - saved func arg
3752 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3753 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
3756 else if (po->flags & OPF_RSAVE) {
3757 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3758 fprintf(fout, " s_%s = %s;", buf1, buf1);
3761 if (!(g_ida_func_attr & IDAFA_NORETURN))
3762 ferr(po, "stray push encountered\n");
3767 if (po->flags & OPF_RSAVE) {
3768 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3769 fprintf(fout, " %s = s_%s;", buf1, buf1);
3772 ferr(po, "stray pop encountered\n");
3781 ferr(po, "unhandled op type %d, flags %x\n",
3786 if (g_comment[0] != 0) {
3787 fprintf(fout, " // %s", g_comment);
3792 fprintf(fout, "\n");
3794 // some sanity checking
3795 if ((po->flags & OPF_REP) && po->op != OP_STOS
3796 && po->op != OP_MOVS && po->op != OP_CMPS)
3797 ferr(po, "unexpected rep\n");
3798 if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3799 ferr(po, "unexpected repz/repnz\n");
3802 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3804 // see is delayed flag stuff is still valid
3805 if (delayed_flag_op != NULL && delayed_flag_op != po) {
3806 if (is_any_opr_modified(delayed_flag_op, po))
3807 delayed_flag_op = NULL;
3810 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3811 if (is_opr_modified(last_arith_dst, po))
3812 last_arith_dst = NULL;
3818 if (g_stack_fsz && !g_stack_frame_used)
3819 fprintf(fout, " (void)sf;\n");
3821 fprintf(fout, "}\n\n");
3824 for (i = 0; i < opcnt; i++) {
3825 struct label_ref *lr, *lr_del;
3827 lr = g_label_refs[i].next;
3828 while (lr != NULL) {
3833 g_label_refs[i].i = -1;
3834 g_label_refs[i].next = NULL;
3836 if (ops[i].op == OP_CALL) {
3845 static void set_label(int i, const char *name)
3851 p = strchr(name, ':');
3855 if (len > sizeof(g_labels[0]) - 1)
3856 aerr("label '%s' too long: %d\n", name, len);
3857 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
3858 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
3859 memcpy(g_labels[i], name, len);
3860 g_labels[i][len] = 0;
3863 // '=' needs special treatment..
3864 static char *next_word_s(char *w, size_t wsize, char *s)
3870 for (i = 0; i < wsize - 1; i++) {
3871 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
3877 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
3878 printf("warning: '%s' truncated\n", w);
3889 static struct chunk_item *func_chunks;
3890 static int func_chunk_cnt;
3891 static int func_chunk_alloc;
3893 static void add_func_chunk(FILE *fasm, const char *name, int line)
3895 if (func_chunk_cnt >= func_chunk_alloc) {
3896 func_chunk_alloc *= 2;
3897 func_chunks = realloc(func_chunks,
3898 func_chunk_alloc * sizeof(func_chunks[0]));
3899 my_assert_not(func_chunks, NULL);
3901 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
3902 func_chunks[func_chunk_cnt].name = strdup(name);
3903 func_chunks[func_chunk_cnt].asmln = line;
3907 static int cmp_chunks(const void *p1, const void *p2)
3909 const struct chunk_item *c1 = p1, *c2 = p2;
3910 return strcmp(c1->name, c2->name);
3913 static int cmpstringp(const void *p1, const void *p2)
3915 return strcmp(*(char * const *)p1, *(char * const *)p2);
3918 static void scan_ahead(FILE *fasm)
3928 oldpos = ftell(fasm);
3931 while (fgets(line, sizeof(line), fasm))
3942 // get rid of random tabs
3943 for (i = 0; line[i] != 0; i++)
3944 if (line[i] == '\t')
3947 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3950 next_word(words[0], sizeof(words[0]), p);
3951 if (words[0][0] == 0)
3952 aerr("missing name for func chunk?\n");
3954 add_func_chunk(fasm, words[0], asmln);
3959 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3960 words[wordc][0] = 0;
3961 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3962 if (*p == 0 || *p == ';') {
3968 if (wordc == 2 && IS(words[1], "ends"))
3972 fseek(fasm, oldpos, SEEK_SET);
3976 int main(int argc, char *argv[])
3978 FILE *fout, *fasm, *frlist;
3979 struct parsed_data *pd = NULL;
3981 char **rlist = NULL;
3983 int rlist_alloc = 0;
3984 int func_chunks_used = 0;
3985 int func_chunks_sorted = 0;
3986 int func_chunk_i = -1;
3987 long func_chunk_ret = 0;
3988 int func_chunk_ret_ln = 0;
3989 int scanned_ahead = 0;
3991 char words[20][256];
3992 enum opr_lenmod lmod;
3994 int pending_endp = 0;
3996 int skip_warned = 0;
4007 if (argv[1] && IS(argv[1], "-v")) {
4012 if (argc < arg + 3) {
4013 printf("usage:\n%s [-v] <.c> <.asm> <hdrf> [rlist]*\n",
4020 asmfn = argv[arg++];
4021 fasm = fopen(asmfn, "r");
4022 my_assert_not(fasm, NULL);
4024 hdrfn = argv[arg++];
4025 g_fhdr = fopen(hdrfn, "r");
4026 my_assert_not(g_fhdr, NULL);
4029 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4030 my_assert_not(rlist, NULL);
4031 // needs special handling..
4032 rlist[rlist_len++] = "__alloca_probe";
4034 func_chunk_alloc = 32;
4035 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4036 my_assert_not(func_chunks, NULL);
4038 memset(words, 0, sizeof(words));
4040 for (; arg < argc; arg++) {
4041 frlist = fopen(argv[arg], "r");
4042 my_assert_not(frlist, NULL);
4044 while (fgets(line, sizeof(line), frlist)) {
4046 if (*p == 0 || *p == ';')
4049 if (IS_START(p, "#if 0"))
4051 else if (IS_START(p, "#endif"))
4058 p = next_word(words[0], sizeof(words[0]), p);
4059 if (words[0][0] == 0)
4062 if (rlist_len >= rlist_alloc) {
4063 rlist_alloc = rlist_alloc * 2 + 64;
4064 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4065 my_assert_not(rlist, NULL);
4067 rlist[rlist_len++] = strdup(words[0]);
4076 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4078 fout = fopen(argv[arg_out], "w");
4079 my_assert_not(fout, NULL);
4082 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4083 my_assert_not(g_eqs, NULL);
4085 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4086 g_label_refs[i].i = -1;
4087 g_label_refs[i].next = NULL;
4090 while (fgets(line, sizeof(line), fasm))
4099 // get rid of random tabs
4100 for (i = 0; line[i] != 0; i++)
4101 if (line[i] == '\t')
4106 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4107 goto do_pending_endp; // eww..
4109 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4111 static const char *attrs[] = {
4120 // parse IDA's attribute-list comment
4121 g_ida_func_attr = 0;
4124 for (; *p != 0; p = sskip(p)) {
4125 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4126 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4127 g_ida_func_attr |= 1 << i;
4128 p += strlen(attrs[i]);
4132 if (i == ARRAY_SIZE(attrs)) {
4133 anote("unparsed IDA attr: %s\n", p);
4136 if (IS(attrs[i], "fpd=")) {
4137 p = next_word(words[0], sizeof(words[0]), p);
4142 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4145 next_word(words[0], sizeof(words[0]), p);
4146 if (words[0][0] == 0)
4147 aerr("missing name for func chunk?\n");
4149 if (!scanned_ahead) {
4150 add_func_chunk(fasm, words[0], asmln);
4151 func_chunks_sorted = 0;
4154 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4156 if (func_chunk_i >= 0) {
4157 if (func_chunk_i < func_chunk_cnt
4158 && IS(func_chunks[func_chunk_i].name, g_func))
4160 // move on to next chunk
4161 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4163 aerr("seek failed for '%s' chunk #%d\n",
4164 g_func, func_chunk_i);
4165 asmln = func_chunks[func_chunk_i].asmln;
4169 if (func_chunk_ret == 0)
4170 aerr("no return from chunk?\n");
4171 fseek(fasm, func_chunk_ret, SEEK_SET);
4172 asmln = func_chunk_ret_ln;
4178 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4179 func_chunks_used = 1;
4181 if (IS_START(g_func, "sub_")) {
4182 unsigned long addr = strtoul(p, NULL, 16);
4183 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4184 if (addr > f_addr && !scanned_ahead) {
4185 anote("scan_ahead caused by '%s', addr %lx\n",
4189 func_chunks_sorted = 0;
4197 for (i = wordc; i < ARRAY_SIZE(words); i++)
4199 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4200 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4201 if (*p == 0 || *p == ';') {
4206 if (*p != 0 && *p != ';')
4207 aerr("too many words\n");
4209 // alow asm patches in comments
4210 if (*p == ';' && IS_START(p, "; sctpatch:")) {
4212 if (*p == 0 || *p == ';')
4214 goto parse_words; // lame
4219 awarn("wordc == 0?\n");
4223 // don't care about this:
4224 if (words[0][0] == '.'
4225 || IS(words[0], "include")
4226 || IS(words[0], "assume") || IS(words[1], "segment")
4227 || IS(words[0], "align"))
4233 // do delayed endp processing to collect switch jumptables
4235 if (in_func && !skip_func && wordc >= 2
4236 && ((words[0][0] == 'd' && words[0][2] == 0)
4237 || (words[1][0] == 'd' && words[1][2] == 0)))
4240 if (words[1][0] == 'd' && words[1][2] == 0) {
4242 if (g_func_pd_cnt >= pd_alloc) {
4243 pd_alloc = pd_alloc * 2 + 16;
4244 g_func_pd = realloc(g_func_pd,
4245 sizeof(g_func_pd[0]) * pd_alloc);
4246 my_assert_not(g_func_pd, NULL);
4248 pd = &g_func_pd[g_func_pd_cnt];
4250 memset(pd, 0, sizeof(*pd));
4251 strcpy(pd->label, words[0]);
4252 pd->type = OPT_CONST;
4253 pd->lmod = lmod_from_directive(words[1]);
4257 lmod = lmod_from_directive(words[0]);
4258 if (lmod != pd->lmod)
4259 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4262 if (pd->count_alloc < pd->count + wordc) {
4263 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4264 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4265 my_assert_not(pd->d, NULL);
4267 for (; i < wordc; i++) {
4268 if (IS(words[i], "offset")) {
4269 pd->type = OPT_OFFSET;
4272 p = strchr(words[i], ',');
4275 if (pd->type == OPT_OFFSET)
4276 pd->d[pd->count].u.label = strdup(words[i]);
4278 pd->d[pd->count].u.val = parse_number(words[i]);
4279 pd->d[pd->count].bt_i = -1;
4285 if (in_func && !skip_func)
4286 gen_func(fout, g_fhdr, g_func, pi);
4290 g_ida_func_attr = 0;
4294 func_chunks_used = 0;
4297 memset(&ops, 0, pi * sizeof(ops[0]));
4298 memset(g_labels, 0, pi * sizeof(g_labels[0]));
4302 for (i = 0; i < g_func_pd_cnt; i++) {
4304 if (pd->type == OPT_OFFSET) {
4305 for (j = 0; j < pd->count; j++)
4306 free(pd->d[j].u.label);
4317 if (IS(words[1], "proc")) {
4319 aerr("proc '%s' while in_func '%s'?\n",
4322 if ((g_ida_func_attr & IDAFA_THUNK)
4323 || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4325 strcpy(g_func, words[0]);
4326 set_label(0, words[0]);
4331 if (IS(words[1], "endp"))
4334 aerr("endp '%s' while not in_func?\n", words[0]);
4335 if (!IS(g_func, words[0]))
4336 aerr("endp '%s' while in_func '%s'?\n",
4339 if (!skip_func && func_chunks_used) {
4340 // start processing chunks
4341 struct chunk_item *ci, key = { g_func, 0 };
4343 func_chunk_ret = ftell(fasm);
4344 func_chunk_ret_ln = asmln;
4345 if (!func_chunks_sorted) {
4346 qsort(func_chunks, func_chunk_cnt,
4347 sizeof(func_chunks[0]), cmp_chunks);
4348 func_chunks_sorted = 1;
4350 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4351 sizeof(func_chunks[0]), cmp_chunks);
4353 aerr("'%s' needs chunks, but none found\n", g_func);
4354 func_chunk_i = ci - func_chunks;
4355 for (; func_chunk_i > 0; func_chunk_i--)
4356 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4359 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4361 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4362 asmln = func_chunks[func_chunk_i].asmln;
4370 if (wordc == 2 && IS(words[1], "ends"))
4373 p = strchr(words[0], ':');
4375 set_label(pi, words[0]);
4379 if (!in_func || skip_func) {
4380 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4382 anote("skipping from '%s'\n", g_labels[pi]);
4385 g_labels[pi][0] = 0;
4389 if (wordc > 1 && IS(words[1], "=")) {
4391 aerr("unhandled equ, wc=%d\n", wordc);
4392 if (g_eqcnt >= eq_alloc) {
4394 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4395 my_assert_not(g_eqs, NULL);
4398 len = strlen(words[0]);
4399 if (len > sizeof(g_eqs[0].name) - 1)
4400 aerr("equ name too long: %d\n", len);
4401 strcpy(g_eqs[g_eqcnt].name, words[0]);
4403 if (!IS(words[3], "ptr"))
4404 aerr("unhandled equ\n");
4405 if (IS(words[2], "dword"))
4406 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4407 else if (IS(words[2], "word"))
4408 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4409 else if (IS(words[2], "byte"))
4410 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4412 aerr("bad lmod: '%s'\n", words[2]);
4414 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4419 if (pi >= ARRAY_SIZE(ops))
4420 aerr("too many ops\n");
4422 parse_op(&ops[pi], words, wordc);
4433 // vim:ts=2:shiftwidth=2:expandtab