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__); \
29 #include "masm_tools.h"
32 OPF_RMD = (1 << 0), /* removed or optimized out */
33 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
34 OPF_FLAGS = (1 << 2), /* sets flags */
35 OPF_JMP = (1 << 3), /* branch, call */
36 OPF_CJMP = (1 << 4), /* cond. branch (cc or jecxz) */
37 OPF_CC = (1 << 5), /* uses flags */
38 OPF_TAIL = (1 << 6), /* ret or tail call */
39 OPF_RSAVE = (1 << 7), /* push/pop is local reg save/load */
40 OPF_REP = (1 << 8), /* prefixed by rep */
41 OPF_REPZ = (1 << 9), /* rep is repe/repz */
42 OPF_REPNZ = (1 << 10), /* rep is repne/repnz */
43 OPF_FARG = (1 << 11), /* push collected as func arg (no reuse) */
44 OPF_EBP_S = (1 << 12), /* ebp used as scratch here, not BP */
45 OPF_DF = (1 << 13), /* DF flag set */
119 // must be sorted (larger len must be further in enum)
127 #define MAX_OPERANDS 3
131 enum opr_lenmod lmod;
132 unsigned int is_ptr:1; // pointer in C
133 unsigned int is_array:1; // array in C
134 unsigned int type_from_var:1; // .. in header, sometimes wrong
135 unsigned int size_mismatch:1; // type override differs from C
136 unsigned int size_lt:1; // type override is larger than C
137 unsigned int had_ds:1; // had ds: prefix
145 struct parsed_opr operand[MAX_OPERANDS];
148 int regmask_src; // all referensed regs
150 int pfomask; // flagop: parsed_flag_op that can't be delayed
151 int argnum; // push: altered before call arg #
152 int cc_scratch; // scratch storage during analysis
153 int bt_i; // branch target for branches
154 struct parsed_data *btj;// branch targets for jumptables
159 // OP_CALL - parser proto hint (str), ptr to struct parsed_proto
160 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
161 // OP_POP - point to OP_PUSH in push/pop pair
165 enum opr_lenmod lmod;
172 enum opr_lenmod lmod;
186 struct label_ref *next;
190 IDAFA_BP_FRAME = (1 << 0),
191 IDAFA_LIB_FUNC = (1 << 1),
192 IDAFA_STATIC = (1 << 2),
193 IDAFA_NORETURN = (1 << 3),
194 IDAFA_THUNK = (1 << 4),
195 IDAFA_FPD = (1 << 5),
200 static struct parsed_op ops[MAX_OPS];
201 static struct parsed_equ *g_eqs;
203 static char g_labels[MAX_OPS][32];
204 static struct label_ref g_label_refs[MAX_OPS];
205 static const struct parsed_proto *g_func_pp;
206 static struct parsed_data *g_func_pd;
207 static int g_func_pd_cnt;
208 static char g_func[256];
209 static char g_comment[256];
210 static int g_bp_frame;
211 static int g_sp_frame;
212 static int g_stack_frame_used;
213 static int g_stack_fsz;
214 static int g_ida_func_attr;
215 static int g_allow_regfunc;
216 #define ferr(op_, fmt, ...) do { \
217 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
218 dump_op(op_), ##__VA_ARGS__); \
222 #define fnote(op_, fmt, ...) \
223 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
224 dump_op(op_), ##__VA_ARGS__)
228 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
229 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
230 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
231 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
233 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
235 // possible basic comparison types (without inversion)
236 enum parsed_flag_op {
240 PFO_BE, // 6 CF=1||ZF=1
244 PFO_LE, // e ZF=1||SF!=OF
247 static const char *parsed_flag_op_names[] = {
248 "o", "c", "z", "be", "s", "p", "l", "le"
251 static int char_array_i(const char *array[], size_t len, const char *s)
255 for (i = 0; i < len; i++)
262 static void printf_number(char *buf, size_t buf_size,
263 unsigned long number)
265 // output in C-friendly form
266 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
269 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
273 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
275 *reg_lmod = OPLM_DWORD;
278 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
280 *reg_lmod = OPLM_WORD;
283 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
285 *reg_lmod = OPLM_BYTE;
288 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
290 *reg_lmod = OPLM_BYTE;
297 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
299 enum opr_lenmod lmod;
312 while (my_isblank(*s))
314 for (; my_issep(*s); d++, s++)
316 while (my_isblank(*s))
321 if (IS_START(s, "ds:"))
324 s = next_idt(w, sizeof(w), s);
329 reg = parse_reg(&lmod, w);
331 *regmask |= 1 << reg;
335 if ('0' <= w[0] && w[0] <= '9') {
336 number = parse_number(w);
337 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
341 // probably some label/identifier - pass
344 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
348 strcpy(name, cvtbuf);
353 static int is_reg_in_str(const char *s)
357 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
360 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
361 if (!strncmp(s, regs_r32[i], 3))
367 static const char *parse_stack_el(const char *name, char *extra_reg)
369 const char *p, *p2, *s;
376 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
378 if (extra_reg != NULL) {
379 strncpy(extra_reg, name, 3);
384 if (IS_START(p, "ebp+")) {
388 if (p2 != NULL && is_reg_in_str(p)) {
389 if (extra_reg != NULL) {
390 strncpy(extra_reg, p, p2 - p);
391 extra_reg[p2 - p] = 0;
396 if (!('0' <= *p && *p <= '9'))
402 if (!IS_START(name, "esp+"))
405 p = strchr(name + 4, '+');
407 // must be a number after esp+, already converted to 0x..
409 if (!('0' <= *s && *s <= '9')) {
410 aerr("%s nan?\n", __func__);
413 if (s[0] == '0' && s[1] == 'x')
416 if (len < sizeof(buf) - 1) {
417 strncpy(buf, s, len);
419 val = strtol(buf, &endp, 16);
420 if (val == 0 || *endp != 0) {
421 aerr("%s num parse fail for '%s'\n", __func__, buf);
430 if ('0' <= *p && *p <= '9')
436 static int guess_lmod_from_name(struct parsed_opr *opr)
438 if (!strncmp(opr->name, "dword_", 6)) {
439 opr->lmod = OPLM_DWORD;
442 if (!strncmp(opr->name, "word_", 5)) {
443 opr->lmod = OPLM_WORD;
446 if (!strncmp(opr->name, "byte_", 5)) {
447 opr->lmod = OPLM_BYTE;
453 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
454 const struct parsed_type *c_type)
456 static const char *dword_types[] = {
457 "int", "_DWORD", "UINT_PTR", "DWORD",
458 "WPARAM", "LPARAM", "UINT",
461 static const char *word_types[] = {
462 "uint16_t", "int16_t", "_WORD",
463 "unsigned __int16", "__int16",
465 static const char *byte_types[] = {
466 "uint8_t", "int8_t", "char",
467 "unsigned __int8", "__int8", "BYTE", "_BYTE",
473 if (c_type->is_ptr) {
478 n = skip_type_mod(c_type->name);
480 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
481 if (IS(n, dword_types[i])) {
487 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
488 if (IS(n, word_types[i])) {
494 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
495 if (IS(n, byte_types[i])) {
504 static enum opr_type lmod_from_directive(const char *d)
508 else if (IS(d, "dw"))
510 else if (IS(d, "db"))
513 aerr("unhandled directive: '%s'\n", d);
517 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
523 *regmask |= 1 << reg;
526 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
529 static int parse_operand(struct parsed_opr *opr,
530 int *regmask, int *regmask_indirect,
531 char words[16][256], int wordc, int w, unsigned int op_flags)
533 const struct parsed_proto *pp;
534 enum opr_lenmod tmplmod;
535 unsigned long number;
543 aerr("parse_operand w %d, wordc %d\n", w, wordc);
547 for (i = w; i < wordc; i++) {
548 len = strlen(words[i]);
549 if (words[i][len - 1] == ',') {
550 words[i][len - 1] = 0;
556 wordc_in = wordc - w;
558 if ((op_flags & OPF_JMP) && wordc_in > 0
559 && !('0' <= words[w][0] && words[w][0] <= '9'))
561 const char *label = NULL;
563 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
564 && IS(words[w + 1], "ptr"))
565 label = words[w + 2];
566 else if (wordc_in == 2 && IS(words[w], "short"))
567 label = words[w + 1];
568 else if (wordc_in == 1
569 && strchr(words[w], '[') == NULL
570 && parse_reg(&tmplmod, words[w]) < 0)
574 opr->type = OPT_LABEL;
575 if (IS_START(label, "ds:")) {
579 strcpy(opr->name, label);
585 if (IS(words[w + 1], "ptr")) {
586 if (IS(words[w], "dword"))
587 opr->lmod = OPLM_DWORD;
588 else if (IS(words[w], "word"))
589 opr->lmod = OPLM_WORD;
590 else if (IS(words[w], "byte"))
591 opr->lmod = OPLM_BYTE;
593 aerr("type parsing failed\n");
595 wordc_in = wordc - w;
600 if (IS(words[w], "offset")) {
601 opr->type = OPT_OFFSET;
602 strcpy(opr->name, words[w + 1]);
605 if (IS(words[w], "(offset")) {
606 p = strchr(words[w + 1], ')');
608 aerr("parse of bracketed offset failed\n");
610 opr->type = OPT_OFFSET;
611 strcpy(opr->name, words[w + 1]);
617 aerr("parse_operand 1 word expected\n");
619 if (IS_START(words[w], "ds:")) {
621 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
623 strcpy(opr->name, words[w]);
625 if (words[w][0] == '[') {
626 opr->type = OPT_REGMEM;
627 ret = sscanf(words[w], "[%[^]]]", opr->name);
629 aerr("[] parse failure\n");
631 parse_indmode(opr->name, regmask_indirect, 1);
632 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
634 struct parsed_equ *eq =
635 equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
637 opr->lmod = eq->lmod;
641 else if (strchr(words[w], '[')) {
643 p = strchr(words[w], '[');
644 opr->type = OPT_REGMEM;
645 parse_indmode(p, regmask_indirect, 0);
646 strncpy(buf, words[w], p - words[w]);
647 buf[p - words[w]] = 0;
648 pp = proto_parse(g_fhdr, buf, 1);
651 else if (('0' <= words[w][0] && words[w][0] <= '9')
652 || words[w][0] == '-')
654 number = parse_number(words[w]);
655 opr->type = OPT_CONST;
657 printf_number(opr->name, sizeof(opr->name), number);
661 ret = parse_reg(&tmplmod, opr->name);
663 setup_reg_opr(opr, ret, tmplmod, regmask);
667 // most likely var in data segment
668 opr->type = OPT_LABEL;
669 pp = proto_parse(g_fhdr, opr->name, 0);
673 if (pp->is_fptr || pp->is_func) {
674 opr->lmod = OPLM_DWORD;
678 tmplmod = OPLM_UNSPEC;
679 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
680 anote("unhandled C type '%s' for '%s'\n",
681 pp->type.name, opr->name);
683 if (opr->lmod == OPLM_UNSPEC) {
685 opr->type_from_var = 1;
687 else if (opr->lmod != tmplmod) {
688 opr->size_mismatch = 1;
689 if (tmplmod < opr->lmod)
692 opr->is_ptr = pp->type.is_ptr;
694 opr->is_array = pp->type.is_array;
697 if (opr->lmod == OPLM_UNSPEC)
698 guess_lmod_from_name(opr);
702 static const struct {
707 { "repe", OPF_REP|OPF_REPZ },
708 { "repz", OPF_REP|OPF_REPZ },
709 { "repne", OPF_REP|OPF_REPNZ },
710 { "repnz", OPF_REP|OPF_REPNZ },
713 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
715 static const struct {
722 { "nop", OP_NOP, 0, 0, 0 },
723 { "push", OP_PUSH, 1, 1, 0 },
724 { "pop", OP_POP, 1, 1, OPF_DATA },
725 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
726 { "mov" , OP_MOV, 2, 2, OPF_DATA },
727 { "lea", OP_LEA, 2, 2, OPF_DATA },
728 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
729 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
730 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
731 { "not", OP_NOT, 1, 1, OPF_DATA },
732 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
733 { "stosb",OP_STOS, 0, 0, OPF_DATA },
734 { "stosw",OP_STOS, 0, 0, OPF_DATA },
735 { "stosd",OP_STOS, 0, 0, OPF_DATA },
736 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
737 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
738 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
739 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
740 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
741 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
742 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
743 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
744 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
745 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
746 { "cld", OP_CLD, 0, 0, OPF_DATA },
747 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
748 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
749 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
750 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
751 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
752 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
753 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
754 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
755 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
756 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
757 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
758 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
759 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
760 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
761 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
762 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
763 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
764 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
765 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
766 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
767 { "test", OP_TEST, 2, 2, OPF_FLAGS },
768 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
769 { "retn", OP_RET, 0, 1, OPF_TAIL },
770 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
771 { "jmp", OP_JMP, 1, 1, OPF_JMP },
772 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
773 { "jo", OP_JO, 1, 1, OPF_CJMP_CC }, // 70 OF=1
774 { "jno", OP_JNO, 1, 1, OPF_CJMP_CC }, // 71 OF=0
775 { "jc", OP_JC, 1, 1, OPF_CJMP_CC }, // 72 CF=1
776 { "jb", OP_JC, 1, 1, OPF_CJMP_CC }, // 72
777 { "jnc", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73 CF=0
778 { "jnb", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73
779 { "jae", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73
780 { "jz", OP_JZ, 1, 1, OPF_CJMP_CC }, // 74 ZF=1
781 { "je", OP_JZ, 1, 1, OPF_CJMP_CC }, // 74
782 { "jnz", OP_JNZ, 1, 1, OPF_CJMP_CC }, // 75 ZF=0
783 { "jne", OP_JNZ, 1, 1, OPF_CJMP_CC }, // 75
784 { "jbe", OP_JBE, 1, 1, OPF_CJMP_CC }, // 76 CF=1 || ZF=1
785 { "jna", OP_JBE, 1, 1, OPF_CJMP_CC }, // 76
786 { "ja", OP_JA, 1, 1, OPF_CJMP_CC }, // 77 CF=0 && ZF=0
787 { "jnbe", OP_JA, 1, 1, OPF_CJMP_CC }, // 77
788 { "js", OP_JS, 1, 1, OPF_CJMP_CC }, // 78 SF=1
789 { "jns", OP_JNS, 1, 1, OPF_CJMP_CC }, // 79 SF=0
790 { "jp", OP_JP, 1, 1, OPF_CJMP_CC }, // 7a PF=1
791 { "jpe", OP_JP, 1, 1, OPF_CJMP_CC }, // 7a
792 { "jnp", OP_JNP, 1, 1, OPF_CJMP_CC }, // 7b PF=0
793 { "jpo", OP_JNP, 1, 1, OPF_CJMP_CC }, // 7b
794 { "jl", OP_JL, 1, 1, OPF_CJMP_CC }, // 7c SF!=OF
795 { "jnge", OP_JL, 1, 1, OPF_CJMP_CC }, // 7c
796 { "jge", OP_JGE, 1, 1, OPF_CJMP_CC }, // 7d SF=OF
797 { "jnl", OP_JGE, 1, 1, OPF_CJMP_CC }, // 7d
798 { "jle", OP_JLE, 1, 1, OPF_CJMP_CC }, // 7e ZF=1 || SF!=OF
799 { "jng", OP_JLE, 1, 1, OPF_CJMP_CC }, // 7e
800 { "jg", OP_JG, 1, 1, OPF_CJMP_CC }, // 7f ZF=0 && SF=OF
801 { "jnle", OP_JG, 1, 1, OPF_CJMP_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);
906 if (op->operand_cnt != 0)
908 if (words[op_w][4] == 'b')
910 else if (words[op_w][4] == 'w')
912 else if (words[op_w][4] == 'd')
915 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
916 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
917 op->regmask_dst = op->regmask_src;
918 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
923 if (op->operand_cnt != 0)
925 if (words[op_w][4] == 'b')
927 else if (words[op_w][4] == 'w')
929 else if (words[op_w][4] == 'd')
932 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
933 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
934 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
935 op->regmask_dst = op->regmask_src;
939 op->regmask_src |= op->regmask_dst;
940 op->regmask_dst |= op->regmask_src;
945 op->regmask_src = 1 << xCX;
946 op->operand[0].type = OPT_REG;
947 op->operand[0].reg = xCX;
948 op->operand[0].lmod = OPLM_DWORD;
952 if (op->operand_cnt != 1)
957 op->regmask_dst = (1 << xDX) | (1 << xAX);
958 op->regmask_src |= (1 << xAX);
959 if (op->operand[0].lmod == OPLM_UNSPEC)
960 op->operand[0].lmod = OPLM_DWORD;
965 // we could set up operands for edx:eax, but there is no real need to
966 // (see is_opr_modified())
967 regmask = (1 << xDX) | (1 << xAX);
968 op->regmask_dst = regmask;
969 op->regmask_src |= regmask;
970 if (op->operand[0].lmod == OPLM_UNSPEC)
971 op->operand[0].lmod = OPLM_DWORD;
979 if (op->operand[1].lmod == OPLM_UNSPEC)
980 op->operand[1].lmod = OPLM_BYTE;
984 if (op->operand[0].lmod == OPLM_UNSPEC
985 && (op->operand[0].type == OPT_CONST
986 || op->operand[0].type == OPT_OFFSET
987 || op->operand[0].type == OPT_LABEL))
988 op->operand[0].lmod = OPLM_DWORD;
993 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
994 && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
996 op->flags |= OPF_RMD;
1001 if (op->operand[0].type == OPT_REG
1002 && op->operand[1].type == OPT_REGMEM)
1005 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1006 if (IS(buf, op->operand[1].name))
1007 op->flags |= OPF_RMD;
1012 // trashed regs must be explicitly detected later
1013 op->regmask_dst = 0;
1021 static const char *op_name(enum op_op op)
1025 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1026 if (op_table[i].op == op)
1027 return op_table[i].name;
1033 static const char *dump_op(struct parsed_op *po)
1035 static char out[128];
1042 snprintf(out, sizeof(out), "%s", op_name(po->op));
1043 for (i = 0; i < po->operand_cnt; i++) {
1047 snprintf(p, sizeof(out) - (p - out),
1048 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1049 po->operand[i].name);
1055 static const char *lmod_type_u(struct parsed_op *po,
1056 enum opr_lenmod lmod)
1066 ferr(po, "invalid lmod: %d\n", lmod);
1067 return "(_invalid_)";
1071 static const char *lmod_cast_u(struct parsed_op *po,
1072 enum opr_lenmod lmod)
1082 ferr(po, "invalid lmod: %d\n", lmod);
1083 return "(_invalid_)";
1087 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1088 enum opr_lenmod lmod)
1098 ferr(po, "invalid lmod: %d\n", lmod);
1099 return "(_invalid_)";
1103 static const char *lmod_cast_s(struct parsed_op *po,
1104 enum opr_lenmod lmod)
1114 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1115 return "(_invalid_)";
1119 static const char *lmod_cast(struct parsed_op *po,
1120 enum opr_lenmod lmod, int is_signed)
1123 lmod_cast_s(po, lmod) :
1124 lmod_cast_u(po, lmod);
1127 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1137 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1142 static const char *opr_name(struct parsed_op *po, int opr_num)
1144 if (opr_num >= po->operand_cnt)
1145 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1146 return po->operand[opr_num].name;
1149 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1151 if (opr_num >= po->operand_cnt)
1152 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1153 if (po->operand[opr_num].type != OPT_CONST)
1154 ferr(po, "opr %d: const expected\n", opr_num);
1155 return po->operand[opr_num].val;
1158 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1160 if ((unsigned int)popr->reg >= MAX_REGS)
1161 ferr(po, "invalid reg: %d\n", popr->reg);
1162 return regs_r32[popr->reg];
1165 // cast1 is the "final" cast
1166 static const char *simplify_cast(const char *cast1, const char *cast2)
1168 static char buf[256];
1174 if (IS(cast1, cast2))
1176 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1178 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1180 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1182 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1184 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1187 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1191 static const char *simplify_cast_num(const char *cast, unsigned int val)
1193 if (IS(cast, "(u8)") && val < 0x100)
1195 if (IS(cast, "(s8)") && val < 0x80)
1197 if (IS(cast, "(u16)") && val < 0x10000)
1199 if (IS(cast, "(s16)") && val < 0x8000)
1201 if (IS(cast, "(s32)") && val < 0x80000000)
1207 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1216 namelen = strlen(name);
1218 p = strchr(name, '+');
1222 ferr(po, "equ parse failed for '%s'\n", name);
1224 if (IS_START(p, "0x"))
1226 *extra_offs = strtol(p, &endp, 16);
1228 ferr(po, "equ parse failed for '%s'\n", name);
1231 for (i = 0; i < g_eqcnt; i++)
1232 if (strncmp(g_eqs[i].name, name, namelen) == 0
1233 && g_eqs[i].name[namelen] == 0)
1237 ferr(po, "unresolved equ name: '%s'\n", name);
1244 static int is_stack_access(struct parsed_op *po,
1245 const struct parsed_opr *popr)
1247 return (parse_stack_el(popr->name, NULL)
1248 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1249 && IS_START(popr->name, "ebp")));
1252 static void parse_stack_access(struct parsed_op *po,
1253 const char *name, char *ofs_reg, int *offset_out,
1254 int *stack_ra_out, const char **bp_arg_out)
1256 const char *bp_arg = "";
1257 const char *p = NULL;
1258 struct parsed_equ *eq;
1265 if (IS_START(name, "ebp-")
1266 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1269 if (IS_START(p, "0x"))
1271 offset = strtoul(p, &endp, 16);
1275 ferr(po, "ebp- parse of '%s' failed\n", name);
1278 bp_arg = parse_stack_el(name, ofs_reg);
1279 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1280 eq = equ_find(po, bp_arg, &offset);
1282 ferr(po, "detected but missing eq\n");
1283 offset += eq->offset;
1286 if (!strncmp(name, "ebp", 3))
1289 if (ofs_reg[0] == 0 && stack_ra <= offset && offset < stack_ra + 4)
1290 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1292 *offset_out = offset;
1293 *stack_ra_out = stack_ra;
1295 *bp_arg_out = bp_arg;
1298 static void stack_frame_access(struct parsed_op *po,
1299 struct parsed_opr *popr, char *buf, size_t buf_size,
1300 const char *name, const char *cast, int is_src, int is_lea)
1302 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1303 const char *prefix = "";
1304 const char *bp_arg = NULL;
1305 char ofs_reg[16] = { 0, };
1306 int i, arg_i, arg_s;
1313 if (po->flags & OPF_EBP_S)
1314 ferr(po, "stack_frame_access while ebp is scratch\n");
1316 parse_stack_access(po, name, ofs_reg, &offset, &stack_ra, &bp_arg);
1318 if (offset > stack_ra)
1320 arg_i = (offset - stack_ra - 4) / 4;
1321 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1323 if (g_func_pp->is_vararg
1324 && arg_i == g_func_pp->argc_stack && is_lea)
1326 // should be va_list
1329 snprintf(buf, buf_size, "%sap", cast);
1332 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1333 offset, bp_arg, arg_i);
1335 if (ofs_reg[0] != 0)
1336 ferr(po, "offset reg on arg access?\n");
1338 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1339 if (g_func_pp->arg[i].reg != NULL)
1345 if (i == g_func_pp->argc)
1346 ferr(po, "arg %d not in prototype?\n", arg_i);
1348 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1354 ferr(po, "lea/byte to arg?\n");
1355 if (is_src && (offset & 3) == 0)
1356 snprintf(buf, buf_size, "%sa%d",
1357 simplify_cast(cast, "(u8)"), i + 1);
1359 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1360 cast, offset & 3, i + 1);
1365 ferr(po, "lea/word to arg?\n");
1370 ferr(po, "problematic arg store\n");
1371 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1372 simplify_cast(cast, "*(u16 *)"), i + 1);
1375 ferr(po, "unaligned arg word load\n");
1377 else if (is_src && (offset & 2) == 0)
1378 snprintf(buf, buf_size, "%sa%d",
1379 simplify_cast(cast, "(u16)"), i + 1);
1381 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1382 cast, (offset & 2) ? "HI" : "LO", i + 1);
1394 snprintf(buf, buf_size, "(u32)&a%d + %d",
1397 ferr(po, "unaligned arg store\n");
1399 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1400 snprintf(buf, buf_size, "%s(a%d >> %d)",
1401 prefix, i + 1, (offset & 3) * 8);
1405 snprintf(buf, buf_size, "%s%sa%d",
1406 prefix, is_lea ? "&" : "", i + 1);
1411 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1415 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1418 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1419 if (tmp_lmod != OPLM_DWORD
1420 && (unaligned || (!is_src && tmp_lmod < popr->lmod)))
1422 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1423 i + 1, offset, g_func_pp->arg[i].type.name);
1425 if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1426 ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1430 if (g_stack_fsz == 0)
1431 ferr(po, "stack var access without stackframe\n");
1432 g_stack_frame_used = 1;
1434 sf_ofs = g_stack_fsz + offset;
1435 lim = (ofs_reg[0] != 0) ? -4 : 0;
1436 if (offset > 0 || sf_ofs < lim)
1437 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1447 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1448 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1452 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1453 // known unaligned or possibly unaligned
1454 strcat(g_comment, " unaligned");
1456 prefix = "*(u16 *)&";
1457 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1458 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1461 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1465 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1466 // known unaligned or possibly unaligned
1467 strcat(g_comment, " unaligned");
1469 prefix = "*(u32 *)&";
1470 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1471 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1474 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1478 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1483 static void check_func_pp(struct parsed_op *po,
1484 const struct parsed_proto *pp, const char *pfx)
1488 if (pp->argc_reg != 0) {
1489 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1490 pp_print(buf, sizeof(buf), pp);
1491 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1493 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1494 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1495 pfx, pp->argc_reg, pp->argc_stack);
1499 static void check_label_read_ref(struct parsed_op *po, const char *name)
1501 const struct parsed_proto *pp;
1503 pp = proto_parse(g_fhdr, name, 0);
1505 ferr(po, "proto_parse failed for ref '%s'\n", name);
1508 check_func_pp(po, pp, "ref");
1511 static char *out_src_opr(char *buf, size_t buf_size,
1512 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1515 char tmp1[256], tmp2[256];
1523 switch (popr->type) {
1526 ferr(po, "lea from reg?\n");
1528 switch (popr->lmod) {
1530 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1533 snprintf(buf, buf_size, "%s%s",
1534 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1537 if (popr->name[1] == 'h') // XXX..
1538 snprintf(buf, buf_size, "%s(%s >> 8)",
1539 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1541 snprintf(buf, buf_size, "%s%s",
1542 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1545 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1550 if (is_stack_access(po, popr)) {
1551 stack_frame_access(po, popr, buf, buf_size,
1552 popr->name, cast, 1, is_lea);
1556 strcpy(expr, popr->name);
1557 if (strchr(expr, '[')) {
1558 // special case: '[' can only be left for label[reg] form
1559 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1561 ferr(po, "parse failure for '%s'\n", expr);
1562 if (tmp1[0] == '(') {
1563 // (off_4FFF50+3)[eax]
1564 p = strchr(tmp1 + 1, ')');
1565 if (p == NULL || p[1] != 0)
1566 ferr(po, "parse failure (2) for '%s'\n", expr);
1568 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1570 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1573 // XXX: do we need more parsing?
1575 snprintf(buf, buf_size, "%s", expr);
1579 snprintf(buf, buf_size, "%s(%s)",
1580 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1584 check_label_read_ref(po, popr->name);
1585 if (cast[0] == 0 && popr->is_ptr)
1589 snprintf(buf, buf_size, "(u32)&%s", popr->name);
1590 else if (popr->size_lt)
1591 snprintf(buf, buf_size, "%s%s%s%s", cast,
1592 lmod_cast_u_ptr(po, popr->lmod),
1593 popr->is_array ? "" : "&",
1596 snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1597 popr->is_array ? "[0]" : "");
1601 check_label_read_ref(po, popr->name);
1605 ferr(po, "lea an offset?\n");
1606 snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1611 ferr(po, "lea from const?\n");
1613 printf_number(tmp1, sizeof(tmp1), popr->val);
1614 if (popr->val == 0 && strchr(cast, '*'))
1615 snprintf(buf, buf_size, "NULL");
1617 snprintf(buf, buf_size, "%s%s",
1618 simplify_cast_num(cast, popr->val), tmp1);
1622 ferr(po, "invalid src type: %d\n", popr->type);
1628 // note: may set is_ptr (we find that out late for ebp frame..)
1629 static char *out_dst_opr(char *buf, size_t buf_size,
1630 struct parsed_op *po, struct parsed_opr *popr)
1632 switch (popr->type) {
1634 switch (popr->lmod) {
1636 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1640 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1644 if (popr->name[1] == 'h') // XXX..
1645 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1647 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1650 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1655 if (is_stack_access(po, popr)) {
1656 stack_frame_access(po, popr, buf, buf_size,
1657 popr->name, "", 0, 0);
1661 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1664 if (popr->size_mismatch)
1665 snprintf(buf, buf_size, "%s%s%s",
1666 lmod_cast_u_ptr(po, popr->lmod),
1667 popr->is_array ? "" : "&", popr->name);
1669 snprintf(buf, buf_size, "%s%s", popr->name,
1670 popr->is_array ? "[0]" : "");
1674 ferr(po, "invalid dst type: %d\n", popr->type);
1680 static char *out_src_opr_u32(char *buf, size_t buf_size,
1681 struct parsed_op *po, struct parsed_opr *popr)
1683 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1686 static enum parsed_flag_op split_cond(struct parsed_op *po,
1687 enum op_op op, int *is_inv)
1739 ferr(po, "split_cond: bad op %d\n", op);
1744 static void out_test_for_cc(char *buf, size_t buf_size,
1745 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1746 enum opr_lenmod lmod, const char *expr)
1748 const char *cast, *scast;
1750 cast = lmod_cast_u(po, lmod);
1751 scast = lmod_cast_s(po, lmod);
1755 case PFO_BE: // CF=1||ZF=1; CF=0
1756 snprintf(buf, buf_size, "(%s%s %s 0)",
1757 cast, expr, is_inv ? "!=" : "==");
1761 case PFO_L: // SF!=OF; OF=0
1762 snprintf(buf, buf_size, "(%s%s %s 0)",
1763 scast, expr, is_inv ? ">=" : "<");
1766 case PFO_LE: // ZF=1||SF!=OF; OF=0
1767 snprintf(buf, buf_size, "(%s%s %s 0)",
1768 scast, expr, is_inv ? ">" : "<=");
1772 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1776 static void out_cmp_for_cc(char *buf, size_t buf_size,
1777 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1779 const char *cast, *scast, *cast_use;
1780 char buf1[256], buf2[256];
1781 enum opr_lenmod lmod;
1783 if (po->operand[0].lmod != po->operand[1].lmod)
1784 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1785 po->operand[0].lmod, po->operand[1].lmod);
1786 lmod = po->operand[0].lmod;
1788 cast = lmod_cast_u(po, lmod);
1789 scast = lmod_cast_s(po, lmod);
1805 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1808 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1809 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1813 // note: must be unsigned compare
1814 snprintf(buf, buf_size, "(%s %s %s)",
1815 buf1, is_inv ? ">=" : "<", buf2);
1819 snprintf(buf, buf_size, "(%s %s %s)",
1820 buf1, is_inv ? "!=" : "==", buf2);
1824 // note: must be unsigned compare
1825 snprintf(buf, buf_size, "(%s %s %s)",
1826 buf1, is_inv ? ">" : "<=", buf2);
1829 if (is_inv && lmod == OPLM_BYTE
1830 && po->operand[1].type == OPT_CONST
1831 && po->operand[1].val == 0xff)
1833 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1834 snprintf(buf, buf_size, "(0)");
1838 // note: must be signed compare
1840 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1841 scast, buf1, buf2, is_inv ? ">=" : "<");
1845 snprintf(buf, buf_size, "(%s %s %s)",
1846 buf1, is_inv ? ">=" : "<", buf2);
1850 snprintf(buf, buf_size, "(%s %s %s)",
1851 buf1, is_inv ? ">" : "<=", buf2);
1859 static void out_cmp_test(char *buf, size_t buf_size,
1860 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1862 char buf1[256], buf2[256], buf3[256];
1864 if (po->op == OP_TEST) {
1865 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1866 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1869 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1870 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1871 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1873 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1874 po->operand[0].lmod, buf3);
1876 else if (po->op == OP_CMP) {
1877 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1880 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1883 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1884 struct parsed_opr *popr2)
1886 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1887 ferr(po, "missing lmod for both operands\n");
1889 if (popr1->lmod == OPLM_UNSPEC)
1890 popr1->lmod = popr2->lmod;
1891 else if (popr2->lmod == OPLM_UNSPEC)
1892 popr2->lmod = popr1->lmod;
1893 else if (popr1->lmod != popr2->lmod) {
1894 if (popr1->type_from_var) {
1895 popr1->size_mismatch = 1;
1896 if (popr1->lmod < popr2->lmod)
1898 popr1->lmod = popr2->lmod;
1900 else if (popr2->type_from_var) {
1901 popr2->size_mismatch = 1;
1902 if (popr2->lmod < popr1->lmod)
1904 popr2->lmod = popr1->lmod;
1907 ferr(po, "conflicting lmods: %d vs %d\n",
1908 popr1->lmod, popr2->lmod);
1912 static const char *op_to_c(struct parsed_op *po)
1936 ferr(po, "op_to_c was supplied with %d\n", po->op);
1940 static void op_set_clear_flag(struct parsed_op *po,
1941 enum op_flags flag_set, enum op_flags flag_clear)
1943 po->flags |= flag_set;
1944 po->flags &= ~flag_clear;
1947 // last op in stream - unconditional branch or ret
1948 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1949 || (ops[_i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
1951 static int scan_for_pop(int i, int opcnt, const char *reg,
1952 int magic, int depth, int *maxdepth, int do_flags)
1954 const struct parsed_proto *pp;
1955 struct parsed_op *po;
1959 for (; i < opcnt; i++) {
1961 if (po->cc_scratch == magic)
1962 break; // already checked
1963 po->cc_scratch = magic;
1965 if (po->flags & OPF_TAIL) {
1966 if (po->op == OP_CALL) {
1967 pp = proto_parse(g_fhdr, po->operand[0].name, 0);
1968 if (pp != NULL && pp->is_noreturn)
1969 // no stack cleanup for noreturn
1972 return -1; // deadend
1975 if ((po->flags & OPF_RMD)
1976 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1979 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1980 if (po->btj != NULL) {
1982 for (j = 0; j < po->btj->count; j++) {
1983 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1984 depth, maxdepth, do_flags);
1986 return ret; // dead end
1992 ferr(po, "dead branch\n");
1996 if (po->flags & OPF_CJMP) {
1997 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1998 depth, maxdepth, do_flags);
2000 return ret; // dead end
2008 if ((po->op == OP_POP || po->op == OP_PUSH)
2009 && po->operand[0].type == OPT_REG
2010 && IS(po->operand[0].name, reg))
2012 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
2014 if (depth > *maxdepth)
2017 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2019 else if (po->op == OP_POP) {
2022 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2027 if (depth < 0) // should not happen
2028 ferr(po, "fail with depth\n");
2030 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2039 // scan for pop starting from 'ret' op (all paths)
2040 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2046 for (; i < opcnt; i++) {
2047 if (!(ops[i].flags & OPF_TAIL))
2050 for (j = i - 1; j >= 0; j--) {
2051 if (ops[j].flags & OPF_RMD)
2053 if (ops[j].flags & OPF_JMP)
2056 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2057 && IS(ops[j].operand[0].name, reg))
2060 ops[j].flags |= flag_set;
2064 if (g_labels[j][0] != 0)
2069 return found ? 0 : -1;
2072 static void scan_propagate_df(int i, int opcnt)
2074 struct parsed_op *po = &ops[i];
2077 for (; i < opcnt; i++) {
2079 if (po->flags & OPF_DF)
2080 return; // already resolved
2081 po->flags |= OPF_DF;
2083 if (po->op == OP_CALL)
2084 ferr(po, "call with DF set?\n");
2086 if (po->flags & OPF_JMP) {
2087 if (po->btj != NULL) {
2089 for (j = 0; j < po->btj->count; j++)
2090 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2095 ferr(po, "dead branch\n");
2099 if (po->flags & OPF_CJMP)
2100 scan_propagate_df(po->bt_i, opcnt);
2106 if (po->flags & OPF_TAIL)
2109 if (po->op == OP_CLD) {
2110 po->flags |= OPF_RMD;
2115 ferr(po, "missing DF clear?\n");
2118 // is operand 'opr' modified by parsed_op 'po'?
2119 static int is_opr_modified(const struct parsed_opr *opr,
2120 const struct parsed_op *po)
2124 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2127 if (opr->type == OPT_REG) {
2128 if (po->op == OP_CALL) {
2129 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2130 if ((1 << opr->reg) & mask)
2136 if (po->operand[0].type == OPT_REG) {
2137 if (po->regmask_dst & (1 << opr->reg))
2144 return IS(po->operand[0].name, opr->name);
2147 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2148 static int is_any_opr_modified(const struct parsed_op *po_test,
2149 const struct parsed_op *po, int c_mode)
2154 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2157 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2160 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2163 // in reality, it can wreck any register, but in decompiled C
2164 // version it can only overwrite eax or edx:eax
2165 mask = (1 << xAX) | (1 << xDX);
2169 if (po->op == OP_CALL
2170 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2173 for (i = 0; i < po_test->operand_cnt; i++)
2174 if (IS(po_test->operand[i].name, po->operand[0].name))
2180 // scan for any po_test operand modification in range given
2181 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2184 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2187 for (; i < opcnt; i++) {
2188 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2195 // scan for po_test operand[0] modification in range given
2196 static int scan_for_mod_opr0(struct parsed_op *po_test,
2199 for (; i < opcnt; i++) {
2200 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2207 static int scan_for_flag_set(int i, int magic, int *branched,
2208 int *setters, int *setter_cnt)
2210 struct label_ref *lr;
2214 if (ops[i].cc_scratch == magic) {
2215 ferr(&ops[i], "%s looped\n", __func__);
2218 ops[i].cc_scratch = magic;
2220 if (g_labels[i][0] != 0) {
2223 lr = &g_label_refs[i];
2224 for (; lr->next; lr = lr->next) {
2225 ret = scan_for_flag_set(lr->i, magic,
2226 branched, setters, setter_cnt);
2231 if (i > 0 && LAST_OP(i - 1)) {
2235 ret = scan_for_flag_set(lr->i, magic,
2236 branched, setters, setter_cnt);
2242 if (ops[i].flags & OPF_FLAGS) {
2243 setters[*setter_cnt] = i;
2248 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2255 // scan back for cdq, if anything modifies edx, fail
2256 static int scan_for_cdq_edx(int i)
2259 if (g_labels[i][0] != 0) {
2260 if (g_label_refs[i].next != NULL)
2262 if (i > 0 && LAST_OP(i - 1)) {
2263 i = g_label_refs[i].i;
2270 if (ops[i].op == OP_CDQ)
2273 if (ops[i].regmask_dst & (1 << xDX))
2280 static int scan_for_reg_clear(int i, int reg)
2283 if (g_labels[i][0] != 0) {
2284 if (g_label_refs[i].next != NULL)
2286 if (i > 0 && LAST_OP(i - 1)) {
2287 i = g_label_refs[i].i;
2294 if (ops[i].op == OP_XOR
2295 && ops[i].operand[0].lmod == OPLM_DWORD
2296 && ops[i].operand[0].reg == ops[i].operand[1].reg
2297 && ops[i].operand[0].reg == reg)
2300 if (ops[i].regmask_dst & (1 << reg))
2307 // scan for positive, constant esp adjust
2308 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2310 const struct parsed_proto *pp;
2311 struct parsed_op *po;
2315 for (; i < opcnt; i++) {
2318 if (g_labels[i][0] != 0)
2321 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2322 if (po->operand[1].type != OPT_CONST)
2323 ferr(&ops[i], "non-const esp adjust?\n");
2324 *adj += po->operand[1].val;
2326 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2329 else if (po->op == OP_PUSH && !(po->flags & OPF_RMD)) {
2330 //if (first_pop == -1)
2331 // first_pop = -2; // none
2332 *adj -= lmod_bytes(po, po->operand[0].lmod);
2334 else if (po->op == OP_POP && !(po->flags & OPF_RMD)) {
2335 // seems like msvc only uses 'pop ecx' for stack realignment..
2336 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2338 if (first_pop == -1 && *adj >= 0)
2340 *adj += lmod_bytes(po, po->operand[0].lmod);
2342 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2343 if (po->op != OP_CALL)
2345 if (po->operand[0].type != OPT_LABEL)
2348 if (pp != NULL && pp->is_stdcall)
2353 if (first_pop >= 0) {
2354 // probably 'pop ecx' was used..
2361 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2363 struct parsed_op *po;
2367 ferr(ops, "%s: followed bad branch?\n", __func__);
2369 for (; i < opcnt; i++) {
2371 if (po->cc_scratch == magic)
2373 po->cc_scratch = magic;
2376 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2377 if (po->btj != NULL) {
2379 for (j = 0; j < po->btj->count; j++)
2380 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2384 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2385 if (!(po->flags & OPF_CJMP))
2388 if (po->flags & OPF_TAIL)
2393 static const struct parsed_proto *try_recover_pp(
2394 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2396 const struct parsed_proto *pp = NULL;
2400 // maybe an arg of g_func?
2401 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2403 char ofs_reg[16] = { 0, };
2404 int arg, arg_s, arg_i;
2408 parse_stack_access(po, opr->name, ofs_reg,
2409 &offset, &stack_ra, NULL);
2410 if (ofs_reg[0] != 0)
2411 ferr(po, "offset reg on arg access?\n");
2412 if (offset <= stack_ra) {
2413 // search who set the stack var instead
2414 if (search_instead != NULL)
2415 *search_instead = 1;
2419 arg_i = (offset - stack_ra - 4) / 4;
2420 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2421 if (g_func_pp->arg[arg].reg != NULL)
2427 if (arg == g_func_pp->argc)
2428 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2430 pp = g_func_pp->arg[arg].fptr;
2432 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2433 check_func_pp(po, pp, "icall arg");
2435 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2437 p = strchr(opr->name + 1, '[');
2438 memcpy(buf, opr->name, p - opr->name);
2439 buf[p - opr->name] = 0;
2440 pp = proto_parse(g_fhdr, buf, 0);
2442 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2443 pp = proto_parse(g_fhdr, opr->name, 0);
2445 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2446 check_func_pp(po, pp, "reg-fptr ref");
2452 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2453 int magic, const struct parsed_proto **pp_found, int *multi)
2455 const struct parsed_proto *pp = NULL;
2456 struct parsed_op *po;
2457 struct label_ref *lr;
2460 if (ops[i].cc_scratch == magic)
2462 ops[i].cc_scratch = magic;
2464 if (g_labels[i][0] != 0) {
2465 lr = &g_label_refs[i];
2466 for (; lr != NULL; lr = lr->next)
2467 scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2468 if (i > 0 && LAST_OP(i - 1))
2473 if (!(ops[i].flags & OPF_DATA))
2475 if (!is_opr_modified(opr, &ops[i]))
2477 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2478 // most probably trashed by some processing
2483 opr = &ops[i].operand[1];
2484 if (opr->type != OPT_REG)
2488 po = (i >= 0) ? &ops[i] : ops;
2491 // reached the top - can only be an arg-reg
2492 if (opr->type != OPT_REG)
2495 for (i = 0; i < g_func_pp->argc; i++) {
2496 if (g_func_pp->arg[i].reg == NULL)
2498 if (IS(opr->name, g_func_pp->arg[i].reg))
2501 if (i == g_func_pp->argc)
2503 pp = g_func_pp->arg[i].fptr;
2505 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2506 i + 1, g_func_pp->arg[i].reg);
2507 check_func_pp(po, pp, "icall reg-arg");
2510 pp = try_recover_pp(po, opr, NULL);
2512 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2513 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2514 || (*pp_found)->is_stdcall != pp->is_stdcall
2515 || (*pp_found)->is_fptr != pp->is_fptr
2516 || (*pp_found)->argc != pp->argc
2517 || (*pp_found)->argc_reg != pp->argc_reg
2518 || (*pp_found)->argc_stack != pp->argc_stack)
2520 ferr(po, "icall: parsed_proto mismatch\n");
2528 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2531 const struct parsed_proto *pp = NULL;
2532 int search_advice = 0;
2536 switch (ops[i].operand[0].type) {
2540 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2545 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2553 static int collect_call_args_r(struct parsed_op *po, int i,
2554 struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2555 int magic, int need_op_saving, int may_reuse)
2557 struct parsed_proto *pp_tmp;
2558 struct label_ref *lr;
2559 int need_to_save_current;
2564 ferr(po, "dead label encountered\n");
2568 for (; arg < pp->argc; arg++)
2569 if (pp->arg[arg].reg == NULL)
2571 magic = (magic & 0xffffff) | (arg << 24);
2573 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2575 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2576 if (ops[j].cc_scratch != magic) {
2577 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2581 // ok: have already been here
2584 ops[j].cc_scratch = magic;
2586 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2587 lr = &g_label_refs[j];
2588 if (lr->next != NULL)
2590 for (; lr->next; lr = lr->next) {
2591 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2593 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2594 arg, magic, need_op_saving, may_reuse);
2599 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2601 if (j > 0 && LAST_OP(j - 1)) {
2602 // follow last branch in reverse
2607 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2608 arg, magic, need_op_saving, may_reuse);
2614 if (ops[j].op == OP_CALL)
2616 if (pp->is_unresolved)
2619 pp_tmp = ops[j].datap;
2621 ferr(po, "arg collect hit unparsed call '%s'\n",
2622 ops[j].operand[0].name);
2623 if (may_reuse && pp_tmp->argc_stack > 0)
2624 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2625 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2627 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2628 if (pp->is_unresolved)
2631 ferr(po, "arg collect %d/%d hit esp adjust\n",
2634 else if (ops[j].op == OP_POP) {
2635 if (pp->is_unresolved)
2638 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2640 else if (ops[j].flags & OPF_CJMP)
2642 if (pp->is_unresolved)
2647 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2649 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2652 pp->arg[arg].datap = &ops[j];
2653 need_to_save_current = 0;
2654 if (!need_op_saving) {
2655 ret = scan_for_mod(&ops[j], j + 1, i, 1);
2656 need_to_save_current = (ret >= 0);
2658 if (need_op_saving || need_to_save_current) {
2659 // mark this push as one that needs operand saving
2660 ops[j].flags &= ~OPF_RMD;
2661 if (ops[j].argnum == 0) {
2662 ops[j].argnum = arg + 1;
2663 *save_arg_vars |= 1 << arg;
2665 else if (ops[j].argnum < arg + 1)
2666 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2667 ops[j].argnum, arg + 1, pp->name);
2669 else if (ops[j].argnum == 0)
2670 ops[j].flags |= OPF_RMD;
2672 // some PUSHes are reused by different calls on other branches,
2673 // but that can't happen if we didn't branch, so they
2674 // can be removed from future searches (handles nested calls)
2676 ops[j].flags |= OPF_FARG;
2678 ops[j].flags &= ~OPF_RSAVE;
2681 if (!pp->is_unresolved) {
2683 for (; arg < pp->argc; arg++)
2684 if (pp->arg[arg].reg == NULL)
2687 magic = (magic & 0xffffff) | (arg << 24);
2689 // tracking reg usage
2690 if (ops[j].operand[0].type == OPT_REG)
2691 *regmask |= 1 << ops[j].operand[0].reg;
2695 if (arg < pp->argc) {
2696 ferr(po, "arg collect failed for '%s': %d/%d\n",
2697 pp->name, arg, pp->argc);
2704 static int collect_call_args(struct parsed_op *po, int i,
2705 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2711 ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2716 if (pp->is_unresolved) {
2718 pp->argc_stack += ret;
2719 for (a = 0; a < pp->argc; a++)
2720 if (pp->arg[a].type.name == NULL)
2721 pp->arg[a].type.name = strdup("int");
2727 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2731 for (i = 0; i < pp->argc; i++)
2732 if (pp->arg[i].reg == NULL)
2736 memmove(&pp->arg[i + 1], &pp->arg[i],
2737 sizeof(pp->arg[0]) * pp->argc_stack);
2738 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2739 pp->arg[i].reg = strdup(reg);
2740 pp->arg[i].type.name = strdup("int");
2745 static void add_label_ref(struct label_ref *lr, int op_i)
2747 struct label_ref *lr_new;
2754 lr_new = calloc(1, sizeof(*lr_new));
2756 lr_new->next = lr->next;
2760 static void output_std_flags(FILE *fout, struct parsed_op *po,
2761 int *pfomask, const char *dst_opr_text)
2763 if (*pfomask & (1 << PFO_Z)) {
2764 fprintf(fout, "\n cond_z = (%s%s == 0);",
2765 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2766 *pfomask &= ~(1 << PFO_Z);
2768 if (*pfomask & (1 << PFO_S)) {
2769 fprintf(fout, "\n cond_s = (%s%s < 0);",
2770 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2771 *pfomask &= ~(1 << PFO_S);
2775 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
2778 if (pp->is_fastcall)
2779 fprintf(fout, "__fastcall ");
2780 else if (pp->is_stdcall && pp->argc_reg == 0)
2781 fprintf(fout, "__stdcall ");
2782 if (pp->is_noreturn || is_noreturn)
2783 fprintf(fout, "noreturn ");
2786 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2788 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2789 struct parsed_opr *last_arith_dst = NULL;
2790 char buf1[256], buf2[256], buf3[256], cast[64];
2791 const struct parsed_proto *pp_c;
2792 struct parsed_proto *pp, *pp_tmp;
2793 struct parsed_data *pd;
2794 const char *tmpname;
2795 enum parsed_flag_op pfo;
2796 int save_arg_vars = 0;
2797 int cmp_result_vars = 0;
2798 int need_tmp_var = 0;
2799 int need_mul_var = 0;
2801 int label_pending = 0;
2802 int regmask_save = 0;
2803 int regmask_arg = 0;
2804 int regmask_now = 0;
2805 int regmask_init = 0;
2817 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2818 g_stack_frame_used = 0;
2820 g_func_pp = proto_parse(fhdr, funcn, 0);
2821 if (g_func_pp == NULL)
2822 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2824 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2825 output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
2826 fprintf(fout, "%s(", funcn);
2828 for (i = 0; i < g_func_pp->argc; i++) {
2830 fprintf(fout, ", ");
2831 if (g_func_pp->arg[i].fptr != NULL) {
2833 pp = g_func_pp->arg[i].fptr;
2834 fprintf(fout, "%s (", pp->ret_type.name);
2835 output_pp_attrs(fout, pp, 0);
2836 fprintf(fout, "*a%d)(", i + 1);
2837 for (j = 0; j < pp->argc; j++) {
2839 fprintf(fout, ", ");
2840 if (pp->arg[j].fptr)
2841 ferr(ops, "nested fptr\n");
2842 fprintf(fout, "%s", pp->arg[j].type.name);
2847 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2849 if (g_func_pp->arg[i].reg != NULL) {
2850 reg = char_array_i(regs_r32,
2851 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2853 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2854 regmask_arg |= 1 << reg;
2857 if (g_func_pp->is_vararg) {
2859 fprintf(fout, ", ");
2860 fprintf(fout, "...");
2863 fprintf(fout, ")\n{\n");
2866 // - handle ebp/esp frame, remove ops related to it
2867 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2868 && ops[1].op == OP_MOV
2869 && IS(opr_name(&ops[1], 0), "ebp")
2870 && IS(opr_name(&ops[1], 1), "esp"))
2875 ops[0].flags |= OPF_RMD;
2876 ops[1].flags |= OPF_RMD;
2879 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2880 g_stack_fsz = opr_const(&ops[2], 1);
2881 ops[2].flags |= OPF_RMD;
2885 // another way msvc builds stack frame..
2887 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2889 ops[i].flags |= OPF_RMD;
2893 // and another way..
2894 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2895 && ops[i].operand[1].type == OPT_CONST
2896 && ops[i + 1].op == OP_CALL
2897 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2899 g_stack_fsz += ops[i].operand[1].val;
2900 ops[i].flags |= OPF_RMD;
2902 ops[i].flags |= OPF_RMD;
2909 for (; i < opcnt; i++)
2910 if (ops[i].op == OP_RET)
2912 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2915 if ((ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2916 || ops[i - 1].op == OP_LEAVE)
2918 ops[i - 1].flags |= OPF_RMD;
2920 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2921 ferr(&ops[i - 1], "'pop ebp' expected\n");
2923 if (g_stack_fsz != 0) {
2924 if (ops[i - 2].op == OP_MOV
2925 && IS(opr_name(&ops[i - 2], 0), "esp")
2926 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2928 ops[i - 2].flags |= OPF_RMD;
2930 else if (ops[i - 1].op != OP_LEAVE
2931 && !(g_ida_func_attr & IDAFA_NORETURN))
2933 ferr(&ops[i - 2], "esp restore expected\n");
2936 if (ecx_push && ops[i - 3].op == OP_POP
2937 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2939 ferr(&ops[i - 3], "unexpected ecx pop\n");
2945 } while (i < opcnt);
2948 for (i = 0; i < opcnt; i++) {
2949 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2951 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2952 && ops[i].operand[1].type == OPT_CONST)
2961 g_stack_fsz = ops[i].operand[1].val;
2962 ops[i].flags |= OPF_RMD;
2966 for (; i < opcnt; i++)
2967 if (ops[i].op == OP_RET)
2969 if (ops[i - 1].op != OP_ADD
2970 || !IS(opr_name(&ops[i - 1], 0), "esp")
2971 || ops[i - 1].operand[1].type != OPT_CONST
2972 || ops[i - 1].operand[1].val != g_stack_fsz)
2973 ferr(&ops[i - 1], "'add esp' expected\n");
2974 ops[i - 1].flags |= OPF_RMD;
2977 } while (i < opcnt);
2982 // - parse calls with labels
2983 // - resolve all branches
2984 for (i = 0; i < opcnt; i++)
2990 if (po->flags & OPF_RMD)
2993 if (po->op == OP_CALL) {
2996 if (po->operand[0].type == OPT_LABEL) {
2997 tmpname = opr_name(po, 0);
2998 if (IS_START(tmpname, "loc_"))
2999 ferr(po, "call to loc_*\n");
3000 pp_c = proto_parse(fhdr, tmpname, 0);
3002 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3004 pp = proto_clone(pp_c);
3005 my_assert_not(pp, NULL);
3007 else if (po->datap != NULL) {
3008 pp = calloc(1, sizeof(*pp));
3009 my_assert_not(pp, NULL);
3011 ret = parse_protostr(po->datap, pp);
3013 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3020 check_func_pp(po, pp, "fptr var call");
3021 if (pp->is_noreturn)
3022 po->flags |= OPF_TAIL;
3028 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3031 if (po->operand[0].type == OPT_REGMEM) {
3032 char *p = strchr(po->operand[0].name, '[');
3035 ret = p - po->operand[0].name;
3036 strncpy(buf1, po->operand[0].name, ret);
3039 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3040 if (IS(g_func_pd[j].label, buf1)) {
3046 //ferr(po, "label '%s' not parsed?\n", buf1);
3048 if (pd->type != OPT_OFFSET)
3049 ferr(po, "label '%s' with non-offset data?\n", buf1);
3051 // find all labels, link
3052 for (j = 0; j < pd->count; j++) {
3053 for (l = 0; l < opcnt; l++) {
3054 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
3055 add_label_ref(&g_label_refs[l], i);
3066 for (l = 0; l < opcnt; l++) {
3067 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
3068 add_label_ref(&g_label_refs[l], i);
3077 if (po->operand[0].type == OPT_LABEL)
3081 ferr(po, "unhandled branch\n");
3085 po->flags |= OPF_TAIL;
3090 // - remove dead labels
3092 for (i = 0; i < opcnt; i++)
3094 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3098 if (po->flags & OPF_RMD)
3101 if (po->op == OP_CALL)
3103 tmpname = opr_name(po, 0);
3108 pp_c = resolve_icall(i, opcnt, &l);
3110 pp = proto_clone(pp_c);
3111 my_assert_not(pp, NULL);
3113 // not resolved just to single func
3117 pp = calloc(1, sizeof(*pp));
3118 my_assert_not(pp, NULL);
3120 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3122 if (!g_allow_regfunc)
3123 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3124 pp->is_unresolved = 1;
3128 if (j > ARRAY_SIZE(pp->arg))
3129 ferr(po, "esp adjust too large: %d\n", j);
3130 pp->ret_type.name = strdup("int");
3131 pp->argc = pp->argc_stack = j;
3132 for (arg = 0; arg < pp->argc; arg++)
3133 pp->arg[arg].type.name = strdup("int");
3138 // look for and make use of esp adjust
3140 if (!pp->is_stdcall && pp->argc_stack > 0)
3141 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3143 if (pp->is_vararg) {
3144 if (j / 4 < pp->argc_stack)
3145 ferr(po, "esp adjust is too small: %x < %x\n",
3146 j, pp->argc_stack * 4);
3147 // modify pp to make it have varargs as normal args
3149 pp->argc += j / 4 - pp->argc_stack;
3150 for (; arg < pp->argc; arg++) {
3151 pp->arg[arg].type.name = strdup("int");
3154 if (pp->argc > ARRAY_SIZE(pp->arg))
3155 ferr(po, "too many args for '%s'\n", tmpname);
3157 if (pp->argc_stack != j / 4)
3158 ferr(po, "stack tracking failed for '%s': %x %x\n",
3159 tmpname, pp->argc_stack * 4, j);
3161 ops[ret].flags |= OPF_RMD;
3162 if (ops[ret].op == OP_POP && j > 4) {
3163 // deal with multi-pop stack adjust
3165 while (ops[ret].op == OP_POP && j > 0 && ret < opcnt) {
3166 ops[ret].flags |= OPF_RMD;
3172 // a bit of a hack, but deals with use of
3173 // single adj for multiple calls
3174 ops[ret].operand[1].val -= j;
3177 else if (pp->is_vararg)
3178 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3181 if (!pp->is_unresolved) {
3182 // since we know the args, collect them
3183 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3187 if (strstr(pp->ret_type.name, "int64"))
3193 // - find POPs for PUSHes, rm both
3194 // - scan for STD/CLD, propagate DF
3195 // - scan for all used registers
3196 // - find flag set ops for their users
3197 // - do unreselved calls
3198 // - declare indirect functions
3199 for (i = 0; i < opcnt; i++) {
3201 if (po->flags & OPF_RMD)
3204 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3205 reg = po->operand[0].reg;
3206 if (!(regmask & (1 << reg)))
3207 // not a reg save after all, rerun scan_for_pop
3208 po->flags &= ~OPF_RSAVE;
3210 regmask_save |= 1 << reg;
3213 if (po->op == OP_PUSH && po->argnum == 0
3214 && !(po->flags & OPF_RSAVE))
3216 if (po->operand[0].type == OPT_REG)
3218 reg = po->operand[0].reg;
3220 ferr(po, "reg not set for push?\n");
3223 ret = scan_for_pop(i + 1, opcnt,
3224 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3227 ferr(po, "too much depth: %d\n", depth);
3229 po->flags |= OPF_RMD;
3230 scan_for_pop(i + 1, opcnt, po->operand[0].name,
3231 i + opcnt * 4, 0, &depth, 1);
3234 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3237 if (regmask & (1 << reg)) {
3238 if (regmask_save & (1 << reg))
3239 ferr(po, "%s already saved?\n", po->operand[0].name);
3243 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3247 else if (po->operand[0].type == OPT_CONST) {
3248 for (j = i + 1; j < opcnt; j++) {
3249 if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
3250 || ops[j].op == OP_PUSH || g_labels[i][0] != 0)
3255 if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
3257 po->flags |= OPF_RMD;
3265 if (po->op == OP_STD) {
3266 po->flags |= OPF_DF | OPF_RMD;
3267 scan_propagate_df(i + 1, opcnt);
3270 regmask_now = po->regmask_src | po->regmask_dst;
3271 if (regmask_now & (1 << xBP)) {
3272 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3273 if (po->regmask_dst & (1 << xBP))
3274 // compiler decided to drop bp frame and use ebp as scratch
3275 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
3277 regmask_now &= ~(1 << xBP);
3281 regmask |= regmask_now;
3283 if (po->flags & OPF_CC)
3285 int setters[16], cnt = 0, branched = 0;
3287 ret = scan_for_flag_set(i, i + opcnt * 6,
3288 &branched, setters, &cnt);
3289 if (ret < 0 || cnt <= 0)
3290 ferr(po, "unable to trace flag setter(s)\n");
3291 if (cnt > ARRAY_SIZE(setters))
3292 ferr(po, "too many flag setters\n");
3294 pfo = split_cond(po, po->op, &dummy);
3295 for (j = 0; j < cnt; j++)
3297 tmp_op = &ops[setters[j]]; // flag setter
3300 // to get nicer code, we try to delay test and cmp;
3301 // if we can't because of operand modification, or if we
3302 // have arith op, or branch, make it calculate flags explicitly
3303 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
3305 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3308 else if (tmp_op->op == OP_SCAS) {
3311 else if (tmp_op->op == OP_CMPS) {
3312 pfomask = 1 << PFO_Z;
3315 // see if we'll be able to handle based on op result
3316 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3317 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3319 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3323 tmp_op->pfomask |= pfomask;
3324 cmp_result_vars |= pfomask;
3326 // note: may overwrite, currently not a problem
3330 if (po->op == OP_ADC || po->op == OP_SBB)
3331 cmp_result_vars |= 1 << PFO_C;
3333 else if (po->op == OP_CMPS || po->op == OP_SCAS) {
3334 cmp_result_vars |= 1 << PFO_Z;
3336 else if (po->op == OP_MUL
3337 || (po->op == OP_IMUL && po->operand_cnt == 1))
3341 else if (po->op == OP_XCHG) {
3344 else if (po->op == OP_CALL) {
3347 ferr(po, "NULL pp\n");
3349 if (pp->is_unresolved) {
3350 int regmask_stack = 0;
3351 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3354 // this is pretty rough guess:
3355 // see ecx and edx were pushed (and not their saved versions)
3356 for (arg = 0; arg < pp->argc; arg++) {
3357 if (pp->arg[arg].reg != NULL)
3360 tmp_op = pp->arg[arg].datap;
3362 ferr(po, "parsed_op missing for arg%d\n", arg);
3363 if (tmp_op->argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3364 regmask_stack |= 1 << tmp_op->operand[0].reg;
3367 if (!((regmask_stack & (1 << xCX))
3368 && (regmask_stack & (1 << xDX))))
3370 if (pp->argc_stack != 0
3371 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3373 pp_insert_reg_arg(pp, "ecx");
3374 pp->is_fastcall = 1;
3375 regmask_init |= 1 << xCX;
3376 regmask |= 1 << xCX;
3378 if (pp->argc_stack != 0
3379 || ((regmask | regmask_arg) & (1 << xDX)))
3381 pp_insert_reg_arg(pp, "edx");
3382 regmask_init |= 1 << xDX;
3383 regmask |= 1 << xDX;
3387 // note: __cdecl doesn't fall into is_unresolved category
3388 if (pp->argc_stack > 0)
3392 for (arg = 0; arg < pp->argc; arg++) {
3393 if (pp->arg[arg].reg != NULL) {
3394 reg = char_array_i(regs_r32,
3395 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3397 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3398 if (!(regmask & (1 << reg))) {
3399 regmask_init |= 1 << reg;
3400 regmask |= 1 << reg;
3406 if (pp->name[0] != 0) {
3407 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3408 memcpy(pp->name, "i_", 2);
3410 // might be declared already
3412 for (j = 0; j < i; j++) {
3413 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].datap)) {
3414 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3424 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3426 fprintf(fout, " %s (", pp->ret_type.name);
3427 output_pp_attrs(fout, pp, 0);
3428 fprintf(fout, "*%s)(", pp->name);
3429 for (j = 0; j < pp->argc; j++) {
3431 fprintf(fout, ", ");
3432 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3434 fprintf(fout, ");\n");
3437 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3438 regmask |= 1 << xAX;
3442 // - confirm regmask_save, it might have been reduced
3443 if (regmask_save != 0)
3446 for (i = 0; i < opcnt; i++) {
3448 if (po->flags & OPF_RMD)
3451 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3452 regmask_save |= 1 << po->operand[0].reg;
3457 // output LUTs/jumptables
3458 for (i = 0; i < g_func_pd_cnt; i++) {
3460 fprintf(fout, " static const ");
3461 if (pd->type == OPT_OFFSET) {
3462 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3464 for (j = 0; j < pd->count; j++) {
3466 fprintf(fout, ", ");
3467 fprintf(fout, "&&%s", pd->d[j].u.label);
3471 fprintf(fout, "%s %s[] =\n { ",
3472 lmod_type_u(ops, pd->lmod), pd->label);
3474 for (j = 0; j < pd->count; j++) {
3476 fprintf(fout, ", ");
3477 fprintf(fout, "%u", pd->d[j].u.val);
3480 fprintf(fout, " };\n");
3483 // declare stack frame, va_arg
3485 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3486 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3488 if (g_func_pp->is_vararg)
3489 fprintf(fout, " va_list ap;\n");
3491 // declare arg-registers
3492 for (i = 0; i < g_func_pp->argc; i++) {
3493 if (g_func_pp->arg[i].reg != NULL) {
3494 reg = char_array_i(regs_r32,
3495 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3496 if (regmask & (1 << reg)) {
3497 fprintf(fout, " u32 %s = (u32)a%d;\n",
3498 g_func_pp->arg[i].reg, i + 1);
3501 fprintf(fout, " // %s = a%d; // unused\n",
3502 g_func_pp->arg[i].reg, i + 1);
3507 regmask_now = regmask & ~regmask_arg;
3508 regmask_now &= ~(1 << xSP);
3510 for (reg = 0; reg < 8; reg++) {
3511 if (regmask_now & (1 << reg)) {
3512 fprintf(fout, " u32 %s", regs_r32[reg]);
3513 if (regmask_init & (1 << reg))
3514 fprintf(fout, " = 0");
3515 fprintf(fout, ";\n");
3522 for (reg = 0; reg < 8; reg++) {
3523 if (regmask_save & (1 << reg)) {
3524 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3530 if (save_arg_vars) {
3531 for (reg = 0; reg < 32; reg++) {
3532 if (save_arg_vars & (1 << reg)) {
3533 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3539 if (cmp_result_vars) {
3540 for (i = 0; i < 8; i++) {
3541 if (cmp_result_vars & (1 << i)) {
3542 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3549 fprintf(fout, " u32 tmp;\n");
3554 fprintf(fout, " u64 mul_tmp;\n");
3559 fprintf(fout, "\n");
3561 if (g_func_pp->is_vararg) {
3562 if (g_func_pp->argc_stack == 0)
3563 ferr(ops, "vararg func without stack args?\n");
3564 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3568 for (i = 0; i < opcnt; i++)
3570 if (g_labels[i][0] != 0) {
3571 fprintf(fout, "\n%s:\n", g_labels[i]);
3574 delayed_flag_op = NULL;
3575 last_arith_dst = NULL;
3579 if (po->flags & OPF_RMD)
3584 #define assert_operand_cnt(n_) \
3585 if (po->operand_cnt != n_) \
3586 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3588 // conditional/flag using op?
3589 if (po->flags & OPF_CC)
3594 pfo = split_cond(po, po->op, &is_inv);
3597 // we go through all this trouble to avoid using parsed_flag_op,
3598 // which makes generated code much nicer
3599 if (delayed_flag_op != NULL)
3601 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3604 else if (last_arith_dst != NULL
3605 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3606 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3609 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3610 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3611 last_arith_dst->lmod, buf3);
3614 else if (tmp_op != NULL) {
3615 // use preprocessed flag calc results
3616 if (!(tmp_op->pfomask & (1 << pfo)))
3617 ferr(po, "not prepared for pfo %d\n", pfo);
3619 // note: is_inv was not yet applied
3620 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3621 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3624 ferr(po, "all methods of finding comparison failed\n");
3627 if (po->flags & OPF_JMP) {
3628 fprintf(fout, " if %s\n", buf1);
3630 else if (po->op == OP_ADC || po->op == OP_SBB) {
3632 fprintf(fout, " cond_%s = %s;\n",
3633 parsed_flag_op_names[pfo], buf1);
3635 else if (po->flags & OPF_DATA) { // SETcc
3636 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3637 fprintf(fout, " %s = %s;", buf2, buf1);
3640 ferr(po, "unhandled conditional op\n");
3644 pfomask = po->pfomask;
3649 assert_operand_cnt(2);
3650 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3651 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3652 fprintf(fout, " %s = %s;", buf1,
3653 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3654 po->operand[0].is_ptr ? "(void *)" : "", 0));
3658 assert_operand_cnt(2);
3659 po->operand[1].lmod = OPLM_DWORD; // always
3660 fprintf(fout, " %s = %s;",
3661 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3662 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3667 assert_operand_cnt(2);
3668 fprintf(fout, " %s = %s;",
3669 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3670 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3674 assert_operand_cnt(2);
3675 switch (po->operand[1].lmod) {
3677 strcpy(buf3, "(s8)");
3680 strcpy(buf3, "(s16)");
3683 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3685 fprintf(fout, " %s = %s;",
3686 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3687 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3692 assert_operand_cnt(2);
3693 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3694 fprintf(fout, " tmp = %s;",
3695 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
3696 fprintf(fout, " %s = %s;",
3697 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3698 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], "", 0));
3699 fprintf(fout, " %s = tmp;",
3700 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]));
3701 snprintf(g_comment, sizeof(g_comment), "xchg");
3705 assert_operand_cnt(1);
3706 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3707 fprintf(fout, " %s = ~%s;", buf1, buf1);
3711 assert_operand_cnt(2);
3712 fprintf(fout, " %s = (s32)%s >> 31;",
3713 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3714 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3715 strcpy(g_comment, "cdq");
3719 assert_operand_cnt(3);
3720 if (po->flags & OPF_REP) {
3721 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
3722 (po->flags & OPF_DF) ? '-' : '+',
3723 lmod_bytes(po, po->operand[0].lmod));
3724 fprintf(fout, " %sedi = eax;",
3725 lmod_cast_u_ptr(po, po->operand[0].lmod));
3726 strcpy(g_comment, "rep stos");
3729 fprintf(fout, " %sedi = eax; edi %c= %d;",
3730 lmod_cast_u_ptr(po, po->operand[0].lmod),
3731 (po->flags & OPF_DF) ? '-' : '+',
3732 lmod_bytes(po, po->operand[0].lmod));
3733 strcpy(g_comment, "stos");
3738 assert_operand_cnt(3);
3739 j = lmod_bytes(po, po->operand[0].lmod);
3740 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3741 l = (po->flags & OPF_DF) ? '-' : '+';
3742 if (po->flags & OPF_REP) {
3744 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
3747 " %sedi = %sesi;", buf1, buf1);
3748 strcpy(g_comment, "rep movs");
3751 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
3752 buf1, buf1, l, j, l, j);
3753 strcpy(g_comment, "movs");
3758 // repe ~ repeat while ZF=1
3759 assert_operand_cnt(3);
3760 j = lmod_bytes(po, po->operand[0].lmod);
3761 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3762 l = (po->flags & OPF_DF) ? '-' : '+';
3763 if (po->flags & OPF_REP) {
3765 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
3768 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3769 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3772 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3773 (po->flags & OPF_REPZ) ? "e" : "ne");
3777 " cond_z = (%sedi = %sesi); edi %c= %d; esi %c= %d;",
3778 buf1, buf1, l, j, l, j);
3779 strcpy(g_comment, "cmps");
3781 pfomask &= ~(1 << PFO_Z);
3782 last_arith_dst = NULL;
3783 delayed_flag_op = NULL;
3787 // only does ZF (for now)
3788 // repe ~ repeat while ZF=1
3789 assert_operand_cnt(3);
3790 j = lmod_bytes(po, po->operand[0].lmod);
3791 l = (po->flags & OPF_DF) ? '-' : '+';
3792 if (po->flags & OPF_REP) {
3794 " for (; ecx != 0; ecx--, edi %c= %d)\n", l, j);
3796 " if ((cond_z = (%seax == %sedi)) %s 0)\n",
3797 lmod_cast_u(po, po->operand[0].lmod),
3798 lmod_cast_u_ptr(po, po->operand[0].lmod),
3799 (po->flags & OPF_REPZ) ? "==" : "!=");
3802 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
3803 (po->flags & OPF_REPZ) ? "e" : "ne");
3806 fprintf(fout, " cond_z = (%seax = %sedi); edi %c= %d;",
3807 lmod_cast_u(po, po->operand[0].lmod),
3808 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
3809 strcpy(g_comment, "scas");
3811 pfomask &= ~(1 << PFO_Z);
3812 last_arith_dst = NULL;
3813 delayed_flag_op = NULL;
3816 // arithmetic w/flags
3821 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3824 assert_operand_cnt(2);
3825 fprintf(fout, " %s %s= %s;",
3826 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3828 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3829 output_std_flags(fout, po, &pfomask, buf1);
3830 last_arith_dst = &po->operand[0];
3831 delayed_flag_op = NULL;
3836 assert_operand_cnt(2);
3837 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3838 if (pfomask & (1 << PFO_C)) {
3839 if (po->operand[1].type == OPT_CONST) {
3840 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3841 j = po->operand[1].val;
3844 if (po->op == OP_SHL)
3848 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3852 ferr(po, "zero shift?\n");
3856 pfomask &= ~(1 << PFO_C);
3858 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3859 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3860 output_std_flags(fout, po, &pfomask, buf1);
3861 last_arith_dst = &po->operand[0];
3862 delayed_flag_op = NULL;
3866 assert_operand_cnt(2);
3867 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3868 fprintf(fout, " %s = %s%s >> %s;", buf1,
3869 lmod_cast_s(po, po->operand[0].lmod), buf1,
3870 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3871 output_std_flags(fout, po, &pfomask, buf1);
3872 last_arith_dst = &po->operand[0];
3873 delayed_flag_op = NULL;
3878 assert_operand_cnt(2);
3879 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3880 if (po->operand[1].type == OPT_CONST) {
3881 j = po->operand[1].val;
3882 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3883 fprintf(fout, po->op == OP_ROL ?
3884 " %s = (%s << %d) | (%s >> %d);" :
3885 " %s = (%s >> %d) | (%s << %d);",
3886 buf1, buf1, j, buf1,
3887 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3891 output_std_flags(fout, po, &pfomask, buf1);
3892 last_arith_dst = &po->operand[0];
3893 delayed_flag_op = NULL;
3897 assert_operand_cnt(2);
3898 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3899 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3900 // special case for XOR
3901 fprintf(fout, " %s = 0;",
3902 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3903 last_arith_dst = &po->operand[0];
3904 delayed_flag_op = NULL;
3911 assert_operand_cnt(2);
3912 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3913 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3914 if (po->op == OP_SBB
3915 && IS(po->operand[0].name, po->operand[1].name))
3917 // avoid use of unitialized var
3918 fprintf(fout, " %s = -cond_c;", buf1);
3919 // carry remains what it was
3920 pfomask &= ~(1 << PFO_C);
3923 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3924 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3926 output_std_flags(fout, po, &pfomask, buf1);
3927 last_arith_dst = &po->operand[0];
3928 delayed_flag_op = NULL;
3933 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3934 if (po->operand[0].type == OPT_REG) {
3935 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3936 fprintf(fout, " %s%s;", buf1, buf2);
3939 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3940 fprintf(fout, " %s %s= 1;", buf1, buf2);
3942 output_std_flags(fout, po, &pfomask, buf1);
3943 last_arith_dst = &po->operand[0];
3944 delayed_flag_op = NULL;
3948 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3949 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3950 fprintf(fout, " %s = -%s%s;", buf1,
3951 lmod_cast_s(po, po->operand[0].lmod), buf2);
3952 last_arith_dst = &po->operand[0];
3953 delayed_flag_op = NULL;
3954 if (pfomask & (1 << PFO_C)) {
3955 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3956 pfomask &= ~(1 << PFO_C);
3961 if (po->operand_cnt == 2) {
3962 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3965 if (po->operand_cnt == 3)
3966 ferr(po, "TODO imul3\n");
3969 assert_operand_cnt(1);
3970 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3971 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3972 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3973 fprintf(fout, " edx = mul_tmp >> 32;\n");
3974 fprintf(fout, " eax = mul_tmp;");
3975 last_arith_dst = NULL;
3976 delayed_flag_op = NULL;
3981 assert_operand_cnt(1);
3982 if (po->operand[0].lmod != OPLM_DWORD)
3983 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3985 // 32bit division is common, look for it
3986 if (po->op == OP_DIV)
3987 ret = scan_for_reg_clear(i, xDX);
3989 ret = scan_for_cdq_edx(i);
3991 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3992 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3993 po->op == OP_IDIV));
3994 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3995 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3998 ferr(po, "TODO 64bit divident\n");
3999 last_arith_dst = NULL;
4000 delayed_flag_op = NULL;
4005 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4007 for (j = 0; j < 8; j++) {
4008 if (pfomask & (1 << j)) {
4009 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
4010 fprintf(fout, " cond_%s = %s;",
4011 parsed_flag_op_names[j], buf1);
4018 last_arith_dst = NULL;
4019 delayed_flag_op = po;
4022 // note: we reuse OP_Jcc for SETcc, only flags differ
4023 case OP_JO ... OP_JG:
4024 if (po->flags & OPF_JMP)
4025 fprintf(fout, " goto %s;", po->operand[0].name);
4026 // else SETcc - should already be handled
4030 fprintf(fout, " if (ecx == 0)\n");
4031 fprintf(fout, " goto %s;", po->operand[0].name);
4032 strcat(g_comment, "jecxz");
4036 assert_operand_cnt(1);
4037 last_arith_dst = NULL;
4038 delayed_flag_op = NULL;
4040 if (po->operand[0].type == OPT_REGMEM) {
4041 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
4044 ferr(po, "parse failure for jmp '%s'\n",
4045 po->operand[0].name);
4046 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
4049 else if (po->operand[0].type != OPT_LABEL)
4050 ferr(po, "unhandled jmp type\n");
4052 fprintf(fout, " goto %s;", po->operand[0].name);
4056 assert_operand_cnt(1);
4058 my_assert_not(pp, NULL);
4061 fprintf(fout, " %s = %s;\n", pp->name,
4062 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
4066 if (strstr(pp->ret_type.name, "int64")) {
4067 if (po->flags & OPF_TAIL)
4068 ferr(po, "int64 and tail?\n");
4069 fprintf(fout, "mul_tmp = ");
4071 else if (!IS(pp->ret_type.name, "void")) {
4072 if (po->flags & OPF_TAIL) {
4073 if (!IS(g_func_pp->ret_type.name, "void")) {
4074 fprintf(fout, "return ");
4075 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
4076 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
4079 else if (regmask & (1 << xAX)) {
4080 fprintf(fout, "eax = ");
4081 if (pp->ret_type.is_ptr)
4082 fprintf(fout, "(u32)");
4086 if (pp->name[0] == 0)
4087 ferr(po, "missing pp->name\n");
4088 fprintf(fout, "%s%s(", pp->name,
4089 pp->has_structarg ? "_sa" : "");
4091 for (arg = 0; arg < pp->argc; arg++) {
4093 fprintf(fout, ", ");
4096 if (pp->arg[arg].type.is_ptr)
4097 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
4099 if (pp->arg[arg].reg != NULL) {
4100 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4105 tmp_op = pp->arg[arg].datap;
4107 ferr(po, "parsed_op missing for arg%d\n", arg);
4108 if (tmp_op->argnum != 0) {
4109 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
4113 out_src_opr(buf1, sizeof(buf1),
4114 tmp_op, &tmp_op->operand[0], cast, 0));
4117 fprintf(fout, ");");
4119 if (strstr(pp->ret_type.name, "int64")) {
4120 fprintf(fout, "\n");
4121 fprintf(fout, " edx = mul_tmp >> 32;\n");
4122 fprintf(fout, " eax = mul_tmp;");
4125 if (pp->is_unresolved) {
4126 snprintf(buf3, sizeof(buf3), " unresoved %dreg",
4128 strcat(g_comment, buf3);
4131 if (po->flags & OPF_TAIL) {
4133 if (i == opcnt - 1 || pp->is_noreturn)
4135 else if (IS(pp->ret_type.name, "void"))
4137 else if (IS(g_func_pp->ret_type.name, "void"))
4139 // else already handled as 'return f()'
4142 if (!IS(g_func_pp->ret_type.name, "void")) {
4143 ferr(po, "int func -> void func tailcall?\n");
4146 fprintf(fout, "\n return;");
4147 strcat(g_comment, " ^ tailcall");
4151 strcat(g_comment, " tailcall");
4153 if (pp->is_noreturn)
4154 strcat(g_comment, " noreturn");
4155 delayed_flag_op = NULL;
4156 last_arith_dst = NULL;
4160 if (g_func_pp->is_vararg)
4161 fprintf(fout, " va_end(ap);\n");
4163 if (IS(g_func_pp->ret_type.name, "void")) {
4164 if (i != opcnt - 1 || label_pending)
4165 fprintf(fout, " return;");
4167 else if (g_func_pp->ret_type.is_ptr) {
4168 fprintf(fout, " return (%s)eax;",
4169 g_func_pp->ret_type.name);
4172 fprintf(fout, " return eax;");
4174 last_arith_dst = NULL;
4175 delayed_flag_op = NULL;
4179 if (po->argnum != 0) {
4180 // special case - saved func arg
4181 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4182 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
4185 else if (po->flags & OPF_RSAVE) {
4186 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4187 fprintf(fout, " s_%s = %s;", buf1, buf1);
4190 if (!(g_ida_func_attr & IDAFA_NORETURN))
4191 ferr(po, "stray push encountered\n");
4196 if (po->flags & OPF_RSAVE) {
4197 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4198 fprintf(fout, " %s = s_%s;", buf1, buf1);
4201 else if (po->datap != NULL) {
4204 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4205 fprintf(fout, " %s = %s;", buf1,
4206 out_src_opr(buf2, sizeof(buf2),
4207 tmp_op, &tmp_op->operand[0],
4208 po->operand[0].is_ptr ? "(void *)" : "", 0));
4211 ferr(po, "stray pop encountered\n");
4220 ferr(po, "unhandled op type %d, flags %x\n",
4225 if (g_comment[0] != 0) {
4226 char *p = g_comment;
4227 while (my_isblank(*p))
4229 fprintf(fout, " // %s", p);
4234 fprintf(fout, "\n");
4236 // some sanity checking
4237 if (po->flags & OPF_REP) {
4238 if (po->op != OP_STOS && po->op != OP_MOVS
4239 && po->op != OP_CMPS && po->op != OP_SCAS)
4240 ferr(po, "unexpected rep\n");
4241 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
4242 && (po->op == OP_CMPS || po->op == OP_SCAS))
4243 ferr(po, "cmps/scas with plain rep\n");
4245 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
4246 && po->op != OP_CMPS && po->op != OP_SCAS)
4247 ferr(po, "unexpected repz/repnz\n");
4250 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4252 // see is delayed flag stuff is still valid
4253 if (delayed_flag_op != NULL && delayed_flag_op != po) {
4254 if (is_any_opr_modified(delayed_flag_op, po, 0))
4255 delayed_flag_op = NULL;
4258 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4259 if (is_opr_modified(last_arith_dst, po))
4260 last_arith_dst = NULL;
4266 if (g_stack_fsz && !g_stack_frame_used)
4267 fprintf(fout, " (void)sf;\n");
4269 fprintf(fout, "}\n\n");
4272 for (i = 0; i < opcnt; i++) {
4273 struct label_ref *lr, *lr_del;
4275 lr = g_label_refs[i].next;
4276 while (lr != NULL) {
4281 g_label_refs[i].i = -1;
4282 g_label_refs[i].next = NULL;
4284 if (ops[i].op == OP_CALL) {
4293 static void set_label(int i, const char *name)
4299 p = strchr(name, ':');
4303 if (len > sizeof(g_labels[0]) - 1)
4304 aerr("label '%s' too long: %d\n", name, len);
4305 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4306 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4307 memcpy(g_labels[i], name, len);
4308 g_labels[i][len] = 0;
4311 // '=' needs special treatment..
4312 static char *next_word_s(char *w, size_t wsize, char *s)
4318 for (i = 0; i < wsize - 1; i++) {
4319 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4325 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4326 printf("warning: '%s' truncated\n", w);
4337 static struct chunk_item *func_chunks;
4338 static int func_chunk_cnt;
4339 static int func_chunk_alloc;
4341 static void add_func_chunk(FILE *fasm, const char *name, int line)
4343 if (func_chunk_cnt >= func_chunk_alloc) {
4344 func_chunk_alloc *= 2;
4345 func_chunks = realloc(func_chunks,
4346 func_chunk_alloc * sizeof(func_chunks[0]));
4347 my_assert_not(func_chunks, NULL);
4349 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4350 func_chunks[func_chunk_cnt].name = strdup(name);
4351 func_chunks[func_chunk_cnt].asmln = line;
4355 static int cmp_chunks(const void *p1, const void *p2)
4357 const struct chunk_item *c1 = p1, *c2 = p2;
4358 return strcmp(c1->name, c2->name);
4361 static int cmpstringp(const void *p1, const void *p2)
4363 return strcmp(*(char * const *)p1, *(char * const *)p2);
4366 static void scan_ahead(FILE *fasm)
4376 oldpos = ftell(fasm);
4379 while (fgets(line, sizeof(line), fasm))
4390 // get rid of random tabs
4391 for (i = 0; line[i] != 0; i++)
4392 if (line[i] == '\t')
4395 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4398 next_word(words[0], sizeof(words[0]), p);
4399 if (words[0][0] == 0)
4400 aerr("missing name for func chunk?\n");
4402 add_func_chunk(fasm, words[0], asmln);
4407 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4408 words[wordc][0] = 0;
4409 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4410 if (*p == 0 || *p == ';') {
4416 if (wordc == 2 && IS(words[1], "ends"))
4420 fseek(fasm, oldpos, SEEK_SET);
4424 int main(int argc, char *argv[])
4426 FILE *fout, *fasm, *frlist;
4427 struct parsed_data *pd = NULL;
4429 char **rlist = NULL;
4431 int rlist_alloc = 0;
4432 int func_chunks_used = 0;
4433 int func_chunks_sorted = 0;
4434 int func_chunk_i = -1;
4435 long func_chunk_ret = 0;
4436 int func_chunk_ret_ln = 0;
4437 int scanned_ahead = 0;
4439 char words[20][256];
4440 enum opr_lenmod lmod;
4441 char *sctproto = NULL;
4443 int pending_endp = 0;
4445 int skip_warned = 0;
4456 for (arg = 1; arg < argc; arg++) {
4457 if (IS(argv[arg], "-v"))
4459 else if (IS(argv[arg], "-rf"))
4460 g_allow_regfunc = 1;
4465 if (argc < arg + 3) {
4466 printf("usage:\n%s [-v] [-rf] <.c> <.asm> <hdrf> [rlist]*\n",
4473 asmfn = argv[arg++];
4474 fasm = fopen(asmfn, "r");
4475 my_assert_not(fasm, NULL);
4477 hdrfn = argv[arg++];
4478 g_fhdr = fopen(hdrfn, "r");
4479 my_assert_not(g_fhdr, NULL);
4482 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4483 my_assert_not(rlist, NULL);
4484 // needs special handling..
4485 rlist[rlist_len++] = "__alloca_probe";
4487 func_chunk_alloc = 32;
4488 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4489 my_assert_not(func_chunks, NULL);
4491 memset(words, 0, sizeof(words));
4493 for (; arg < argc; arg++) {
4494 frlist = fopen(argv[arg], "r");
4495 my_assert_not(frlist, NULL);
4497 while (fgets(line, sizeof(line), frlist)) {
4499 if (*p == 0 || *p == ';')
4502 if (IS_START(p, "#if 0")
4503 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4507 else if (IS_START(p, "#endif"))
4514 p = next_word(words[0], sizeof(words[0]), p);
4515 if (words[0][0] == 0)
4518 if (rlist_len >= rlist_alloc) {
4519 rlist_alloc = rlist_alloc * 2 + 64;
4520 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4521 my_assert_not(rlist, NULL);
4523 rlist[rlist_len++] = strdup(words[0]);
4532 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4534 fout = fopen(argv[arg_out], "w");
4535 my_assert_not(fout, NULL);
4538 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4539 my_assert_not(g_eqs, NULL);
4541 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4542 g_label_refs[i].i = -1;
4543 g_label_refs[i].next = NULL;
4546 while (fgets(line, sizeof(line), fasm))
4555 // get rid of random tabs
4556 for (i = 0; line[i] != 0; i++)
4557 if (line[i] == '\t')
4562 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4563 goto do_pending_endp; // eww..
4565 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4567 static const char *attrs[] = {
4576 // parse IDA's attribute-list comment
4577 g_ida_func_attr = 0;
4580 for (; *p != 0; p = sskip(p)) {
4581 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4582 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4583 g_ida_func_attr |= 1 << i;
4584 p += strlen(attrs[i]);
4588 if (i == ARRAY_SIZE(attrs)) {
4589 anote("unparsed IDA attr: %s\n", p);
4592 if (IS(attrs[i], "fpd=")) {
4593 p = next_word(words[0], sizeof(words[0]), p);
4598 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4601 next_word(words[0], sizeof(words[0]), p);
4602 if (words[0][0] == 0)
4603 aerr("missing name for func chunk?\n");
4605 if (!scanned_ahead) {
4606 add_func_chunk(fasm, words[0], asmln);
4607 func_chunks_sorted = 0;
4610 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4612 if (func_chunk_i >= 0) {
4613 if (func_chunk_i < func_chunk_cnt
4614 && IS(func_chunks[func_chunk_i].name, g_func))
4616 // move on to next chunk
4617 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4619 aerr("seek failed for '%s' chunk #%d\n",
4620 g_func, func_chunk_i);
4621 asmln = func_chunks[func_chunk_i].asmln;
4625 if (func_chunk_ret == 0)
4626 aerr("no return from chunk?\n");
4627 fseek(fasm, func_chunk_ret, SEEK_SET);
4628 asmln = func_chunk_ret_ln;
4634 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4635 func_chunks_used = 1;
4637 if (IS_START(g_func, "sub_")) {
4638 unsigned long addr = strtoul(p, NULL, 16);
4639 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4640 if (addr > f_addr && !scanned_ahead) {
4641 anote("scan_ahead caused by '%s', addr %lx\n",
4645 func_chunks_sorted = 0;
4653 for (i = wordc; i < ARRAY_SIZE(words); i++)
4655 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4656 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4657 if (*p == 0 || *p == ';') {
4662 if (*p != 0 && *p != ';')
4663 aerr("too many words\n");
4665 // alow asm patches in comments
4667 if (IS_START(p, "; sctpatch:")) {
4669 if (*p == 0 || *p == ';')
4671 goto parse_words; // lame
4673 if (IS_START(p, "; sctproto:")) {
4674 sctproto = strdup(p + 11);
4680 awarn("wordc == 0?\n");
4684 // don't care about this:
4685 if (words[0][0] == '.'
4686 || IS(words[0], "include")
4687 || IS(words[0], "assume") || IS(words[1], "segment")
4688 || IS(words[0], "align"))
4694 // do delayed endp processing to collect switch jumptables
4696 if (in_func && !skip_func && wordc >= 2
4697 && ((words[0][0] == 'd' && words[0][2] == 0)
4698 || (words[1][0] == 'd' && words[1][2] == 0)))
4701 if (words[1][0] == 'd' && words[1][2] == 0) {
4703 if (g_func_pd_cnt >= pd_alloc) {
4704 pd_alloc = pd_alloc * 2 + 16;
4705 g_func_pd = realloc(g_func_pd,
4706 sizeof(g_func_pd[0]) * pd_alloc);
4707 my_assert_not(g_func_pd, NULL);
4709 pd = &g_func_pd[g_func_pd_cnt];
4711 memset(pd, 0, sizeof(*pd));
4712 strcpy(pd->label, words[0]);
4713 pd->type = OPT_CONST;
4714 pd->lmod = lmod_from_directive(words[1]);
4720 anote("skipping alignment byte?\n");
4723 lmod = lmod_from_directive(words[0]);
4724 if (lmod != pd->lmod)
4725 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4728 if (pd->count_alloc < pd->count + wordc) {
4729 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4730 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4731 my_assert_not(pd->d, NULL);
4733 for (; i < wordc; i++) {
4734 if (IS(words[i], "offset")) {
4735 pd->type = OPT_OFFSET;
4738 p = strchr(words[i], ',');
4741 if (pd->type == OPT_OFFSET)
4742 pd->d[pd->count].u.label = strdup(words[i]);
4744 pd->d[pd->count].u.val = parse_number(words[i]);
4745 pd->d[pd->count].bt_i = -1;
4751 if (in_func && !skip_func)
4752 gen_func(fout, g_fhdr, g_func, pi);
4756 g_ida_func_attr = 0;
4760 func_chunks_used = 0;
4763 memset(&ops, 0, pi * sizeof(ops[0]));
4764 memset(g_labels, 0, pi * sizeof(g_labels[0]));
4768 for (i = 0; i < g_func_pd_cnt; i++) {
4770 if (pd->type == OPT_OFFSET) {
4771 for (j = 0; j < pd->count; j++)
4772 free(pd->d[j].u.label);
4783 if (IS(words[1], "proc")) {
4785 aerr("proc '%s' while in_func '%s'?\n",
4788 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4790 strcpy(g_func, words[0]);
4791 set_label(0, words[0]);
4796 if (IS(words[1], "endp"))
4799 aerr("endp '%s' while not in_func?\n", words[0]);
4800 if (!IS(g_func, words[0]))
4801 aerr("endp '%s' while in_func '%s'?\n",
4804 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
4805 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
4811 if (!skip_func && func_chunks_used) {
4812 // start processing chunks
4813 struct chunk_item *ci, key = { g_func, 0 };
4815 func_chunk_ret = ftell(fasm);
4816 func_chunk_ret_ln = asmln;
4817 if (!func_chunks_sorted) {
4818 qsort(func_chunks, func_chunk_cnt,
4819 sizeof(func_chunks[0]), cmp_chunks);
4820 func_chunks_sorted = 1;
4822 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4823 sizeof(func_chunks[0]), cmp_chunks);
4825 aerr("'%s' needs chunks, but none found\n", g_func);
4826 func_chunk_i = ci - func_chunks;
4827 for (; func_chunk_i > 0; func_chunk_i--)
4828 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4831 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4833 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4834 asmln = func_chunks[func_chunk_i].asmln;
4842 if (wordc == 2 && IS(words[1], "ends"))
4845 p = strchr(words[0], ':');
4847 set_label(pi, words[0]);
4851 if (!in_func || skip_func) {
4852 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4854 anote("skipping from '%s'\n", g_labels[pi]);
4857 g_labels[pi][0] = 0;
4861 if (wordc > 1 && IS(words[1], "="))
4864 aerr("unhandled equ, wc=%d\n", wordc);
4865 if (g_eqcnt >= eq_alloc) {
4867 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4868 my_assert_not(g_eqs, NULL);
4871 len = strlen(words[0]);
4872 if (len > sizeof(g_eqs[0].name) - 1)
4873 aerr("equ name too long: %d\n", len);
4874 strcpy(g_eqs[g_eqcnt].name, words[0]);
4876 if (!IS(words[3], "ptr"))
4877 aerr("unhandled equ\n");
4878 if (IS(words[2], "dword"))
4879 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4880 else if (IS(words[2], "word"))
4881 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4882 else if (IS(words[2], "byte"))
4883 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4885 aerr("bad lmod: '%s'\n", words[2]);
4887 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4892 if (pi >= ARRAY_SIZE(ops))
4893 aerr("too many ops\n");
4895 parse_op(&ops[pi], words, wordc);
4897 if (sctproto != NULL) {
4898 if (ops[pi].op == OP_CALL)
4899 ops[pi].datap = sctproto;
4912 // vim:ts=2:shiftwidth=2:expandtab