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 */
46 OPF_ATAIL = (1 << 14), /* tail call with reused arg frame */
47 OPF_32BIT = (1 << 15), /* 32bit division */
48 OPF_LOCK = (1 << 16), /* op has lock prefix */
125 // must be sorted (larger len must be further in enum)
133 #define MAX_OPERANDS 3
137 enum opr_lenmod lmod;
138 unsigned int is_ptr:1; // pointer in C
139 unsigned int is_array:1; // array in C
140 unsigned int type_from_var:1; // .. in header, sometimes wrong
141 unsigned int size_mismatch:1; // type override differs from C
142 unsigned int size_lt:1; // type override is larger than C
143 unsigned int had_ds:1; // had ds: prefix
151 struct parsed_opr operand[MAX_OPERANDS];
154 int regmask_src; // all referensed regs
156 int pfomask; // flagop: parsed_flag_op that can't be delayed
157 int argnum; // push: altered before call arg #
158 int cc_scratch; // scratch storage during analysis
159 int bt_i; // branch target for branches
160 struct parsed_data *btj;// branch targets for jumptables
165 // OP_CALL - parser proto hint (str), ptr to struct parsed_proto
166 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
167 // OP_POP - point to OP_PUSH in push/pop pair
171 enum opr_lenmod lmod;
178 enum opr_lenmod lmod;
192 struct label_ref *next;
196 IDAFA_BP_FRAME = (1 << 0),
197 IDAFA_LIB_FUNC = (1 << 1),
198 IDAFA_STATIC = (1 << 2),
199 IDAFA_NORETURN = (1 << 3),
200 IDAFA_THUNK = (1 << 4),
201 IDAFA_FPD = (1 << 5),
206 static struct parsed_op ops[MAX_OPS];
207 static struct parsed_equ *g_eqs;
209 static char g_labels[MAX_OPS][48];
210 static struct label_ref g_label_refs[MAX_OPS];
211 static const struct parsed_proto *g_func_pp;
212 static struct parsed_data *g_func_pd;
213 static int g_func_pd_cnt;
214 static char g_func[256];
215 static char g_comment[256];
216 static int g_bp_frame;
217 static int g_sp_frame;
218 static int g_stack_frame_used;
219 static int g_stack_fsz;
220 static int g_ida_func_attr;
221 static int g_allow_regfunc;
222 #define ferr(op_, fmt, ...) do { \
223 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
224 dump_op(op_), ##__VA_ARGS__); \
228 #define fnote(op_, fmt, ...) \
229 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
230 dump_op(op_), ##__VA_ARGS__)
234 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
235 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
236 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
237 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
239 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
241 // possible basic comparison types (without inversion)
242 enum parsed_flag_op {
246 PFO_BE, // 6 CF=1||ZF=1
250 PFO_LE, // e ZF=1||SF!=OF
253 static const char *parsed_flag_op_names[] = {
254 "o", "c", "z", "be", "s", "p", "l", "le"
257 static int char_array_i(const char *array[], size_t len, const char *s)
261 for (i = 0; i < len; i++)
268 static void printf_number(char *buf, size_t buf_size,
269 unsigned long number)
271 // output in C-friendly form
272 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
275 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
279 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
281 *reg_lmod = OPLM_DWORD;
284 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
286 *reg_lmod = OPLM_WORD;
289 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
291 *reg_lmod = OPLM_BYTE;
294 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
296 *reg_lmod = OPLM_BYTE;
303 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
305 enum opr_lenmod lmod;
318 while (my_isblank(*s))
320 for (; my_issep(*s); d++, s++)
322 while (my_isblank(*s))
327 if (IS_START(s, "ds:"))
330 s = next_idt(w, sizeof(w), s);
335 reg = parse_reg(&lmod, w);
337 *regmask |= 1 << reg;
341 if ('0' <= w[0] && w[0] <= '9') {
342 number = parse_number(w);
343 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
347 // probably some label/identifier - pass
350 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
354 strcpy(name, cvtbuf);
359 static int is_reg_in_str(const char *s)
363 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
366 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
367 if (!strncmp(s, regs_r32[i], 3))
373 static const char *parse_stack_el(const char *name, char *extra_reg)
375 const char *p, *p2, *s;
382 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
384 if (extra_reg != NULL) {
385 strncpy(extra_reg, name, 3);
390 if (IS_START(p, "ebp+")) {
394 if (p2 != NULL && is_reg_in_str(p)) {
395 if (extra_reg != NULL) {
396 strncpy(extra_reg, p, p2 - p);
397 extra_reg[p2 - p] = 0;
402 if (!('0' <= *p && *p <= '9'))
408 if (!IS_START(name, "esp+"))
414 if (is_reg_in_str(s)) {
415 if (extra_reg != NULL) {
416 strncpy(extra_reg, s, p - s);
417 extra_reg[p - s] = 0;
422 aerr("%s IDA stackvar not set?\n", __func__);
424 if (!('0' <= *s && *s <= '9')) {
425 aerr("%s IDA stackvar offset not set?\n", __func__);
428 if (s[0] == '0' && s[1] == 'x')
431 if (len < sizeof(buf) - 1) {
432 strncpy(buf, s, len);
434 val = strtol(buf, &endp, 16);
435 if (val == 0 || *endp != 0) {
436 aerr("%s num parse fail for '%s'\n", __func__, buf);
445 if ('0' <= *p && *p <= '9')
451 static int guess_lmod_from_name(struct parsed_opr *opr)
453 if (!strncmp(opr->name, "dword_", 6)) {
454 opr->lmod = OPLM_DWORD;
457 if (!strncmp(opr->name, "word_", 5)) {
458 opr->lmod = OPLM_WORD;
461 if (!strncmp(opr->name, "byte_", 5)) {
462 opr->lmod = OPLM_BYTE;
468 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
469 const struct parsed_type *c_type)
471 static const char *dword_types[] = {
472 "int", "_DWORD", "UINT_PTR", "DWORD",
473 "WPARAM", "LPARAM", "UINT", "__int32",
476 static const char *word_types[] = {
477 "uint16_t", "int16_t", "_WORD",
478 "unsigned __int16", "__int16",
480 static const char *byte_types[] = {
481 "uint8_t", "int8_t", "char",
482 "unsigned __int8", "__int8", "BYTE", "_BYTE",
488 if (c_type->is_ptr) {
493 n = skip_type_mod(c_type->name);
495 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
496 if (IS(n, dword_types[i])) {
502 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
503 if (IS(n, word_types[i])) {
509 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
510 if (IS(n, byte_types[i])) {
519 static enum opr_type lmod_from_directive(const char *d)
523 else if (IS(d, "dw"))
525 else if (IS(d, "db"))
528 aerr("unhandled directive: '%s'\n", d);
532 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
538 *regmask |= 1 << reg;
541 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
544 static int parse_operand(struct parsed_opr *opr,
545 int *regmask, int *regmask_indirect,
546 char words[16][256], int wordc, int w, unsigned int op_flags)
548 const struct parsed_proto *pp;
549 enum opr_lenmod tmplmod;
550 unsigned long number;
558 aerr("parse_operand w %d, wordc %d\n", w, wordc);
562 for (i = w; i < wordc; i++) {
563 len = strlen(words[i]);
564 if (words[i][len - 1] == ',') {
565 words[i][len - 1] = 0;
571 wordc_in = wordc - w;
573 if ((op_flags & OPF_JMP) && wordc_in > 0
574 && !('0' <= words[w][0] && words[w][0] <= '9'))
576 const char *label = NULL;
578 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
579 && IS(words[w + 1], "ptr"))
580 label = words[w + 2];
581 else if (wordc_in == 2 && IS(words[w], "short"))
582 label = words[w + 1];
583 else if (wordc_in == 1
584 && strchr(words[w], '[') == NULL
585 && parse_reg(&tmplmod, words[w]) < 0)
589 opr->type = OPT_LABEL;
590 if (IS_START(label, "ds:")) {
594 strcpy(opr->name, label);
600 if (IS(words[w + 1], "ptr")) {
601 if (IS(words[w], "dword"))
602 opr->lmod = OPLM_DWORD;
603 else if (IS(words[w], "word"))
604 opr->lmod = OPLM_WORD;
605 else if (IS(words[w], "byte"))
606 opr->lmod = OPLM_BYTE;
608 aerr("type parsing failed\n");
610 wordc_in = wordc - w;
615 if (IS(words[w], "offset")) {
616 opr->type = OPT_OFFSET;
617 strcpy(opr->name, words[w + 1]);
620 if (IS(words[w], "(offset")) {
621 p = strchr(words[w + 1], ')');
623 aerr("parse of bracketed offset failed\n");
625 opr->type = OPT_OFFSET;
626 strcpy(opr->name, words[w + 1]);
632 aerr("parse_operand 1 word expected\n");
634 if (IS_START(words[w], "ds:")) {
636 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
638 strcpy(opr->name, words[w]);
640 if (words[w][0] == '[') {
641 opr->type = OPT_REGMEM;
642 ret = sscanf(words[w], "[%[^]]]", opr->name);
644 aerr("[] parse failure\n");
646 parse_indmode(opr->name, regmask_indirect, 1);
647 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
649 struct parsed_equ *eq =
650 equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
652 opr->lmod = eq->lmod;
656 else if (strchr(words[w], '[')) {
658 p = strchr(words[w], '[');
659 opr->type = OPT_REGMEM;
660 parse_indmode(p, regmask_indirect, 0);
661 strncpy(buf, words[w], p - words[w]);
662 buf[p - words[w]] = 0;
663 pp = proto_parse(g_fhdr, buf, 1);
666 else if (('0' <= words[w][0] && words[w][0] <= '9')
667 || words[w][0] == '-')
669 number = parse_number(words[w]);
670 opr->type = OPT_CONST;
672 printf_number(opr->name, sizeof(opr->name), number);
676 ret = parse_reg(&tmplmod, opr->name);
678 setup_reg_opr(opr, ret, tmplmod, regmask);
682 // most likely var in data segment
683 opr->type = OPT_LABEL;
684 pp = proto_parse(g_fhdr, opr->name, 0);
688 if (pp->is_fptr || pp->is_func) {
689 opr->lmod = OPLM_DWORD;
693 tmplmod = OPLM_UNSPEC;
694 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
695 anote("unhandled C type '%s' for '%s'\n",
696 pp->type.name, opr->name);
698 if (opr->lmod == OPLM_UNSPEC) {
700 opr->type_from_var = 1;
702 else if (opr->lmod != tmplmod) {
703 opr->size_mismatch = 1;
704 if (tmplmod < opr->lmod)
707 opr->is_ptr = pp->type.is_ptr;
709 opr->is_array = pp->type.is_array;
712 if (opr->lmod == OPLM_UNSPEC)
713 guess_lmod_from_name(opr);
717 static const struct {
722 { "repe", OPF_REP|OPF_REPZ },
723 { "repz", OPF_REP|OPF_REPZ },
724 { "repne", OPF_REP|OPF_REPNZ },
725 { "repnz", OPF_REP|OPF_REPNZ },
726 { "lock", OPF_LOCK }, // ignored for now..
729 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
731 static const struct {
738 { "nop", OP_NOP, 0, 0, 0 },
739 { "push", OP_PUSH, 1, 1, 0 },
740 { "pop", OP_POP, 1, 1, OPF_DATA },
741 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
742 { "mov" , OP_MOV, 2, 2, OPF_DATA },
743 { "lea", OP_LEA, 2, 2, OPF_DATA },
744 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
745 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
746 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
747 { "not", OP_NOT, 1, 1, OPF_DATA },
748 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
749 { "stosb",OP_STOS, 0, 0, OPF_DATA },
750 { "stosw",OP_STOS, 0, 0, OPF_DATA },
751 { "stosd",OP_STOS, 0, 0, OPF_DATA },
752 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
753 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
754 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
755 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
756 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
757 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
758 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
759 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
760 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
761 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
762 { "cld", OP_CLD, 0, 0, OPF_DATA },
763 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
764 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
765 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
766 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
767 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
768 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
769 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
770 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
771 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
772 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
773 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
774 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
775 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
776 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
777 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
778 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
779 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
780 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
781 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
782 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
783 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
784 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
785 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
786 { "test", OP_TEST, 2, 2, OPF_FLAGS },
787 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
788 { "retn", OP_RET, 0, 1, OPF_TAIL },
789 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
790 { "jmp", OP_JMP, 1, 1, OPF_JMP },
791 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
792 { "jo", OP_JO, 1, 1, OPF_CJMP_CC }, // 70 OF=1
793 { "jno", OP_JNO, 1, 1, OPF_CJMP_CC }, // 71 OF=0
794 { "jc", OP_JC, 1, 1, OPF_CJMP_CC }, // 72 CF=1
795 { "jb", OP_JC, 1, 1, OPF_CJMP_CC }, // 72
796 { "jnc", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73 CF=0
797 { "jnb", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73
798 { "jae", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73
799 { "jz", OP_JZ, 1, 1, OPF_CJMP_CC }, // 74 ZF=1
800 { "je", OP_JZ, 1, 1, OPF_CJMP_CC }, // 74
801 { "jnz", OP_JNZ, 1, 1, OPF_CJMP_CC }, // 75 ZF=0
802 { "jne", OP_JNZ, 1, 1, OPF_CJMP_CC }, // 75
803 { "jbe", OP_JBE, 1, 1, OPF_CJMP_CC }, // 76 CF=1 || ZF=1
804 { "jna", OP_JBE, 1, 1, OPF_CJMP_CC }, // 76
805 { "ja", OP_JA, 1, 1, OPF_CJMP_CC }, // 77 CF=0 && ZF=0
806 { "jnbe", OP_JA, 1, 1, OPF_CJMP_CC }, // 77
807 { "js", OP_JS, 1, 1, OPF_CJMP_CC }, // 78 SF=1
808 { "jns", OP_JNS, 1, 1, OPF_CJMP_CC }, // 79 SF=0
809 { "jp", OP_JP, 1, 1, OPF_CJMP_CC }, // 7a PF=1
810 { "jpe", OP_JP, 1, 1, OPF_CJMP_CC }, // 7a
811 { "jnp", OP_JNP, 1, 1, OPF_CJMP_CC }, // 7b PF=0
812 { "jpo", OP_JNP, 1, 1, OPF_CJMP_CC }, // 7b
813 { "jl", OP_JL, 1, 1, OPF_CJMP_CC }, // 7c SF!=OF
814 { "jnge", OP_JL, 1, 1, OPF_CJMP_CC }, // 7c
815 { "jge", OP_JGE, 1, 1, OPF_CJMP_CC }, // 7d SF=OF
816 { "jnl", OP_JGE, 1, 1, OPF_CJMP_CC }, // 7d
817 { "jle", OP_JLE, 1, 1, OPF_CJMP_CC }, // 7e ZF=1 || SF!=OF
818 { "jng", OP_JLE, 1, 1, OPF_CJMP_CC }, // 7e
819 { "jg", OP_JG, 1, 1, OPF_CJMP_CC }, // 7f ZF=0 && SF=OF
820 { "jnle", OP_JG, 1, 1, OPF_CJMP_CC }, // 7f
821 { "seto", OP_JO, 1, 1, OPF_DATA|OPF_CC },
822 { "setno", OP_JNO, 1, 1, OPF_DATA|OPF_CC },
823 { "setc", OP_JC, 1, 1, OPF_DATA|OPF_CC },
824 { "setb", OP_JC, 1, 1, OPF_DATA|OPF_CC },
825 { "setnc", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
826 { "setae", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
827 { "setz", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
828 { "sete", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
829 { "setnz", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
830 { "setne", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
831 { "setbe", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
832 { "setna", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
833 { "seta", OP_JA, 1, 1, OPF_DATA|OPF_CC },
834 { "setnbe", OP_JA, 1, 1, OPF_DATA|OPF_CC },
835 { "sets", OP_JS, 1, 1, OPF_DATA|OPF_CC },
836 { "setns", OP_JNS, 1, 1, OPF_DATA|OPF_CC },
837 { "setp", OP_JP, 1, 1, OPF_DATA|OPF_CC },
838 { "setpe", OP_JP, 1, 1, OPF_DATA|OPF_CC },
839 { "setnp", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
840 { "setpo", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
841 { "setl", OP_JL, 1, 1, OPF_DATA|OPF_CC },
842 { "setnge", OP_JL, 1, 1, OPF_DATA|OPF_CC },
843 { "setge", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
844 { "setnl", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
845 { "setle", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
846 { "setng", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
847 { "setg", OP_JG, 1, 1, OPF_DATA|OPF_CC },
848 { "setnle", OP_JG, 1, 1, OPF_DATA|OPF_CC },
851 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
853 enum opr_lenmod lmod = OPLM_UNSPEC;
854 int prefix_flags = 0;
862 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
863 if (IS(words[w], pref_table[i].name)) {
864 prefix_flags = pref_table[i].flags;
871 aerr("lone prefix: '%s'\n", words[0]);
876 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
877 if (IS(words[w], op_table[i].name))
881 if (i == ARRAY_SIZE(op_table))
882 aerr("unhandled op: '%s'\n", words[0]);
885 op->op = op_table[i].op;
886 op->flags = op_table[i].flags | prefix_flags;
887 op->regmask_src = op->regmask_dst = 0;
889 for (opr = 0; opr < op_table[i].minopr; opr++) {
890 regmask = regmask_ind = 0;
891 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
892 words, wordc, w, op->flags);
894 if (opr == 0 && (op->flags & OPF_DATA))
895 op->regmask_dst = regmask;
896 // for now, mark dst as src too
897 op->regmask_src |= regmask | regmask_ind;
900 for (; w < wordc && opr < op_table[i].maxopr; opr++) {
901 w = parse_operand(&op->operand[opr],
902 &op->regmask_src, &op->regmask_src,
903 words, wordc, w, op->flags);
907 aerr("parse_op %s incomplete: %d/%d\n",
911 op->operand_cnt = opr;
912 if (!strncmp(op_table[i].name, "set", 3))
913 op->operand[0].lmod = OPLM_BYTE;
915 // ops with implicit argumets
919 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
920 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
925 if (op->operand_cnt != 0)
927 if (words[op_w][4] == 'b')
929 else if (words[op_w][4] == 'w')
931 else if (words[op_w][4] == 'd')
934 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
935 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
936 op->regmask_dst = op->regmask_src;
937 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
942 if (op->operand_cnt != 0)
944 if (words[op_w][4] == 'b')
946 else if (words[op_w][4] == 'w')
948 else if (words[op_w][4] == 'd')
951 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
952 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
953 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
954 op->regmask_dst = op->regmask_src;
958 op->regmask_src |= op->regmask_dst;
959 op->regmask_dst |= op->regmask_src;
964 op->regmask_src = 1 << xCX;
965 op->operand[0].type = OPT_REG;
966 op->operand[0].reg = xCX;
967 op->operand[0].lmod = OPLM_DWORD;
971 if (op->operand_cnt != 1)
976 op->regmask_dst = (1 << xDX) | (1 << xAX);
977 op->regmask_src |= (1 << xAX);
978 if (op->operand[0].lmod == OPLM_UNSPEC)
979 op->operand[0].lmod = OPLM_DWORD;
984 // we could set up operands for edx:eax, but there is no real need to
985 // (see is_opr_modified())
986 regmask = (1 << xDX) | (1 << xAX);
987 op->regmask_dst = regmask;
988 op->regmask_src |= regmask;
989 if (op->operand[0].lmod == OPLM_UNSPEC)
990 op->operand[0].lmod = OPLM_DWORD;
998 if (op->operand[1].lmod == OPLM_UNSPEC)
999 op->operand[1].lmod = OPLM_BYTE;
1003 if (op->operand[0].lmod == OPLM_UNSPEC
1004 && (op->operand[0].type == OPT_CONST
1005 || op->operand[0].type == OPT_OFFSET
1006 || op->operand[0].type == OPT_LABEL))
1007 op->operand[0].lmod = OPLM_DWORD;
1012 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1013 && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
1015 op->flags |= OPF_RMD;
1020 if (op->operand[0].type == OPT_REG
1021 && op->operand[1].type == OPT_REGMEM)
1024 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1025 if (IS(buf, op->operand[1].name))
1026 op->flags |= OPF_RMD;
1031 // trashed regs must be explicitly detected later
1032 op->regmask_dst = 0;
1040 static const char *op_name(enum op_op op)
1044 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1045 if (op_table[i].op == op)
1046 return op_table[i].name;
1052 static const char *dump_op(struct parsed_op *po)
1054 static char out[128];
1061 snprintf(out, sizeof(out), "%s", op_name(po->op));
1062 for (i = 0; i < po->operand_cnt; i++) {
1066 snprintf(p, sizeof(out) - (p - out),
1067 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1068 po->operand[i].name);
1074 static const char *lmod_type_u(struct parsed_op *po,
1075 enum opr_lenmod lmod)
1085 ferr(po, "invalid lmod: %d\n", lmod);
1086 return "(_invalid_)";
1090 static const char *lmod_cast_u(struct parsed_op *po,
1091 enum opr_lenmod lmod)
1101 ferr(po, "invalid lmod: %d\n", lmod);
1102 return "(_invalid_)";
1106 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1107 enum opr_lenmod lmod)
1117 ferr(po, "invalid lmod: %d\n", lmod);
1118 return "(_invalid_)";
1122 static const char *lmod_cast_s(struct parsed_op *po,
1123 enum opr_lenmod lmod)
1133 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1134 return "(_invalid_)";
1138 static const char *lmod_cast(struct parsed_op *po,
1139 enum opr_lenmod lmod, int is_signed)
1142 lmod_cast_s(po, lmod) :
1143 lmod_cast_u(po, lmod);
1146 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1156 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1161 static const char *opr_name(struct parsed_op *po, int opr_num)
1163 if (opr_num >= po->operand_cnt)
1164 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1165 return po->operand[opr_num].name;
1168 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1170 if (opr_num >= po->operand_cnt)
1171 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1172 if (po->operand[opr_num].type != OPT_CONST)
1173 ferr(po, "opr %d: const expected\n", opr_num);
1174 return po->operand[opr_num].val;
1177 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1179 if ((unsigned int)popr->reg >= MAX_REGS)
1180 ferr(po, "invalid reg: %d\n", popr->reg);
1181 return regs_r32[popr->reg];
1184 // cast1 is the "final" cast
1185 static const char *simplify_cast(const char *cast1, const char *cast2)
1187 static char buf[256];
1193 if (IS(cast1, cast2))
1195 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1197 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1199 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1201 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1203 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1206 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1210 static const char *simplify_cast_num(const char *cast, unsigned int val)
1212 if (IS(cast, "(u8)") && val < 0x100)
1214 if (IS(cast, "(s8)") && val < 0x80)
1216 if (IS(cast, "(u16)") && val < 0x10000)
1218 if (IS(cast, "(s16)") && val < 0x8000)
1220 if (IS(cast, "(s32)") && val < 0x80000000)
1226 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1235 namelen = strlen(name);
1237 p = strchr(name, '+');
1241 ferr(po, "equ parse failed for '%s'\n", name);
1243 if (IS_START(p, "0x"))
1245 *extra_offs = strtol(p, &endp, 16);
1247 ferr(po, "equ parse failed for '%s'\n", name);
1250 for (i = 0; i < g_eqcnt; i++)
1251 if (strncmp(g_eqs[i].name, name, namelen) == 0
1252 && g_eqs[i].name[namelen] == 0)
1256 ferr(po, "unresolved equ name: '%s'\n", name);
1263 static int is_stack_access(struct parsed_op *po,
1264 const struct parsed_opr *popr)
1266 return (parse_stack_el(popr->name, NULL)
1267 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1268 && IS_START(popr->name, "ebp")));
1271 static void parse_stack_access(struct parsed_op *po,
1272 const char *name, char *ofs_reg, int *offset_out,
1273 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1275 const char *bp_arg = "";
1276 const char *p = NULL;
1277 struct parsed_equ *eq;
1284 if (IS_START(name, "ebp-")
1285 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1288 if (IS_START(p, "0x"))
1290 offset = strtoul(p, &endp, 16);
1294 ferr(po, "ebp- parse of '%s' failed\n", name);
1297 bp_arg = parse_stack_el(name, ofs_reg);
1298 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1299 eq = equ_find(po, bp_arg, &offset);
1301 ferr(po, "detected but missing eq\n");
1302 offset += eq->offset;
1305 if (!strncmp(name, "ebp", 3))
1308 // yes it sometimes LEAs ra for compares..
1309 if (!is_lea && ofs_reg[0] == 0
1310 && stack_ra <= offset && offset < stack_ra + 4)
1312 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1315 *offset_out = offset;
1316 *stack_ra_out = stack_ra;
1318 *bp_arg_out = bp_arg;
1321 static void stack_frame_access(struct parsed_op *po,
1322 struct parsed_opr *popr, char *buf, size_t buf_size,
1323 const char *name, const char *cast, int is_src, int is_lea)
1325 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1326 const char *prefix = "";
1327 const char *bp_arg = NULL;
1328 char ofs_reg[16] = { 0, };
1329 int i, arg_i, arg_s;
1336 if (po->flags & OPF_EBP_S)
1337 ferr(po, "stack_frame_access while ebp is scratch\n");
1339 parse_stack_access(po, name, ofs_reg, &offset,
1340 &stack_ra, &bp_arg, is_lea);
1342 if (offset > stack_ra)
1344 arg_i = (offset - stack_ra - 4) / 4;
1345 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1347 if (g_func_pp->is_vararg
1348 && arg_i == g_func_pp->argc_stack && is_lea)
1350 // should be va_list
1353 snprintf(buf, buf_size, "%sap", cast);
1356 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1357 offset, bp_arg, arg_i);
1359 if (ofs_reg[0] != 0)
1360 ferr(po, "offset reg on arg access?\n");
1362 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1363 if (g_func_pp->arg[i].reg != NULL)
1369 if (i == g_func_pp->argc)
1370 ferr(po, "arg %d not in prototype?\n", arg_i);
1372 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1378 ferr(po, "lea/byte to arg?\n");
1379 if (is_src && (offset & 3) == 0)
1380 snprintf(buf, buf_size, "%sa%d",
1381 simplify_cast(cast, "(u8)"), i + 1);
1383 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1384 cast, offset & 3, i + 1);
1389 ferr(po, "lea/word to arg?\n");
1394 ferr(po, "problematic arg store\n");
1395 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1396 simplify_cast(cast, "*(u16 *)"), i + 1);
1399 ferr(po, "unaligned arg word load\n");
1401 else if (is_src && (offset & 2) == 0)
1402 snprintf(buf, buf_size, "%sa%d",
1403 simplify_cast(cast, "(u16)"), i + 1);
1405 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1406 cast, (offset & 2) ? "HI" : "LO", i + 1);
1418 snprintf(buf, buf_size, "(u32)&a%d + %d",
1421 ferr(po, "unaligned arg store\n");
1423 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1424 snprintf(buf, buf_size, "%s(a%d >> %d)",
1425 prefix, i + 1, (offset & 3) * 8);
1429 snprintf(buf, buf_size, "%s%sa%d",
1430 prefix, is_lea ? "&" : "", i + 1);
1435 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1439 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1442 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1443 if (tmp_lmod != OPLM_DWORD
1444 && (unaligned || (!is_src && tmp_lmod < popr->lmod)))
1446 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1447 i + 1, offset, g_func_pp->arg[i].type.name);
1449 // can't check this because msvc likes to reuse
1450 // arg space for scratch..
1451 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1452 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1456 if (g_stack_fsz == 0)
1457 ferr(po, "stack var access without stackframe\n");
1458 g_stack_frame_used = 1;
1460 sf_ofs = g_stack_fsz + offset;
1461 lim = (ofs_reg[0] != 0) ? -4 : 0;
1462 if (offset > 0 || sf_ofs < lim)
1463 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1473 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1474 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1478 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1479 // known unaligned or possibly unaligned
1480 strcat(g_comment, " unaligned");
1482 prefix = "*(u16 *)&";
1483 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1484 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1487 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1491 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1492 // known unaligned or possibly unaligned
1493 strcat(g_comment, " unaligned");
1495 prefix = "*(u32 *)&";
1496 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1497 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1500 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1504 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1509 static void check_func_pp(struct parsed_op *po,
1510 const struct parsed_proto *pp, const char *pfx)
1514 if (pp->argc_reg != 0) {
1515 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1516 pp_print(buf, sizeof(buf), pp);
1517 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1519 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1520 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1521 pfx, pp->argc_reg, pp->argc_stack);
1525 static const char *check_label_read_ref(struct parsed_op *po,
1528 const struct parsed_proto *pp;
1530 pp = proto_parse(g_fhdr, name, 0);
1532 ferr(po, "proto_parse failed for ref '%s'\n", name);
1535 check_func_pp(po, pp, "ref");
1540 static char *out_src_opr(char *buf, size_t buf_size,
1541 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1544 char tmp1[256], tmp2[256];
1553 switch (popr->type) {
1556 ferr(po, "lea from reg?\n");
1558 switch (popr->lmod) {
1560 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1563 snprintf(buf, buf_size, "%s%s",
1564 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1567 if (popr->name[1] == 'h') // XXX..
1568 snprintf(buf, buf_size, "%s(%s >> 8)",
1569 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1571 snprintf(buf, buf_size, "%s%s",
1572 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1575 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1580 if (is_stack_access(po, popr)) {
1581 stack_frame_access(po, popr, buf, buf_size,
1582 popr->name, cast, 1, is_lea);
1586 strcpy(expr, popr->name);
1587 if (strchr(expr, '[')) {
1588 // special case: '[' can only be left for label[reg] form
1589 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1591 ferr(po, "parse failure for '%s'\n", expr);
1592 if (tmp1[0] == '(') {
1593 // (off_4FFF50+3)[eax]
1594 p = strchr(tmp1 + 1, ')');
1595 if (p == NULL || p[1] != 0)
1596 ferr(po, "parse failure (2) for '%s'\n", expr);
1598 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1600 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1603 // XXX: do we need more parsing?
1605 snprintf(buf, buf_size, "%s", expr);
1609 snprintf(buf, buf_size, "%s(%s)",
1610 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1614 name = check_label_read_ref(po, popr->name);
1615 if (cast[0] == 0 && popr->is_ptr)
1619 snprintf(buf, buf_size, "(u32)&%s", name);
1620 else if (popr->size_lt)
1621 snprintf(buf, buf_size, "%s%s%s%s", cast,
1622 lmod_cast_u_ptr(po, popr->lmod),
1623 popr->is_array ? "" : "&", name);
1625 snprintf(buf, buf_size, "%s%s%s", cast, name,
1626 popr->is_array ? "[0]" : "");
1630 name = check_label_read_ref(po, popr->name);
1634 ferr(po, "lea an offset?\n");
1635 snprintf(buf, buf_size, "%s&%s", cast, name);
1640 ferr(po, "lea from const?\n");
1642 printf_number(tmp1, sizeof(tmp1), popr->val);
1643 if (popr->val == 0 && strchr(cast, '*'))
1644 snprintf(buf, buf_size, "NULL");
1646 snprintf(buf, buf_size, "%s%s",
1647 simplify_cast_num(cast, popr->val), tmp1);
1651 ferr(po, "invalid src type: %d\n", popr->type);
1657 // note: may set is_ptr (we find that out late for ebp frame..)
1658 static char *out_dst_opr(char *buf, size_t buf_size,
1659 struct parsed_op *po, struct parsed_opr *popr)
1661 switch (popr->type) {
1663 switch (popr->lmod) {
1665 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1669 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1673 if (popr->name[1] == 'h') // XXX..
1674 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1676 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1679 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1684 if (is_stack_access(po, popr)) {
1685 stack_frame_access(po, popr, buf, buf_size,
1686 popr->name, "", 0, 0);
1690 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1693 if (popr->size_mismatch)
1694 snprintf(buf, buf_size, "%s%s%s",
1695 lmod_cast_u_ptr(po, popr->lmod),
1696 popr->is_array ? "" : "&", popr->name);
1698 snprintf(buf, buf_size, "%s%s", popr->name,
1699 popr->is_array ? "[0]" : "");
1703 ferr(po, "invalid dst type: %d\n", popr->type);
1709 static char *out_src_opr_u32(char *buf, size_t buf_size,
1710 struct parsed_op *po, struct parsed_opr *popr)
1712 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1715 static enum parsed_flag_op split_cond(struct parsed_op *po,
1716 enum op_op op, int *is_inv)
1770 ferr(po, "split_cond: bad op %d\n", op);
1775 static void out_test_for_cc(char *buf, size_t buf_size,
1776 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1777 enum opr_lenmod lmod, const char *expr)
1779 const char *cast, *scast;
1781 cast = lmod_cast_u(po, lmod);
1782 scast = lmod_cast_s(po, lmod);
1786 case PFO_BE: // CF=1||ZF=1; CF=0
1787 snprintf(buf, buf_size, "(%s%s %s 0)",
1788 cast, expr, is_inv ? "!=" : "==");
1792 case PFO_L: // SF!=OF; OF=0
1793 snprintf(buf, buf_size, "(%s%s %s 0)",
1794 scast, expr, is_inv ? ">=" : "<");
1797 case PFO_LE: // ZF=1||SF!=OF; OF=0
1798 snprintf(buf, buf_size, "(%s%s %s 0)",
1799 scast, expr, is_inv ? ">" : "<=");
1803 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1807 static void out_cmp_for_cc(char *buf, size_t buf_size,
1808 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1810 const char *cast, *scast, *cast_use;
1811 char buf1[256], buf2[256];
1812 enum opr_lenmod lmod;
1814 if (po->operand[0].lmod != po->operand[1].lmod)
1815 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1816 po->operand[0].lmod, po->operand[1].lmod);
1817 lmod = po->operand[0].lmod;
1819 cast = lmod_cast_u(po, lmod);
1820 scast = lmod_cast_s(po, lmod);
1836 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1839 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1840 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1844 // note: must be unsigned compare
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);
1855 // note: must be unsigned compare
1856 snprintf(buf, buf_size, "(%s %s %s)",
1857 buf1, is_inv ? ">" : "<=", buf2);
1860 if (is_inv && lmod == OPLM_BYTE
1861 && po->operand[1].type == OPT_CONST
1862 && po->operand[1].val == 0xff)
1864 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1865 snprintf(buf, buf_size, "(0)");
1869 // note: must be signed compare
1871 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1872 scast, buf1, buf2, is_inv ? ">=" : "<");
1876 snprintf(buf, buf_size, "(%s %s %s)",
1877 buf1, is_inv ? ">=" : "<", buf2);
1881 snprintf(buf, buf_size, "(%s %s %s)",
1882 buf1, is_inv ? ">" : "<=", buf2);
1890 static void out_cmp_test(char *buf, size_t buf_size,
1891 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1893 char buf1[256], buf2[256], buf3[256];
1895 if (po->op == OP_TEST) {
1896 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1897 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1900 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1901 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1902 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1904 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1905 po->operand[0].lmod, buf3);
1907 else if (po->op == OP_CMP) {
1908 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1911 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1914 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1915 struct parsed_opr *popr2)
1917 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1918 ferr(po, "missing lmod for both operands\n");
1920 if (popr1->lmod == OPLM_UNSPEC)
1921 popr1->lmod = popr2->lmod;
1922 else if (popr2->lmod == OPLM_UNSPEC)
1923 popr2->lmod = popr1->lmod;
1924 else if (popr1->lmod != popr2->lmod) {
1925 if (popr1->type_from_var) {
1926 popr1->size_mismatch = 1;
1927 if (popr1->lmod < popr2->lmod)
1929 popr1->lmod = popr2->lmod;
1931 else if (popr2->type_from_var) {
1932 popr2->size_mismatch = 1;
1933 if (popr2->lmod < popr1->lmod)
1935 popr2->lmod = popr1->lmod;
1938 ferr(po, "conflicting lmods: %d vs %d\n",
1939 popr1->lmod, popr2->lmod);
1943 static const char *op_to_c(struct parsed_op *po)
1967 ferr(po, "op_to_c was supplied with %d\n", po->op);
1971 static void op_set_clear_flag(struct parsed_op *po,
1972 enum op_flags flag_set, enum op_flags flag_clear)
1974 po->flags |= flag_set;
1975 po->flags &= ~flag_clear;
1978 // last op in stream - unconditional branch or ret
1979 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1980 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP \
1981 && ops[_i].op != OP_CALL))
1983 static int scan_for_pop(int i, int opcnt, const char *reg,
1984 int magic, int depth, int *maxdepth, int do_flags)
1986 const struct parsed_proto *pp;
1987 struct parsed_op *po;
1991 for (; i < opcnt; i++) {
1993 if (po->cc_scratch == magic)
1994 break; // already checked
1995 po->cc_scratch = magic;
1997 if (po->flags & OPF_TAIL) {
1998 if (po->op == OP_CALL) {
1999 pp = proto_parse(g_fhdr, po->operand[0].name, 0);
2000 if (pp != NULL && pp->is_noreturn)
2001 // no stack cleanup for noreturn
2004 return -1; // deadend
2007 if ((po->flags & OPF_RMD)
2008 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
2011 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2012 if (po->btj != NULL) {
2014 for (j = 0; j < po->btj->count; j++) {
2015 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2016 depth, maxdepth, do_flags);
2018 return ret; // dead end
2024 ferr(po, "dead branch\n");
2028 if (po->flags & OPF_CJMP) {
2029 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2030 depth, maxdepth, do_flags);
2032 return ret; // dead end
2040 if ((po->op == OP_POP || po->op == OP_PUSH)
2041 && po->operand[0].type == OPT_REG
2042 && IS(po->operand[0].name, reg))
2044 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
2046 if (depth > *maxdepth)
2049 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2051 else if (po->op == OP_POP) {
2054 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2059 if (depth < 0) // should not happen
2060 ferr(po, "fail with depth\n");
2062 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2071 // scan for pop starting from 'ret' op (all paths)
2072 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2078 for (; i < opcnt; i++) {
2079 if (!(ops[i].flags & OPF_TAIL))
2082 for (j = i - 1; j >= 0; j--) {
2083 if (ops[j].flags & OPF_RMD)
2085 if (ops[j].flags & OPF_JMP)
2088 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2089 && IS(ops[j].operand[0].name, reg))
2092 ops[j].flags |= flag_set;
2096 if (g_labels[j][0] != 0)
2101 return found ? 0 : -1;
2104 static void scan_propagate_df(int i, int opcnt)
2106 struct parsed_op *po = &ops[i];
2109 for (; i < opcnt; i++) {
2111 if (po->flags & OPF_DF)
2112 return; // already resolved
2113 po->flags |= OPF_DF;
2115 if (po->op == OP_CALL)
2116 ferr(po, "call with DF set?\n");
2118 if (po->flags & OPF_JMP) {
2119 if (po->btj != NULL) {
2121 for (j = 0; j < po->btj->count; j++)
2122 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2127 ferr(po, "dead branch\n");
2131 if (po->flags & OPF_CJMP)
2132 scan_propagate_df(po->bt_i, opcnt);
2138 if (po->flags & OPF_TAIL)
2141 if (po->op == OP_CLD) {
2142 po->flags |= OPF_RMD;
2147 ferr(po, "missing DF clear?\n");
2150 // is operand 'opr' modified by parsed_op 'po'?
2151 static int is_opr_modified(const struct parsed_opr *opr,
2152 const struct parsed_op *po)
2156 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2159 if (opr->type == OPT_REG) {
2160 if (po->op == OP_CALL) {
2161 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2162 if ((1 << opr->reg) & mask)
2168 if (po->operand[0].type == OPT_REG) {
2169 if (po->regmask_dst & (1 << opr->reg))
2176 return IS(po->operand[0].name, opr->name);
2179 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2180 static int is_any_opr_modified(const struct parsed_op *po_test,
2181 const struct parsed_op *po, int c_mode)
2186 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2189 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2192 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2195 // in reality, it can wreck any register, but in decompiled C
2196 // version it can only overwrite eax or edx:eax
2197 mask = (1 << xAX) | (1 << xDX);
2201 if (po->op == OP_CALL
2202 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2205 for (i = 0; i < po_test->operand_cnt; i++)
2206 if (IS(po_test->operand[i].name, po->operand[0].name))
2212 // scan for any po_test operand modification in range given
2213 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2216 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2219 for (; i < opcnt; i++) {
2220 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2227 // scan for po_test operand[0] modification in range given
2228 static int scan_for_mod_opr0(struct parsed_op *po_test,
2231 for (; i < opcnt; i++) {
2232 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2239 static int scan_for_flag_set(int i, int magic, int *branched,
2240 int *setters, int *setter_cnt)
2242 struct label_ref *lr;
2246 if (ops[i].cc_scratch == magic) {
2247 ferr(&ops[i], "%s looped\n", __func__);
2250 ops[i].cc_scratch = magic;
2252 if (g_labels[i][0] != 0) {
2255 lr = &g_label_refs[i];
2256 for (; lr->next; lr = lr->next) {
2257 ret = scan_for_flag_set(lr->i, magic,
2258 branched, setters, setter_cnt);
2263 if (i > 0 && LAST_OP(i - 1)) {
2267 ret = scan_for_flag_set(lr->i, magic,
2268 branched, setters, setter_cnt);
2274 if (ops[i].flags & OPF_FLAGS) {
2275 setters[*setter_cnt] = i;
2280 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2287 // scan back for cdq, if anything modifies edx, fail
2288 static int scan_for_cdq_edx(int i)
2291 if (g_labels[i][0] != 0) {
2292 if (g_label_refs[i].next != NULL)
2294 if (i > 0 && LAST_OP(i - 1)) {
2295 i = g_label_refs[i].i;
2302 if (ops[i].op == OP_CDQ)
2305 if (ops[i].regmask_dst & (1 << xDX))
2312 static int scan_for_reg_clear(int i, int reg)
2315 if (g_labels[i][0] != 0) {
2316 if (g_label_refs[i].next != NULL)
2318 if (i > 0 && LAST_OP(i - 1)) {
2319 i = g_label_refs[i].i;
2326 if (ops[i].op == OP_XOR
2327 && ops[i].operand[0].lmod == OPLM_DWORD
2328 && ops[i].operand[0].reg == ops[i].operand[1].reg
2329 && ops[i].operand[0].reg == reg)
2332 if (ops[i].regmask_dst & (1 << reg))
2339 // scan for positive, constant esp adjust
2340 static int scan_for_esp_adjust(int i, int opcnt, int *adj,
2343 const struct parsed_proto *pp;
2344 struct parsed_op *po;
2347 *adj = *multipath = 0;
2349 for (; i < opcnt; i++) {
2352 if (g_labels[i][0] != 0)
2355 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2356 if (po->operand[1].type != OPT_CONST)
2357 ferr(&ops[i], "non-const esp adjust?\n");
2358 *adj += po->operand[1].val;
2360 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2363 else if (po->op == OP_PUSH && !(po->flags & OPF_RMD)) {
2364 //if (first_pop == -1)
2365 // first_pop = -2; // none
2366 *adj -= lmod_bytes(po, po->operand[0].lmod);
2368 else if (po->op == OP_POP && !(po->flags & OPF_RMD)) {
2369 // seems like msvc only uses 'pop ecx' for stack realignment..
2370 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2372 if (first_pop == -1 && *adj >= 0)
2374 *adj += lmod_bytes(po, po->operand[0].lmod);
2376 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2377 if (po->op == OP_JMP && po->btj == NULL) {
2381 if (po->op != OP_CALL)
2383 if (po->operand[0].type != OPT_LABEL)
2386 if (pp != NULL && pp->is_stdcall)
2391 if (first_pop >= 0) {
2392 // probably 'pop ecx' was used..
2399 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2401 struct parsed_op *po;
2405 ferr(ops, "%s: followed bad branch?\n", __func__);
2407 for (; i < opcnt; i++) {
2409 if (po->cc_scratch == magic)
2411 po->cc_scratch = magic;
2414 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2415 if (po->btj != NULL) {
2417 for (j = 0; j < po->btj->count; j++)
2418 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2422 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2423 if (!(po->flags & OPF_CJMP))
2426 if (po->flags & OPF_TAIL)
2431 static const struct parsed_proto *try_recover_pp(
2432 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2434 const struct parsed_proto *pp = NULL;
2438 // maybe an arg of g_func?
2439 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2441 char ofs_reg[16] = { 0, };
2442 int arg, arg_s, arg_i;
2446 parse_stack_access(po, opr->name, ofs_reg,
2447 &offset, &stack_ra, NULL, 0);
2448 if (ofs_reg[0] != 0)
2449 ferr(po, "offset reg on arg access?\n");
2450 if (offset <= stack_ra) {
2451 // search who set the stack var instead
2452 if (search_instead != NULL)
2453 *search_instead = 1;
2457 arg_i = (offset - stack_ra - 4) / 4;
2458 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2459 if (g_func_pp->arg[arg].reg != NULL)
2465 if (arg == g_func_pp->argc)
2466 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2468 pp = g_func_pp->arg[arg].fptr;
2470 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2471 check_func_pp(po, pp, "icall arg");
2473 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2475 p = strchr(opr->name + 1, '[');
2476 memcpy(buf, opr->name, p - opr->name);
2477 buf[p - opr->name] = 0;
2478 pp = proto_parse(g_fhdr, buf, 0);
2480 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2481 pp = proto_parse(g_fhdr, opr->name, 0);
2483 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2484 check_func_pp(po, pp, "reg-fptr ref");
2490 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2491 int magic, const struct parsed_proto **pp_found, int *multi)
2493 const struct parsed_proto *pp = NULL;
2494 struct parsed_op *po;
2495 struct label_ref *lr;
2497 ops[i].cc_scratch = magic;
2500 if (g_labels[i][0] != 0) {
2501 lr = &g_label_refs[i];
2502 for (; lr != NULL; lr = lr->next)
2503 scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2504 if (i > 0 && LAST_OP(i - 1))
2512 if (ops[i].cc_scratch == magic)
2514 ops[i].cc_scratch = magic;
2516 if (!(ops[i].flags & OPF_DATA))
2518 if (!is_opr_modified(opr, &ops[i]))
2520 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2521 // most probably trashed by some processing
2526 opr = &ops[i].operand[1];
2527 if (opr->type != OPT_REG)
2531 po = (i >= 0) ? &ops[i] : ops;
2534 // reached the top - can only be an arg-reg
2535 if (opr->type != OPT_REG)
2538 for (i = 0; i < g_func_pp->argc; i++) {
2539 if (g_func_pp->arg[i].reg == NULL)
2541 if (IS(opr->name, g_func_pp->arg[i].reg))
2544 if (i == g_func_pp->argc)
2546 pp = g_func_pp->arg[i].fptr;
2548 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2549 i + 1, g_func_pp->arg[i].reg);
2550 check_func_pp(po, pp, "icall reg-arg");
2553 pp = try_recover_pp(po, opr, NULL);
2555 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2556 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2557 || (*pp_found)->is_stdcall != pp->is_stdcall
2558 || (*pp_found)->is_fptr != pp->is_fptr
2559 || (*pp_found)->argc != pp->argc
2560 || (*pp_found)->argc_reg != pp->argc_reg
2561 || (*pp_found)->argc_stack != pp->argc_stack)
2563 ferr(po, "icall: parsed_proto mismatch\n");
2571 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2574 const struct parsed_proto *pp = NULL;
2575 int search_advice = 0;
2579 switch (ops[i].operand[0].type) {
2583 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2588 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2596 static int try_resolve_const(int i, const struct parsed_opr *opr,
2597 int magic, unsigned int *val)
2599 struct label_ref *lr;
2602 ops[i].cc_scratch = magic;
2605 if (g_labels[i][0] != 0) {
2606 lr = &g_label_refs[i];
2607 for (; lr != NULL; lr = lr->next)
2608 ret |= try_resolve_const(lr->i, opr, magic, val);
2609 if (i > 0 && LAST_OP(i - 1))
2617 if (ops[i].cc_scratch == magic)
2619 ops[i].cc_scratch = magic;
2621 if (!(ops[i].flags & OPF_DATA))
2623 if (!is_opr_modified(opr, &ops[i]))
2625 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
2628 *val = ops[i].operand[1].val;
2633 static int collect_call_args_r(struct parsed_op *po, int i,
2634 struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2635 int magic, int need_op_saving, int may_reuse)
2637 struct parsed_proto *pp_tmp;
2638 struct label_ref *lr;
2639 int need_to_save_current;
2644 ferr(po, "dead label encountered\n");
2648 for (; arg < pp->argc; arg++)
2649 if (pp->arg[arg].reg == NULL)
2651 magic = (magic & 0xffffff) | (arg << 24);
2653 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2655 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2656 if (ops[j].cc_scratch != magic) {
2657 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2661 // ok: have already been here
2664 ops[j].cc_scratch = magic;
2666 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2667 lr = &g_label_refs[j];
2668 if (lr->next != NULL)
2670 for (; lr->next; lr = lr->next) {
2671 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2673 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2674 arg, magic, need_op_saving, may_reuse);
2679 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2681 if (j > 0 && LAST_OP(j - 1)) {
2682 // follow last branch in reverse
2687 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2688 arg, magic, need_op_saving, may_reuse);
2694 if (ops[j].op == OP_CALL)
2696 if (pp->is_unresolved)
2699 pp_tmp = ops[j].datap;
2701 ferr(po, "arg collect hit unparsed call '%s'\n",
2702 ops[j].operand[0].name);
2703 if (may_reuse && pp_tmp->argc_stack > 0)
2704 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2705 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2707 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2708 if (pp->is_unresolved)
2711 ferr(po, "arg collect %d/%d hit esp adjust\n",
2714 else if (ops[j].op == OP_POP) {
2715 if (pp->is_unresolved)
2718 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2720 else if (ops[j].flags & OPF_CJMP)
2722 if (pp->is_unresolved)
2727 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2729 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2732 pp->arg[arg].datap = &ops[j];
2733 need_to_save_current = 0;
2734 if (!need_op_saving) {
2735 ret = scan_for_mod(&ops[j], j + 1, i, 1);
2736 need_to_save_current = (ret >= 0);
2738 if (need_op_saving || need_to_save_current) {
2739 // mark this push as one that needs operand saving
2740 ops[j].flags &= ~OPF_RMD;
2741 if (ops[j].argnum == 0) {
2742 ops[j].argnum = arg + 1;
2743 *save_arg_vars |= 1 << arg;
2745 else if (ops[j].argnum < arg + 1)
2746 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2747 ops[j].argnum, arg + 1, pp->name);
2749 else if (ops[j].argnum == 0)
2750 ops[j].flags |= OPF_RMD;
2752 // some PUSHes are reused by different calls on other branches,
2753 // but that can't happen if we didn't branch, so they
2754 // can be removed from future searches (handles nested calls)
2756 ops[j].flags |= OPF_FARG;
2758 ops[j].flags &= ~OPF_RSAVE;
2761 if (!pp->is_unresolved) {
2763 for (; arg < pp->argc; arg++)
2764 if (pp->arg[arg].reg == NULL)
2767 magic = (magic & 0xffffff) | (arg << 24);
2769 // tracking reg usage
2770 if (ops[j].operand[0].type == OPT_REG)
2771 *regmask |= 1 << ops[j].operand[0].reg;
2775 if (arg < pp->argc) {
2776 ferr(po, "arg collect failed for '%s': %d/%d\n",
2777 pp->name, arg, pp->argc);
2784 static int collect_call_args(struct parsed_op *po, int i,
2785 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2791 ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2796 if (pp->is_unresolved) {
2798 pp->argc_stack += ret;
2799 for (a = 0; a < pp->argc; a++)
2800 if (pp->arg[a].type.name == NULL)
2801 pp->arg[a].type.name = strdup("int");
2807 // early check for tail call or branch back
2808 static int is_like_tailjmp(int j)
2810 if (!(ops[j].flags & OPF_JMP))
2813 if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2814 // probably local branch back..
2816 if (ops[j].op == OP_CALL)
2817 // probably noreturn call..
2823 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2827 for (i = 0; i < pp->argc; i++)
2828 if (pp->arg[i].reg == NULL)
2832 memmove(&pp->arg[i + 1], &pp->arg[i],
2833 sizeof(pp->arg[0]) * pp->argc_stack);
2834 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2835 pp->arg[i].reg = strdup(reg);
2836 pp->arg[i].type.name = strdup("int");
2841 static void add_label_ref(struct label_ref *lr, int op_i)
2843 struct label_ref *lr_new;
2850 lr_new = calloc(1, sizeof(*lr_new));
2852 lr_new->next = lr->next;
2856 static void output_std_flags(FILE *fout, struct parsed_op *po,
2857 int *pfomask, const char *dst_opr_text)
2859 if (*pfomask & (1 << PFO_Z)) {
2860 fprintf(fout, "\n cond_z = (%s%s == 0);",
2861 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2862 *pfomask &= ~(1 << PFO_Z);
2864 if (*pfomask & (1 << PFO_S)) {
2865 fprintf(fout, "\n cond_s = (%s%s < 0);",
2866 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2867 *pfomask &= ~(1 << PFO_S);
2871 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
2874 if (pp->is_fastcall)
2875 fprintf(fout, "__fastcall ");
2876 else if (pp->is_stdcall && pp->argc_reg == 0)
2877 fprintf(fout, "__stdcall ");
2878 if (pp->is_noreturn || is_noreturn)
2879 fprintf(fout, "noreturn ");
2882 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2884 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2885 struct parsed_opr *last_arith_dst = NULL;
2886 char buf1[256], buf2[256], buf3[256], cast[64];
2887 const struct parsed_proto *pp_c;
2888 struct parsed_proto *pp, *pp_tmp;
2889 struct parsed_data *pd;
2890 const char *tmpname;
2891 enum parsed_flag_op pfo;
2893 int save_arg_vars = 0;
2895 int need_tmp_var = 0;
2898 int label_pending = 0;
2899 int regmask_save = 0;
2900 int regmask_arg = 0;
2901 int regmask_now = 0;
2902 int regmask_init = 0;
2914 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2915 g_stack_frame_used = 0;
2917 g_func_pp = proto_parse(fhdr, funcn, 0);
2918 if (g_func_pp == NULL)
2919 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2921 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2922 output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
2923 fprintf(fout, "%s(", g_func_pp->name);
2925 for (i = 0; i < g_func_pp->argc; i++) {
2927 fprintf(fout, ", ");
2928 if (g_func_pp->arg[i].fptr != NULL) {
2930 pp = g_func_pp->arg[i].fptr;
2931 fprintf(fout, "%s (", pp->ret_type.name);
2932 output_pp_attrs(fout, pp, 0);
2933 fprintf(fout, "*a%d)(", i + 1);
2934 for (j = 0; j < pp->argc; j++) {
2936 fprintf(fout, ", ");
2937 if (pp->arg[j].fptr)
2938 ferr(ops, "nested fptr\n");
2939 fprintf(fout, "%s", pp->arg[j].type.name);
2941 if (pp->is_vararg) {
2943 fprintf(fout, ", ");
2944 fprintf(fout, "...");
2948 else if (g_func_pp->arg[i].type.is_retreg) {
2949 fprintf(fout, "u32 *r_%s", g_func_pp->arg[i].reg);
2952 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2954 if (g_func_pp->arg[i].reg != NULL) {
2955 reg = char_array_i(regs_r32,
2956 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2958 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2959 regmask_arg |= 1 << reg;
2962 if (g_func_pp->is_vararg) {
2964 fprintf(fout, ", ");
2965 fprintf(fout, "...");
2968 fprintf(fout, ")\n{\n");
2971 // - handle ebp/esp frame, remove ops related to it
2972 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2973 && ops[1].op == OP_MOV
2974 && IS(opr_name(&ops[1], 0), "ebp")
2975 && IS(opr_name(&ops[1], 1), "esp"))
2980 ops[0].flags |= OPF_RMD;
2981 ops[1].flags |= OPF_RMD;
2984 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2985 g_stack_fsz = opr_const(&ops[2], 1);
2986 ops[2].flags |= OPF_RMD;
2990 // another way msvc builds stack frame..
2992 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2994 ops[i].flags |= OPF_RMD;
2998 // and another way..
2999 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3000 && ops[i].operand[1].type == OPT_CONST
3001 && ops[i + 1].op == OP_CALL
3002 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3004 g_stack_fsz += ops[i].operand[1].val;
3005 ops[i].flags |= OPF_RMD;
3007 ops[i].flags |= OPF_RMD;
3014 for (; i < opcnt; i++)
3015 if (ops[i].op == OP_RET)
3018 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3019 if (found && is_like_tailjmp(j))
3024 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3025 || ops[j].op == OP_LEAVE)
3027 ops[j].flags |= OPF_RMD;
3029 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3030 ferr(&ops[j], "'pop ebp' expected\n");
3032 if (g_stack_fsz != 0) {
3033 if (ops[j - 1].op == OP_MOV
3034 && IS(opr_name(&ops[j - 1], 0), "esp")
3035 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3037 ops[j - 1].flags |= OPF_RMD;
3039 else if (ops[j].op != OP_LEAVE
3040 && !(g_ida_func_attr & IDAFA_NORETURN))
3042 ferr(&ops[j - 1], "esp restore expected\n");
3045 if (ecx_push && ops[j - 2].op == OP_POP
3046 && IS(opr_name(&ops[j - 2], 0), "ecx"))
3048 ferr(&ops[j - 2], "unexpected ecx pop\n");
3054 } while (i < opcnt);
3057 for (i = 0; i < opcnt; i++) {
3058 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3060 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3061 && ops[i].operand[1].type == OPT_CONST)
3071 g_stack_fsz = ops[i].operand[1].val;
3072 ops[i].flags |= OPF_RMD;
3076 for (; i < opcnt; i++)
3077 if (ops[i].op == OP_RET)
3080 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3081 if (found && is_like_tailjmp(j))
3086 if (ops[j].op != OP_ADD
3087 || !IS(opr_name(&ops[j], 0), "esp")
3088 || ops[j].operand[1].type != OPT_CONST
3089 || ops[j].operand[1].val != g_stack_fsz)
3090 ferr(&ops[j], "'add esp' expected\n");
3091 ops[j].flags |= OPF_RMD;
3095 } while (i < opcnt);
3100 // - parse calls with labels
3101 // - resolve all branches
3102 for (i = 0; i < opcnt; i++)
3108 if (po->flags & OPF_RMD)
3111 if (po->op == OP_CALL) {
3114 if (po->operand[0].type == OPT_LABEL) {
3115 tmpname = opr_name(po, 0);
3116 if (IS_START(tmpname, "loc_"))
3117 ferr(po, "call to loc_*\n");
3118 pp_c = proto_parse(fhdr, tmpname, 0);
3120 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3122 pp = proto_clone(pp_c);
3123 my_assert_not(pp, NULL);
3125 else if (po->datap != NULL) {
3126 pp = calloc(1, sizeof(*pp));
3127 my_assert_not(pp, NULL);
3129 ret = parse_protostr(po->datap, pp);
3131 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3138 check_func_pp(po, pp, "fptr var call");
3139 if (pp->is_noreturn)
3140 po->flags |= OPF_TAIL;
3146 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3149 if (po->operand[0].type == OPT_REGMEM) {
3150 char *p = strchr(po->operand[0].name, '[');
3153 ret = p - po->operand[0].name;
3154 strncpy(buf1, po->operand[0].name, ret);
3157 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3158 if (IS(g_func_pd[j].label, buf1)) {
3164 //ferr(po, "label '%s' not parsed?\n", buf1);
3166 if (pd->type != OPT_OFFSET)
3167 ferr(po, "label '%s' with non-offset data?\n", buf1);
3169 // find all labels, link
3170 for (j = 0; j < pd->count; j++) {
3171 for (l = 0; l < opcnt; l++) {
3172 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
3173 add_label_ref(&g_label_refs[l], i);
3184 for (l = 0; l < opcnt; l++) {
3185 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
3186 add_label_ref(&g_label_refs[l], i);
3195 if (po->operand[0].type == OPT_LABEL)
3199 ferr(po, "unhandled branch\n");
3203 po->flags |= OPF_TAIL;
3204 if (i > 0 && ops[i - 1].op == OP_POP)
3205 po->flags |= OPF_ATAIL;
3210 // - remove dead labels
3212 for (i = 0; i < opcnt; i++)
3214 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3218 if (po->flags & OPF_RMD)
3221 if (po->op == OP_CALL)
3223 tmpname = opr_name(po, 0);
3228 pp_c = resolve_icall(i, opcnt, &l);
3230 pp = proto_clone(pp_c);
3231 my_assert_not(pp, NULL);
3233 // not resolved just to single func
3236 switch (po->operand[0].type) {
3238 // we resolved this call and no longer need the register
3239 po->regmask_src &= ~(1 << po->operand[0].reg);
3249 pp = calloc(1, sizeof(*pp));
3250 my_assert_not(pp, NULL);
3252 ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3254 if (!g_allow_regfunc)
3255 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3256 pp->is_unresolved = 1;
3260 if (j > ARRAY_SIZE(pp->arg))
3261 ferr(po, "esp adjust too large: %d\n", j);
3262 pp->ret_type.name = strdup("int");
3263 pp->argc = pp->argc_stack = j;
3264 for (arg = 0; arg < pp->argc; arg++)
3265 pp->arg[arg].type.name = strdup("int");
3270 // look for and make use of esp adjust
3272 if (!pp->is_stdcall && pp->argc_stack > 0)
3273 ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3275 if (pp->is_vararg) {
3276 if (j / 4 < pp->argc_stack)
3277 ferr(po, "esp adjust is too small: %x < %x\n",
3278 j, pp->argc_stack * 4);
3279 // modify pp to make it have varargs as normal args
3281 pp->argc += j / 4 - pp->argc_stack;
3282 for (; arg < pp->argc; arg++) {
3283 pp->arg[arg].type.name = strdup("int");
3286 if (pp->argc > ARRAY_SIZE(pp->arg))
3287 ferr(po, "too many args for '%s'\n", tmpname);
3289 if (pp->argc_stack != j / 4)
3290 ferr(po, "stack tracking failed for '%s': %x %x\n",
3291 tmpname, pp->argc_stack * 4, j);
3293 ops[ret].flags |= OPF_RMD;
3294 if (ops[ret].op == OP_POP && j > 4) {
3295 // deal with multi-pop stack adjust
3297 while (ops[ret].op == OP_POP && j > 0 && ret < opcnt) {
3298 ops[ret].flags |= OPF_RMD;
3304 // a bit of a hack, but deals with use of
3305 // single adj for multiple calls
3306 ops[ret].operand[1].val -= j;
3309 else if (pp->is_vararg)
3310 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3313 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3314 // since we know the args, collect them
3315 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3319 if (strstr(pp->ret_type.name, "int64"))
3325 // - find POPs for PUSHes, rm both
3326 // - scan for STD/CLD, propagate DF
3327 // - scan for all used registers
3328 // - find flag set ops for their users
3329 // - do unreselved calls
3330 // - declare indirect functions
3331 for (i = 0; i < opcnt; i++) {
3333 if (po->flags & OPF_RMD)
3336 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3337 reg = po->operand[0].reg;
3338 if (!(regmask & (1 << reg)))
3339 // not a reg save after all, rerun scan_for_pop
3340 po->flags &= ~OPF_RSAVE;
3342 regmask_save |= 1 << reg;
3345 if (po->op == OP_PUSH && po->argnum == 0
3346 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
3348 if (po->operand[0].type == OPT_REG)
3350 reg = po->operand[0].reg;
3352 ferr(po, "reg not set for push?\n");
3355 ret = scan_for_pop(i + 1, opcnt,
3356 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3359 ferr(po, "too much depth: %d\n", depth);
3361 po->flags |= OPF_RMD;
3362 scan_for_pop(i + 1, opcnt, po->operand[0].name,
3363 i + opcnt * 4, 0, &depth, 1);
3366 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3369 if (regmask & (1 << reg)) {
3370 if (regmask_save & (1 << reg))
3371 ferr(po, "%s already saved?\n", po->operand[0].name);
3375 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3379 else if (po->operand[0].type == OPT_CONST) {
3380 for (j = i + 1; j < opcnt; j++) {
3381 if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
3382 || ops[j].op == OP_PUSH || g_labels[i][0] != 0)
3387 if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
3389 po->flags |= OPF_RMD;
3397 if (po->op == OP_STD) {
3398 po->flags |= OPF_DF | OPF_RMD;
3399 scan_propagate_df(i + 1, opcnt);
3402 regmask_now = po->regmask_src | po->regmask_dst;
3403 if (regmask_now & (1 << xBP)) {
3404 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3405 if (po->regmask_dst & (1 << xBP))
3406 // compiler decided to drop bp frame and use ebp as scratch
3407 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
3409 regmask_now &= ~(1 << xBP);
3413 regmask |= regmask_now;
3415 if (po->flags & OPF_CC)
3417 int setters[16], cnt = 0, branched = 0;
3419 ret = scan_for_flag_set(i, i + opcnt * 6,
3420 &branched, setters, &cnt);
3421 if (ret < 0 || cnt <= 0)
3422 ferr(po, "unable to trace flag setter(s)\n");
3423 if (cnt > ARRAY_SIZE(setters))
3424 ferr(po, "too many flag setters\n");
3426 pfo = split_cond(po, po->op, &dummy);
3427 for (j = 0; j < cnt; j++)
3429 tmp_op = &ops[setters[j]]; // flag setter
3432 // to get nicer code, we try to delay test and cmp;
3433 // if we can't because of operand modification, or if we
3434 // have arith op, or branch, make it calculate flags explicitly
3435 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
3437 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3440 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
3444 // see if we'll be able to handle based on op result
3445 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3446 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3448 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3451 if (tmp_op->op == OP_ADD && pfo == PFO_C)
3455 tmp_op->pfomask |= pfomask;
3456 cond_vars |= pfomask;
3458 // note: may overwrite, currently not a problem
3462 if (po->op == OP_RCL || po->op == OP_RCR
3463 || po->op == OP_ADC || po->op == OP_SBB)
3464 cond_vars |= 1 << PFO_C;
3466 else if (po->op == OP_CMPS || po->op == OP_SCAS) {
3467 cond_vars |= 1 << PFO_Z;
3469 else if (po->op == OP_MUL
3470 || (po->op == OP_IMUL && po->operand_cnt == 1))
3474 else if (po->op == OP_CALL) {
3477 ferr(po, "NULL pp\n");
3479 if (pp->is_unresolved) {
3480 int regmask_stack = 0;
3481 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3484 // this is pretty rough guess:
3485 // see ecx and edx were pushed (and not their saved versions)
3486 for (arg = 0; arg < pp->argc; arg++) {
3487 if (pp->arg[arg].reg != NULL)
3490 tmp_op = pp->arg[arg].datap;
3492 ferr(po, "parsed_op missing for arg%d\n", arg);
3493 if (tmp_op->argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3494 regmask_stack |= 1 << tmp_op->operand[0].reg;
3497 if (!((regmask_stack & (1 << xCX))
3498 && (regmask_stack & (1 << xDX))))
3500 if (pp->argc_stack != 0
3501 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3503 pp_insert_reg_arg(pp, "ecx");
3504 pp->is_fastcall = 1;
3505 regmask_init |= 1 << xCX;
3506 regmask |= 1 << xCX;
3508 if (pp->argc_stack != 0
3509 || ((regmask | regmask_arg) & (1 << xDX)))
3511 pp_insert_reg_arg(pp, "edx");
3512 regmask_init |= 1 << xDX;
3513 regmask |= 1 << xDX;
3517 // note: __cdecl doesn't fall into is_unresolved category
3518 if (pp->argc_stack > 0)
3522 for (arg = 0; arg < pp->argc; arg++) {
3523 if (pp->arg[arg].reg != NULL) {
3524 reg = char_array_i(regs_r32,
3525 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3527 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3528 if (!(regmask & (1 << reg))) {
3529 regmask_init |= 1 << reg;
3530 regmask |= 1 << reg;
3535 // declare indirect funcs
3536 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
3537 if (pp->name[0] != 0) {
3538 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3539 memcpy(pp->name, "i_", 2);
3541 // might be declared already
3543 for (j = 0; j < i; j++) {
3544 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].datap)) {
3545 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3555 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3557 fprintf(fout, " %s (", pp->ret_type.name);
3558 output_pp_attrs(fout, pp, 0);
3559 fprintf(fout, "*%s)(", pp->name);
3560 for (j = 0; j < pp->argc; j++) {
3562 fprintf(fout, ", ");
3563 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3565 fprintf(fout, ");\n");
3568 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3569 regmask |= 1 << xAX;
3570 else if (po->op == OP_DIV || po->op == OP_IDIV) {
3571 // 32bit division is common, look for it
3572 if (po->op == OP_DIV)
3573 ret = scan_for_reg_clear(i, xDX);
3575 ret = scan_for_cdq_edx(i);
3577 po->flags |= OPF_32BIT;
3581 else if (po->op == OP_CLD)
3582 po->flags |= OPF_RMD;
3584 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
3590 // - confirm regmask_save, it might have been reduced
3591 if (regmask_save != 0)
3594 for (i = 0; i < opcnt; i++) {
3596 if (po->flags & OPF_RMD)
3599 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3600 regmask_save |= 1 << po->operand[0].reg;
3605 // output LUTs/jumptables
3606 for (i = 0; i < g_func_pd_cnt; i++) {
3608 fprintf(fout, " static const ");
3609 if (pd->type == OPT_OFFSET) {
3610 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3612 for (j = 0; j < pd->count; j++) {
3614 fprintf(fout, ", ");
3615 fprintf(fout, "&&%s", pd->d[j].u.label);
3619 fprintf(fout, "%s %s[] =\n { ",
3620 lmod_type_u(ops, pd->lmod), pd->label);
3622 for (j = 0; j < pd->count; j++) {
3624 fprintf(fout, ", ");
3625 fprintf(fout, "%u", pd->d[j].u.val);
3628 fprintf(fout, " };\n");
3632 // declare stack frame, va_arg
3634 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3635 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3639 if (g_func_pp->is_userstack) {
3640 fprintf(fout, " u32 fake_sf[1024];\n");
3641 fprintf(fout, " u32 *esp = &fake_sf[1024];\n");
3645 if (g_func_pp->is_vararg) {
3646 fprintf(fout, " va_list ap;\n");
3650 // declare arg-registers
3651 for (i = 0; i < g_func_pp->argc; i++) {
3652 if (g_func_pp->arg[i].reg != NULL) {
3653 reg = char_array_i(regs_r32,
3654 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3655 if (regmask & (1 << reg)) {
3656 if (g_func_pp->arg[i].type.is_retreg)
3657 fprintf(fout, " u32 %s = *r_%s;\n",
3658 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
3660 fprintf(fout, " u32 %s = (u32)a%d;\n",
3661 g_func_pp->arg[i].reg, i + 1);
3664 if (g_func_pp->arg[i].type.is_retreg)
3665 ferr(ops, "retreg '%s' is unused?\n",
3666 g_func_pp->arg[i].reg);
3667 fprintf(fout, " // %s = a%d; // unused\n",
3668 g_func_pp->arg[i].reg, i + 1);
3674 regmask_now = regmask & ~regmask_arg;
3675 regmask_now &= ~(1 << xSP);
3677 for (reg = 0; reg < 8; reg++) {
3678 if (regmask_now & (1 << reg)) {
3679 fprintf(fout, " u32 %s", regs_r32[reg]);
3680 if (regmask_init & (1 << reg))
3681 fprintf(fout, " = 0");
3682 fprintf(fout, ";\n");
3689 for (reg = 0; reg < 8; reg++) {
3690 if (regmask_save & (1 << reg)) {
3691 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3697 if (save_arg_vars) {
3698 for (reg = 0; reg < 32; reg++) {
3699 if (save_arg_vars & (1 << reg)) {
3700 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3707 for (i = 0; i < 8; i++) {
3708 if (cond_vars & (1 << i)) {
3709 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3716 fprintf(fout, " u32 tmp;\n");
3721 fprintf(fout, " u64 tmp64;\n");
3726 fprintf(fout, "\n");
3728 if (g_func_pp->is_vararg) {
3729 if (g_func_pp->argc_stack == 0)
3730 ferr(ops, "vararg func without stack args?\n");
3731 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3735 for (i = 0; i < opcnt; i++)
3737 if (g_labels[i][0] != 0) {
3738 fprintf(fout, "\n%s:\n", g_labels[i]);
3741 delayed_flag_op = NULL;
3742 last_arith_dst = NULL;
3746 if (po->flags & OPF_RMD)
3751 #define assert_operand_cnt(n_) \
3752 if (po->operand_cnt != n_) \
3753 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3755 // conditional/flag using op?
3756 if (po->flags & OPF_CC)
3761 pfo = split_cond(po, po->op, &is_inv);
3764 // we go through all this trouble to avoid using parsed_flag_op,
3765 // which makes generated code much nicer
3766 if (delayed_flag_op != NULL)
3768 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3771 else if (last_arith_dst != NULL
3772 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3773 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3776 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3777 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3778 last_arith_dst->lmod, buf3);
3781 else if (tmp_op != NULL) {
3782 // use preprocessed flag calc results
3783 if (!(tmp_op->pfomask & (1 << pfo)))
3784 ferr(po, "not prepared for pfo %d\n", pfo);
3786 // note: is_inv was not yet applied
3787 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3788 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3791 ferr(po, "all methods of finding comparison failed\n");
3794 if (po->flags & OPF_JMP) {
3795 fprintf(fout, " if %s\n", buf1);
3797 else if (po->op == OP_RCL || po->op == OP_RCR
3798 || po->op == OP_ADC || po->op == OP_SBB)
3801 fprintf(fout, " cond_%s = %s;\n",
3802 parsed_flag_op_names[pfo], buf1);
3804 else if (po->flags & OPF_DATA) { // SETcc
3805 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3806 fprintf(fout, " %s = %s;", buf2, buf1);
3809 ferr(po, "unhandled conditional op\n");
3813 pfomask = po->pfomask;
3815 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
3816 struct parsed_opr opr = {0,};
3819 opr.lmod = OPLM_DWORD;
3820 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
3822 if (ret != 1 || uval == 0) {
3823 // we need initial flags for ecx=0 case..
3824 if (i > 0 && ops[i - 1].op == OP_XOR
3825 && IS(ops[i - 1].operand[0].name,
3826 ops[i - 1].operand[1].name))
3828 fprintf(fout, " cond_z = ");
3829 if (pfomask & (1 << PFO_C))
3830 fprintf(fout, "cond_c = ");
3831 fprintf(fout, "0;\n");
3833 else if (last_arith_dst != NULL) {
3834 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3835 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
3836 last_arith_dst->lmod, buf3);
3837 fprintf(fout, " cond_z = %s;\n", buf1);
3840 ferr(po, "missing initial ZF\n");
3847 assert_operand_cnt(2);
3848 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3849 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3850 fprintf(fout, " %s = %s;", buf1,
3851 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3852 po->operand[0].is_ptr ? "(void *)" : "", 0));
3856 assert_operand_cnt(2);
3857 po->operand[1].lmod = OPLM_DWORD; // always
3858 fprintf(fout, " %s = %s;",
3859 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3860 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3865 assert_operand_cnt(2);
3866 fprintf(fout, " %s = %s;",
3867 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3868 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3872 assert_operand_cnt(2);
3873 switch (po->operand[1].lmod) {
3875 strcpy(buf3, "(s8)");
3878 strcpy(buf3, "(s16)");
3881 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3883 fprintf(fout, " %s = %s;",
3884 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3885 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3890 assert_operand_cnt(2);
3891 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3892 fprintf(fout, " tmp = %s;",
3893 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
3894 fprintf(fout, " %s = %s;",
3895 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3896 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], "", 0));
3897 fprintf(fout, " %s = tmp;",
3898 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]));
3899 snprintf(g_comment, sizeof(g_comment), "xchg");
3903 assert_operand_cnt(1);
3904 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3905 fprintf(fout, " %s = ~%s;", buf1, buf1);
3909 assert_operand_cnt(2);
3910 fprintf(fout, " %s = (s32)%s >> 31;",
3911 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3912 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3913 strcpy(g_comment, "cdq");
3917 assert_operand_cnt(3);
3918 if (po->flags & OPF_REP) {
3919 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
3920 (po->flags & OPF_DF) ? '-' : '+',
3921 lmod_bytes(po, po->operand[0].lmod));
3922 fprintf(fout, " %sedi = eax;",
3923 lmod_cast_u_ptr(po, po->operand[0].lmod));
3924 strcpy(g_comment, "rep stos");
3927 fprintf(fout, " %sedi = eax; edi %c= %d;",
3928 lmod_cast_u_ptr(po, po->operand[0].lmod),
3929 (po->flags & OPF_DF) ? '-' : '+',
3930 lmod_bytes(po, po->operand[0].lmod));
3931 strcpy(g_comment, "stos");
3936 assert_operand_cnt(3);
3937 j = lmod_bytes(po, po->operand[0].lmod);
3938 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3939 l = (po->flags & OPF_DF) ? '-' : '+';
3940 if (po->flags & OPF_REP) {
3942 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
3945 " %sedi = %sesi;", buf1, buf1);
3946 strcpy(g_comment, "rep movs");
3949 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
3950 buf1, buf1, l, j, l, j);
3951 strcpy(g_comment, "movs");
3956 // repe ~ repeat while ZF=1
3957 assert_operand_cnt(3);
3958 j = lmod_bytes(po, po->operand[0].lmod);
3959 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3960 l = (po->flags & OPF_DF) ? '-' : '+';
3961 if (po->flags & OPF_REP) {
3963 " for (; ecx != 0; ecx--) {\n");
3964 if (pfomask & (1 << PFO_C)) {
3967 " cond_c = %sedi < %sesi;\n", buf1, buf1);
3968 pfomask &= ~(1 << PFO_C);
3971 " cond_z = (%sedi == %sesi); edi %c= %d, esi %c= %d;\n",
3972 buf1, buf1, l, j, l, j);
3974 " if (cond_z %s 0) break;\n",
3975 (po->flags & OPF_REPZ) ? "==" : "!=");
3978 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3979 (po->flags & OPF_REPZ) ? "e" : "ne");
3983 " cond_z = (%sedi = %sesi); edi %c= %d; esi %c= %d;",
3984 buf1, buf1, l, j, l, j);
3985 strcpy(g_comment, "cmps");
3987 pfomask &= ~(1 << PFO_Z);
3988 last_arith_dst = NULL;
3989 delayed_flag_op = NULL;
3993 // only does ZF (for now)
3994 // repe ~ repeat while ZF=1
3995 assert_operand_cnt(3);
3996 j = lmod_bytes(po, po->operand[0].lmod);
3997 l = (po->flags & OPF_DF) ? '-' : '+';
3998 if (po->flags & OPF_REP) {
4000 " for (; ecx != 0; ecx--) {\n");
4002 " cond_z = (%seax == %sedi); edi %c= %d;\n",
4003 lmod_cast_u(po, po->operand[0].lmod),
4004 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4006 " if (cond_z %s 0) break;\n",
4007 (po->flags & OPF_REPZ) ? "==" : "!=");
4010 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4011 (po->flags & OPF_REPZ) ? "e" : "ne");
4014 fprintf(fout, " cond_z = (%seax = %sedi); edi %c= %d;",
4015 lmod_cast_u(po, po->operand[0].lmod),
4016 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4017 strcpy(g_comment, "scas");
4019 pfomask &= ~(1 << PFO_Z);
4020 last_arith_dst = NULL;
4021 delayed_flag_op = NULL;
4024 // arithmetic w/flags
4027 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4030 assert_operand_cnt(2);
4031 fprintf(fout, " %s %s= %s;",
4032 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4034 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4035 output_std_flags(fout, po, &pfomask, buf1);
4036 last_arith_dst = &po->operand[0];
4037 delayed_flag_op = NULL;
4042 assert_operand_cnt(2);
4043 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4044 if (pfomask & (1 << PFO_C)) {
4045 if (po->operand[1].type == OPT_CONST) {
4046 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4047 j = po->operand[1].val;
4050 if (po->op == OP_SHL)
4054 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
4058 ferr(po, "zero shift?\n");
4062 pfomask &= ~(1 << PFO_C);
4064 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
4065 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4066 output_std_flags(fout, po, &pfomask, buf1);
4067 last_arith_dst = &po->operand[0];
4068 delayed_flag_op = NULL;
4072 assert_operand_cnt(2);
4073 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4074 fprintf(fout, " %s = %s%s >> %s;", buf1,
4075 lmod_cast_s(po, po->operand[0].lmod), buf1,
4076 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4077 output_std_flags(fout, po, &pfomask, buf1);
4078 last_arith_dst = &po->operand[0];
4079 delayed_flag_op = NULL;
4084 assert_operand_cnt(2);
4085 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4086 if (po->operand[1].type == OPT_CONST) {
4087 j = po->operand[1].val;
4088 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4089 fprintf(fout, po->op == OP_ROL ?
4090 " %s = (%s << %d) | (%s >> %d);" :
4091 " %s = (%s >> %d) | (%s << %d);",
4092 buf1, buf1, j, buf1,
4093 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4097 output_std_flags(fout, po, &pfomask, buf1);
4098 last_arith_dst = &po->operand[0];
4099 delayed_flag_op = NULL;
4104 assert_operand_cnt(2);
4105 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4106 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4107 if (po->operand[1].type == OPT_CONST) {
4108 j = po->operand[1].val % l;
4110 ferr(po, "zero rotate\n");
4111 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
4112 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4113 if (po->op == OP_RCL) {
4115 " %s = (%s << %d) | (cond_c << %d)",
4116 buf1, buf1, j, j - 1);
4118 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4122 " %s = (%s >> %d) | (cond_c << %d)",
4123 buf1, buf1, j, l - j);
4125 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4127 fprintf(fout, ";\n");
4128 fprintf(fout, " cond_c = tmp;");
4132 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4133 output_std_flags(fout, po, &pfomask, buf1);
4134 last_arith_dst = &po->operand[0];
4135 delayed_flag_op = NULL;
4139 assert_operand_cnt(2);
4140 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4141 if (IS(opr_name(po, 0), opr_name(po, 1))) {
4142 // special case for XOR
4143 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4144 fprintf(fout, " cond_be = 1;\n");
4145 pfomask &= ~(1 << PFO_BE);
4147 fprintf(fout, " %s = 0;",
4148 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4149 last_arith_dst = &po->operand[0];
4150 delayed_flag_op = NULL;
4156 assert_operand_cnt(2);
4157 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4158 if (pfomask & (1 << PFO_C)) {
4159 fprintf(fout, " tmp64 = (u64)%s + %s;\n",
4160 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]),
4161 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4162 fprintf(fout, " cond_c = tmp64 >> 32;\n");
4163 fprintf(fout, " %s = (u32)tmp64;",
4164 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4165 strcat(g_comment, "add64");
4166 pfomask &= ~(1 << PFO_C);
4167 output_std_flags(fout, po, &pfomask, buf1);
4168 last_arith_dst = &po->operand[0];
4169 delayed_flag_op = NULL;
4175 assert_operand_cnt(2);
4176 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4177 if (pfomask & (1 << PFO_C)) {
4178 fprintf(fout, " cond_c = %s < %s;\n",
4179 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]),
4180 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4181 pfomask &= ~(1 << PFO_C);
4187 assert_operand_cnt(2);
4188 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4189 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4190 if (po->op == OP_SBB
4191 && IS(po->operand[0].name, po->operand[1].name))
4193 // avoid use of unitialized var
4194 fprintf(fout, " %s = -cond_c;", buf1);
4195 // carry remains what it was
4196 pfomask &= ~(1 << PFO_C);
4199 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
4200 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4202 output_std_flags(fout, po, &pfomask, buf1);
4203 last_arith_dst = &po->operand[0];
4204 delayed_flag_op = NULL;
4208 assert_operand_cnt(2);
4209 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4210 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4211 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4213 output_std_flags(fout, po, &pfomask, buf1);
4214 last_arith_dst = &po->operand[0];
4215 delayed_flag_op = NULL;
4216 strcat(g_comment, "bsf");
4221 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4222 if (po->operand[0].type == OPT_REG) {
4223 strcpy(buf2, po->op == OP_INC ? "++" : "--");
4224 fprintf(fout, " %s%s;", buf1, buf2);
4227 strcpy(buf2, po->op == OP_INC ? "+" : "-");
4228 fprintf(fout, " %s %s= 1;", buf1, buf2);
4230 output_std_flags(fout, po, &pfomask, buf1);
4231 last_arith_dst = &po->operand[0];
4232 delayed_flag_op = NULL;
4236 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4237 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
4238 fprintf(fout, " %s = -%s%s;", buf1,
4239 lmod_cast_s(po, po->operand[0].lmod), buf2);
4240 last_arith_dst = &po->operand[0];
4241 delayed_flag_op = NULL;
4242 if (pfomask & (1 << PFO_C)) {
4243 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
4244 pfomask &= ~(1 << PFO_C);
4249 if (po->operand_cnt == 2) {
4250 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4253 if (po->operand_cnt == 3)
4254 ferr(po, "TODO imul3\n");
4257 assert_operand_cnt(1);
4258 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
4259 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
4260 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
4261 fprintf(fout, " edx = tmp64 >> 32;\n");
4262 fprintf(fout, " eax = tmp64;");
4263 last_arith_dst = NULL;
4264 delayed_flag_op = NULL;
4269 assert_operand_cnt(1);
4270 if (po->operand[0].lmod != OPLM_DWORD)
4271 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
4273 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4274 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
4275 po->op == OP_IDIV));
4276 switch (po->operand[0].lmod) {
4278 if (po->flags & OPF_32BIT)
4279 snprintf(buf3, sizeof(buf3), "%seax", buf2);
4281 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
4282 snprintf(buf3, sizeof(buf3), "%stmp64",
4283 (po->op == OP_IDIV) ? "(s64)" : "");
4285 if (po->operand[0].type == OPT_REG
4286 && po->operand[0].reg == xDX)
4288 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
4289 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
4292 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
4293 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
4297 ferr(po, "unhandled division type\n");
4299 last_arith_dst = NULL;
4300 delayed_flag_op = NULL;
4305 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4307 for (j = 0; j < 8; j++) {
4308 if (pfomask & (1 << j)) {
4309 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
4310 fprintf(fout, " cond_%s = %s;",
4311 parsed_flag_op_names[j], buf1);
4318 last_arith_dst = NULL;
4319 delayed_flag_op = po;
4322 // note: we reuse OP_Jcc for SETcc, only flags differ
4323 case OP_JO ... OP_JG:
4324 if (po->flags & OPF_JMP)
4325 fprintf(fout, " goto %s;", po->operand[0].name);
4326 // else SETcc - should already be handled
4330 fprintf(fout, " if (ecx == 0)\n");
4331 fprintf(fout, " goto %s;", po->operand[0].name);
4332 strcat(g_comment, "jecxz");
4336 assert_operand_cnt(1);
4337 last_arith_dst = NULL;
4338 delayed_flag_op = NULL;
4340 if (po->operand[0].type == OPT_REGMEM) {
4341 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
4344 ferr(po, "parse failure for jmp '%s'\n",
4345 po->operand[0].name);
4346 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
4349 else if (po->operand[0].type != OPT_LABEL)
4350 ferr(po, "unhandled jmp type\n");
4352 fprintf(fout, " goto %s;", po->operand[0].name);
4356 assert_operand_cnt(1);
4358 my_assert_not(pp, NULL);
4360 if (pp->is_fptr && !pp->is_arg)
4361 fprintf(fout, " %s = %s;\n", pp->name,
4362 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
4366 if (strstr(pp->ret_type.name, "int64")) {
4367 if (po->flags & OPF_TAIL)
4368 ferr(po, "int64 and tail?\n");
4369 fprintf(fout, "tmp64 = ");
4371 else if (!IS(pp->ret_type.name, "void")) {
4372 if (po->flags & OPF_TAIL) {
4373 if (!IS(g_func_pp->ret_type.name, "void")) {
4374 fprintf(fout, "return ");
4375 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
4376 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
4379 else if (regmask & (1 << xAX)) {
4380 fprintf(fout, "eax = ");
4381 if (pp->ret_type.is_ptr)
4382 fprintf(fout, "(u32)");
4386 if (pp->name[0] == 0)
4387 ferr(po, "missing pp->name\n");
4388 fprintf(fout, "%s%s(", pp->name,
4389 pp->has_structarg ? "_sa" : "");
4391 if (po->flags & OPF_ATAIL) {
4392 if (pp->argc_stack != g_func_pp->argc_stack
4393 || (pp->argc_stack > 0
4394 && pp->is_stdcall != g_func_pp->is_stdcall))
4395 ferr(po, "incompatible tailcall\n");
4396 if (g_func_pp->has_retreg)
4397 ferr(po, "TODO: retreg+tailcall\n");
4399 for (arg = j = 0; arg < pp->argc; arg++) {
4401 fprintf(fout, ", ");
4404 if (pp->arg[arg].type.is_ptr)
4405 snprintf(cast, sizeof(cast), "(%s)",
4406 pp->arg[arg].type.name);
4408 if (pp->arg[arg].reg != NULL) {
4409 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4413 for (; j < g_func_pp->argc; j++)
4414 if (g_func_pp->arg[j].reg == NULL)
4416 fprintf(fout, "%sa%d", cast, j + 1);
4421 for (arg = 0; arg < pp->argc; arg++) {
4423 fprintf(fout, ", ");
4426 if (pp->arg[arg].type.is_ptr)
4427 snprintf(cast, sizeof(cast), "(%s)",
4428 pp->arg[arg].type.name);
4430 if (pp->arg[arg].reg != NULL) {
4431 if (pp->arg[arg].type.is_retreg)
4432 fprintf(fout, "&%s", pp->arg[arg].reg);
4434 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4439 tmp_op = pp->arg[arg].datap;
4441 ferr(po, "parsed_op missing for arg%d\n", arg);
4442 if (tmp_op->argnum != 0) {
4443 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
4447 out_src_opr(buf1, sizeof(buf1),
4448 tmp_op, &tmp_op->operand[0], cast, 0));
4452 fprintf(fout, ");");
4454 if (strstr(pp->ret_type.name, "int64")) {
4455 fprintf(fout, "\n");
4456 fprintf(fout, " edx = tmp64 >> 32;\n");
4457 fprintf(fout, " eax = tmp64;");
4460 if (pp->is_unresolved) {
4461 snprintf(buf3, sizeof(buf3), " unresoved %dreg",
4463 strcat(g_comment, buf3);
4466 if (po->flags & OPF_TAIL) {
4468 if (i == opcnt - 1 || pp->is_noreturn)
4470 else if (IS(pp->ret_type.name, "void"))
4472 else if (IS(g_func_pp->ret_type.name, "void"))
4474 // else already handled as 'return f()'
4477 if (!IS(g_func_pp->ret_type.name, "void")) {
4478 ferr(po, "int func -> void func tailcall?\n");
4481 fprintf(fout, "\n return;");
4482 strcat(g_comment, " ^ tailcall");
4486 strcat(g_comment, " tailcall");
4488 if (pp->is_noreturn)
4489 strcat(g_comment, " noreturn");
4490 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
4491 strcat(g_comment, " argframe");
4492 delayed_flag_op = NULL;
4493 last_arith_dst = NULL;
4497 if (g_func_pp->is_vararg)
4498 fprintf(fout, " va_end(ap);\n");
4499 if (g_func_pp->has_retreg) {
4500 for (arg = 0; arg < g_func_pp->argc; arg++)
4501 if (g_func_pp->arg[arg].type.is_retreg)
4502 fprintf(fout, " *r_%s = %s;\n",
4503 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
4506 if (IS(g_func_pp->ret_type.name, "void")) {
4507 if (i != opcnt - 1 || label_pending)
4508 fprintf(fout, " return;");
4510 else if (g_func_pp->ret_type.is_ptr) {
4511 fprintf(fout, " return (%s)eax;",
4512 g_func_pp->ret_type.name);
4514 else if (IS(g_func_pp->ret_type.name, "__int64"))
4515 fprintf(fout, " return ((u64)edx << 32) | eax;");
4517 fprintf(fout, " return eax;");
4519 last_arith_dst = NULL;
4520 delayed_flag_op = NULL;
4524 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4525 if (po->argnum != 0) {
4526 // special case - saved func arg
4527 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
4530 else if (po->flags & OPF_RSAVE) {
4531 fprintf(fout, " s_%s = %s;", buf1, buf1);
4534 else if (g_func_pp->is_userstack) {
4535 fprintf(fout, " *(--esp) = %s;", buf1);
4538 if (!(g_ida_func_attr & IDAFA_NORETURN))
4539 ferr(po, "stray push encountered\n");
4544 if (po->flags & OPF_RSAVE) {
4545 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4546 fprintf(fout, " %s = s_%s;", buf1, buf1);
4549 else if (po->datap != NULL) {
4552 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4553 fprintf(fout, " %s = %s;", buf1,
4554 out_src_opr(buf2, sizeof(buf2),
4555 tmp_op, &tmp_op->operand[0],
4556 po->operand[0].is_ptr ? "(void *)" : "", 0));
4559 else if (g_func_pp->is_userstack) {
4560 fprintf(fout, " %s = *esp++;",
4561 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4565 ferr(po, "stray pop encountered\n");
4574 ferr(po, "unhandled op type %d, flags %x\n",
4579 if (g_comment[0] != 0) {
4580 char *p = g_comment;
4581 while (my_isblank(*p))
4583 fprintf(fout, " // %s", p);
4588 fprintf(fout, "\n");
4590 // some sanity checking
4591 if (po->flags & OPF_REP) {
4592 if (po->op != OP_STOS && po->op != OP_MOVS
4593 && po->op != OP_CMPS && po->op != OP_SCAS)
4594 ferr(po, "unexpected rep\n");
4595 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
4596 && (po->op == OP_CMPS || po->op == OP_SCAS))
4597 ferr(po, "cmps/scas with plain rep\n");
4599 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
4600 && po->op != OP_CMPS && po->op != OP_SCAS)
4601 ferr(po, "unexpected repz/repnz\n");
4604 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4606 // see is delayed flag stuff is still valid
4607 if (delayed_flag_op != NULL && delayed_flag_op != po) {
4608 if (is_any_opr_modified(delayed_flag_op, po, 0))
4609 delayed_flag_op = NULL;
4612 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4613 if (is_opr_modified(last_arith_dst, po))
4614 last_arith_dst = NULL;
4620 if (g_stack_fsz && !g_stack_frame_used)
4621 fprintf(fout, " (void)sf;\n");
4623 fprintf(fout, "}\n\n");
4626 for (i = 0; i < opcnt; i++) {
4627 struct label_ref *lr, *lr_del;
4629 lr = g_label_refs[i].next;
4630 while (lr != NULL) {
4635 g_label_refs[i].i = -1;
4636 g_label_refs[i].next = NULL;
4638 if (ops[i].op == OP_CALL) {
4647 static void set_label(int i, const char *name)
4653 p = strchr(name, ':');
4657 if (len > sizeof(g_labels[0]) - 1)
4658 aerr("label '%s' too long: %d\n", name, len);
4659 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4660 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4661 memcpy(g_labels[i], name, len);
4662 g_labels[i][len] = 0;
4665 // '=' needs special treatment..
4666 static char *next_word_s(char *w, size_t wsize, char *s)
4672 for (i = 0; i < wsize - 1; i++) {
4673 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4679 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4680 printf("warning: '%s' truncated\n", w);
4691 static struct chunk_item *func_chunks;
4692 static int func_chunk_cnt;
4693 static int func_chunk_alloc;
4695 static void add_func_chunk(FILE *fasm, const char *name, int line)
4697 if (func_chunk_cnt >= func_chunk_alloc) {
4698 func_chunk_alloc *= 2;
4699 func_chunks = realloc(func_chunks,
4700 func_chunk_alloc * sizeof(func_chunks[0]));
4701 my_assert_not(func_chunks, NULL);
4703 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4704 func_chunks[func_chunk_cnt].name = strdup(name);
4705 func_chunks[func_chunk_cnt].asmln = line;
4709 static int cmp_chunks(const void *p1, const void *p2)
4711 const struct chunk_item *c1 = p1, *c2 = p2;
4712 return strcmp(c1->name, c2->name);
4715 static int cmpstringp(const void *p1, const void *p2)
4717 return strcmp(*(char * const *)p1, *(char * const *)p2);
4720 static void scan_ahead(FILE *fasm)
4730 oldpos = ftell(fasm);
4733 while (fgets(line, sizeof(line), fasm))
4744 // get rid of random tabs
4745 for (i = 0; line[i] != 0; i++)
4746 if (line[i] == '\t')
4749 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4752 next_word(words[0], sizeof(words[0]), p);
4753 if (words[0][0] == 0)
4754 aerr("missing name for func chunk?\n");
4756 add_func_chunk(fasm, words[0], asmln);
4761 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4762 words[wordc][0] = 0;
4763 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4764 if (*p == 0 || *p == ';') {
4770 if (wordc == 2 && IS(words[1], "ends"))
4774 fseek(fasm, oldpos, SEEK_SET);
4778 int main(int argc, char *argv[])
4780 FILE *fout, *fasm, *frlist;
4781 struct parsed_data *pd = NULL;
4783 char **rlist = NULL;
4785 int rlist_alloc = 0;
4786 int func_chunks_used = 0;
4787 int func_chunks_sorted = 0;
4788 int func_chunk_i = -1;
4789 long func_chunk_ret = 0;
4790 int func_chunk_ret_ln = 0;
4791 int scanned_ahead = 0;
4793 char words[20][256];
4794 enum opr_lenmod lmod;
4795 char *sctproto = NULL;
4797 int pending_endp = 0;
4799 int skip_warned = 0;
4811 for (arg = 1; arg < argc; arg++) {
4812 if (IS(argv[arg], "-v"))
4814 else if (IS(argv[arg], "-rf"))
4815 g_allow_regfunc = 1;
4816 else if (IS(argv[arg], "-m"))
4822 if (argc < arg + 3) {
4823 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdrf> [rlist]*\n",
4830 asmfn = argv[arg++];
4831 fasm = fopen(asmfn, "r");
4832 my_assert_not(fasm, NULL);
4834 hdrfn = argv[arg++];
4835 g_fhdr = fopen(hdrfn, "r");
4836 my_assert_not(g_fhdr, NULL);
4839 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4840 my_assert_not(rlist, NULL);
4841 // needs special handling..
4842 rlist[rlist_len++] = "__alloca_probe";
4844 func_chunk_alloc = 32;
4845 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4846 my_assert_not(func_chunks, NULL);
4848 memset(words, 0, sizeof(words));
4850 for (; arg < argc; arg++) {
4851 frlist = fopen(argv[arg], "r");
4852 my_assert_not(frlist, NULL);
4854 while (fgets(line, sizeof(line), frlist)) {
4856 if (*p == 0 || *p == ';')
4859 if (IS_START(p, "#if 0")
4860 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4864 else if (IS_START(p, "#endif"))
4871 p = next_word(words[0], sizeof(words[0]), p);
4872 if (words[0][0] == 0)
4875 if (rlist_len >= rlist_alloc) {
4876 rlist_alloc = rlist_alloc * 2 + 64;
4877 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4878 my_assert_not(rlist, NULL);
4880 rlist[rlist_len++] = strdup(words[0]);
4889 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4891 fout = fopen(argv[arg_out], "w");
4892 my_assert_not(fout, NULL);
4895 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4896 my_assert_not(g_eqs, NULL);
4898 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4899 g_label_refs[i].i = -1;
4900 g_label_refs[i].next = NULL;
4903 while (fgets(line, sizeof(line), fasm))
4912 // get rid of random tabs
4913 for (i = 0; line[i] != 0; i++)
4914 if (line[i] == '\t')
4919 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4920 goto do_pending_endp; // eww..
4922 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4924 static const char *attrs[] = {
4933 // parse IDA's attribute-list comment
4934 g_ida_func_attr = 0;
4937 for (; *p != 0; p = sskip(p)) {
4938 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4939 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4940 g_ida_func_attr |= 1 << i;
4941 p += strlen(attrs[i]);
4945 if (i == ARRAY_SIZE(attrs)) {
4946 anote("unparsed IDA attr: %s\n", p);
4949 if (IS(attrs[i], "fpd=")) {
4950 p = next_word(words[0], sizeof(words[0]), p);
4955 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4958 next_word(words[0], sizeof(words[0]), p);
4959 if (words[0][0] == 0)
4960 aerr("missing name for func chunk?\n");
4962 if (!scanned_ahead) {
4963 add_func_chunk(fasm, words[0], asmln);
4964 func_chunks_sorted = 0;
4967 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4969 if (func_chunk_i >= 0) {
4970 if (func_chunk_i < func_chunk_cnt
4971 && IS(func_chunks[func_chunk_i].name, g_func))
4973 // move on to next chunk
4974 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4976 aerr("seek failed for '%s' chunk #%d\n",
4977 g_func, func_chunk_i);
4978 asmln = func_chunks[func_chunk_i].asmln;
4982 if (func_chunk_ret == 0)
4983 aerr("no return from chunk?\n");
4984 fseek(fasm, func_chunk_ret, SEEK_SET);
4985 asmln = func_chunk_ret_ln;
4991 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4992 func_chunks_used = 1;
4994 if (IS_START(g_func, "sub_")) {
4995 unsigned long addr = strtoul(p, NULL, 16);
4996 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4997 if (addr > f_addr && !scanned_ahead) {
4998 anote("scan_ahead caused by '%s', addr %lx\n",
5002 func_chunks_sorted = 0;
5010 for (i = wordc; i < ARRAY_SIZE(words); i++)
5012 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
5013 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
5014 if (*p == 0 || *p == ';') {
5019 if (*p != 0 && *p != ';')
5020 aerr("too many words\n");
5022 // alow asm patches in comments
5024 if (IS_START(p, "; sctpatch:")) {
5026 if (*p == 0 || *p == ';')
5028 goto parse_words; // lame
5030 if (IS_START(p, "; sctproto:")) {
5031 sctproto = strdup(p + 11);
5037 awarn("wordc == 0?\n");
5041 // don't care about this:
5042 if (words[0][0] == '.'
5043 || IS(words[0], "include")
5044 || IS(words[0], "assume") || IS(words[1], "segment")
5045 || IS(words[0], "align"))
5051 // do delayed endp processing to collect switch jumptables
5053 if (in_func && !skip_func && wordc >= 2
5054 && ((words[0][0] == 'd' && words[0][2] == 0)
5055 || (words[1][0] == 'd' && words[1][2] == 0)))
5058 if (words[1][0] == 'd' && words[1][2] == 0) {
5060 if (g_func_pd_cnt >= pd_alloc) {
5061 pd_alloc = pd_alloc * 2 + 16;
5062 g_func_pd = realloc(g_func_pd,
5063 sizeof(g_func_pd[0]) * pd_alloc);
5064 my_assert_not(g_func_pd, NULL);
5066 pd = &g_func_pd[g_func_pd_cnt];
5068 memset(pd, 0, sizeof(*pd));
5069 strcpy(pd->label, words[0]);
5070 pd->type = OPT_CONST;
5071 pd->lmod = lmod_from_directive(words[1]);
5077 anote("skipping alignment byte?\n");
5080 lmod = lmod_from_directive(words[0]);
5081 if (lmod != pd->lmod)
5082 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
5085 if (pd->count_alloc < pd->count + wordc) {
5086 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
5087 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
5088 my_assert_not(pd->d, NULL);
5090 for (; i < wordc; i++) {
5091 if (IS(words[i], "offset")) {
5092 pd->type = OPT_OFFSET;
5095 p = strchr(words[i], ',');
5098 if (pd->type == OPT_OFFSET)
5099 pd->d[pd->count].u.label = strdup(words[i]);
5101 pd->d[pd->count].u.val = parse_number(words[i]);
5102 pd->d[pd->count].bt_i = -1;
5108 if (in_func && !skip_func)
5109 gen_func(fout, g_fhdr, g_func, pi);
5113 g_ida_func_attr = 0;
5117 func_chunks_used = 0;
5120 memset(&ops, 0, pi * sizeof(ops[0]));
5121 memset(g_labels, 0, pi * sizeof(g_labels[0]));
5125 for (i = 0; i < g_func_pd_cnt; i++) {
5127 if (pd->type == OPT_OFFSET) {
5128 for (j = 0; j < pd->count; j++)
5129 free(pd->d[j].u.label);
5140 if (IS(words[1], "proc")) {
5142 aerr("proc '%s' while in_func '%s'?\n",
5145 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
5147 strcpy(g_func, words[0]);
5148 set_label(0, words[0]);
5153 if (IS(words[1], "endp"))
5156 aerr("endp '%s' while not in_func?\n", words[0]);
5157 if (!IS(g_func, words[0]))
5158 aerr("endp '%s' while in_func '%s'?\n",
5161 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
5162 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
5168 if (!skip_func && func_chunks_used) {
5169 // start processing chunks
5170 struct chunk_item *ci, key = { g_func, 0 };
5172 func_chunk_ret = ftell(fasm);
5173 func_chunk_ret_ln = asmln;
5174 if (!func_chunks_sorted) {
5175 qsort(func_chunks, func_chunk_cnt,
5176 sizeof(func_chunks[0]), cmp_chunks);
5177 func_chunks_sorted = 1;
5179 ci = bsearch(&key, func_chunks, func_chunk_cnt,
5180 sizeof(func_chunks[0]), cmp_chunks);
5182 aerr("'%s' needs chunks, but none found\n", g_func);
5183 func_chunk_i = ci - func_chunks;
5184 for (; func_chunk_i > 0; func_chunk_i--)
5185 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
5188 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5190 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
5191 asmln = func_chunks[func_chunk_i].asmln;
5199 if (wordc == 2 && IS(words[1], "ends")) {
5203 // scan for next text segment
5204 while (fgets(line, sizeof(line), fasm)) {
5207 if (*p == 0 || *p == ';')
5210 if (strstr(p, "segment para public 'CODE' use32"))
5217 p = strchr(words[0], ':');
5219 set_label(pi, words[0]);
5223 if (!in_func || skip_func) {
5224 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
5226 anote("skipping from '%s'\n", g_labels[pi]);
5229 g_labels[pi][0] = 0;
5233 if (wordc > 1 && IS(words[1], "="))
5236 aerr("unhandled equ, wc=%d\n", wordc);
5237 if (g_eqcnt >= eq_alloc) {
5239 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
5240 my_assert_not(g_eqs, NULL);
5243 len = strlen(words[0]);
5244 if (len > sizeof(g_eqs[0].name) - 1)
5245 aerr("equ name too long: %d\n", len);
5246 strcpy(g_eqs[g_eqcnt].name, words[0]);
5248 if (!IS(words[3], "ptr"))
5249 aerr("unhandled equ\n");
5250 if (IS(words[2], "dword"))
5251 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
5252 else if (IS(words[2], "word"))
5253 g_eqs[g_eqcnt].lmod = OPLM_WORD;
5254 else if (IS(words[2], "byte"))
5255 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
5257 aerr("bad lmod: '%s'\n", words[2]);
5259 g_eqs[g_eqcnt].offset = parse_number(words[4]);
5264 if (pi >= ARRAY_SIZE(ops))
5265 aerr("too many ops\n");
5267 parse_op(&ops[pi], words, wordc);
5269 if (sctproto != NULL) {
5270 if (ops[pi].op == OP_CALL)
5271 ops[pi].datap = sctproto;
5284 // vim:ts=2:shiftwidth=2:expandtab