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), /* branches, ret and call */
36 OPF_CC = (1 << 4), /* uses flags */
37 OPF_TAIL = (1 << 5), /* ret or tail call */
38 OPF_RSAVE = (1 << 6), /* push/pop is local reg save/load */
39 OPF_REP = (1 << 7), /* prefixed by rep */
40 OPF_REPZ = (1 << 8), /* rep is repe/repz */
41 OPF_REPNZ = (1 << 9), /* rep is repne/repnz */
42 OPF_FARG = (1 << 10), /* push collected as func arg (no reuse) */
43 OPF_EBP_S = (1 << 11), /* ebp used as scratch, not BP */
111 // must be sorted (larger len must be further in enum)
119 #define MAX_OPERANDS 3
123 enum opr_lenmod lmod;
124 unsigned int is_ptr:1; // pointer in C
125 unsigned int is_array:1; // array in C
126 unsigned int type_from_var:1; // .. in header, sometimes wrong
127 unsigned int size_mismatch:1; // type override differs from C
128 unsigned int size_lt:1; // type override is larger than C
136 struct parsed_opr operand[MAX_OPERANDS];
139 int regmask_src; // all referensed regs
141 int pfomask; // flagop: parsed_flag_op that can't be delayed
142 int argnum; // push: altered before call arg #
143 int cc_scratch; // scratch storage during analysis
144 int bt_i; // branch target for branches
145 struct parsed_data *btj;// branch targets for jumptables
150 // OP_CALL - ptr to parsed_proto
151 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
155 enum opr_lenmod lmod;
162 enum opr_lenmod lmod;
176 struct label_ref *next;
180 IDAFA_BP_FRAME = (1 << 0),
181 IDAFA_LIB_FUNC = (1 << 1),
182 IDAFA_STATIC = (1 << 2),
183 IDAFA_NORETURN = (1 << 3),
184 IDAFA_THUNK = (1 << 4),
185 IDAFA_FPD = (1 << 5),
190 static struct parsed_op ops[MAX_OPS];
191 static struct parsed_equ *g_eqs;
193 static char g_labels[MAX_OPS][32];
194 static struct label_ref g_label_refs[MAX_OPS];
195 static const struct parsed_proto *g_func_pp;
196 static struct parsed_data *g_func_pd;
197 static int g_func_pd_cnt;
198 static char g_func[256];
199 static char g_comment[256];
200 static int g_bp_frame;
201 static int g_sp_frame;
202 static int g_stack_frame_used;
203 static int g_stack_fsz;
204 static int g_ida_func_attr;
205 #define ferr(op_, fmt, ...) do { \
206 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
207 dump_op(op_), ##__VA_ARGS__); \
211 #define fnote(op_, fmt, ...) \
212 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
213 dump_op(op_), ##__VA_ARGS__)
217 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
218 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
219 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
220 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
222 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
224 // possible basic comparison types (without inversion)
225 enum parsed_flag_op {
229 PFO_BE, // 6 CF=1||ZF=1
233 PFO_LE, // e ZF=1||SF!=OF
236 static const char *parsed_flag_op_names[] = {
237 "o", "c", "z", "be", "s", "p", "l", "le"
240 static int char_array_i(const char *array[], size_t len, const char *s)
244 for (i = 0; i < len; i++)
251 static void printf_number(char *buf, size_t buf_size,
252 unsigned long number)
254 // output in C-friendly form
255 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
258 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
262 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
264 *reg_lmod = OPLM_DWORD;
267 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
269 *reg_lmod = OPLM_WORD;
272 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
274 *reg_lmod = OPLM_BYTE;
277 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
279 *reg_lmod = OPLM_BYTE;
286 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
288 enum opr_lenmod lmod;
301 while (my_isblank(*s))
303 for (; my_issep(*s); d++, s++)
305 while (my_isblank(*s))
310 if (IS_START(s, "ds:"))
313 s = next_idt(w, sizeof(w), s);
318 reg = parse_reg(&lmod, w);
320 *regmask |= 1 << reg;
324 if ('0' <= w[0] && w[0] <= '9') {
325 number = parse_number(w);
326 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
330 // probably some label/identifier - pass
333 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
337 strcpy(name, cvtbuf);
342 static int is_reg_in_str(const char *s)
346 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
349 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
350 if (!strncmp(s, regs_r32[i], 3))
356 static const char *parse_stack_el(const char *name, char *extra_reg)
358 const char *p, *p2, *s;
365 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
367 if (extra_reg != NULL) {
368 strncpy(extra_reg, name, 3);
373 if (IS_START(p, "ebp+")) {
377 if (p2 != NULL && is_reg_in_str(p)) {
378 if (extra_reg != NULL) {
379 strncpy(extra_reg, p, p2 - p);
380 extra_reg[p2 - p] = 0;
385 if (!('0' <= *p && *p <= '9'))
391 if (!IS_START(name, "esp+"))
394 p = strchr(name + 4, '+');
396 // must be a number after esp+, already converted to 0x..
398 if (!('0' <= *s && *s <= '9')) {
399 aerr("%s nan?\n", __func__);
402 if (s[0] == '0' && s[1] == 'x')
405 if (len < sizeof(buf) - 1) {
406 strncpy(buf, s, len);
408 val = strtol(buf, &endp, 16);
409 if (val == 0 || *endp != 0) {
410 aerr("%s num parse fail for '%s'\n", __func__, buf);
419 if ('0' <= *p && *p <= '9')
425 static int guess_lmod_from_name(struct parsed_opr *opr)
427 if (!strncmp(opr->name, "dword_", 6)) {
428 opr->lmod = OPLM_DWORD;
431 if (!strncmp(opr->name, "word_", 5)) {
432 opr->lmod = OPLM_WORD;
435 if (!strncmp(opr->name, "byte_", 5)) {
436 opr->lmod = OPLM_BYTE;
442 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
443 const struct parsed_type *c_type)
445 static const char *dword_types[] = {
446 "int", "_DWORD", "UINT_PTR",
447 "DWORD", "HANDLE", "HWND", "HMODULE",
448 "WPARAM", "LPARAM", "UINT",
450 static const char *word_types[] = {
451 "uint16_t", "int16_t",
452 "unsigned __int16", "__int16",
454 static const char *byte_types[] = {
455 "uint8_t", "int8_t", "char",
456 "unsigned __int8", "__int8", "BYTE",
462 if (c_type->is_ptr) {
467 n = skip_type_mod(c_type->name);
469 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
470 if (IS(n, dword_types[i])) {
476 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
477 if (IS(n, word_types[i])) {
483 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
484 if (IS(n, byte_types[i])) {
493 static enum opr_type lmod_from_directive(const char *d)
497 else if (IS(d, "dw"))
499 else if (IS(d, "db"))
502 aerr("unhandled directive: '%s'\n", d);
506 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
512 *regmask |= 1 << reg;
515 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
518 static int parse_operand(struct parsed_opr *opr,
519 int *regmask, int *regmask_indirect,
520 char words[16][256], int wordc, int w, unsigned int op_flags)
522 const struct parsed_proto *pp;
523 enum opr_lenmod tmplmod;
524 unsigned long number;
531 aerr("parse_operand w %d, wordc %d\n", w, wordc);
535 for (i = w; i < wordc; i++) {
536 len = strlen(words[i]);
537 if (words[i][len - 1] == ',') {
538 words[i][len - 1] = 0;
544 wordc_in = wordc - w;
546 if ((op_flags & OPF_JMP) && wordc_in > 0
547 && !('0' <= words[w][0] && words[w][0] <= '9'))
549 const char *label = NULL;
551 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
552 && IS(words[w + 1], "ptr"))
553 label = words[w + 2];
554 else if (wordc_in == 2 && IS(words[w], "short"))
555 label = words[w + 1];
556 else if (wordc_in == 1
557 && strchr(words[w], '[') == NULL
558 && parse_reg(&tmplmod, words[w]) < 0)
562 opr->type = OPT_LABEL;
563 if (IS_START(label, "ds:"))
565 strcpy(opr->name, label);
571 if (IS(words[w + 1], "ptr")) {
572 if (IS(words[w], "dword"))
573 opr->lmod = OPLM_DWORD;
574 else if (IS(words[w], "word"))
575 opr->lmod = OPLM_WORD;
576 else if (IS(words[w], "byte"))
577 opr->lmod = OPLM_BYTE;
579 aerr("type parsing failed\n");
581 wordc_in = wordc - w;
586 if (IS(words[w], "offset")) {
587 opr->type = OPT_OFFSET;
588 strcpy(opr->name, words[w + 1]);
591 if (IS(words[w], "(offset")) {
592 char *p = strchr(words[w + 1], ')');
594 aerr("parse of bracketed offset failed\n");
596 opr->type = OPT_OFFSET;
597 strcpy(opr->name, words[w + 1]);
603 aerr("parse_operand 1 word expected\n");
606 if (IS_START(tmp, "ds:"))
608 strcpy(opr->name, tmp);
610 if (words[w][0] == '[') {
611 opr->type = OPT_REGMEM;
612 ret = sscanf(words[w], "[%[^]]]", opr->name);
614 aerr("[] parse failure\n");
616 parse_indmode(opr->name, regmask_indirect, 1);
617 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
619 struct parsed_equ *eq =
620 equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
622 opr->lmod = eq->lmod;
626 else if (strchr(words[w], '[')) {
628 opr->type = OPT_REGMEM;
629 if (opr->lmod == OPLM_UNSPEC)
630 guess_lmod_from_name(opr);
631 parse_indmode(strchr(words[w], '['), regmask_indirect, 0);
634 else if (('0' <= words[w][0] && words[w][0] <= '9')
635 || words[w][0] == '-')
637 number = parse_number(words[w]);
638 opr->type = OPT_CONST;
640 printf_number(opr->name, sizeof(opr->name), number);
644 ret = parse_reg(&tmplmod, opr->name);
646 setup_reg_opr(opr, ret, tmplmod, regmask);
650 // most likely var in data segment
651 opr->type = OPT_LABEL;
653 pp = proto_parse(g_fhdr, opr->name, 0);
655 if (pp->is_fptr || pp->is_func) {
656 opr->lmod = OPLM_DWORD;
660 tmplmod = OPLM_UNSPEC;
661 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
662 anote("unhandled C type '%s' for '%s'\n",
663 pp->type.name, opr->name);
665 if (opr->lmod == OPLM_UNSPEC) {
667 opr->type_from_var = 1;
669 else if (opr->lmod != tmplmod) {
670 opr->size_mismatch = 1;
671 if (tmplmod < opr->lmod)
674 opr->is_ptr = pp->type.is_ptr;
676 opr->is_array = pp->type.is_array;
679 if (opr->lmod == OPLM_UNSPEC)
680 guess_lmod_from_name(opr);
684 static const struct {
689 { "repe", OPF_REP|OPF_REPZ },
690 { "repz", OPF_REP|OPF_REPZ },
691 { "repne", OPF_REP|OPF_REPNZ },
692 { "repnz", OPF_REP|OPF_REPNZ },
695 static const struct {
702 { "nop", OP_NOP, 0, 0, 0 },
703 { "push", OP_PUSH, 1, 1, 0 },
704 { "pop", OP_POP, 1, 1, OPF_DATA },
705 { "mov" , OP_MOV, 2, 2, OPF_DATA },
706 { "lea", OP_LEA, 2, 2, OPF_DATA },
707 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
708 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
709 { "not", OP_NOT, 1, 1, OPF_DATA },
710 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
711 { "stosb",OP_STOS, 0, 0, OPF_DATA },
712 { "stosw",OP_STOS, 0, 0, OPF_DATA },
713 { "stosd",OP_STOS, 0, 0, OPF_DATA },
714 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
715 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
716 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
717 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
718 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
719 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
720 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
721 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
722 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
723 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
724 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
725 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
726 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
727 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
728 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
729 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
730 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
731 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
732 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
733 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
734 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
735 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
736 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
737 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
738 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
739 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
740 { "test", OP_TEST, 2, 2, OPF_FLAGS },
741 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
742 { "retn", OP_RET, 0, 1, OPF_TAIL },
743 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
744 { "jmp", OP_JMP, 1, 1, OPF_JMP },
745 { "jo", OP_JO, 1, 1, OPF_JMP|OPF_CC }, // 70 OF=1
746 { "jno", OP_JNO, 1, 1, OPF_JMP|OPF_CC }, // 71 OF=0
747 { "jc", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72 CF=1
748 { "jb", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72
749 { "jnc", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73 CF=0
750 { "jnb", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
751 { "jae", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
752 { "jz", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74 ZF=1
753 { "je", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74
754 { "jnz", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75 ZF=0
755 { "jne", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75
756 { "jbe", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76 CF=1 || ZF=1
757 { "jna", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76
758 { "ja", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77 CF=0 && ZF=0
759 { "jnbe", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77
760 { "js", OP_JS, 1, 1, OPF_JMP|OPF_CC }, // 78 SF=1
761 { "jns", OP_JNS, 1, 1, OPF_JMP|OPF_CC }, // 79 SF=0
762 { "jp", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a PF=1
763 { "jpe", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a
764 { "jnp", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b PF=0
765 { "jpo", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b
766 { "jl", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c SF!=OF
767 { "jnge", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c
768 { "jge", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d SF=OF
769 { "jnl", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d
770 { "jle", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e ZF=1 || SF!=OF
771 { "jng", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e
772 { "jg", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f ZF=0 && SF=OF
773 { "jnle", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f
774 { "seto", OP_JO, 1, 1, OPF_DATA|OPF_CC },
775 { "setno", OP_JNO, 1, 1, OPF_DATA|OPF_CC },
776 { "setc", OP_JC, 1, 1, OPF_DATA|OPF_CC },
777 { "setb", OP_JC, 1, 1, OPF_DATA|OPF_CC },
778 { "setnc", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
779 { "setae", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
780 { "setz", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
781 { "sete", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
782 { "setnz", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
783 { "setne", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
784 { "setbe", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
785 { "setna", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
786 { "seta", OP_JA, 1, 1, OPF_DATA|OPF_CC },
787 { "setnbe", OP_JA, 1, 1, OPF_DATA|OPF_CC },
788 { "sets", OP_JS, 1, 1, OPF_DATA|OPF_CC },
789 { "setns", OP_JNS, 1, 1, OPF_DATA|OPF_CC },
790 { "setp", OP_JP, 1, 1, OPF_DATA|OPF_CC },
791 { "setpe", OP_JP, 1, 1, OPF_DATA|OPF_CC },
792 { "setnp", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
793 { "setpo", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
794 { "setl", OP_JL, 1, 1, OPF_DATA|OPF_CC },
795 { "setnge", OP_JL, 1, 1, OPF_DATA|OPF_CC },
796 { "setge", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
797 { "setnl", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
798 { "setle", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
799 { "setng", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
800 { "setg", OP_JG, 1, 1, OPF_DATA|OPF_CC },
801 { "setnle", OP_JG, 1, 1, OPF_DATA|OPF_CC },
804 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
806 enum opr_lenmod lmod = OPLM_UNSPEC;
807 int prefix_flags = 0;
815 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
816 if (IS(words[w], pref_table[i].name)) {
817 prefix_flags = pref_table[i].flags;
824 aerr("lone prefix: '%s'\n", words[0]);
829 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
830 if (IS(words[w], op_table[i].name))
834 if (i == ARRAY_SIZE(op_table))
835 aerr("unhandled op: '%s'\n", words[0]);
838 op->op = op_table[i].op;
839 op->flags = op_table[i].flags | prefix_flags;
840 op->regmask_src = op->regmask_dst = 0;
842 for (opr = 0; opr < op_table[i].minopr; opr++) {
843 regmask = regmask_ind = 0;
844 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
845 words, wordc, w, op->flags);
847 if (opr == 0 && (op->flags & OPF_DATA))
848 op->regmask_dst = regmask;
849 // for now, mark dst as src too
850 op->regmask_src |= regmask | regmask_ind;
853 for (; w < wordc && opr < op_table[i].maxopr; opr++) {
854 w = parse_operand(&op->operand[opr],
855 &op->regmask_src, &op->regmask_src,
856 words, wordc, w, op->flags);
860 aerr("parse_op %s incomplete: %d/%d\n",
864 op->operand_cnt = opr;
865 if (!strncmp(op_table[i].name, "set", 3))
866 op->operand[0].lmod = OPLM_BYTE;
868 // ops with implicit argumets
872 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
873 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
877 if (op->operand_cnt != 0)
879 if (IS(words[op_w], "stosb"))
881 else if (IS(words[op_w], "stosw"))
883 else if (IS(words[op_w], "stosd"))
886 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
887 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
888 op->regmask_dst = op->regmask_src;
889 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
894 if (op->operand_cnt != 0)
896 if (words[op_w][4] == 'b')
898 else if (words[op_w][4] == 'w')
900 else if (words[op_w][4] == 'd')
903 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
904 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
905 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
906 op->regmask_dst = op->regmask_src;
910 if (op->operand_cnt != 1)
915 op->regmask_dst = (1 << xDX) | (1 << xAX);
916 op->regmask_src |= (1 << xAX);
917 if (op->operand[0].lmod == OPLM_UNSPEC)
918 op->operand[0].lmod = OPLM_DWORD;
923 // we could set up operands for edx:eax, but there is no real need to
924 // (see is_opr_modified())
925 regmask = (1 << xDX) | (1 << xAX);
926 op->regmask_dst = regmask;
927 op->regmask_src |= regmask;
928 if (op->operand[0].lmod == OPLM_UNSPEC)
929 op->operand[0].lmod = OPLM_DWORD;
937 if (op->operand[1].lmod == OPLM_UNSPEC)
938 op->operand[1].lmod = OPLM_BYTE;
942 if (op->operand[0].lmod == OPLM_UNSPEC
943 && (op->operand[0].type == OPT_CONST
944 || op->operand[0].type == OPT_OFFSET
945 || op->operand[0].type == OPT_LABEL))
946 op->operand[0].lmod = OPLM_DWORD;
951 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
952 && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
954 op->flags |= OPF_RMD;
959 if (op->operand[0].type == OPT_REG
960 && op->operand[1].type == OPT_REGMEM)
963 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
964 if (IS(buf, op->operand[1].name))
965 op->flags |= OPF_RMD;
974 static const char *op_name(enum op_op op)
978 for (i = 0; i < ARRAY_SIZE(op_table); i++)
979 if (op_table[i].op == op)
980 return op_table[i].name;
986 static const char *dump_op(struct parsed_op *po)
988 static char out[128];
995 snprintf(out, sizeof(out), "%s", op_name(po->op));
996 for (i = 0; i < po->operand_cnt; i++) {
1000 snprintf(p, sizeof(out) - (p - out),
1001 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1002 po->operand[i].name);
1008 static const char *lmod_type_u(struct parsed_op *po,
1009 enum opr_lenmod lmod)
1019 ferr(po, "invalid lmod: %d\n", lmod);
1020 return "(_invalid_)";
1024 static const char *lmod_cast_u(struct parsed_op *po,
1025 enum opr_lenmod lmod)
1035 ferr(po, "invalid lmod: %d\n", lmod);
1036 return "(_invalid_)";
1040 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1041 enum opr_lenmod lmod)
1051 ferr(po, "invalid lmod: %d\n", lmod);
1052 return "(_invalid_)";
1056 static const char *lmod_cast_s(struct parsed_op *po,
1057 enum opr_lenmod lmod)
1067 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1068 return "(_invalid_)";
1072 static const char *lmod_cast(struct parsed_op *po,
1073 enum opr_lenmod lmod, int is_signed)
1076 lmod_cast_s(po, lmod) :
1077 lmod_cast_u(po, lmod);
1080 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1090 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1095 static const char *opr_name(struct parsed_op *po, int opr_num)
1097 if (opr_num >= po->operand_cnt)
1098 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1099 return po->operand[opr_num].name;
1102 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1104 if (opr_num >= po->operand_cnt)
1105 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1106 if (po->operand[opr_num].type != OPT_CONST)
1107 ferr(po, "opr %d: const expected\n", opr_num);
1108 return po->operand[opr_num].val;
1111 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1113 if ((unsigned int)popr->reg >= MAX_REGS)
1114 ferr(po, "invalid reg: %d\n", popr->reg);
1115 return regs_r32[popr->reg];
1118 // cast1 is the "final" cast
1119 static const char *simplify_cast(const char *cast1, const char *cast2)
1121 static char buf[256];
1127 if (IS(cast1, cast2))
1129 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1131 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1133 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1135 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1137 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1140 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1144 static const char *simplify_cast_num(const char *cast, unsigned int val)
1146 if (IS(cast, "(u8)") && val < 0x100)
1148 if (IS(cast, "(s8)") && val < 0x80)
1150 if (IS(cast, "(u16)") && val < 0x10000)
1152 if (IS(cast, "(s16)") && val < 0x8000)
1154 if (IS(cast, "(s32)") && val < 0x80000000)
1160 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1169 namelen = strlen(name);
1171 p = strchr(name, '+');
1175 ferr(po, "equ parse failed for '%s'\n", name);
1177 if (IS_START(p, "0x"))
1179 *extra_offs = strtol(p, &endp, 16);
1181 ferr(po, "equ parse failed for '%s'\n", name);
1184 for (i = 0; i < g_eqcnt; i++)
1185 if (strncmp(g_eqs[i].name, name, namelen) == 0
1186 && g_eqs[i].name[namelen] == 0)
1190 ferr(po, "unresolved equ name: '%s'\n", name);
1197 static int is_stack_access(struct parsed_op *po,
1198 const struct parsed_opr *popr)
1200 return (parse_stack_el(popr->name, NULL)
1201 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1202 && IS_START(popr->name, "ebp")));
1205 static void parse_stack_access(struct parsed_op *po,
1206 const char *name, char *ofs_reg, int *offset_out,
1207 int *stack_ra_out, const char **bp_arg_out)
1209 const char *bp_arg = "";
1210 const char *p = NULL;
1211 struct parsed_equ *eq;
1218 if (IS_START(name, "ebp-")
1219 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1222 if (IS_START(p, "0x"))
1224 offset = strtoul(p, &endp, 16);
1228 ferr(po, "ebp- parse of '%s' failed\n", name);
1231 bp_arg = parse_stack_el(name, ofs_reg);
1232 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1233 eq = equ_find(po, bp_arg, &offset);
1235 ferr(po, "detected but missing eq\n");
1236 offset += eq->offset;
1239 if (!strncmp(name, "ebp", 3))
1242 if (ofs_reg[0] == 0 && stack_ra <= offset && offset < stack_ra + 4)
1243 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1245 *offset_out = offset;
1246 *stack_ra_out = stack_ra;
1248 *bp_arg_out = bp_arg;
1251 static void stack_frame_access(struct parsed_op *po,
1252 struct parsed_opr *popr, char *buf, size_t buf_size,
1253 const char *name, const char *cast, int is_src, int is_lea)
1255 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1256 const char *prefix = "";
1257 const char *bp_arg = NULL;
1258 char ofs_reg[16] = { 0, };
1259 int i, arg_i, arg_s;
1266 if (po->flags & OPF_EBP_S)
1267 ferr(po, "stack_frame_access while ebp is scratch\n");
1269 parse_stack_access(po, name, ofs_reg, &offset, &stack_ra, &bp_arg);
1271 if (offset > stack_ra)
1273 arg_i = (offset - stack_ra - 4) / 4;
1274 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1276 if (g_func_pp->is_vararg
1277 && arg_i == g_func_pp->argc_stack && is_lea)
1279 // should be va_list
1282 snprintf(buf, buf_size, "%sap", cast);
1285 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1286 offset, bp_arg, arg_i);
1288 if (ofs_reg[0] != 0)
1289 ferr(po, "offset reg on arg access?\n");
1291 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1292 if (g_func_pp->arg[i].reg != NULL)
1298 if (i == g_func_pp->argc)
1299 ferr(po, "arg %d not in prototype?\n", arg_i);
1301 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1307 ferr(po, "lea/byte to arg?\n");
1308 if (is_src && (offset & 3) == 0)
1309 snprintf(buf, buf_size, "%sa%d",
1310 simplify_cast(cast, "(u8)"), i + 1);
1312 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1313 cast, offset & 3, i + 1);
1318 ferr(po, "lea/word to arg?\n");
1323 ferr(po, "problematic arg store\n");
1324 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1325 simplify_cast(cast, "*(u16 *)"), i + 1);
1328 ferr(po, "unaligned arg word load\n");
1330 else if (is_src && (offset & 2) == 0)
1331 snprintf(buf, buf_size, "%sa%d",
1332 simplify_cast(cast, "(u16)"), i + 1);
1334 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1335 cast, (offset & 2) ? "HI" : "LO", i + 1);
1347 snprintf(buf, buf_size, "(u32)&a%d + %d",
1350 ferr(po, "unaligned arg store\n");
1352 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1353 snprintf(buf, buf_size, "%s(a%d >> %d)",
1354 prefix, i + 1, (offset & 3) * 8);
1358 snprintf(buf, buf_size, "%s%sa%d",
1359 prefix, is_lea ? "&" : "", i + 1);
1364 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1368 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1371 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1372 if (tmp_lmod != OPLM_DWORD
1373 && (unaligned || (!is_src && tmp_lmod < popr->lmod)))
1375 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1376 i + 1, offset, g_func_pp->arg[i].type.name);
1378 if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1379 ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1383 if (g_stack_fsz == 0)
1384 ferr(po, "stack var access without stackframe\n");
1385 g_stack_frame_used = 1;
1387 sf_ofs = g_stack_fsz + offset;
1388 lim = (ofs_reg[0] != 0) ? -4 : 0;
1389 if (offset > 0 || sf_ofs < lim)
1390 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1400 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1401 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1405 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1406 // known unaligned or possibly unaligned
1407 strcat(g_comment, " unaligned");
1409 prefix = "*(u16 *)&";
1410 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1411 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1414 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1418 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1419 // known unaligned or possibly unaligned
1420 strcat(g_comment, " unaligned");
1422 prefix = "*(u32 *)&";
1423 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1424 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1427 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1431 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1436 static void check_label_read_ref(struct parsed_op *po, const char *name)
1438 const struct parsed_proto *pp;
1440 pp = proto_parse(g_fhdr, name, 0);
1442 ferr(po, "proto_parse failed for ref '%s'\n", name);
1444 // currently we can take __cdecl and __stdcall
1445 if (pp->is_func && pp->argc_reg != 0)
1446 ferr(po, "reg-arg func reference?\n");
1449 static char *out_src_opr(char *buf, size_t buf_size,
1450 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1453 char tmp1[256], tmp2[256];
1461 switch (popr->type) {
1464 ferr(po, "lea from reg?\n");
1466 switch (popr->lmod) {
1468 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1471 snprintf(buf, buf_size, "%s%s",
1472 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1475 if (popr->name[1] == 'h') // XXX..
1476 snprintf(buf, buf_size, "%s(%s >> 8)",
1477 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1479 snprintf(buf, buf_size, "%s%s",
1480 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1483 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1488 if (is_stack_access(po, popr)) {
1489 stack_frame_access(po, popr, buf, buf_size,
1490 popr->name, cast, 1, is_lea);
1494 strcpy(expr, popr->name);
1495 if (strchr(expr, '[')) {
1496 // special case: '[' can only be left for label[reg] form
1497 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1499 ferr(po, "parse failure for '%s'\n", expr);
1500 if (tmp1[0] == '(') {
1501 // (off_4FFF50+3)[eax]
1502 p = strchr(tmp1 + 1, ')');
1503 if (p == NULL || p[1] != 0)
1504 ferr(po, "parse failure (2) for '%s'\n", expr);
1506 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1508 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1511 // XXX: do we need more parsing?
1513 snprintf(buf, buf_size, "%s", expr);
1517 snprintf(buf, buf_size, "%s(%s)",
1518 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1522 check_label_read_ref(po, popr->name);
1523 if (cast[0] == 0 && popr->is_ptr)
1527 snprintf(buf, buf_size, "(u32)&%s", popr->name);
1528 else if (popr->size_lt)
1529 snprintf(buf, buf_size, "%s%s%s%s", cast,
1530 lmod_cast_u_ptr(po, popr->lmod),
1531 popr->is_array ? "" : "&",
1534 snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1535 popr->is_array ? "[0]" : "");
1539 check_label_read_ref(po, popr->name);
1543 ferr(po, "lea an offset?\n");
1544 snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1549 ferr(po, "lea from const?\n");
1551 printf_number(tmp1, sizeof(tmp1), popr->val);
1552 snprintf(buf, buf_size, "%s%s",
1553 simplify_cast_num(cast, popr->val), tmp1);
1557 ferr(po, "invalid src type: %d\n", popr->type);
1563 // note: may set is_ptr (we find that out late for ebp frame..)
1564 static char *out_dst_opr(char *buf, size_t buf_size,
1565 struct parsed_op *po, struct parsed_opr *popr)
1567 switch (popr->type) {
1569 switch (popr->lmod) {
1571 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1575 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1579 if (popr->name[1] == 'h') // XXX..
1580 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1582 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1585 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1590 if (is_stack_access(po, popr)) {
1591 stack_frame_access(po, popr, buf, buf_size,
1592 popr->name, "", 0, 0);
1596 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1599 if (popr->size_mismatch)
1600 snprintf(buf, buf_size, "%s%s%s",
1601 lmod_cast_u_ptr(po, popr->lmod),
1602 popr->is_array ? "" : "&", popr->name);
1604 snprintf(buf, buf_size, "%s%s", popr->name,
1605 popr->is_array ? "[0]" : "");
1609 ferr(po, "invalid dst type: %d\n", popr->type);
1615 static char *out_src_opr_u32(char *buf, size_t buf_size,
1616 struct parsed_op *po, struct parsed_opr *popr)
1618 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1621 static enum parsed_flag_op split_cond(struct parsed_op *po,
1622 enum op_op op, int *is_inv)
1674 ferr(po, "split_cond: bad op %d\n", op);
1679 static void out_test_for_cc(char *buf, size_t buf_size,
1680 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1681 enum opr_lenmod lmod, const char *expr)
1683 const char *cast, *scast;
1685 cast = lmod_cast_u(po, lmod);
1686 scast = lmod_cast_s(po, lmod);
1690 case PFO_BE: // CF=1||ZF=1; CF=0
1691 snprintf(buf, buf_size, "(%s%s %s 0)",
1692 cast, expr, is_inv ? "!=" : "==");
1696 case PFO_L: // SF!=OF; OF=0
1697 snprintf(buf, buf_size, "(%s%s %s 0)",
1698 scast, expr, is_inv ? ">=" : "<");
1701 case PFO_LE: // ZF=1||SF!=OF; OF=0
1702 snprintf(buf, buf_size, "(%s%s %s 0)",
1703 scast, expr, is_inv ? ">" : "<=");
1707 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1711 static void out_cmp_for_cc(char *buf, size_t buf_size,
1712 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1714 const char *cast, *scast, *cast_use;
1715 char buf1[256], buf2[256];
1716 enum opr_lenmod lmod;
1718 if (po->operand[0].lmod != po->operand[1].lmod)
1719 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1720 po->operand[0].lmod, po->operand[1].lmod);
1721 lmod = po->operand[0].lmod;
1723 cast = lmod_cast_u(po, lmod);
1724 scast = lmod_cast_s(po, lmod);
1740 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1743 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1744 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1748 // note: must be unsigned compare
1749 snprintf(buf, buf_size, "(%s %s %s)",
1750 buf1, is_inv ? ">=" : "<", buf2);
1754 snprintf(buf, buf_size, "(%s %s %s)",
1755 buf1, is_inv ? "!=" : "==", buf2);
1759 // note: must be unsigned compare
1760 snprintf(buf, buf_size, "(%s %s %s)",
1761 buf1, is_inv ? ">" : "<=", buf2);
1764 if (is_inv && lmod == OPLM_BYTE
1765 && po->operand[1].type == OPT_CONST
1766 && po->operand[1].val == 0xff)
1768 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1769 snprintf(buf, buf_size, "(0)");
1773 // note: must be signed compare
1775 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1776 scast, buf1, buf2, is_inv ? ">=" : "<");
1780 snprintf(buf, buf_size, "(%s %s %s)",
1781 buf1, is_inv ? ">=" : "<", buf2);
1785 snprintf(buf, buf_size, "(%s %s %s)",
1786 buf1, is_inv ? ">" : "<=", buf2);
1794 static void out_cmp_test(char *buf, size_t buf_size,
1795 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1797 char buf1[256], buf2[256], buf3[256];
1799 if (po->op == OP_TEST) {
1800 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1801 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1804 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1805 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1806 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1808 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1809 po->operand[0].lmod, buf3);
1811 else if (po->op == OP_CMP) {
1812 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1815 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1818 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1819 struct parsed_opr *popr2)
1821 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1822 ferr(po, "missing lmod for both operands\n");
1824 if (popr1->lmod == OPLM_UNSPEC)
1825 popr1->lmod = popr2->lmod;
1826 else if (popr2->lmod == OPLM_UNSPEC)
1827 popr2->lmod = popr1->lmod;
1828 else if (popr1->lmod != popr2->lmod) {
1829 if (popr1->type_from_var) {
1830 popr1->size_mismatch = 1;
1831 if (popr1->lmod < popr2->lmod)
1833 popr1->lmod = popr2->lmod;
1835 else if (popr2->type_from_var) {
1836 popr2->size_mismatch = 1;
1837 if (popr2->lmod < popr1->lmod)
1839 popr2->lmod = popr1->lmod;
1842 ferr(po, "conflicting lmods: %d vs %d\n",
1843 popr1->lmod, popr2->lmod);
1847 static const char *op_to_c(struct parsed_op *po)
1871 ferr(po, "op_to_c was supplied with %d\n", po->op);
1875 static void op_set_clear_flag(struct parsed_op *po,
1876 enum op_flags flag_set, enum op_flags flag_clear)
1878 po->flags |= flag_set;
1879 po->flags &= ~flag_clear;
1882 // last op in stream - unconditional branch or ret
1883 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1884 || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1886 static int scan_for_pop(int i, int opcnt, const char *reg,
1887 int magic, int depth, int *maxdepth, int do_flags)
1889 struct parsed_op *po;
1893 for (; i < opcnt; i++) {
1895 if (po->cc_scratch == magic)
1896 break; // already checked
1897 po->cc_scratch = magic;
1899 if (po->flags & OPF_TAIL)
1900 return -1; // deadend
1902 if ((po->flags & OPF_RMD)
1903 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1906 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1907 if (po->btj != NULL) {
1909 for (j = 0; j < po->btj->count - 1; j++) {
1910 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1911 depth, maxdepth, do_flags);
1913 return ret; // dead end
1915 // follow last jumptable entry
1916 i = po->btj->d[j].bt_i - 1;
1921 ferr(po, "dead branch\n");
1925 if (po->flags & OPF_CC) {
1926 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1927 depth, maxdepth, do_flags);
1929 return ret; // dead end
1937 if ((po->op == OP_POP || po->op == OP_PUSH)
1938 && po->operand[0].type == OPT_REG
1939 && IS(po->operand[0].name, reg))
1941 if (po->op == OP_PUSH) {
1943 if (depth > *maxdepth)
1946 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1948 else if (depth == 0) {
1950 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1955 if (depth < 0) // should not happen
1956 ferr(po, "fail with depth\n");
1958 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1966 // scan for pop starting from 'ret' op (all paths)
1967 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
1973 for (; i < opcnt; i++) {
1974 if (!(ops[i].flags & OPF_TAIL))
1977 for (j = i - 1; j >= 0; j--) {
1978 if (ops[j].flags & OPF_RMD)
1980 if (ops[j].flags & OPF_JMP)
1983 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
1984 && IS(ops[j].operand[0].name, reg))
1987 ops[j].flags |= flag_set;
1991 if (g_labels[j][0] != 0)
1996 return found ? 0 : -1;
1999 // is operand 'opr' modified by parsed_op 'po'?
2000 static int is_opr_modified(const struct parsed_opr *opr,
2001 const struct parsed_op *po)
2003 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2006 if (opr->type == OPT_REG && po->operand[0].type == OPT_REG) {
2007 if (po->regmask_dst & (1 << opr->reg))
2013 return IS(po->operand[0].name, opr->name);
2016 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2017 static int is_any_opr_modified(const struct parsed_op *po_test,
2018 const struct parsed_op *po)
2022 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2025 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2028 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2031 // in reality, it can wreck any register, but in decompiled C
2032 // version it can only overwrite eax or edx:eax
2033 if (po->op == OP_CALL
2034 && ((po_test->regmask_src | po_test->regmask_dst)
2035 & ((1 << xAX)|(1 << xDX))))
2038 for (i = 0; i < po_test->operand_cnt; i++)
2039 if (IS(po_test->operand[i].name, po->operand[0].name))
2045 // scan for any po_test operand modification in range given
2046 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt)
2048 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2051 for (; i < opcnt; i++) {
2052 if (is_any_opr_modified(po_test, &ops[i]))
2059 // scan for po_test operand[0] modification in range given
2060 static int scan_for_mod_opr0(struct parsed_op *po_test,
2063 for (; i < opcnt; i++) {
2064 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2071 static int scan_for_flag_set(int i, int magic, int *branched,
2072 int *setters, int *setter_cnt)
2074 struct label_ref *lr;
2078 if (ops[i].cc_scratch == magic) {
2079 ferr(&ops[i], "%s looped\n", __func__);
2082 ops[i].cc_scratch = magic;
2084 if (g_labels[i][0] != 0) {
2087 lr = &g_label_refs[i];
2088 for (; lr->next; lr = lr->next) {
2089 ret = scan_for_flag_set(lr->i, magic,
2090 branched, setters, setter_cnt);
2095 if (i > 0 && LAST_OP(i - 1)) {
2099 ret = scan_for_flag_set(lr->i, magic,
2100 branched, setters, setter_cnt);
2106 if (ops[i].flags & OPF_FLAGS) {
2107 setters[*setter_cnt] = i;
2112 if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2119 // scan back for cdq, if anything modifies edx, fail
2120 static int scan_for_cdq_edx(int i)
2123 if (g_labels[i][0] != 0) {
2124 if (g_label_refs[i].next != NULL)
2126 if (i > 0 && LAST_OP(i - 1)) {
2127 i = g_label_refs[i].i;
2134 if (ops[i].op == OP_CDQ)
2137 if (ops[i].regmask_dst & (1 << xDX))
2139 if (g_labels[i][0] != 0)
2146 static int scan_for_reg_clear(int i, int reg)
2149 if (g_labels[i][0] != 0) {
2150 if (g_label_refs[i].next != NULL)
2152 if (i > 0 && LAST_OP(i - 1)) {
2153 i = g_label_refs[i].i;
2160 if (ops[i].op == OP_XOR
2161 && ops[i].operand[0].lmod == OPLM_DWORD
2162 && ops[i].operand[0].reg == ops[i].operand[1].reg
2163 && ops[i].operand[0].reg == reg)
2166 if (ops[i].regmask_dst & (1 << reg))
2168 if (g_labels[i][0] != 0)
2175 // scan for positive, constant esp adjust
2176 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2178 struct parsed_op *po;
2182 for (; i < opcnt; i++) {
2185 if (g_labels[i][0] != 0)
2188 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2189 if (po->operand[1].type != OPT_CONST)
2190 ferr(&ops[i], "non-const esp adjust?\n");
2191 *adj += po->operand[1].val;
2193 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2196 else if (po->op == OP_PUSH) {
2197 if (first_pop == -1)
2198 first_pop = -2; // none
2199 *adj -= lmod_bytes(po, po->operand[0].lmod);
2201 else if (po->op == OP_POP) {
2202 if (first_pop == -1)
2204 *adj += lmod_bytes(po, po->operand[0].lmod);
2206 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2207 if (po->op != OP_CALL)
2209 if (po->operand[0].type != OPT_LABEL)
2211 // TODO: should only allow combining __cdecl calls..
2215 if (*adj == 4 && first_pop >= 0 && ops[first_pop].op == OP_POP
2216 && ops[first_pop].operand[0].type == OPT_REG
2217 && ops[first_pop].operand[0].reg == xCX)
2219 // probably 'pop ecx' was used..
2226 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2228 struct parsed_op *po;
2232 ferr(ops, "%s: followed bad branch?\n", __func__);
2234 for (; i < opcnt; i++) {
2236 if (po->cc_scratch == magic)
2238 po->cc_scratch = magic;
2241 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2242 if (po->btj != NULL) {
2244 for (j = 0; j < po->btj->count; j++)
2245 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2249 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2250 if (!(po->flags & OPF_CC))
2253 if (po->flags & OPF_TAIL)
2258 static const struct parsed_proto *try_recover_pp(
2259 struct parsed_op *po, const struct parsed_opr *opr)
2261 const struct parsed_proto *pp = NULL;
2263 // maybe an arg of g_func?
2264 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2266 char ofs_reg[16] = { 0, };
2267 int arg, arg_s, arg_i;
2271 parse_stack_access(po, opr->name, ofs_reg,
2272 &offset, &stack_ra, NULL);
2273 if (ofs_reg[0] != 0)
2274 ferr(po, "offset reg on arg access?\n");
2275 if (offset <= stack_ra)
2276 ferr(po, "stack var call unhandled yet\n");
2278 arg_i = (offset - stack_ra - 4) / 4;
2279 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2280 if (g_func_pp->arg[arg].reg != NULL)
2286 if (arg == g_func_pp->argc)
2287 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2289 pp = g_func_pp->arg[arg].fptr;
2291 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2292 if (pp->argc_reg != 0)
2293 ferr(po, "icall sa: reg arg in arg-call unhandled yet\n");
2295 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2296 pp = proto_parse(g_fhdr, opr->name, 0);
2298 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2299 if (pp->argc_reg != 0)
2300 ferr(po, "arg-call unhandled yet for '%s'\n", opr->name);
2306 static void scan_for_call_type(int i, struct parsed_opr *opr,
2307 int magic, const struct parsed_proto **pp_found)
2309 const struct parsed_proto *pp = NULL;
2310 struct parsed_op *po;
2311 struct label_ref *lr;
2314 if (ops[i].cc_scratch == magic)
2316 ops[i].cc_scratch = magic;
2318 if (g_labels[i][0] != 0) {
2319 lr = &g_label_refs[i];
2320 for (; lr != NULL; lr = lr->next)
2321 scan_for_call_type(lr->i, opr, magic, pp_found);
2322 if (i > 0 && LAST_OP(i - 1))
2327 if (!(ops[i].flags & OPF_DATA))
2329 if (!is_opr_modified(opr, &ops[i]))
2331 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2332 // most probably trashed by some processing
2337 opr = &ops[i].operand[1];
2338 if (opr->type != OPT_REG)
2342 po = (i >= 0) ? &ops[i] : ops;
2345 // reached the top - can only be an arg-reg
2346 if (opr->type != OPT_REG)
2349 for (i = 0; i < g_func_pp->argc; i++) {
2350 if (g_func_pp->arg[i].reg == NULL)
2352 if (IS(opr->name, g_func_pp->arg[i].reg))
2355 if (i == g_func_pp->argc)
2357 pp = g_func_pp->arg[i].fptr;
2359 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2360 i + 1, g_func_pp->arg[i].reg);
2361 if (pp->argc_reg != 0)
2362 ferr(po, "icall: reg arg in arg-call unhandled yet\n");
2365 pp = try_recover_pp(po, opr);
2367 if (*pp_found != NULL && pp != NULL) {
2368 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2369 || (*pp_found)->is_stdcall != pp->is_stdcall
2370 || (*pp_found)->argc != pp->argc
2371 || (*pp_found)->argc_reg != pp->argc_reg
2372 || (*pp_found)->argc_stack != pp->argc_stack)
2374 ferr(po, "icall: parsed_proto mismatch\n");
2381 static const struct parsed_proto *resolve_call(int i, int opcnt)
2383 const struct parsed_proto *pp = NULL;
2385 switch (ops[i].operand[0].type) {
2389 pp = try_recover_pp(&ops[i], &ops[i].operand[0]);
2392 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp);
2399 static int collect_call_args(struct parsed_op *po, int i,
2400 struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2401 int magic, int need_op_saving, int may_reuse)
2403 struct parsed_proto *pp_tmp;
2404 struct label_ref *lr;
2405 int need_to_save_current;
2410 ferr(po, "dead label encountered\n");
2414 for (; arg < pp->argc; arg++)
2415 if (pp->arg[arg].reg == NULL)
2417 magic = (magic & 0xffffff) | (arg << 24);
2419 for (j = i; j >= 0 && arg < pp->argc; )
2421 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2422 if (ops[j].cc_scratch != magic) {
2423 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2427 // ok: have already been here
2430 ops[j].cc_scratch = magic;
2432 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2433 lr = &g_label_refs[j];
2434 if (lr->next != NULL)
2436 for (; lr->next; lr = lr->next) {
2437 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2439 ret = collect_call_args(po, lr->i, pp, regmask, save_arg_vars,
2440 arg, magic, need_op_saving, may_reuse);
2445 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2447 if (j > 0 && LAST_OP(j - 1)) {
2448 // follow last branch in reverse
2453 ret = collect_call_args(po, lr->i, pp, regmask, save_arg_vars,
2454 arg, magic, need_op_saving, may_reuse);
2460 if (ops[j].op == OP_CALL)
2462 pp_tmp = ops[j].datap;
2464 ferr(po, "arg collect hit unparsed call '%s'\n",
2465 ops[j].operand[0].name);
2466 if (may_reuse && pp_tmp->argc_stack > 0)
2467 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2468 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2470 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2471 ferr(po, "arg collect %d/%d hit esp adjust\n",
2474 else if (ops[j].op == OP_POP) {
2475 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2477 else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2481 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2483 pp->arg[arg].datap = &ops[j];
2484 need_to_save_current = 0;
2485 if (!need_op_saving) {
2486 ret = scan_for_mod(&ops[j], j + 1, i);
2487 need_to_save_current = (ret >= 0);
2489 if (need_op_saving || need_to_save_current) {
2490 // mark this push as one that needs operand saving
2491 ops[j].flags &= ~OPF_RMD;
2492 if (ops[j].argnum == 0) {
2493 ops[j].argnum = arg + 1;
2494 *save_arg_vars |= 1 << arg;
2496 else if (ops[j].argnum < arg + 1)
2497 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2498 ops[j].argnum, arg + 1, pp->name);
2500 else if (ops[j].argnum == 0)
2501 ops[j].flags |= OPF_RMD;
2503 // some PUSHes are reused by different calls on other branches,
2504 // but that can't happen if we didn't branch, so they
2505 // can be removed from future searches (handles nested calls)
2507 ops[j].flags |= OPF_FARG;
2510 for (arg++; arg < pp->argc; arg++)
2511 if (pp->arg[arg].reg == NULL)
2513 magic = (magic & 0xffffff) | (arg << 24);
2515 // tracking reg usage
2516 if (ops[j].operand[0].type == OPT_REG)
2517 *regmask |= 1 << ops[j].operand[0].reg;
2521 if (arg < pp->argc) {
2522 ferr(po, "arg collect failed for '%s': %d/%d\n",
2523 pp->name, arg, pp->argc);
2529 static void add_label_ref(struct label_ref *lr, int op_i)
2531 struct label_ref *lr_new;
2538 lr_new = calloc(1, sizeof(*lr_new));
2540 lr_new->next = lr->next;
2544 static void output_std_flags(FILE *fout, struct parsed_op *po,
2545 int *pfomask, const char *dst_opr_text)
2547 if (*pfomask & (1 << PFO_Z)) {
2548 fprintf(fout, "\n cond_z = (%s%s == 0);",
2549 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2550 *pfomask &= ~(1 << PFO_Z);
2552 if (*pfomask & (1 << PFO_S)) {
2553 fprintf(fout, "\n cond_s = (%s%s < 0);",
2554 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2555 *pfomask &= ~(1 << PFO_S);
2559 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2561 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2562 struct parsed_opr *last_arith_dst = NULL;
2563 char buf1[256], buf2[256], buf3[256], cast[64];
2564 const struct parsed_proto *pp_c;
2565 struct parsed_proto *pp, *pp_tmp;
2566 struct parsed_data *pd;
2567 const char *tmpname;
2568 enum parsed_flag_op pfo;
2569 int save_arg_vars = 0;
2570 int cmp_result_vars = 0;
2571 int need_mul_var = 0;
2573 int label_pending = 0;
2574 int regmask_save = 0;
2575 int regmask_arg = 0;
2576 int regmask_now = 0;
2588 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2589 g_stack_frame_used = 0;
2591 g_func_pp = proto_parse(fhdr, funcn, 0);
2592 if (g_func_pp == NULL)
2593 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2595 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2596 if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2597 fprintf(fout, "__stdcall ");
2598 if (g_ida_func_attr & IDAFA_NORETURN)
2599 fprintf(fout, "noreturn ");
2600 fprintf(fout, "%s(", funcn);
2602 for (i = 0; i < g_func_pp->argc; i++) {
2604 fprintf(fout, ", ");
2605 if (g_func_pp->arg[i].fptr != NULL) {
2607 pp = g_func_pp->arg[i].fptr;
2608 fprintf(fout, "%s (", pp->ret_type.name);
2609 if (pp->is_stdcall && pp->argc_reg == 0)
2610 fprintf(fout, "__stdcall ");
2611 fprintf(fout, "*a%d)(", i + 1);
2612 for (j = 0; j < pp->argc; j++) {
2614 fprintf(fout, ", ");
2615 if (pp->arg[j].fptr)
2616 ferr(ops, "nested fptr\n");
2617 fprintf(fout, "%s", pp->arg[j].type.name);
2622 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2625 if (g_func_pp->is_vararg) {
2627 fprintf(fout, ", ");
2628 fprintf(fout, "...");
2631 fprintf(fout, ")\n{\n");
2634 // - handle ebp/esp frame, remove ops related to it
2635 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2636 && ops[1].op == OP_MOV
2637 && IS(opr_name(&ops[1], 0), "ebp")
2638 && IS(opr_name(&ops[1], 1), "esp"))
2643 ops[0].flags |= OPF_RMD;
2644 ops[1].flags |= OPF_RMD;
2647 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2648 g_stack_fsz = opr_const(&ops[2], 1);
2649 ops[2].flags |= OPF_RMD;
2653 // another way msvc builds stack frame..
2655 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2657 ops[i].flags |= OPF_RMD;
2661 // and another way..
2662 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2663 && ops[i].operand[1].type == OPT_CONST
2664 && ops[i + 1].op == OP_CALL
2665 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2667 g_stack_fsz += ops[i].operand[1].val;
2668 ops[i].flags |= OPF_RMD;
2670 ops[i].flags |= OPF_RMD;
2677 for (; i < opcnt; i++)
2678 if (ops[i].op == OP_RET)
2680 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2683 if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2684 ops[i - 1].flags |= OPF_RMD;
2685 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2686 ferr(&ops[i - 1], "'pop ebp' expected\n");
2688 if (g_stack_fsz != 0) {
2689 if (ops[i - 2].op == OP_MOV
2690 && IS(opr_name(&ops[i - 2], 0), "esp")
2691 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2693 ops[i - 2].flags |= OPF_RMD;
2695 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2696 ferr(&ops[i - 2], "esp restore expected\n");
2698 if (ecx_push && ops[i - 3].op == OP_POP
2699 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2701 ferr(&ops[i - 3], "unexpected ecx pop\n");
2707 } while (i < opcnt);
2710 for (i = 0; i < opcnt; i++) {
2711 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2713 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2714 && ops[i].operand[1].type == OPT_CONST)
2723 g_stack_fsz = ops[i].operand[1].val;
2724 ops[i].flags |= OPF_RMD;
2728 for (; i < opcnt; i++)
2729 if (ops[i].op == OP_RET)
2731 if (ops[i - 1].op != OP_ADD
2732 || !IS(opr_name(&ops[i - 1], 0), "esp")
2733 || ops[i - 1].operand[1].type != OPT_CONST
2734 || ops[i - 1].operand[1].val != g_stack_fsz)
2735 ferr(&ops[i - 1], "'add esp' expected\n");
2736 ops[i - 1].flags |= OPF_RMD;
2739 } while (i < opcnt);
2744 // - parse calls with labels
2745 // - resolve all branches
2746 for (i = 0; i < opcnt; i++)
2752 if (po->flags & OPF_RMD)
2755 if (po->op == OP_CALL) {
2756 if (po->operand[0].type == OPT_LABEL) {
2757 tmpname = opr_name(po, 0);
2758 if (IS_START(tmpname, "loc_"))
2759 ferr(po, "call to loc_*\n");
2760 pp_c = proto_parse(fhdr, tmpname, 0);
2762 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2763 if (pp_c->is_fptr && pp_c->argc_reg != 0)
2764 ferr(po, "fptr call with reg arg\n");
2765 pp = proto_clone(pp_c);
2766 my_assert_not(pp, NULL);
2772 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2775 if (po->operand[0].type == OPT_REGMEM) {
2776 char *p = strchr(po->operand[0].name, '[');
2778 ferr(po, "unhandled indirect branch\n");
2779 ret = p - po->operand[0].name;
2780 strncpy(buf1, po->operand[0].name, ret);
2783 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2784 if (IS(g_func_pd[j].label, buf1)) {
2790 //ferr(po, "label '%s' not parsed?\n", buf1);
2792 if (pd->type != OPT_OFFSET)
2793 ferr(po, "label '%s' with non-offset data?\n", buf1);
2795 // find all labels, link
2796 for (j = 0; j < pd->count; j++) {
2797 for (l = 0; l < opcnt; l++) {
2798 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2799 add_label_ref(&g_label_refs[l], i);
2810 for (l = 0; l < opcnt; l++) {
2811 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2812 add_label_ref(&g_label_refs[l], i);
2821 if (po->operand[0].type == OPT_LABEL)
2825 ferr(po, "unhandled branch\n");
2829 po->flags |= OPF_TAIL;
2834 // - remove dead labels
2836 for (i = 0; i < opcnt; i++)
2838 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
2842 if (po->flags & OPF_RMD)
2845 if (po->op == OP_CALL)
2847 tmpname = opr_name(po, 0);
2852 pp_c = resolve_call(i, opcnt);
2854 pp = proto_clone(pp_c);
2856 pp = calloc(1, sizeof(*pp));
2857 my_assert_not(pp, NULL);
2858 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2860 ferr(po, "non-__cdecl indirect call unhandled yet\n");
2862 if (j > ARRAY_SIZE(pp->arg))
2863 ferr(po, "esp adjust too large?\n");
2864 pp->ret_type.name = strdup("int");
2865 pp->argc = pp->argc_stack = j;
2866 for (arg = 0; arg < pp->argc; arg++)
2867 pp->arg[arg].type.name = strdup("int");
2872 // look for and make use of esp adjust
2874 if (!pp->is_stdcall && pp->argc_stack > 0)
2875 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2877 if (pp->is_vararg) {
2878 if (j / 4 < pp->argc_stack)
2879 ferr(po, "esp adjust is too small: %x < %x\n",
2880 j, pp->argc_stack * 4);
2881 // modify pp to make it have varargs as normal args
2883 pp->argc += j / 4 - pp->argc_stack;
2884 for (; arg < pp->argc; arg++) {
2885 pp->arg[arg].type.name = strdup("int");
2888 if (pp->argc > ARRAY_SIZE(pp->arg))
2889 ferr(po, "too many args for '%s'\n", tmpname);
2891 if (pp->argc_stack != j / 4)
2892 ferr(po, "stack tracking failed for '%s': %x %x\n",
2893 tmpname, pp->argc_stack * 4, j);
2895 ops[ret].flags |= OPF_RMD;
2896 // a bit of a hack, but deals with use of
2897 // single adj for multiple calls
2898 ops[ret].operand[1].val -= j;
2900 else if (pp->is_vararg)
2901 ferr(po, "missing esp_adjust for vararg func '%s'\n",
2904 for (arg = 0; arg < pp->argc; arg++) {
2905 if (pp->arg[arg].reg != NULL) {
2906 reg = char_array_i(regs_r32,
2907 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
2909 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
2910 regmask |= 1 << reg;
2912 if (pp->arg[arg].fptr != NULL) {
2913 // can't call functions with non-__cdecl callbacks yet
2914 pp_tmp = pp->arg[arg].fptr;
2915 if (pp_tmp->argc_reg != 0)
2916 ferr(po, "'%s' has a callback with reg-args\n", tmpname);
2920 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
2921 0, i + opcnt * 2, 0, 0);
2923 if (strstr(pp->ret_type.name, "int64"))
2929 // - find POPs for PUSHes, rm both
2930 // - scan for all used registers
2931 // - find flag set ops for their users
2932 // - declare indirect functions
2933 for (i = 0; i < opcnt; i++) {
2935 if (po->flags & OPF_RMD)
2938 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
2939 reg = po->operand[0].reg;
2940 if (!(regmask & (1 << reg)))
2941 // not a reg save after all, rerun scan_for_pop
2942 po->flags &= ~OPF_RSAVE;
2944 regmask_save |= 1 << reg;
2947 if (po->op == OP_PUSH
2948 && po->argnum == 0 && !(po->flags & OPF_RSAVE)
2949 && po->operand[0].type == OPT_REG)
2951 reg = po->operand[0].reg;
2953 ferr(po, "reg not set for push?\n");
2956 ret = scan_for_pop(i + 1, opcnt,
2957 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
2960 ferr(po, "too much depth: %d\n", depth);
2962 po->flags |= OPF_RMD;
2963 scan_for_pop(i + 1, opcnt, po->operand[0].name,
2964 i + opcnt * 4, 0, &depth, 1);
2967 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
2970 if (regmask & (1 << reg)) {
2971 if (regmask_save & (1 << reg))
2972 ferr(po, "%s already saved?\n", po->operand[0].name);
2976 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
2981 regmask_now = po->regmask_src | po->regmask_dst;
2982 if (regmask_now & (1 << xBP)) {
2983 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
2984 if (po->regmask_dst & (1 << xBP))
2985 // compiler decided to drop bp frame and use ebp as scratch
2986 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
2988 regmask_now &= ~(1 << xBP);
2992 regmask |= regmask_now;
2994 if (po->flags & OPF_CC)
2996 int setters[16], cnt = 0, branched = 0;
2998 ret = scan_for_flag_set(i, i + opcnt * 6,
2999 &branched, setters, &cnt);
3000 if (ret < 0 || cnt <= 0)
3001 ferr(po, "unable to trace flag setter(s)\n");
3002 if (cnt > ARRAY_SIZE(setters))
3003 ferr(po, "too many flag setters\n");
3005 pfo = split_cond(po, po->op, &dummy);
3006 for (j = 0; j < cnt; j++)
3008 tmp_op = &ops[setters[j]]; // flag setter
3011 // to get nicer code, we try to delay test and cmp;
3012 // if we can't because of operand modification, or if we
3013 // have math op, or branch, make it calculate flags explicitly
3014 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
3015 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i) >= 0)
3018 else if (tmp_op->op == OP_CMPS) {
3019 pfomask = 1 << PFO_Z;
3022 // see if we'll be able to handle based on op result
3023 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3024 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3026 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3030 tmp_op->pfomask |= pfomask;
3031 cmp_result_vars |= pfomask;
3033 // note: may overwrite, currently not a problem
3037 if (po->op == OP_ADC || po->op == OP_SBB)
3038 cmp_result_vars |= 1 << PFO_C;
3040 else if (po->op == OP_MUL
3041 || (po->op == OP_IMUL && po->operand_cnt == 1))
3045 else if (po->op == OP_CALL && po->operand[0].type != OPT_LABEL) {
3047 my_assert_not(pp, NULL);
3048 fprintf(fout, " %s (", pp->ret_type.name);
3049 if (pp->is_stdcall && pp->argc_reg == 0)
3050 fprintf(fout, "__stdcall ");
3051 fprintf(fout, "*icall%d)(", i);
3052 for (j = 0; j < pp->argc; j++) {
3054 fprintf(fout, ", ");
3055 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3057 fprintf(fout, ");\n");
3059 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3060 regmask |= 1 << xAX;
3063 // output LUTs/jumptables
3064 for (i = 0; i < g_func_pd_cnt; i++) {
3066 fprintf(fout, " static const ");
3067 if (pd->type == OPT_OFFSET) {
3068 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3070 for (j = 0; j < pd->count; j++) {
3072 fprintf(fout, ", ");
3073 fprintf(fout, "&&%s", pd->d[j].u.label);
3077 fprintf(fout, "%s %s[] =\n { ",
3078 lmod_type_u(ops, pd->lmod), pd->label);
3080 for (j = 0; j < pd->count; j++) {
3082 fprintf(fout, ", ");
3083 fprintf(fout, "%u", pd->d[j].u.val);
3086 fprintf(fout, " };\n");
3089 // declare stack frame, va_arg
3091 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3092 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3094 if (g_func_pp->is_vararg)
3095 fprintf(fout, " va_list ap;\n");
3097 // declare arg-registers
3098 for (i = 0; i < g_func_pp->argc; i++) {
3099 if (g_func_pp->arg[i].reg != NULL) {
3100 reg = char_array_i(regs_r32,
3101 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3103 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
3105 regmask_arg |= 1 << reg;
3106 if (regmask & (1 << reg)) {
3107 fprintf(fout, " u32 %s = (u32)a%d;\n",
3108 g_func_pp->arg[i].reg, i + 1);
3111 fprintf(fout, " // %s = a%d; // unused\n",
3112 g_func_pp->arg[i].reg, i + 1);
3117 regmask_now = regmask & ~regmask_arg;
3118 regmask_now &= ~(1 << xSP);
3120 for (reg = 0; reg < 8; reg++) {
3121 if (regmask_now & (1 << reg)) {
3122 fprintf(fout, " u32 %s;\n", regs_r32[reg]);
3129 for (reg = 0; reg < 8; reg++) {
3130 if (regmask_save & (1 << reg)) {
3131 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3137 if (save_arg_vars) {
3138 for (reg = 0; reg < 32; reg++) {
3139 if (save_arg_vars & (1 << reg)) {
3140 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3146 if (cmp_result_vars) {
3147 for (i = 0; i < 8; i++) {
3148 if (cmp_result_vars & (1 << i)) {
3149 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3156 fprintf(fout, " u64 mul_tmp;\n");
3161 fprintf(fout, "\n");
3163 if (g_func_pp->is_vararg) {
3164 if (g_func_pp->argc_stack == 0)
3165 ferr(ops, "vararg func without stack args?\n");
3166 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3170 for (i = 0; i < opcnt; i++)
3172 if (g_labels[i][0] != 0) {
3173 fprintf(fout, "\n%s:\n", g_labels[i]);
3176 delayed_flag_op = NULL;
3177 last_arith_dst = NULL;
3181 if (po->flags & OPF_RMD)
3186 #define assert_operand_cnt(n_) \
3187 if (po->operand_cnt != n_) \
3188 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3190 // conditional/flag using op?
3191 if (po->flags & OPF_CC)
3196 pfo = split_cond(po, po->op, &is_inv);
3199 // we go through all this trouble to avoid using parsed_flag_op,
3200 // which makes generated code much nicer
3201 if (delayed_flag_op != NULL)
3203 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3206 else if (last_arith_dst != NULL
3207 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3208 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3211 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3212 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3213 last_arith_dst->lmod, buf3);
3216 else if (tmp_op != NULL) {
3217 // use preprocessed flag calc results
3218 if (!(tmp_op->pfomask & (1 << pfo)))
3219 ferr(po, "not prepared for pfo %d\n", pfo);
3221 // note: is_inv was not yet applied
3222 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3223 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3226 ferr(po, "all methods of finding comparison failed\n");
3229 if (po->flags & OPF_JMP) {
3230 fprintf(fout, " if %s\n", buf1);
3232 else if (po->op == OP_ADC || po->op == OP_SBB) {
3234 fprintf(fout, " cond_%s = %s;\n",
3235 parsed_flag_op_names[pfo], buf1);
3237 else if (po->flags & OPF_DATA) { // SETcc
3238 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3239 fprintf(fout, " %s = %s;", buf2, buf1);
3242 ferr(po, "unhandled conditional op\n");
3246 pfomask = po->pfomask;
3251 assert_operand_cnt(2);
3252 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3253 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3254 fprintf(fout, " %s = %s;", buf1,
3255 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3256 po->operand[0].is_ptr ? "(void *)" : "", 0));
3260 assert_operand_cnt(2);
3261 po->operand[1].lmod = OPLM_DWORD; // always
3262 fprintf(fout, " %s = %s;",
3263 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3264 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3269 assert_operand_cnt(2);
3270 fprintf(fout, " %s = %s;",
3271 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3272 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3276 assert_operand_cnt(2);
3277 switch (po->operand[1].lmod) {
3279 strcpy(buf3, "(s8)");
3282 strcpy(buf3, "(s16)");
3285 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3287 fprintf(fout, " %s = %s;",
3288 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3289 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3294 assert_operand_cnt(1);
3295 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3296 fprintf(fout, " %s = ~%s;", buf1, buf1);
3300 assert_operand_cnt(2);
3301 fprintf(fout, " %s = (s32)%s >> 31;",
3302 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3303 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3304 strcpy(g_comment, "cdq");
3309 assert_operand_cnt(3);
3310 if (po->flags & OPF_REP) {
3311 fprintf(fout, " for (; ecx != 0; ecx--, edi += %d)\n",
3312 lmod_bytes(po, po->operand[0].lmod));
3313 fprintf(fout, " %sedi = eax;",
3314 lmod_cast_u_ptr(po, po->operand[0].lmod));
3315 strcpy(g_comment, "rep stos");
3318 fprintf(fout, " %sedi = eax; edi += %d;",
3319 lmod_cast_u_ptr(po, po->operand[0].lmod),
3320 lmod_bytes(po, po->operand[0].lmod));
3321 strcpy(g_comment, "stos");
3327 assert_operand_cnt(3);
3328 j = lmod_bytes(po, po->operand[0].lmod);
3329 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3330 if (po->flags & OPF_REP) {
3332 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3335 " %sedi = %sesi;", buf1, buf1);
3336 strcpy(g_comment, "rep movs");
3339 fprintf(fout, " %sedi = %sesi; edi += %d; esi += %d;",
3341 strcpy(g_comment, "movs");
3347 // repe ~ repeat while ZF=1
3348 assert_operand_cnt(3);
3349 j = lmod_bytes(po, po->operand[0].lmod);
3350 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3351 if (po->flags & OPF_REP) {
3353 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3356 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3357 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3360 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3361 (po->flags & OPF_REPZ) ? "e" : "ne");
3365 " cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3367 strcpy(g_comment, "cmps");
3369 pfomask &= ~(1 << PFO_Z);
3370 last_arith_dst = NULL;
3371 delayed_flag_op = NULL;
3374 // arithmetic w/flags
3379 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3382 assert_operand_cnt(2);
3383 fprintf(fout, " %s %s= %s;",
3384 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3386 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3387 output_std_flags(fout, po, &pfomask, buf1);
3388 last_arith_dst = &po->operand[0];
3389 delayed_flag_op = NULL;
3394 assert_operand_cnt(2);
3395 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3396 if (pfomask & (1 << PFO_C)) {
3397 if (po->operand[1].type == OPT_CONST) {
3398 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3399 j = po->operand[1].val;
3402 if (po->op == OP_SHL)
3406 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3410 ferr(po, "zero shift?\n");
3414 pfomask &= ~(1 << PFO_C);
3416 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3417 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3418 output_std_flags(fout, po, &pfomask, buf1);
3419 last_arith_dst = &po->operand[0];
3420 delayed_flag_op = NULL;
3424 assert_operand_cnt(2);
3425 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3426 fprintf(fout, " %s = %s%s >> %s;", buf1,
3427 lmod_cast_s(po, po->operand[0].lmod), buf1,
3428 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3429 output_std_flags(fout, po, &pfomask, buf1);
3430 last_arith_dst = &po->operand[0];
3431 delayed_flag_op = NULL;
3436 assert_operand_cnt(2);
3437 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3438 if (po->operand[1].type == OPT_CONST) {
3439 j = po->operand[1].val;
3440 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3441 fprintf(fout, po->op == OP_ROL ?
3442 " %s = (%s << %d) | (%s >> %d);" :
3443 " %s = (%s >> %d) | (%s << %d);",
3444 buf1, buf1, j, buf1,
3445 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3449 output_std_flags(fout, po, &pfomask, buf1);
3450 last_arith_dst = &po->operand[0];
3451 delayed_flag_op = NULL;
3455 assert_operand_cnt(2);
3456 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3457 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3458 // special case for XOR
3459 fprintf(fout, " %s = 0;",
3460 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3461 last_arith_dst = &po->operand[0];
3462 delayed_flag_op = NULL;
3469 assert_operand_cnt(2);
3470 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3471 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3472 if (po->op == OP_SBB
3473 && IS(po->operand[0].name, po->operand[1].name))
3475 // avoid use of unitialized var
3476 fprintf(fout, " %s = -cond_c;", buf1);
3477 // carry remains what it was
3478 pfomask &= ~(1 << PFO_C);
3481 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3482 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3484 output_std_flags(fout, po, &pfomask, buf1);
3485 last_arith_dst = &po->operand[0];
3486 delayed_flag_op = NULL;
3491 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3492 if (po->operand[0].type == OPT_REG) {
3493 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3494 fprintf(fout, " %s%s;", buf1, buf2);
3497 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3498 fprintf(fout, " %s %s= 1;", buf1, buf2);
3500 output_std_flags(fout, po, &pfomask, buf1);
3501 last_arith_dst = &po->operand[0];
3502 delayed_flag_op = NULL;
3506 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3507 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3508 fprintf(fout, " %s = -%s%s;", buf1,
3509 lmod_cast_s(po, po->operand[0].lmod), buf2);
3510 last_arith_dst = &po->operand[0];
3511 delayed_flag_op = NULL;
3512 if (pfomask & (1 << PFO_C)) {
3513 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3514 pfomask &= ~(1 << PFO_C);
3519 if (po->operand_cnt == 2) {
3520 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3523 if (po->operand_cnt == 3)
3524 ferr(po, "TODO imul3\n");
3527 assert_operand_cnt(1);
3528 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3529 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3530 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3531 fprintf(fout, " edx = mul_tmp >> 32;\n");
3532 fprintf(fout, " eax = mul_tmp;");
3533 last_arith_dst = NULL;
3534 delayed_flag_op = NULL;
3539 assert_operand_cnt(1);
3540 if (po->operand[0].lmod != OPLM_DWORD)
3541 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3543 // 32bit division is common, look for it
3544 if (po->op == OP_DIV)
3545 ret = scan_for_reg_clear(i, xDX);
3547 ret = scan_for_cdq_edx(i);
3549 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3550 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3551 po->op == OP_IDIV));
3552 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3553 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3556 ferr(po, "TODO 64bit divident\n");
3557 last_arith_dst = NULL;
3558 delayed_flag_op = NULL;
3563 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3565 for (j = 0; j < 8; j++) {
3566 if (pfomask & (1 << j)) {
3567 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3568 fprintf(fout, " cond_%s = %s;",
3569 parsed_flag_op_names[j], buf1);
3576 last_arith_dst = NULL;
3577 delayed_flag_op = po;
3580 // note: we reuse OP_Jcc for SETcc, only flags differ
3581 case OP_JO ... OP_JG:
3582 if (po->flags & OPF_JMP)
3583 fprintf(fout, " goto %s;", po->operand[0].name);
3584 // else SETcc - should already be handled
3588 assert_operand_cnt(1);
3589 last_arith_dst = NULL;
3590 delayed_flag_op = NULL;
3592 if (po->operand[0].type == OPT_REGMEM) {
3593 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3596 ferr(po, "parse failure for jmp '%s'\n",
3597 po->operand[0].name);
3598 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
3601 else if (po->operand[0].type != OPT_LABEL)
3602 ferr(po, "unhandled jmp type\n");
3604 fprintf(fout, " goto %s;", po->operand[0].name);
3608 assert_operand_cnt(1);
3611 ferr(po, "NULL pp\n");
3613 if (po->operand[0].type != OPT_LABEL)
3614 fprintf(fout, " icall%d = %s;\n", i,
3615 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
3619 if (strstr(pp->ret_type.name, "int64")) {
3620 if (po->flags & OPF_TAIL)
3621 ferr(po, "int64 and tail?\n");
3622 fprintf(fout, "mul_tmp = ");
3624 else if (!IS(pp->ret_type.name, "void")) {
3625 if (po->flags & OPF_TAIL) {
3626 if (!IS(g_func_pp->ret_type.name, "void")) {
3627 fprintf(fout, "return ");
3628 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3629 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3632 else if (regmask & (1 << xAX)) {
3633 fprintf(fout, "eax = ");
3634 if (pp->ret_type.is_ptr)
3635 fprintf(fout, "(u32)");
3639 if (po->operand[0].type != OPT_LABEL) {
3640 fprintf(fout, "icall%d(", i);
3643 if (pp->name[0] == 0)
3644 ferr(po, "missing pp->name\n");
3645 fprintf(fout, "%s%s(", pp->name,
3646 pp->has_structarg ? "_sa" : "");
3649 for (arg = 0; arg < pp->argc; arg++) {
3651 fprintf(fout, ", ");
3654 if (pp->arg[arg].type.is_ptr)
3655 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3657 if (pp->arg[arg].reg != NULL) {
3658 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3663 tmp_op = pp->arg[arg].datap;
3665 ferr(po, "parsed_op missing for arg%d\n", arg);
3666 if (tmp_op->argnum != 0) {
3667 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3671 out_src_opr(buf1, sizeof(buf1),
3672 tmp_op, &tmp_op->operand[0], cast, 0));
3675 fprintf(fout, ");");
3677 if (strstr(pp->ret_type.name, "int64")) {
3678 fprintf(fout, "\n");
3679 fprintf(fout, " edx = mul_tmp >> 32;\n");
3680 fprintf(fout, " eax = mul_tmp;");
3683 if (po->flags & OPF_TAIL) {
3684 strcpy(g_comment, "tailcall");
3688 else if (IS(pp->ret_type.name, "void"))
3690 else if (IS(g_func_pp->ret_type.name, "void"))
3692 // else already handled as 'return f()'
3695 if (!IS(g_func_pp->ret_type.name, "void"))
3696 ferr(po, "int func -> void func tailcall?\n");
3697 fprintf(fout, "\n return;");
3698 strcpy(g_comment, "^ tailcall");
3701 delayed_flag_op = NULL;
3702 last_arith_dst = NULL;
3706 if (g_func_pp->is_vararg)
3707 fprintf(fout, " va_end(ap);\n");
3709 if (IS(g_func_pp->ret_type.name, "void")) {
3710 if (i != opcnt - 1 || label_pending)
3711 fprintf(fout, " return;");
3713 else if (g_func_pp->ret_type.is_ptr) {
3714 fprintf(fout, " return (%s)eax;",
3715 g_func_pp->ret_type.name);
3718 fprintf(fout, " return eax;");
3720 last_arith_dst = NULL;
3721 delayed_flag_op = NULL;
3725 if (po->argnum != 0) {
3726 // special case - saved func arg
3727 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3728 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
3731 else if (po->flags & OPF_RSAVE) {
3732 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3733 fprintf(fout, " s_%s = %s;", buf1, buf1);
3736 if (!(g_ida_func_attr & IDAFA_NORETURN))
3737 ferr(po, "stray push encountered\n");
3742 if (po->flags & OPF_RSAVE) {
3743 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3744 fprintf(fout, " %s = s_%s;", buf1, buf1);
3747 ferr(po, "stray pop encountered\n");
3756 ferr(po, "unhandled op type %d, flags %x\n",
3761 if (g_comment[0] != 0) {
3762 fprintf(fout, " // %s", g_comment);
3767 fprintf(fout, "\n");
3769 // some sanity checking
3770 if ((po->flags & OPF_REP) && po->op != OP_STOS
3771 && po->op != OP_MOVS && po->op != OP_CMPS)
3772 ferr(po, "unexpected rep\n");
3773 if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3774 ferr(po, "unexpected repz/repnz\n");
3777 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3779 // see is delayed flag stuff is still valid
3780 if (delayed_flag_op != NULL && delayed_flag_op != po) {
3781 if (is_any_opr_modified(delayed_flag_op, po))
3782 delayed_flag_op = NULL;
3785 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3786 if (is_opr_modified(last_arith_dst, po))
3787 last_arith_dst = NULL;
3793 if (g_stack_fsz && !g_stack_frame_used)
3794 fprintf(fout, " (void)sf;\n");
3796 fprintf(fout, "}\n\n");
3799 for (i = 0; i < opcnt; i++) {
3800 struct label_ref *lr, *lr_del;
3802 lr = g_label_refs[i].next;
3803 while (lr != NULL) {
3808 g_label_refs[i].i = -1;
3809 g_label_refs[i].next = NULL;
3811 if (ops[i].op == OP_CALL) {
3820 static void set_label(int i, const char *name)
3826 p = strchr(name, ':');
3830 if (len > sizeof(g_labels[0]) - 1)
3831 aerr("label '%s' too long: %d\n", name, len);
3832 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
3833 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
3834 memcpy(g_labels[i], name, len);
3835 g_labels[i][len] = 0;
3838 // '=' needs special treatment..
3839 static char *next_word_s(char *w, size_t wsize, char *s)
3845 for (i = 0; i < wsize - 1; i++) {
3846 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
3852 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
3853 printf("warning: '%s' truncated\n", w);
3864 static struct chunk_item *func_chunks;
3865 static int func_chunk_cnt;
3866 static int func_chunk_alloc;
3868 static void add_func_chunk(FILE *fasm, const char *name, int line)
3870 if (func_chunk_cnt >= func_chunk_alloc) {
3871 func_chunk_alloc *= 2;
3872 func_chunks = realloc(func_chunks,
3873 func_chunk_alloc * sizeof(func_chunks[0]));
3874 my_assert_not(func_chunks, NULL);
3876 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
3877 func_chunks[func_chunk_cnt].name = strdup(name);
3878 func_chunks[func_chunk_cnt].asmln = line;
3882 static int cmp_chunks(const void *p1, const void *p2)
3884 const struct chunk_item *c1 = p1, *c2 = p2;
3885 return strcmp(c1->name, c2->name);
3888 static int cmpstringp(const void *p1, const void *p2)
3890 return strcmp(*(char * const *)p1, *(char * const *)p2);
3893 static void scan_ahead(FILE *fasm)
3903 oldpos = ftell(fasm);
3906 while (fgets(line, sizeof(line), fasm))
3917 // get rid of random tabs
3918 for (i = 0; line[i] != 0; i++)
3919 if (line[i] == '\t')
3922 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3925 next_word(words[0], sizeof(words[0]), p);
3926 if (words[0][0] == 0)
3927 aerr("missing name for func chunk?\n");
3929 add_func_chunk(fasm, words[0], asmln);
3934 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3935 words[wordc][0] = 0;
3936 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3937 if (*p == 0 || *p == ';') {
3943 if (wordc == 2 && IS(words[1], "ends"))
3947 fseek(fasm, oldpos, SEEK_SET);
3951 int main(int argc, char *argv[])
3953 FILE *fout, *fasm, *frlist;
3954 struct parsed_data *pd = NULL;
3956 char **rlist = NULL;
3958 int rlist_alloc = 0;
3959 int func_chunks_used = 0;
3960 int func_chunks_sorted = 0;
3961 int func_chunk_i = -1;
3962 long func_chunk_ret = 0;
3963 int func_chunk_ret_ln = 0;
3964 int scanned_ahead = 0;
3966 char words[20][256];
3967 enum opr_lenmod lmod;
3969 int pending_endp = 0;
3971 int skip_warned = 0;
3982 if (argv[1] && IS(argv[1], "-v")) {
3987 if (argc < arg + 3) {
3988 printf("usage:\n%s [-v] <.c> <.asm> <hdrf> [rlist]*\n",
3995 asmfn = argv[arg++];
3996 fasm = fopen(asmfn, "r");
3997 my_assert_not(fasm, NULL);
3999 hdrfn = argv[arg++];
4000 g_fhdr = fopen(hdrfn, "r");
4001 my_assert_not(g_fhdr, NULL);
4004 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4005 my_assert_not(rlist, NULL);
4006 // needs special handling..
4007 rlist[rlist_len++] = "__alloca_probe";
4009 func_chunk_alloc = 32;
4010 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4011 my_assert_not(func_chunks, NULL);
4013 memset(words, 0, sizeof(words));
4015 for (; arg < argc; arg++) {
4016 frlist = fopen(argv[arg], "r");
4017 my_assert_not(frlist, NULL);
4019 while (fgets(line, sizeof(line), frlist)) {
4021 if (*p == 0 || *p == ';')
4024 if (IS_START(p, "#if 0"))
4026 else if (IS_START(p, "#endif"))
4033 p = next_word(words[0], sizeof(words[0]), p);
4034 if (words[0][0] == 0)
4037 if (rlist_len >= rlist_alloc) {
4038 rlist_alloc = rlist_alloc * 2 + 64;
4039 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4040 my_assert_not(rlist, NULL);
4042 rlist[rlist_len++] = strdup(words[0]);
4051 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4053 fout = fopen(argv[arg_out], "w");
4054 my_assert_not(fout, NULL);
4057 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4058 my_assert_not(g_eqs, NULL);
4060 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4061 g_label_refs[i].i = -1;
4062 g_label_refs[i].next = NULL;
4065 while (fgets(line, sizeof(line), fasm))
4074 // get rid of random tabs
4075 for (i = 0; line[i] != 0; i++)
4076 if (line[i] == '\t')
4081 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4082 goto do_pending_endp; // eww..
4084 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4086 static const char *attrs[] = {
4095 // parse IDA's attribute-list comment
4096 g_ida_func_attr = 0;
4099 for (; *p != 0; p = sskip(p)) {
4100 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4101 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4102 g_ida_func_attr |= 1 << i;
4103 p += strlen(attrs[i]);
4107 if (i == ARRAY_SIZE(attrs)) {
4108 anote("unparsed IDA attr: %s\n", p);
4111 if (IS(attrs[i], "fpd=")) {
4112 p = next_word(words[0], sizeof(words[0]), p);
4117 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4120 next_word(words[0], sizeof(words[0]), p);
4121 if (words[0][0] == 0)
4122 aerr("missing name for func chunk?\n");
4124 if (!scanned_ahead) {
4125 add_func_chunk(fasm, words[0], asmln);
4126 func_chunks_sorted = 0;
4129 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4131 if (func_chunk_i >= 0) {
4132 if (func_chunk_i < func_chunk_cnt
4133 && IS(func_chunks[func_chunk_i].name, g_func))
4135 // move on to next chunk
4136 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4138 aerr("seek failed for '%s' chunk #%d\n",
4139 g_func, func_chunk_i);
4140 asmln = func_chunks[func_chunk_i].asmln;
4144 if (func_chunk_ret == 0)
4145 aerr("no return from chunk?\n");
4146 fseek(fasm, func_chunk_ret, SEEK_SET);
4147 asmln = func_chunk_ret_ln;
4153 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4154 func_chunks_used = 1;
4156 if (IS_START(g_func, "sub_")) {
4157 unsigned long addr = strtoul(p, NULL, 16);
4158 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4159 if (addr > f_addr && !scanned_ahead) {
4160 anote("scan_ahead caused by '%s', addr %lx\n",
4164 func_chunks_sorted = 0;
4172 for (i = wordc; i < ARRAY_SIZE(words); i++)
4174 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4175 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4176 if (*p == 0 || *p == ';') {
4181 if (*p != 0 && *p != ';')
4182 aerr("too many words\n");
4184 // alow asm patches in comments
4185 if (*p == ';' && IS_START(p, "; sctpatch:")) {
4187 if (*p == 0 || *p == ';')
4189 goto parse_words; // lame
4194 awarn("wordc == 0?\n");
4198 // don't care about this:
4199 if (words[0][0] == '.'
4200 || IS(words[0], "include")
4201 || IS(words[0], "assume") || IS(words[1], "segment")
4202 || IS(words[0], "align"))
4208 // do delayed endp processing to collect switch jumptables
4210 if (in_func && !skip_func && wordc >= 2
4211 && ((words[0][0] == 'd' && words[0][2] == 0)
4212 || (words[1][0] == 'd' && words[1][2] == 0)))
4215 if (words[1][0] == 'd' && words[1][2] == 0) {
4217 if (g_func_pd_cnt >= pd_alloc) {
4218 pd_alloc = pd_alloc * 2 + 16;
4219 g_func_pd = realloc(g_func_pd,
4220 sizeof(g_func_pd[0]) * pd_alloc);
4221 my_assert_not(g_func_pd, NULL);
4223 pd = &g_func_pd[g_func_pd_cnt];
4225 memset(pd, 0, sizeof(*pd));
4226 strcpy(pd->label, words[0]);
4227 pd->type = OPT_CONST;
4228 pd->lmod = lmod_from_directive(words[1]);
4232 lmod = lmod_from_directive(words[0]);
4233 if (lmod != pd->lmod)
4234 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4237 if (pd->count_alloc < pd->count + wordc) {
4238 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4239 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4240 my_assert_not(pd->d, NULL);
4242 for (; i < wordc; i++) {
4243 if (IS(words[i], "offset")) {
4244 pd->type = OPT_OFFSET;
4247 p = strchr(words[i], ',');
4250 if (pd->type == OPT_OFFSET)
4251 pd->d[pd->count].u.label = strdup(words[i]);
4253 pd->d[pd->count].u.val = parse_number(words[i]);
4254 pd->d[pd->count].bt_i = -1;
4260 if (in_func && !skip_func)
4261 gen_func(fout, g_fhdr, g_func, pi);
4265 g_ida_func_attr = 0;
4269 func_chunks_used = 0;
4272 memset(&ops, 0, pi * sizeof(ops[0]));
4273 memset(g_labels, 0, pi * sizeof(g_labels[0]));
4277 for (i = 0; i < g_func_pd_cnt; i++) {
4279 if (pd->type == OPT_OFFSET) {
4280 for (j = 0; j < pd->count; j++)
4281 free(pd->d[j].u.label);
4292 if (IS(words[1], "proc")) {
4294 aerr("proc '%s' while in_func '%s'?\n",
4297 if ((g_ida_func_attr & IDAFA_THUNK)
4298 || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4300 strcpy(g_func, words[0]);
4301 set_label(0, words[0]);
4306 if (IS(words[1], "endp"))
4309 aerr("endp '%s' while not in_func?\n", words[0]);
4310 if (!IS(g_func, words[0]))
4311 aerr("endp '%s' while in_func '%s'?\n",
4314 if (!skip_func && func_chunks_used) {
4315 // start processing chunks
4316 struct chunk_item *ci, key = { g_func, 0 };
4318 func_chunk_ret = ftell(fasm);
4319 func_chunk_ret_ln = asmln;
4320 if (!func_chunks_sorted) {
4321 qsort(func_chunks, func_chunk_cnt,
4322 sizeof(func_chunks[0]), cmp_chunks);
4323 func_chunks_sorted = 1;
4325 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4326 sizeof(func_chunks[0]), cmp_chunks);
4328 aerr("'%s' needs chunks, but none found\n", g_func);
4329 func_chunk_i = ci - func_chunks;
4330 for (; func_chunk_i > 0; func_chunk_i--)
4331 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4334 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4336 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4337 asmln = func_chunks[func_chunk_i].asmln;
4345 if (wordc == 2 && IS(words[1], "ends"))
4348 p = strchr(words[0], ':');
4350 set_label(pi, words[0]);
4354 if (!in_func || skip_func) {
4355 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4357 anote("skipping from '%s'\n", g_labels[pi]);
4360 g_labels[pi][0] = 0;
4364 if (wordc > 1 && IS(words[1], "=")) {
4366 aerr("unhandled equ, wc=%d\n", wordc);
4367 if (g_eqcnt >= eq_alloc) {
4369 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4370 my_assert_not(g_eqs, NULL);
4373 len = strlen(words[0]);
4374 if (len > sizeof(g_eqs[0].name) - 1)
4375 aerr("equ name too long: %d\n", len);
4376 strcpy(g_eqs[g_eqcnt].name, words[0]);
4378 if (!IS(words[3], "ptr"))
4379 aerr("unhandled equ\n");
4380 if (IS(words[2], "dword"))
4381 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4382 else if (IS(words[2], "word"))
4383 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4384 else if (IS(words[2], "byte"))
4385 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4387 aerr("bad lmod: '%s'\n", words[2]);
4389 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4394 if (pi >= ARRAY_SIZE(ops))
4395 aerr("too many ops\n");
4397 parse_op(&ops[pi], words, wordc);
4408 // vim:ts=2:shiftwidth=2:expandtab