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);
1409 if (g_stack_fsz == 0)
1410 ferr(po, "stack var access without stackframe\n");
1411 g_stack_frame_used = 1;
1413 sf_ofs = g_stack_fsz + offset;
1414 lim = (ofs_reg[0] != 0) ? -4 : 0;
1415 if (offset > 0 || sf_ofs < lim)
1416 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1426 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1427 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1431 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1432 // known unaligned or possibly unaligned
1433 strcat(g_comment, " unaligned");
1435 prefix = "*(u16 *)&";
1436 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1437 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1440 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1444 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1445 // known unaligned or possibly unaligned
1446 strcat(g_comment, " unaligned");
1448 prefix = "*(u32 *)&";
1449 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1450 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1453 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1457 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1462 static void check_label_read_ref(struct parsed_op *po, const char *name)
1464 const struct parsed_proto *pp;
1466 pp = proto_parse(g_fhdr, name);
1468 ferr(po, "proto_parse failed for ref '%s'\n", name);
1470 // currently we can take __cdecl and __stdcall
1471 if (pp->is_func && pp->argc_reg != 0)
1472 ferr(po, "reg-arg func reference?\n");
1475 static char *out_src_opr(char *buf, size_t buf_size,
1476 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1479 char tmp1[256], tmp2[256];
1487 switch (popr->type) {
1490 ferr(po, "lea from reg?\n");
1492 switch (popr->lmod) {
1494 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1497 snprintf(buf, buf_size, "%s%s",
1498 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1501 if (popr->name[1] == 'h') // XXX..
1502 snprintf(buf, buf_size, "%s(%s >> 8)",
1503 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1505 snprintf(buf, buf_size, "%s%s",
1506 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1509 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1514 if (is_stack_access(po, popr)) {
1515 stack_frame_access(po, popr, buf, buf_size,
1516 popr->name, cast, 1, is_lea);
1520 strcpy(expr, popr->name);
1521 if (strchr(expr, '[')) {
1522 // special case: '[' can only be left for label[reg] form
1523 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1525 ferr(po, "parse failure for '%s'\n", expr);
1526 if (tmp1[0] == '(') {
1527 // (off_4FFF50+3)[eax]
1528 p = strchr(tmp1 + 1, ')');
1529 if (p == NULL || p[1] != 0)
1530 ferr(po, "parse failure (2) for '%s'\n", expr);
1532 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1534 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1537 // XXX: do we need more parsing?
1539 snprintf(buf, buf_size, "%s", expr);
1543 snprintf(buf, buf_size, "%s(%s)",
1544 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1548 check_label_read_ref(po, popr->name);
1549 if (cast[0] == 0 && popr->is_ptr)
1553 snprintf(buf, buf_size, "(u32)&%s", popr->name);
1554 else if (popr->size_lt)
1555 snprintf(buf, buf_size, "%s%s%s%s", cast,
1556 lmod_cast_u_ptr(po, popr->lmod),
1557 popr->is_array ? "" : "&",
1560 snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1561 popr->is_array ? "[0]" : "");
1565 check_label_read_ref(po, popr->name);
1569 ferr(po, "lea an offset?\n");
1570 snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1575 ferr(po, "lea from const?\n");
1577 printf_number(tmp1, sizeof(tmp1), popr->val);
1578 snprintf(buf, buf_size, "%s%s",
1579 simplify_cast_num(cast, popr->val), tmp1);
1583 ferr(po, "invalid src type: %d\n", popr->type);
1589 // note: may set is_ptr (we find that out late for ebp frame..)
1590 static char *out_dst_opr(char *buf, size_t buf_size,
1591 struct parsed_op *po, struct parsed_opr *popr)
1593 switch (popr->type) {
1595 switch (popr->lmod) {
1597 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1601 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1605 if (popr->name[1] == 'h') // XXX..
1606 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1608 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1611 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1616 if (is_stack_access(po, popr)) {
1617 stack_frame_access(po, popr, buf, buf_size,
1618 popr->name, "", 0, 0);
1622 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1625 if (popr->size_mismatch)
1626 snprintf(buf, buf_size, "%s%s%s",
1627 lmod_cast_u_ptr(po, popr->lmod),
1628 popr->is_array ? "" : "&", popr->name);
1630 snprintf(buf, buf_size, "%s%s", popr->name,
1631 popr->is_array ? "[0]" : "");
1635 ferr(po, "invalid dst type: %d\n", popr->type);
1641 static char *out_src_opr_u32(char *buf, size_t buf_size,
1642 struct parsed_op *po, struct parsed_opr *popr)
1644 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1647 static enum parsed_flag_op split_cond(struct parsed_op *po,
1648 enum op_op op, int *is_inv)
1700 ferr(po, "split_cond: bad op %d\n", op);
1705 static void out_test_for_cc(char *buf, size_t buf_size,
1706 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1707 enum opr_lenmod lmod, const char *expr)
1709 const char *cast, *scast;
1711 cast = lmod_cast_u(po, lmod);
1712 scast = lmod_cast_s(po, lmod);
1716 case PFO_BE: // CF=1||ZF=1; CF=0
1717 snprintf(buf, buf_size, "(%s%s %s 0)",
1718 cast, expr, is_inv ? "!=" : "==");
1722 case PFO_L: // SF!=OF; OF=0
1723 snprintf(buf, buf_size, "(%s%s %s 0)",
1724 scast, expr, is_inv ? ">=" : "<");
1727 case PFO_LE: // ZF=1||SF!=OF; OF=0
1728 snprintf(buf, buf_size, "(%s%s %s 0)",
1729 scast, expr, is_inv ? ">" : "<=");
1733 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1737 static void out_cmp_for_cc(char *buf, size_t buf_size,
1738 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1740 const char *cast, *scast, *cast_use;
1741 char buf1[256], buf2[256];
1742 enum opr_lenmod lmod;
1744 if (po->operand[0].lmod != po->operand[1].lmod)
1745 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1746 po->operand[0].lmod, po->operand[1].lmod);
1747 lmod = po->operand[0].lmod;
1749 cast = lmod_cast_u(po, lmod);
1750 scast = lmod_cast_s(po, lmod);
1766 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1769 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1770 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1774 // note: must be unsigned compare
1775 snprintf(buf, buf_size, "(%s %s %s)",
1776 buf1, is_inv ? ">=" : "<", buf2);
1780 snprintf(buf, buf_size, "(%s %s %s)",
1781 buf1, is_inv ? "!=" : "==", buf2);
1785 // note: must be unsigned compare
1786 snprintf(buf, buf_size, "(%s %s %s)",
1787 buf1, is_inv ? ">" : "<=", buf2);
1790 if (is_inv && lmod == OPLM_BYTE
1791 && po->operand[1].type == OPT_CONST
1792 && po->operand[1].val == 0xff)
1794 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1795 snprintf(buf, buf_size, "(0)");
1799 // note: must be signed compare
1801 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1802 scast, buf1, buf2, is_inv ? ">=" : "<");
1806 snprintf(buf, buf_size, "(%s %s %s)",
1807 buf1, is_inv ? ">=" : "<", buf2);
1811 snprintf(buf, buf_size, "(%s %s %s)",
1812 buf1, is_inv ? ">" : "<=", buf2);
1820 static void out_cmp_test(char *buf, size_t buf_size,
1821 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1823 char buf1[256], buf2[256], buf3[256];
1825 if (po->op == OP_TEST) {
1826 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1827 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1830 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1831 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1832 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1834 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1835 po->operand[0].lmod, buf3);
1837 else if (po->op == OP_CMP) {
1838 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1841 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1844 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1845 struct parsed_opr *popr2)
1847 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1848 ferr(po, "missing lmod for both operands\n");
1850 if (popr1->lmod == OPLM_UNSPEC)
1851 popr1->lmod = popr2->lmod;
1852 else if (popr2->lmod == OPLM_UNSPEC)
1853 popr2->lmod = popr1->lmod;
1854 else if (popr1->lmod != popr2->lmod) {
1855 if (popr1->type_from_var) {
1856 popr1->size_mismatch = 1;
1857 if (popr1->lmod < popr2->lmod)
1859 popr1->lmod = popr2->lmod;
1861 else if (popr2->type_from_var) {
1862 popr2->size_mismatch = 1;
1863 if (popr2->lmod < popr1->lmod)
1865 popr2->lmod = popr1->lmod;
1868 ferr(po, "conflicting lmods: %d vs %d\n",
1869 popr1->lmod, popr2->lmod);
1873 static const char *op_to_c(struct parsed_op *po)
1897 ferr(po, "op_to_c was supplied with %d\n", po->op);
1901 static void op_set_clear_flag(struct parsed_op *po,
1902 enum op_flags flag_set, enum op_flags flag_clear)
1904 po->flags |= flag_set;
1905 po->flags &= ~flag_clear;
1908 // last op in stream - unconditional branch or ret
1909 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1910 || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1912 static int scan_for_pop(int i, int opcnt, const char *reg,
1913 int magic, int depth, int *maxdepth, int do_flags)
1915 struct parsed_op *po;
1919 for (; i < opcnt; i++) {
1921 if (po->cc_scratch == magic)
1922 break; // already checked
1923 po->cc_scratch = magic;
1925 if (po->flags & OPF_TAIL)
1926 return -1; // deadend
1928 if ((po->flags & OPF_RMD)
1929 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1932 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1933 if (po->btj != NULL) {
1935 for (j = 0; j < po->btj->count - 1; j++) {
1936 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1937 depth, maxdepth, do_flags);
1939 return ret; // dead end
1941 // follow last jumptable entry
1942 i = po->btj->d[j].bt_i - 1;
1947 ferr(po, "dead branch\n");
1951 if (po->flags & OPF_CC) {
1952 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1953 depth, maxdepth, do_flags);
1955 return ret; // dead end
1963 if ((po->op == OP_POP || po->op == OP_PUSH)
1964 && po->operand[0].type == OPT_REG
1965 && IS(po->operand[0].name, reg))
1967 if (po->op == OP_PUSH) {
1969 if (depth > *maxdepth)
1972 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1974 else if (depth == 0) {
1976 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1981 if (depth < 0) // should not happen
1982 ferr(po, "fail with depth\n");
1984 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1992 // scan for pop starting from 'ret' op (all paths)
1993 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
1999 for (; i < opcnt; i++) {
2000 if (!(ops[i].flags & OPF_TAIL))
2003 for (j = i - 1; j >= 0; j--) {
2004 if (ops[j].flags & OPF_RMD)
2006 if (ops[j].flags & OPF_JMP)
2009 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2010 && IS(ops[j].operand[0].name, reg))
2013 ops[j].flags |= flag_set;
2017 if (g_labels[j][0] != 0)
2022 return found ? 0 : -1;
2025 // is operand 'opr' modified by parsed_op 'po'?
2026 static int is_opr_modified(const struct parsed_opr *opr,
2027 const struct parsed_op *po)
2029 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2032 if (opr->type == OPT_REG && po->operand[0].type == OPT_REG) {
2033 if (po->regmask_dst & (1 << opr->reg))
2039 return IS(po->operand[0].name, opr->name);
2042 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2043 static int is_any_opr_modified(const struct parsed_op *po_test,
2044 const struct parsed_op *po)
2048 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2051 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2054 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2057 // in reality, it can wreck any register, but in decompiled C
2058 // version it can only overwrite eax or edx:eax
2059 if (po->op == OP_CALL
2060 && ((po_test->regmask_src | po_test->regmask_dst)
2061 & ((1 << xAX)|(1 << xDX))))
2064 for (i = 0; i < po_test->operand_cnt; i++)
2065 if (IS(po_test->operand[i].name, po->operand[0].name))
2071 // scan for any po_test operand modification in range given
2072 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt)
2074 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2077 for (; i < opcnt; i++) {
2078 if (is_any_opr_modified(po_test, &ops[i]))
2085 // scan for po_test operand[0] modification in range given
2086 static int scan_for_mod_opr0(struct parsed_op *po_test,
2089 for (; i < opcnt; i++) {
2090 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2097 static int scan_for_flag_set(int i, int magic, int *branched,
2098 int *setters, int *setter_cnt)
2100 struct label_ref *lr;
2104 if (ops[i].cc_scratch == magic) {
2105 ferr(&ops[i], "%s looped\n", __func__);
2108 ops[i].cc_scratch = magic;
2110 if (g_labels[i][0] != 0) {
2113 lr = &g_label_refs[i];
2114 for (; lr->next; lr = lr->next) {
2115 ret = scan_for_flag_set(lr->i, magic,
2116 branched, setters, setter_cnt);
2121 if (i > 0 && LAST_OP(i - 1)) {
2125 ret = scan_for_flag_set(lr->i, magic,
2126 branched, setters, setter_cnt);
2132 if (ops[i].flags & OPF_FLAGS) {
2133 setters[*setter_cnt] = i;
2138 if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2145 // scan back for cdq, if anything modifies edx, fail
2146 static int scan_for_cdq_edx(int i)
2149 if (g_labels[i][0] != 0) {
2150 if (g_label_refs[i].next != NULL)
2152 if (i > 0 && LAST_OP(i - 1)) {
2153 i = g_label_refs[i].i;
2160 if (ops[i].op == OP_CDQ)
2163 if (ops[i].regmask_dst & (1 << xDX))
2165 if (g_labels[i][0] != 0)
2172 static int scan_for_reg_clear(int i, int reg)
2175 if (g_labels[i][0] != 0) {
2176 if (g_label_refs[i].next != NULL)
2178 if (i > 0 && LAST_OP(i - 1)) {
2179 i = g_label_refs[i].i;
2186 if (ops[i].op == OP_XOR
2187 && ops[i].operand[0].lmod == OPLM_DWORD
2188 && ops[i].operand[0].reg == ops[i].operand[1].reg
2189 && ops[i].operand[0].reg == reg)
2192 if (ops[i].regmask_dst & (1 << reg))
2194 if (g_labels[i][0] != 0)
2201 // scan for positive, constant esp adjust
2202 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2204 struct parsed_op *po;
2208 for (; i < opcnt; i++) {
2211 if (g_labels[i][0] != 0)
2214 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2215 if (po->operand[1].type != OPT_CONST)
2216 ferr(&ops[i], "non-const esp adjust?\n");
2217 *adj += po->operand[1].val;
2219 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2222 else if (po->op == OP_PUSH)
2223 *adj -= lmod_bytes(po, po->operand[0].lmod);
2224 else if (po->op == OP_POP)
2225 *adj += lmod_bytes(po, po->operand[0].lmod);
2226 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2227 if (po->op != OP_CALL)
2229 if (po->operand[0].type != OPT_LABEL)
2231 // TODO: should only allow combining __cdecl calls..
2235 if (*adj == 4 && ops[i_first].op == OP_POP
2236 && ops[i_first].operand[0].type == OPT_REG
2237 && ops[i_first].operand[0].reg == xCX)
2239 // probably 'pop ecx' was used..
2246 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2248 struct parsed_op *po;
2252 ferr(ops, "%s: followed bad branch?\n", __func__);
2254 for (; i < opcnt; i++) {
2256 if (po->cc_scratch == magic)
2258 po->cc_scratch = magic;
2261 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2262 if (po->btj != NULL) {
2264 for (j = 0; j < po->btj->count; j++)
2265 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2269 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2270 if (!(po->flags & OPF_CC))
2273 if (po->flags & OPF_TAIL)
2278 static const struct parsed_proto *try_recover_pp(
2279 struct parsed_op *po, const struct parsed_opr *opr)
2281 const struct parsed_proto *pp = NULL;
2283 // maybe an arg of g_func?
2284 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2286 char ofs_reg[16] = { 0, };
2287 int arg, arg_s, arg_i;
2291 parse_stack_access(po, opr->name, ofs_reg,
2292 &offset, &stack_ra, NULL);
2293 if (ofs_reg[0] != 0)
2294 ferr(po, "offset reg on arg access?\n");
2295 if (offset <= stack_ra)
2296 ferr(po, "stack var call unhandled yet\n");
2298 arg_i = (offset - stack_ra - 4) / 4;
2299 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2300 if (g_func_pp->arg[arg].reg != NULL)
2306 if (arg == g_func_pp->argc)
2307 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2309 pp = g_func_pp->arg[arg].fptr;
2311 ferr(po, "icall: arg%d is not a fptr?\n", arg + 1);
2312 if (pp->argc_reg != 0)
2313 ferr(po, "icall: reg arg in arg-call unhandled yet\n");
2315 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2316 pp = proto_parse(g_fhdr, opr->name);
2318 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2319 if (pp->argc_reg != 0)
2320 ferr(po, "arg-call unhandled yet for '%s'\n", opr->name);
2326 static void scan_for_call_type(int i, struct parsed_opr *opr,
2327 int magic, const struct parsed_proto **pp_found)
2329 const struct parsed_proto *pp = NULL;
2330 struct parsed_op *po;
2331 struct label_ref *lr;
2334 if (ops[i].cc_scratch == magic)
2336 ops[i].cc_scratch = magic;
2338 if (g_labels[i][0] != 0) {
2339 lr = &g_label_refs[i];
2340 for (; lr != NULL; lr = lr->next)
2341 scan_for_call_type(lr->i, opr, magic, pp_found);
2345 scan_for_call_type(i - 1, opr, magic, pp_found);
2351 if (!(ops[i].flags & OPF_DATA))
2353 if (!is_opr_modified(opr, &ops[i]))
2355 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2356 // most probably trashed by some processing
2361 opr = &ops[i].operand[1];
2362 if (opr->type != OPT_REG)
2366 po = (i >= 0) ? &ops[i] : ops;
2369 // reached the top - can only be an arg-reg
2370 if (opr->type != OPT_REG)
2373 for (i = 0; i < g_func_pp->argc; i++) {
2374 if (g_func_pp->arg[i].reg == NULL)
2376 if (IS(opr->name, g_func_pp->arg[i].reg))
2379 if (i == g_func_pp->argc)
2381 pp = g_func_pp->arg[i].fptr;
2383 ferr(po, "icall: arg%d is not a fptr?\n", i + 1);
2384 if (pp->argc_reg != 0)
2385 ferr(po, "icall: reg arg in arg-call unhandled yet\n");
2388 pp = try_recover_pp(po, opr);
2390 if (*pp_found != NULL && pp != NULL) {
2391 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2392 || (*pp_found)->is_stdcall != pp->is_stdcall
2393 || (*pp_found)->argc != pp->argc
2394 || (*pp_found)->argc_reg != pp->argc_reg
2395 || (*pp_found)->argc_stack != pp->argc_stack)
2397 ferr(po, "icall: parsed_proto mismatch\n");
2404 static const struct parsed_proto *resolve_call(int i, int opcnt)
2406 const struct parsed_proto *pp = NULL;
2408 switch (ops[i].operand[0].type) {
2412 pp = try_recover_pp(&ops[i], &ops[i].operand[0]);
2415 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp);
2422 static int collect_call_args(struct parsed_op *po, int i,
2423 struct parsed_proto *pp, int *save_arg_vars, int arg,
2424 int magic, int need_op_saving, int may_reuse)
2426 struct parsed_proto *pp_tmp;
2427 struct label_ref *lr;
2428 int need_to_save_current;
2433 ferr(po, "dead label encountered\n");
2437 for (; arg < pp->argc; arg++)
2438 if (pp->arg[arg].reg == NULL)
2440 magic = (magic & 0xffffff) | (arg << 24);
2442 for (j = i; j >= 0 && arg < pp->argc; )
2444 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2445 if (ops[j].cc_scratch != magic) {
2446 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2450 // ok: have already been here
2453 ops[j].cc_scratch = magic;
2455 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2456 lr = &g_label_refs[j];
2457 if (lr->next != NULL)
2459 for (; lr->next; lr = lr->next) {
2460 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2462 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2463 arg, magic, need_op_saving, may_reuse);
2468 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2470 if (j > 0 && LAST_OP(j - 1)) {
2471 // follow last branch in reverse
2476 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2477 arg, magic, need_op_saving, may_reuse);
2483 if (ops[j].op == OP_CALL)
2485 pp_tmp = ops[j].datap;
2487 ferr(po, "arg collect hit unparsed call '%s'\n",
2488 ops[j].operand[0].name);
2489 if (may_reuse && pp_tmp->argc_stack > 0)
2490 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2491 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2493 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2494 ferr(po, "arg collect %d/%d hit esp adjust\n",
2497 else if (ops[j].op == OP_POP) {
2498 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2500 else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2504 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2506 pp->arg[arg].datap = &ops[j];
2507 need_to_save_current = 0;
2508 if (!need_op_saving) {
2509 ret = scan_for_mod(&ops[j], j + 1, i);
2510 need_to_save_current = (ret >= 0);
2512 if (need_op_saving || need_to_save_current) {
2513 // mark this push as one that needs operand saving
2514 ops[j].flags &= ~OPF_RMD;
2515 if (ops[j].argnum == 0) {
2516 ops[j].argnum = arg + 1;
2517 *save_arg_vars |= 1 << arg;
2519 else if (ops[j].argnum < arg + 1)
2520 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2521 ops[j].argnum, arg + 1, pp->name);
2523 else if (ops[j].argnum == 0)
2524 ops[j].flags |= OPF_RMD;
2526 // some PUSHes are reused by different calls on other branches,
2527 // but that can't happen if we didn't branch, so they
2528 // can be removed from future searches (handles nested calls)
2530 ops[j].flags |= OPF_FARG;
2533 for (arg++; arg < pp->argc; arg++)
2534 if (pp->arg[arg].reg == NULL)
2536 magic = (magic & 0xffffff) | (arg << 24);
2540 if (arg < pp->argc) {
2541 ferr(po, "arg collect failed for '%s': %d/%d\n",
2542 pp->name, arg, pp->argc);
2548 static void add_label_ref(struct label_ref *lr, int op_i)
2550 struct label_ref *lr_new;
2557 lr_new = calloc(1, sizeof(*lr_new));
2559 lr_new->next = lr->next;
2563 static void output_std_flags(FILE *fout, struct parsed_op *po,
2564 int *pfomask, const char *dst_opr_text)
2566 if (*pfomask & (1 << PFO_Z)) {
2567 fprintf(fout, "\n cond_z = (%s%s == 0);",
2568 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2569 *pfomask &= ~(1 << PFO_Z);
2571 if (*pfomask & (1 << PFO_S)) {
2572 fprintf(fout, "\n cond_s = (%s%s < 0);",
2573 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2574 *pfomask &= ~(1 << PFO_S);
2578 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2580 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2581 struct parsed_opr *last_arith_dst = NULL;
2582 char buf1[256], buf2[256], buf3[256], cast[64];
2583 const struct parsed_proto *pp_c;
2584 struct parsed_proto *pp, *pp_tmp;
2585 struct parsed_data *pd;
2586 const char *tmpname;
2587 enum parsed_flag_op pfo;
2588 int save_arg_vars = 0;
2589 int cmp_result_vars = 0;
2590 int need_mul_var = 0;
2591 int have_func_ret = 0;
2592 int have_normal_ret = 0;
2594 int label_pending = 0;
2595 int regmask_save = 0;
2596 int regmask_arg = 0;
2597 int regmask_now = 0;
2609 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2610 g_stack_frame_used = 0;
2612 g_func_pp = proto_parse(fhdr, funcn);
2613 if (g_func_pp == NULL)
2614 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2616 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2617 if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2618 fprintf(fout, "__stdcall ");
2619 if (g_ida_func_attr & IDAFA_NORETURN)
2620 fprintf(fout, "noreturn ");
2621 fprintf(fout, "%s(", funcn);
2623 for (i = 0; i < g_func_pp->argc; i++) {
2625 fprintf(fout, ", ");
2626 if (g_func_pp->arg[i].fptr != NULL) {
2628 pp = g_func_pp->arg[i].fptr;
2629 fprintf(fout, "%s (", pp->ret_type.name);
2630 if (pp->is_stdcall && pp->argc_reg == 0)
2631 fprintf(fout, "__stdcall ");
2632 fprintf(fout, "*a%d)(", i + 1);
2633 for (j = 0; j < pp->argc; j++) {
2635 fprintf(fout, ", ");
2636 if (pp->arg[j].fptr)
2637 ferr(ops, "nested fptr\n");
2638 fprintf(fout, "%s", pp->arg[j].type.name);
2643 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2646 if (g_func_pp->is_vararg) {
2648 fprintf(fout, ", ");
2649 fprintf(fout, "...");
2652 fprintf(fout, ")\n{\n");
2655 // - handle ebp/esp frame, remove ops related to it
2656 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2657 && ops[1].op == OP_MOV
2658 && IS(opr_name(&ops[1], 0), "ebp")
2659 && IS(opr_name(&ops[1], 1), "esp"))
2664 ops[0].flags |= OPF_RMD;
2665 ops[1].flags |= OPF_RMD;
2668 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2669 g_stack_fsz = opr_const(&ops[2], 1);
2670 ops[2].flags |= OPF_RMD;
2674 // another way msvc builds stack frame..
2676 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2678 ops[i].flags |= OPF_RMD;
2682 // and another way..
2683 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2684 && ops[i].operand[1].type == OPT_CONST
2685 && ops[i + 1].op == OP_CALL
2686 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2688 g_stack_fsz += ops[i].operand[1].val;
2689 ops[i].flags |= OPF_RMD;
2691 ops[i].flags |= OPF_RMD;
2698 for (; i < opcnt; i++)
2699 if (ops[i].op == OP_RET)
2701 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2704 if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2705 ops[i - 1].flags |= OPF_RMD;
2706 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2707 ferr(&ops[i - 1], "'pop ebp' expected\n");
2709 if (g_stack_fsz != 0) {
2710 if (ops[i - 2].op == OP_MOV
2711 && IS(opr_name(&ops[i - 2], 0), "esp")
2712 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2714 ops[i - 2].flags |= OPF_RMD;
2716 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2717 ferr(&ops[i - 2], "esp restore expected\n");
2719 if (ecx_push && ops[i - 3].op == OP_POP
2720 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2722 ferr(&ops[i - 3], "unexpected ecx pop\n");
2728 } while (i < opcnt);
2731 for (i = 0; i < opcnt; i++) {
2732 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2734 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2735 && ops[i].operand[1].type == OPT_CONST)
2744 g_stack_fsz = ops[i].operand[1].val;
2745 ops[i].flags |= OPF_RMD;
2749 for (; i < opcnt; i++)
2750 if (ops[i].op == OP_RET)
2752 if (ops[i - 1].op != OP_ADD
2753 || !IS(opr_name(&ops[i - 1], 0), "esp")
2754 || ops[i - 1].operand[1].type != OPT_CONST
2755 || ops[i - 1].operand[1].val != g_stack_fsz)
2756 ferr(&ops[i - 1], "'add esp' expected\n");
2757 ops[i - 1].flags |= OPF_RMD;
2760 } while (i < opcnt);
2765 // - parse calls with labels
2766 // - resolve all branches
2767 for (i = 0; i < opcnt; i++)
2773 if (po->flags & OPF_RMD)
2776 if (po->op == OP_CALL) {
2777 if (po->operand[0].type == OPT_LABEL) {
2778 tmpname = opr_name(po, 0);
2779 pp_c = proto_parse(fhdr, tmpname);
2781 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2782 if (pp_c->is_fptr && pp_c->argc_reg != 0)
2783 ferr(po, "fptr call with reg arg\n");
2784 pp = proto_clone(pp_c);
2785 my_assert_not(pp, NULL);
2791 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2794 if (po->operand[0].type == OPT_REGMEM) {
2795 char *p = strchr(po->operand[0].name, '[');
2797 ferr(po, "unhandled indirect branch\n");
2798 ret = p - po->operand[0].name;
2799 strncpy(buf1, po->operand[0].name, ret);
2802 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2803 if (IS(g_func_pd[j].label, buf1)) {
2809 //ferr(po, "label '%s' not parsed?\n", buf1);
2811 if (pd->type != OPT_OFFSET)
2812 ferr(po, "label '%s' with non-offset data?\n", buf1);
2814 // find all labels, link
2815 for (j = 0; j < pd->count; j++) {
2816 for (l = 0; l < opcnt; l++) {
2817 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2818 add_label_ref(&g_label_refs[l], i);
2829 for (l = 0; l < opcnt; l++) {
2830 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2831 add_label_ref(&g_label_refs[l], i);
2840 if (po->operand[0].type == OPT_LABEL)
2844 ferr(po, "unhandled branch\n");
2848 po->flags |= OPF_TAIL;
2853 // - remove dead labels
2855 for (i = 0; i < opcnt; i++)
2857 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
2861 if (po->flags & OPF_RMD)
2864 if (po->op == OP_CALL)
2866 tmpname = opr_name(po, 0);
2871 pp_c = resolve_call(i, opcnt);
2873 pp = proto_clone(pp_c);
2875 pp = calloc(1, sizeof(*pp));
2876 my_assert_not(pp, NULL);
2877 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2879 ferr(po, "non-__cdecl indirect call unhandled yet\n");
2881 if (j > ARRAY_SIZE(pp->arg))
2882 ferr(po, "esp adjust too large?\n");
2883 pp->ret_type.name = strdup("int");
2884 pp->argc = pp->argc_stack = j;
2885 for (arg = 0; arg < pp->argc; arg++)
2886 pp->arg[arg].type.name = strdup("int");
2891 // look for and make use of esp adjust
2893 if (!pp->is_stdcall && pp->argc_stack > 0)
2894 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2896 if (pp->is_vararg) {
2897 if (j / 4 < pp->argc_stack)
2898 ferr(po, "esp adjust is too small: %x < %x\n",
2899 j, pp->argc_stack * 4);
2900 // modify pp to make it have varargs as normal args
2902 pp->argc += j / 4 - pp->argc_stack;
2903 for (; arg < pp->argc; arg++) {
2904 pp->arg[arg].type.name = strdup("int");
2907 if (pp->argc > ARRAY_SIZE(pp->arg))
2908 ferr(po, "too many args for '%s'\n", tmpname);
2910 if (pp->argc_stack != j / 4)
2911 ferr(po, "stack tracking failed for '%s': %x %x\n",
2912 tmpname, pp->argc_stack * 4, j);
2914 ops[ret].flags |= OPF_RMD;
2915 // a bit of a hack, but deals with use of
2916 // single adj for multiple calls
2917 ops[ret].operand[1].val -= j;
2919 else if (pp->is_vararg)
2920 ferr(po, "missing esp_adjust for vararg func '%s'\n",
2923 // can't call functions with non-__cdecl callbacks yet
2924 for (arg = 0; arg < pp->argc; arg++) {
2925 if (pp->arg[arg].fptr != NULL) {
2926 pp_tmp = pp->arg[arg].fptr;
2927 if (pp_tmp->argc_reg != 0)
2928 ferr(po, "'%s' has a callback with reg-args\n", tmpname);
2932 collect_call_args(po, i, pp, &save_arg_vars,
2933 0, i + opcnt * 2, 0, 0);
2935 if (strstr(pp->ret_type.name, "int64"))
2937 if (!(po->flags & OPF_TAIL) && !IS(pp->ret_type.name, "void"))
2943 // - find POPs for PUSHes, rm both
2944 // - scan for all used registers
2945 // - find flag set ops for their users
2946 // - declare indirect functions
2947 for (i = 0; i < opcnt; i++) {
2949 if (po->flags & OPF_RMD)
2952 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
2953 reg = po->operand[0].reg;
2954 if (!(regmask & (1 << reg)))
2955 // not a reg save after all, rerun scan_for_pop
2956 po->flags &= ~OPF_RSAVE;
2958 regmask_save |= 1 << reg;
2961 if (po->op == OP_PUSH
2962 && po->argnum == 0 && !(po->flags & OPF_RSAVE)
2963 && po->operand[0].type == OPT_REG)
2965 reg = po->operand[0].reg;
2967 ferr(po, "reg not set for push?\n");
2970 ret = scan_for_pop(i + 1, opcnt,
2971 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
2974 ferr(po, "too much depth: %d\n", depth);
2976 po->flags |= OPF_RMD;
2977 scan_for_pop(i + 1, opcnt, po->operand[0].name,
2978 i + opcnt * 4, 0, &depth, 1);
2981 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
2984 if (regmask & (1 << reg)) {
2985 if (regmask_save & (1 << reg))
2986 ferr(po, "%s already saved?\n", po->operand[0].name);
2990 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
2995 regmask_now = po->regmask_src | po->regmask_dst;
2996 if (regmask_now & (1 << xBP)) {
2997 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
2998 if (po->regmask_dst & (1 << xBP))
2999 // compiler decided to drop bp frame and use ebp as scratch
3000 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
3002 regmask_now &= ~(1 << xBP);
3006 regmask |= regmask_now;
3008 if (po->flags & OPF_CC)
3010 int setters[16], cnt = 0, branched = 0;
3012 ret = scan_for_flag_set(i, i + opcnt * 6,
3013 &branched, setters, &cnt);
3014 if (ret < 0 || cnt <= 0)
3015 ferr(po, "unable to trace flag setter(s)\n");
3016 if (cnt > ARRAY_SIZE(setters))
3017 ferr(po, "too many flag setters\n");
3019 pfo = split_cond(po, po->op, &dummy);
3020 for (j = 0; j < cnt; j++)
3022 tmp_op = &ops[setters[j]]; // flag setter
3025 // to get nicer code, we try to delay test and cmp;
3026 // if we can't because of operand modification, or if we
3027 // have math op, or branch, make it calculate flags explicitly
3028 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
3029 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i) >= 0)
3032 else if (tmp_op->op == OP_CMPS) {
3033 pfomask = 1 << PFO_Z;
3036 // see if we'll be able to handle based on op result
3037 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3038 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3040 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3044 tmp_op->pfomask |= pfomask;
3045 cmp_result_vars |= pfomask;
3047 // note: may overwrite, currently not a problem
3051 if (po->op == OP_ADC || po->op == OP_SBB)
3052 cmp_result_vars |= 1 << PFO_C;
3054 else if (po->op == OP_MUL
3055 || (po->op == OP_IMUL && po->operand_cnt == 1))
3059 else if (po->op == OP_CALL && po->operand[0].type != OPT_LABEL) {
3061 my_assert_not(pp, NULL);
3062 fprintf(fout, " %s (", pp->ret_type.name);
3063 if (pp->is_stdcall && pp->argc_reg == 0)
3064 fprintf(fout, "__stdcall ");
3065 fprintf(fout, "*icall%d)(", i);
3066 for (j = 0; j < pp->argc; j++) {
3068 fprintf(fout, ", ");
3069 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3071 fprintf(fout, ");\n");
3073 else if (po->op == OP_RET)
3074 have_normal_ret = 1;
3077 // output LUTs/jumptables
3078 for (i = 0; i < g_func_pd_cnt; i++) {
3080 fprintf(fout, " static const ");
3081 if (pd->type == OPT_OFFSET) {
3082 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3084 for (j = 0; j < pd->count; j++) {
3086 fprintf(fout, ", ");
3087 fprintf(fout, "&&%s", pd->d[j].u.label);
3091 fprintf(fout, "%s %s[] =\n { ",
3092 lmod_type_u(ops, pd->lmod), pd->label);
3094 for (j = 0; j < pd->count; j++) {
3096 fprintf(fout, ", ");
3097 fprintf(fout, "%u", pd->d[j].u.val);
3100 fprintf(fout, " };\n");
3103 // declare stack frame, va_arg
3105 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3106 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3108 if (g_func_pp->is_vararg)
3109 fprintf(fout, " va_list ap;\n");
3111 // declare arg-registers
3112 for (i = 0; i < g_func_pp->argc; i++) {
3113 if (g_func_pp->arg[i].reg != NULL) {
3114 reg = char_array_i(regs_r32,
3115 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3117 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
3119 regmask_arg |= 1 << reg;
3120 fprintf(fout, " u32 %s = (u32)a%d;\n",
3121 g_func_pp->arg[i].reg, i + 1);
3126 // declare other regs - special case for eax
3127 if (!((regmask | regmask_arg) & 1)
3128 && (have_func_ret || have_normal_ret)
3129 && !IS(g_func_pp->ret_type.name, "void"))
3131 fprintf(fout, " u32 eax = 0;\n");
3135 regmask &= ~regmask_arg;
3136 regmask &= ~(1 << xSP);
3138 for (reg = 0; reg < 8; reg++) {
3139 if (regmask & (1 << reg)) {
3140 fprintf(fout, " u32 %s;\n", regs_r32[reg]);
3147 for (reg = 0; reg < 8; reg++) {
3148 if (regmask_save & (1 << reg)) {
3149 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3155 if (save_arg_vars) {
3156 for (reg = 0; reg < 32; reg++) {
3157 if (save_arg_vars & (1 << reg)) {
3158 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3164 if (cmp_result_vars) {
3165 for (i = 0; i < 8; i++) {
3166 if (cmp_result_vars & (1 << i)) {
3167 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3174 fprintf(fout, " u64 mul_tmp;\n");
3179 fprintf(fout, "\n");
3181 if (g_func_pp->is_vararg) {
3182 if (g_func_pp->argc_stack == 0)
3183 ferr(ops, "vararg func without stack args?\n");
3184 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3188 for (i = 0; i < opcnt; i++)
3190 if (g_labels[i][0] != 0) {
3191 fprintf(fout, "\n%s:\n", g_labels[i]);
3194 delayed_flag_op = NULL;
3195 last_arith_dst = NULL;
3199 if (po->flags & OPF_RMD)
3204 #define assert_operand_cnt(n_) \
3205 if (po->operand_cnt != n_) \
3206 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3208 // conditional/flag using op?
3209 if (po->flags & OPF_CC)
3214 pfo = split_cond(po, po->op, &is_inv);
3217 // we go through all this trouble to avoid using parsed_flag_op,
3218 // which makes generated code much nicer
3219 if (delayed_flag_op != NULL)
3221 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3224 else if (last_arith_dst != NULL
3225 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3226 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3229 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3230 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3231 last_arith_dst->lmod, buf3);
3234 else if (tmp_op != NULL) {
3235 // use preprocessed flag calc results
3236 if (!(tmp_op->pfomask & (1 << pfo)))
3237 ferr(po, "not prepared for pfo %d\n", pfo);
3239 // note: is_inv was not yet applied
3240 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3241 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3244 ferr(po, "all methods of finding comparison failed\n");
3247 if (po->flags & OPF_JMP) {
3248 fprintf(fout, " if %s\n", buf1);
3250 else if (po->op == OP_ADC || po->op == OP_SBB) {
3252 fprintf(fout, " cond_%s = %s;\n",
3253 parsed_flag_op_names[pfo], buf1);
3255 else if (po->flags & OPF_DATA) { // SETcc
3256 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3257 fprintf(fout, " %s = %s;", buf2, buf1);
3260 ferr(po, "unhandled conditional op\n");
3264 pfomask = po->pfomask;
3269 assert_operand_cnt(2);
3270 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3271 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3272 fprintf(fout, " %s = %s;", buf1,
3273 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3274 po->operand[0].is_ptr ? "(void *)" : "", 0));
3278 assert_operand_cnt(2);
3279 po->operand[1].lmod = OPLM_DWORD; // always
3280 fprintf(fout, " %s = %s;",
3281 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3282 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3287 assert_operand_cnt(2);
3288 fprintf(fout, " %s = %s;",
3289 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3290 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3294 assert_operand_cnt(2);
3295 switch (po->operand[1].lmod) {
3297 strcpy(buf3, "(s8)");
3300 strcpy(buf3, "(s16)");
3303 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3305 fprintf(fout, " %s = %s;",
3306 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3307 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3312 assert_operand_cnt(1);
3313 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3314 fprintf(fout, " %s = ~%s;", buf1, buf1);
3318 assert_operand_cnt(2);
3319 fprintf(fout, " %s = (s32)%s >> 31;",
3320 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3321 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3322 strcpy(g_comment, "cdq");
3327 assert_operand_cnt(3);
3328 if (po->flags & OPF_REP) {
3329 fprintf(fout, " for (; ecx != 0; ecx--, edi += %d)\n",
3330 lmod_bytes(po, po->operand[0].lmod));
3331 fprintf(fout, " %sedi = eax;",
3332 lmod_cast_u_ptr(po, po->operand[0].lmod));
3333 strcpy(g_comment, "rep stos");
3336 fprintf(fout, " %sedi = eax; edi += %d;",
3337 lmod_cast_u_ptr(po, po->operand[0].lmod),
3338 lmod_bytes(po, po->operand[0].lmod));
3339 strcpy(g_comment, "stos");
3345 assert_operand_cnt(3);
3346 j = lmod_bytes(po, po->operand[0].lmod);
3347 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3348 if (po->flags & OPF_REP) {
3350 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3353 " %sedi = %sesi;", buf1, buf1);
3354 strcpy(g_comment, "rep movs");
3357 fprintf(fout, " %sedi = %sesi; edi += %d; esi += %d;",
3359 strcpy(g_comment, "movs");
3365 // repe ~ repeat while ZF=1
3366 assert_operand_cnt(3);
3367 j = lmod_bytes(po, po->operand[0].lmod);
3368 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3369 if (po->flags & OPF_REP) {
3371 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3374 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3375 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3378 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3379 (po->flags & OPF_REPZ) ? "e" : "ne");
3383 " cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3385 strcpy(g_comment, "cmps");
3387 pfomask &= ~(1 << PFO_Z);
3388 last_arith_dst = NULL;
3389 delayed_flag_op = NULL;
3392 // arithmetic w/flags
3397 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3400 assert_operand_cnt(2);
3401 fprintf(fout, " %s %s= %s;",
3402 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3404 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3405 output_std_flags(fout, po, &pfomask, buf1);
3406 last_arith_dst = &po->operand[0];
3407 delayed_flag_op = NULL;
3412 assert_operand_cnt(2);
3413 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3414 if (pfomask & (1 << PFO_C)) {
3415 if (po->operand[1].type == OPT_CONST) {
3416 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3417 j = po->operand[1].val;
3420 if (po->op == OP_SHL)
3424 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3428 ferr(po, "zero shift?\n");
3432 pfomask &= ~(1 << PFO_C);
3434 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3435 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3436 output_std_flags(fout, po, &pfomask, buf1);
3437 last_arith_dst = &po->operand[0];
3438 delayed_flag_op = NULL;
3442 assert_operand_cnt(2);
3443 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3444 fprintf(fout, " %s = %s%s >> %s;", buf1,
3445 lmod_cast_s(po, po->operand[0].lmod), buf1,
3446 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3447 output_std_flags(fout, po, &pfomask, buf1);
3448 last_arith_dst = &po->operand[0];
3449 delayed_flag_op = NULL;
3454 assert_operand_cnt(2);
3455 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3456 if (po->operand[1].type == OPT_CONST) {
3457 j = po->operand[1].val;
3458 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3459 fprintf(fout, po->op == OP_ROL ?
3460 " %s = (%s << %d) | (%s >> %d);" :
3461 " %s = (%s >> %d) | (%s << %d);",
3462 buf1, buf1, j, buf1,
3463 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3467 output_std_flags(fout, po, &pfomask, buf1);
3468 last_arith_dst = &po->operand[0];
3469 delayed_flag_op = NULL;
3473 assert_operand_cnt(2);
3474 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3475 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3476 // special case for XOR
3477 fprintf(fout, " %s = 0;",
3478 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3479 last_arith_dst = &po->operand[0];
3480 delayed_flag_op = NULL;
3487 assert_operand_cnt(2);
3488 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3489 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3490 if (po->op == OP_SBB
3491 && IS(po->operand[0].name, po->operand[1].name))
3493 // avoid use of unitialized var
3494 fprintf(fout, " %s = -cond_c;", buf1);
3495 // carry remains what it was
3496 pfomask &= ~(1 << PFO_C);
3499 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3500 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3502 output_std_flags(fout, po, &pfomask, buf1);
3503 last_arith_dst = &po->operand[0];
3504 delayed_flag_op = NULL;
3509 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3510 if (po->operand[0].type == OPT_REG) {
3511 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3512 fprintf(fout, " %s%s;", buf1, buf2);
3515 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3516 fprintf(fout, " %s %s= 1;", buf1, buf2);
3518 output_std_flags(fout, po, &pfomask, buf1);
3519 last_arith_dst = &po->operand[0];
3520 delayed_flag_op = NULL;
3524 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3525 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3526 fprintf(fout, " %s = -%s%s;", buf1,
3527 lmod_cast_s(po, po->operand[0].lmod), buf2);
3528 last_arith_dst = &po->operand[0];
3529 delayed_flag_op = NULL;
3530 if (pfomask & (1 << PFO_C)) {
3531 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3532 pfomask &= ~(1 << PFO_C);
3537 if (po->operand_cnt == 2) {
3538 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3541 if (po->operand_cnt == 3)
3542 ferr(po, "TODO imul3\n");
3545 assert_operand_cnt(1);
3546 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3547 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3548 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3549 fprintf(fout, " edx = mul_tmp >> 32;\n");
3550 fprintf(fout, " eax = mul_tmp;");
3551 last_arith_dst = NULL;
3552 delayed_flag_op = NULL;
3557 assert_operand_cnt(1);
3558 if (po->operand[0].lmod != OPLM_DWORD)
3559 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3561 // 32bit division is common, look for it
3562 if (po->op == OP_DIV)
3563 ret = scan_for_reg_clear(i, xDX);
3565 ret = scan_for_cdq_edx(i);
3567 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3568 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3569 po->op == OP_IDIV));
3570 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3571 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3574 ferr(po, "TODO 64bit divident\n");
3575 last_arith_dst = NULL;
3576 delayed_flag_op = NULL;
3581 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3583 for (j = 0; j < 8; j++) {
3584 if (pfomask & (1 << j)) {
3585 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3586 fprintf(fout, " cond_%s = %s;",
3587 parsed_flag_op_names[j], buf1);
3594 last_arith_dst = NULL;
3595 delayed_flag_op = po;
3598 // note: we reuse OP_Jcc for SETcc, only flags differ
3599 case OP_JO ... OP_JG:
3600 if (po->flags & OPF_JMP)
3601 fprintf(fout, " goto %s;", po->operand[0].name);
3602 // else SETcc - should already be handled
3606 assert_operand_cnt(1);
3607 last_arith_dst = NULL;
3608 delayed_flag_op = NULL;
3610 if (po->operand[0].type == OPT_REGMEM) {
3611 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3614 ferr(po, "parse failure for jmp '%s'\n",
3615 po->operand[0].name);
3616 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
3619 else if (po->operand[0].type != OPT_LABEL)
3620 ferr(po, "unhandled jmp type\n");
3622 fprintf(fout, " goto %s;", po->operand[0].name);
3626 assert_operand_cnt(1);
3629 ferr(po, "NULL pp\n");
3631 if (po->operand[0].type != OPT_LABEL)
3632 fprintf(fout, " icall%d = %s;\n", i,
3633 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
3637 if (strstr(pp->ret_type.name, "int64")) {
3638 if (po->flags & OPF_TAIL)
3639 ferr(po, "int64 and tail?\n");
3640 fprintf(fout, "mul_tmp = ");
3642 else if (!IS(pp->ret_type.name, "void")) {
3643 if (po->flags & OPF_TAIL) {
3644 if (!IS(g_func_pp->ret_type.name, "void")) {
3645 fprintf(fout, "return ");
3646 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3647 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3651 fprintf(fout, "eax = ");
3652 if (pp->ret_type.is_ptr)
3653 fprintf(fout, "(u32)");
3657 if (po->operand[0].type != OPT_LABEL) {
3658 fprintf(fout, "icall%d(", i);
3661 if (pp->name[0] == 0)
3662 ferr(po, "missing pp->name\n");
3663 fprintf(fout, "%s%s(", pp->name,
3664 pp->has_structarg ? "_sa" : "");
3667 for (arg = 0; arg < pp->argc; arg++) {
3669 fprintf(fout, ", ");
3672 if (pp->arg[arg].type.is_ptr)
3673 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3675 if (pp->arg[arg].reg != NULL) {
3676 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3681 tmp_op = pp->arg[arg].datap;
3683 ferr(po, "parsed_op missing for arg%d\n", arg);
3684 if (tmp_op->argnum != 0) {
3685 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3689 out_src_opr(buf1, sizeof(buf1),
3690 tmp_op, &tmp_op->operand[0], cast, 0));
3693 fprintf(fout, ");");
3695 if (strstr(pp->ret_type.name, "int64")) {
3696 fprintf(fout, "\n");
3697 fprintf(fout, " edx = mul_tmp >> 32;\n");
3698 fprintf(fout, " eax = mul_tmp;");
3701 if (po->flags & OPF_TAIL) {
3702 strcpy(g_comment, "tailcall");
3706 else if (IS(pp->ret_type.name, "void"))
3708 else if (IS(g_func_pp->ret_type.name, "void"))
3710 // else already handled as 'return f()'
3713 if (!IS(g_func_pp->ret_type.name, "void"))
3714 ferr(po, "int func -> void func tailcall?\n");
3715 fprintf(fout, "\n return;");
3716 strcpy(g_comment, "^ tailcall");
3719 delayed_flag_op = NULL;
3720 last_arith_dst = NULL;
3724 if (g_func_pp->is_vararg)
3725 fprintf(fout, " va_end(ap);\n");
3727 if (IS(g_func_pp->ret_type.name, "void")) {
3728 if (i != opcnt - 1 || label_pending)
3729 fprintf(fout, " return;");
3731 else if (g_func_pp->ret_type.is_ptr) {
3732 fprintf(fout, " return (%s)eax;",
3733 g_func_pp->ret_type.name);
3736 fprintf(fout, " return eax;");
3738 last_arith_dst = NULL;
3739 delayed_flag_op = NULL;
3743 if (po->argnum != 0) {
3744 // special case - saved func arg
3745 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3746 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
3749 else if (po->flags & OPF_RSAVE) {
3750 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3751 fprintf(fout, " s_%s = %s;", buf1, buf1);
3754 if (!(g_ida_func_attr & IDAFA_NORETURN))
3755 ferr(po, "stray push encountered\n");
3760 if (po->flags & OPF_RSAVE) {
3761 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3762 fprintf(fout, " %s = s_%s;", buf1, buf1);
3765 ferr(po, "stray pop encountered\n");
3774 ferr(po, "unhandled op type %d, flags %x\n",
3779 if (g_comment[0] != 0) {
3780 fprintf(fout, " // %s", g_comment);
3785 fprintf(fout, "\n");
3787 // some sanity checking
3788 if ((po->flags & OPF_REP) && po->op != OP_STOS
3789 && po->op != OP_MOVS && po->op != OP_CMPS)
3790 ferr(po, "unexpected rep\n");
3791 if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3792 ferr(po, "unexpected repz/repnz\n");
3795 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3797 // see is delayed flag stuff is still valid
3798 if (delayed_flag_op != NULL && delayed_flag_op != po) {
3799 if (is_any_opr_modified(delayed_flag_op, po))
3800 delayed_flag_op = NULL;
3803 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3804 if (is_opr_modified(last_arith_dst, po))
3805 last_arith_dst = NULL;
3811 if (g_stack_fsz && !g_stack_frame_used)
3812 fprintf(fout, " (void)sf;\n");
3814 fprintf(fout, "}\n\n");
3817 for (i = 0; i < opcnt; i++) {
3818 struct label_ref *lr, *lr_del;
3820 lr = g_label_refs[i].next;
3821 while (lr != NULL) {
3826 g_label_refs[i].i = -1;
3827 g_label_refs[i].next = NULL;
3829 if (ops[i].op == OP_CALL) {
3838 static void set_label(int i, const char *name)
3844 p = strchr(name, ':');
3848 if (len > sizeof(g_labels[0]) - 1)
3849 aerr("label '%s' too long: %d\n", name, len);
3850 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
3851 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
3852 memcpy(g_labels[i], name, len);
3853 g_labels[i][len] = 0;
3856 // '=' needs special treatment..
3857 static char *next_word_s(char *w, size_t wsize, char *s)
3863 for (i = 0; i < wsize - 1; i++) {
3864 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
3870 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
3871 printf("warning: '%s' truncated\n", w);
3882 static struct chunk_item *func_chunks;
3883 static int func_chunk_cnt;
3884 static int func_chunk_alloc;
3886 static void add_func_chunk(FILE *fasm, const char *name, int line)
3888 if (func_chunk_cnt >= func_chunk_alloc) {
3889 func_chunk_alloc *= 2;
3890 func_chunks = realloc(func_chunks,
3891 func_chunk_alloc * sizeof(func_chunks[0]));
3892 my_assert_not(func_chunks, NULL);
3894 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
3895 func_chunks[func_chunk_cnt].name = strdup(name);
3896 func_chunks[func_chunk_cnt].asmln = line;
3900 static int cmp_chunks(const void *p1, const void *p2)
3902 const struct chunk_item *c1 = p1, *c2 = p2;
3903 return strcmp(c1->name, c2->name);
3906 static int cmpstringp(const void *p1, const void *p2)
3908 return strcmp(*(char * const *)p1, *(char * const *)p2);
3911 static void scan_ahead(FILE *fasm)
3921 oldpos = ftell(fasm);
3924 while (fgets(line, sizeof(line), fasm))
3935 // get rid of random tabs
3936 for (i = 0; line[i] != 0; i++)
3937 if (line[i] == '\t')
3940 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3943 next_word(words[0], sizeof(words[0]), p);
3944 if (words[0][0] == 0)
3945 aerr("missing name for func chunk?\n");
3947 add_func_chunk(fasm, words[0], asmln);
3952 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3953 words[wordc][0] = 0;
3954 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3955 if (*p == 0 || *p == ';') {
3961 if (wordc == 2 && IS(words[1], "ends"))
3965 fseek(fasm, oldpos, SEEK_SET);
3969 int main(int argc, char *argv[])
3971 FILE *fout, *fasm, *frlist;
3972 struct parsed_data *pd = NULL;
3974 char **rlist = NULL;
3976 int rlist_alloc = 0;
3977 int func_chunks_used = 0;
3978 int func_chunks_sorted = 0;
3979 int func_chunk_i = -1;
3980 long func_chunk_ret = 0;
3981 int func_chunk_ret_ln = 0;
3982 int scanned_ahead = 0;
3984 char words[20][256];
3985 enum opr_lenmod lmod;
3987 int pending_endp = 0;
3989 int skip_warned = 0;
4000 if (argv[1] && IS(argv[1], "-v")) {
4005 if (argc < arg + 3) {
4006 printf("usage:\n%s [-v] <.c> <.asm> <hdrf> [rlist]*\n",
4013 asmfn = argv[arg++];
4014 fasm = fopen(asmfn, "r");
4015 my_assert_not(fasm, NULL);
4017 hdrfn = argv[arg++];
4018 g_fhdr = fopen(hdrfn, "r");
4019 my_assert_not(g_fhdr, NULL);
4022 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4023 my_assert_not(rlist, NULL);
4024 // needs special handling..
4025 rlist[rlist_len++] = "__alloca_probe";
4027 func_chunk_alloc = 32;
4028 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4029 my_assert_not(func_chunks, NULL);
4031 memset(words, 0, sizeof(words));
4033 for (; arg < argc; arg++) {
4034 frlist = fopen(argv[arg], "r");
4035 my_assert_not(frlist, NULL);
4037 while (fgets(line, sizeof(line), frlist)) {
4039 if (*p == 0 || *p == ';')
4042 if (IS_START(p, "#if 0"))
4044 else if (IS_START(p, "#endif"))
4051 p = next_word(words[0], sizeof(words[0]), p);
4052 if (words[0][0] == 0)
4055 if (rlist_len >= rlist_alloc) {
4056 rlist_alloc = rlist_alloc * 2 + 64;
4057 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4058 my_assert_not(rlist, NULL);
4060 rlist[rlist_len++] = strdup(words[0]);
4069 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4071 fout = fopen(argv[arg_out], "w");
4072 my_assert_not(fout, NULL);
4075 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4076 my_assert_not(g_eqs, NULL);
4078 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4079 g_label_refs[i].i = -1;
4080 g_label_refs[i].next = NULL;
4083 while (fgets(line, sizeof(line), fasm))
4092 // get rid of random tabs
4093 for (i = 0; line[i] != 0; i++)
4094 if (line[i] == '\t')
4099 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4100 goto do_pending_endp; // eww..
4102 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4104 static const char *attrs[] = {
4113 // parse IDA's attribute-list comment
4114 g_ida_func_attr = 0;
4117 for (; *p != 0; p = sskip(p)) {
4118 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4119 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4120 g_ida_func_attr |= 1 << i;
4121 p += strlen(attrs[i]);
4125 if (i == ARRAY_SIZE(attrs)) {
4126 anote("unparsed IDA attr: %s\n", p);
4129 if (IS(attrs[i], "fpd=")) {
4130 p = next_word(words[0], sizeof(words[0]), p);
4135 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4138 next_word(words[0], sizeof(words[0]), p);
4139 if (words[0][0] == 0)
4140 aerr("missing name for func chunk?\n");
4142 if (!scanned_ahead) {
4143 add_func_chunk(fasm, words[0], asmln);
4144 func_chunks_sorted = 0;
4147 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4149 if (func_chunk_i >= 0) {
4150 if (func_chunk_i < func_chunk_cnt
4151 && IS(func_chunks[func_chunk_i].name, g_func))
4153 // move on to next chunk
4154 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4156 aerr("seek failed for '%s' chunk #%d\n",
4157 g_func, func_chunk_i);
4158 asmln = func_chunks[func_chunk_i].asmln;
4162 if (func_chunk_ret == 0)
4163 aerr("no return from chunk?\n");
4164 fseek(fasm, func_chunk_ret, SEEK_SET);
4165 asmln = func_chunk_ret_ln;
4171 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4172 func_chunks_used = 1;
4174 if (IS_START(g_func, "sub_")) {
4175 unsigned long addr = strtoul(p, NULL, 16);
4176 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4177 if (addr > f_addr && !scanned_ahead) {
4178 anote("scan_ahead caused by '%s', addr %lx\n",
4182 func_chunks_sorted = 0;
4190 for (i = wordc; i < ARRAY_SIZE(words); i++)
4192 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4193 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4194 if (*p == 0 || *p == ';') {
4199 if (*p != 0 && *p != ';')
4200 aerr("too many words\n");
4202 // alow asm patches in comments
4203 if (*p == ';' && IS_START(p, "; sctpatch:")) {
4205 if (*p == 0 || *p == ';')
4207 goto parse_words; // lame
4212 awarn("wordc == 0?\n");
4216 // don't care about this:
4217 if (words[0][0] == '.'
4218 || IS(words[0], "include")
4219 || IS(words[0], "assume") || IS(words[1], "segment")
4220 || IS(words[0], "align"))
4226 // do delayed endp processing to collect switch jumptables
4228 if (in_func && !skip_func && wordc >= 2
4229 && ((words[0][0] == 'd' && words[0][2] == 0)
4230 || (words[1][0] == 'd' && words[1][2] == 0)))
4233 if (words[1][0] == 'd' && words[1][2] == 0) {
4235 if (g_func_pd_cnt >= pd_alloc) {
4236 pd_alloc = pd_alloc * 2 + 16;
4237 g_func_pd = realloc(g_func_pd,
4238 sizeof(g_func_pd[0]) * pd_alloc);
4239 my_assert_not(g_func_pd, NULL);
4241 pd = &g_func_pd[g_func_pd_cnt];
4243 memset(pd, 0, sizeof(*pd));
4244 strcpy(pd->label, words[0]);
4245 pd->type = OPT_CONST;
4246 pd->lmod = lmod_from_directive(words[1]);
4250 lmod = lmod_from_directive(words[0]);
4251 if (lmod != pd->lmod)
4252 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4255 if (pd->count_alloc < pd->count + wordc) {
4256 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4257 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4258 my_assert_not(pd->d, NULL);
4260 for (; i < wordc; i++) {
4261 if (IS(words[i], "offset")) {
4262 pd->type = OPT_OFFSET;
4265 p = strchr(words[i], ',');
4268 if (pd->type == OPT_OFFSET)
4269 pd->d[pd->count].u.label = strdup(words[i]);
4271 pd->d[pd->count].u.val = parse_number(words[i]);
4272 pd->d[pd->count].bt_i = -1;
4278 if (in_func && !skip_func)
4279 gen_func(fout, g_fhdr, g_func, pi);
4283 g_ida_func_attr = 0;
4287 func_chunks_used = 0;
4290 memset(&ops, 0, pi * sizeof(ops[0]));
4291 memset(g_labels, 0, pi * sizeof(g_labels[0]));
4295 for (i = 0; i < g_func_pd_cnt; i++) {
4297 if (pd->type == OPT_OFFSET) {
4298 for (j = 0; j < pd->count; j++)
4299 free(pd->d[j].u.label);
4310 if (IS(words[1], "proc")) {
4312 aerr("proc '%s' while in_func '%s'?\n",
4315 if ((g_ida_func_attr & IDAFA_THUNK)
4316 || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4318 strcpy(g_func, words[0]);
4319 set_label(0, words[0]);
4324 if (IS(words[1], "endp"))
4327 aerr("endp '%s' while not in_func?\n", words[0]);
4328 if (!IS(g_func, words[0]))
4329 aerr("endp '%s' while in_func '%s'?\n",
4332 if (!skip_func && func_chunks_used) {
4333 // start processing chunks
4334 struct chunk_item *ci, key = { g_func, 0 };
4336 func_chunk_ret = ftell(fasm);
4337 func_chunk_ret_ln = asmln;
4338 if (!func_chunks_sorted) {
4339 qsort(func_chunks, func_chunk_cnt,
4340 sizeof(func_chunks[0]), cmp_chunks);
4341 func_chunks_sorted = 1;
4343 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4344 sizeof(func_chunks[0]), cmp_chunks);
4346 aerr("'%s' needs chunks, but none found\n", g_func);
4347 func_chunk_i = ci - func_chunks;
4348 for (; func_chunk_i > 0; func_chunk_i--)
4349 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4352 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4354 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4355 asmln = func_chunks[func_chunk_i].asmln;
4363 if (wordc == 2 && IS(words[1], "ends"))
4366 p = strchr(words[0], ':');
4368 set_label(pi, words[0]);
4372 if (!in_func || skip_func) {
4373 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4375 anote("skipping from '%s'\n", g_labels[pi]);
4378 g_labels[pi][0] = 0;
4382 if (wordc > 1 && IS(words[1], "=")) {
4384 aerr("unhandled equ, wc=%d\n", wordc);
4385 if (g_eqcnt >= eq_alloc) {
4387 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4388 my_assert_not(g_eqs, NULL);
4391 len = strlen(words[0]);
4392 if (len > sizeof(g_eqs[0].name) - 1)
4393 aerr("equ name too long: %d\n", len);
4394 strcpy(g_eqs[g_eqcnt].name, words[0]);
4396 if (!IS(words[3], "ptr"))
4397 aerr("unhandled equ\n");
4398 if (IS(words[2], "dword"))
4399 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4400 else if (IS(words[2], "word"))
4401 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4402 else if (IS(words[2], "byte"))
4403 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4405 aerr("bad lmod: '%s'\n", words[2]);
4407 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4412 if (pi >= ARRAY_SIZE(ops))
4413 aerr("too many ops\n");
4415 parse_op(&ops[pi], words, wordc);
4426 // vim:ts=2:shiftwidth=2:expandtab