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 *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, 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, 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);
2517 if (arg < pp->argc) {
2518 ferr(po, "arg collect failed for '%s': %d/%d\n",
2519 pp->name, arg, pp->argc);
2525 static void add_label_ref(struct label_ref *lr, int op_i)
2527 struct label_ref *lr_new;
2534 lr_new = calloc(1, sizeof(*lr_new));
2536 lr_new->next = lr->next;
2540 static void output_std_flags(FILE *fout, struct parsed_op *po,
2541 int *pfomask, const char *dst_opr_text)
2543 if (*pfomask & (1 << PFO_Z)) {
2544 fprintf(fout, "\n cond_z = (%s%s == 0);",
2545 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2546 *pfomask &= ~(1 << PFO_Z);
2548 if (*pfomask & (1 << PFO_S)) {
2549 fprintf(fout, "\n cond_s = (%s%s < 0);",
2550 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2551 *pfomask &= ~(1 << PFO_S);
2555 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2557 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2558 struct parsed_opr *last_arith_dst = NULL;
2559 char buf1[256], buf2[256], buf3[256], cast[64];
2560 const struct parsed_proto *pp_c;
2561 struct parsed_proto *pp, *pp_tmp;
2562 struct parsed_data *pd;
2563 const char *tmpname;
2564 enum parsed_flag_op pfo;
2565 int save_arg_vars = 0;
2566 int cmp_result_vars = 0;
2567 int need_mul_var = 0;
2568 int have_func_ret = 0;
2569 int have_normal_ret = 0;
2571 int label_pending = 0;
2572 int regmask_save = 0;
2573 int regmask_arg = 0;
2574 int regmask_now = 0;
2586 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2587 g_stack_frame_used = 0;
2589 g_func_pp = proto_parse(fhdr, funcn, 0);
2590 if (g_func_pp == NULL)
2591 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2593 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2594 if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2595 fprintf(fout, "__stdcall ");
2596 if (g_ida_func_attr & IDAFA_NORETURN)
2597 fprintf(fout, "noreturn ");
2598 fprintf(fout, "%s(", funcn);
2600 for (i = 0; i < g_func_pp->argc; i++) {
2602 fprintf(fout, ", ");
2603 if (g_func_pp->arg[i].fptr != NULL) {
2605 pp = g_func_pp->arg[i].fptr;
2606 fprintf(fout, "%s (", pp->ret_type.name);
2607 if (pp->is_stdcall && pp->argc_reg == 0)
2608 fprintf(fout, "__stdcall ");
2609 fprintf(fout, "*a%d)(", i + 1);
2610 for (j = 0; j < pp->argc; j++) {
2612 fprintf(fout, ", ");
2613 if (pp->arg[j].fptr)
2614 ferr(ops, "nested fptr\n");
2615 fprintf(fout, "%s", pp->arg[j].type.name);
2620 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2623 if (g_func_pp->is_vararg) {
2625 fprintf(fout, ", ");
2626 fprintf(fout, "...");
2629 fprintf(fout, ")\n{\n");
2632 // - handle ebp/esp frame, remove ops related to it
2633 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2634 && ops[1].op == OP_MOV
2635 && IS(opr_name(&ops[1], 0), "ebp")
2636 && IS(opr_name(&ops[1], 1), "esp"))
2641 ops[0].flags |= OPF_RMD;
2642 ops[1].flags |= OPF_RMD;
2645 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2646 g_stack_fsz = opr_const(&ops[2], 1);
2647 ops[2].flags |= OPF_RMD;
2651 // another way msvc builds stack frame..
2653 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2655 ops[i].flags |= OPF_RMD;
2659 // and another way..
2660 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2661 && ops[i].operand[1].type == OPT_CONST
2662 && ops[i + 1].op == OP_CALL
2663 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2665 g_stack_fsz += ops[i].operand[1].val;
2666 ops[i].flags |= OPF_RMD;
2668 ops[i].flags |= OPF_RMD;
2675 for (; i < opcnt; i++)
2676 if (ops[i].op == OP_RET)
2678 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2681 if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2682 ops[i - 1].flags |= OPF_RMD;
2683 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2684 ferr(&ops[i - 1], "'pop ebp' expected\n");
2686 if (g_stack_fsz != 0) {
2687 if (ops[i - 2].op == OP_MOV
2688 && IS(opr_name(&ops[i - 2], 0), "esp")
2689 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2691 ops[i - 2].flags |= OPF_RMD;
2693 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2694 ferr(&ops[i - 2], "esp restore expected\n");
2696 if (ecx_push && ops[i - 3].op == OP_POP
2697 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2699 ferr(&ops[i - 3], "unexpected ecx pop\n");
2705 } while (i < opcnt);
2708 for (i = 0; i < opcnt; i++) {
2709 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2711 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2712 && ops[i].operand[1].type == OPT_CONST)
2721 g_stack_fsz = ops[i].operand[1].val;
2722 ops[i].flags |= OPF_RMD;
2726 for (; i < opcnt; i++)
2727 if (ops[i].op == OP_RET)
2729 if (ops[i - 1].op != OP_ADD
2730 || !IS(opr_name(&ops[i - 1], 0), "esp")
2731 || ops[i - 1].operand[1].type != OPT_CONST
2732 || ops[i - 1].operand[1].val != g_stack_fsz)
2733 ferr(&ops[i - 1], "'add esp' expected\n");
2734 ops[i - 1].flags |= OPF_RMD;
2737 } while (i < opcnt);
2742 // - parse calls with labels
2743 // - resolve all branches
2744 for (i = 0; i < opcnt; i++)
2750 if (po->flags & OPF_RMD)
2753 if (po->op == OP_CALL) {
2754 if (po->operand[0].type == OPT_LABEL) {
2755 tmpname = opr_name(po, 0);
2756 if (IS_START(tmpname, "loc_"))
2757 ferr(po, "call to loc_*\n");
2758 pp_c = proto_parse(fhdr, tmpname, 0);
2760 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2761 if (pp_c->is_fptr && pp_c->argc_reg != 0)
2762 ferr(po, "fptr call with reg arg\n");
2763 pp = proto_clone(pp_c);
2764 my_assert_not(pp, NULL);
2770 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2773 if (po->operand[0].type == OPT_REGMEM) {
2774 char *p = strchr(po->operand[0].name, '[');
2776 ferr(po, "unhandled indirect branch\n");
2777 ret = p - po->operand[0].name;
2778 strncpy(buf1, po->operand[0].name, ret);
2781 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2782 if (IS(g_func_pd[j].label, buf1)) {
2788 //ferr(po, "label '%s' not parsed?\n", buf1);
2790 if (pd->type != OPT_OFFSET)
2791 ferr(po, "label '%s' with non-offset data?\n", buf1);
2793 // find all labels, link
2794 for (j = 0; j < pd->count; j++) {
2795 for (l = 0; l < opcnt; l++) {
2796 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2797 add_label_ref(&g_label_refs[l], i);
2808 for (l = 0; l < opcnt; l++) {
2809 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2810 add_label_ref(&g_label_refs[l], i);
2819 if (po->operand[0].type == OPT_LABEL)
2823 ferr(po, "unhandled branch\n");
2827 po->flags |= OPF_TAIL;
2832 // - remove dead labels
2834 for (i = 0; i < opcnt; i++)
2836 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
2840 if (po->flags & OPF_RMD)
2843 if (po->op == OP_CALL)
2845 tmpname = opr_name(po, 0);
2850 pp_c = resolve_call(i, opcnt);
2852 pp = proto_clone(pp_c);
2854 pp = calloc(1, sizeof(*pp));
2855 my_assert_not(pp, NULL);
2856 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2858 ferr(po, "non-__cdecl indirect call unhandled yet\n");
2860 if (j > ARRAY_SIZE(pp->arg))
2861 ferr(po, "esp adjust too large?\n");
2862 pp->ret_type.name = strdup("int");
2863 pp->argc = pp->argc_stack = j;
2864 for (arg = 0; arg < pp->argc; arg++)
2865 pp->arg[arg].type.name = strdup("int");
2870 // look for and make use of esp adjust
2872 if (!pp->is_stdcall && pp->argc_stack > 0)
2873 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2875 if (pp->is_vararg) {
2876 if (j / 4 < pp->argc_stack)
2877 ferr(po, "esp adjust is too small: %x < %x\n",
2878 j, pp->argc_stack * 4);
2879 // modify pp to make it have varargs as normal args
2881 pp->argc += j / 4 - pp->argc_stack;
2882 for (; arg < pp->argc; arg++) {
2883 pp->arg[arg].type.name = strdup("int");
2886 if (pp->argc > ARRAY_SIZE(pp->arg))
2887 ferr(po, "too many args for '%s'\n", tmpname);
2889 if (pp->argc_stack != j / 4)
2890 ferr(po, "stack tracking failed for '%s': %x %x\n",
2891 tmpname, pp->argc_stack * 4, j);
2893 ops[ret].flags |= OPF_RMD;
2894 // a bit of a hack, but deals with use of
2895 // single adj for multiple calls
2896 ops[ret].operand[1].val -= j;
2898 else if (pp->is_vararg)
2899 ferr(po, "missing esp_adjust for vararg func '%s'\n",
2902 // can't call functions with non-__cdecl callbacks yet
2903 for (arg = 0; arg < pp->argc; arg++) {
2904 if (pp->arg[arg].fptr != NULL) {
2905 pp_tmp = pp->arg[arg].fptr;
2906 if (pp_tmp->argc_reg != 0)
2907 ferr(po, "'%s' has a callback with reg-args\n", tmpname);
2911 collect_call_args(po, i, pp, &save_arg_vars,
2912 0, i + opcnt * 2, 0, 0);
2914 if (strstr(pp->ret_type.name, "int64"))
2916 if (!(po->flags & OPF_TAIL) && !IS(pp->ret_type.name, "void"))
2922 // - find POPs for PUSHes, rm both
2923 // - scan for all used registers
2924 // - find flag set ops for their users
2925 // - declare indirect functions
2926 for (i = 0; i < opcnt; i++) {
2928 if (po->flags & OPF_RMD)
2931 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
2932 reg = po->operand[0].reg;
2933 if (!(regmask & (1 << reg)))
2934 // not a reg save after all, rerun scan_for_pop
2935 po->flags &= ~OPF_RSAVE;
2937 regmask_save |= 1 << reg;
2940 if (po->op == OP_PUSH
2941 && po->argnum == 0 && !(po->flags & OPF_RSAVE)
2942 && po->operand[0].type == OPT_REG)
2944 reg = po->operand[0].reg;
2946 ferr(po, "reg not set for push?\n");
2949 ret = scan_for_pop(i + 1, opcnt,
2950 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
2953 ferr(po, "too much depth: %d\n", depth);
2955 po->flags |= OPF_RMD;
2956 scan_for_pop(i + 1, opcnt, po->operand[0].name,
2957 i + opcnt * 4, 0, &depth, 1);
2960 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
2963 if (regmask & (1 << reg)) {
2964 if (regmask_save & (1 << reg))
2965 ferr(po, "%s already saved?\n", po->operand[0].name);
2969 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
2974 regmask_now = po->regmask_src | po->regmask_dst;
2975 if (regmask_now & (1 << xBP)) {
2976 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
2977 if (po->regmask_dst & (1 << xBP))
2978 // compiler decided to drop bp frame and use ebp as scratch
2979 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
2981 regmask_now &= ~(1 << xBP);
2985 regmask |= regmask_now;
2987 if (po->flags & OPF_CC)
2989 int setters[16], cnt = 0, branched = 0;
2991 ret = scan_for_flag_set(i, i + opcnt * 6,
2992 &branched, setters, &cnt);
2993 if (ret < 0 || cnt <= 0)
2994 ferr(po, "unable to trace flag setter(s)\n");
2995 if (cnt > ARRAY_SIZE(setters))
2996 ferr(po, "too many flag setters\n");
2998 pfo = split_cond(po, po->op, &dummy);
2999 for (j = 0; j < cnt; j++)
3001 tmp_op = &ops[setters[j]]; // flag setter
3004 // to get nicer code, we try to delay test and cmp;
3005 // if we can't because of operand modification, or if we
3006 // have math op, or branch, make it calculate flags explicitly
3007 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
3008 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i) >= 0)
3011 else if (tmp_op->op == OP_CMPS) {
3012 pfomask = 1 << PFO_Z;
3015 // see if we'll be able to handle based on op result
3016 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3017 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3019 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3023 tmp_op->pfomask |= pfomask;
3024 cmp_result_vars |= pfomask;
3026 // note: may overwrite, currently not a problem
3030 if (po->op == OP_ADC || po->op == OP_SBB)
3031 cmp_result_vars |= 1 << PFO_C;
3033 else if (po->op == OP_MUL
3034 || (po->op == OP_IMUL && po->operand_cnt == 1))
3038 else if (po->op == OP_CALL && po->operand[0].type != OPT_LABEL) {
3040 my_assert_not(pp, NULL);
3041 fprintf(fout, " %s (", pp->ret_type.name);
3042 if (pp->is_stdcall && pp->argc_reg == 0)
3043 fprintf(fout, "__stdcall ");
3044 fprintf(fout, "*icall%d)(", i);
3045 for (j = 0; j < pp->argc; j++) {
3047 fprintf(fout, ", ");
3048 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3050 fprintf(fout, ");\n");
3052 else if (po->op == OP_RET)
3053 have_normal_ret = 1;
3056 // output LUTs/jumptables
3057 for (i = 0; i < g_func_pd_cnt; i++) {
3059 fprintf(fout, " static const ");
3060 if (pd->type == OPT_OFFSET) {
3061 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3063 for (j = 0; j < pd->count; j++) {
3065 fprintf(fout, ", ");
3066 fprintf(fout, "&&%s", pd->d[j].u.label);
3070 fprintf(fout, "%s %s[] =\n { ",
3071 lmod_type_u(ops, pd->lmod), pd->label);
3073 for (j = 0; j < pd->count; j++) {
3075 fprintf(fout, ", ");
3076 fprintf(fout, "%u", pd->d[j].u.val);
3079 fprintf(fout, " };\n");
3082 // declare stack frame, va_arg
3084 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3085 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3087 if (g_func_pp->is_vararg)
3088 fprintf(fout, " va_list ap;\n");
3090 // declare arg-registers
3091 for (i = 0; i < g_func_pp->argc; i++) {
3092 if (g_func_pp->arg[i].reg != NULL) {
3093 reg = char_array_i(regs_r32,
3094 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3096 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
3098 regmask_arg |= 1 << reg;
3099 fprintf(fout, " u32 %s = (u32)a%d;\n",
3100 g_func_pp->arg[i].reg, i + 1);
3105 // declare other regs - special case for eax
3106 if (!((regmask | regmask_arg) & 1)
3107 && (have_func_ret || have_normal_ret)
3108 && !IS(g_func_pp->ret_type.name, "void"))
3110 fprintf(fout, " u32 eax = 0;\n");
3114 regmask &= ~regmask_arg;
3115 regmask &= ~(1 << xSP);
3117 for (reg = 0; reg < 8; reg++) {
3118 if (regmask & (1 << reg)) {
3119 fprintf(fout, " u32 %s;\n", regs_r32[reg]);
3126 for (reg = 0; reg < 8; reg++) {
3127 if (regmask_save & (1 << reg)) {
3128 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3134 if (save_arg_vars) {
3135 for (reg = 0; reg < 32; reg++) {
3136 if (save_arg_vars & (1 << reg)) {
3137 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3143 if (cmp_result_vars) {
3144 for (i = 0; i < 8; i++) {
3145 if (cmp_result_vars & (1 << i)) {
3146 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3153 fprintf(fout, " u64 mul_tmp;\n");
3158 fprintf(fout, "\n");
3160 if (g_func_pp->is_vararg) {
3161 if (g_func_pp->argc_stack == 0)
3162 ferr(ops, "vararg func without stack args?\n");
3163 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3167 for (i = 0; i < opcnt; i++)
3169 if (g_labels[i][0] != 0) {
3170 fprintf(fout, "\n%s:\n", g_labels[i]);
3173 delayed_flag_op = NULL;
3174 last_arith_dst = NULL;
3178 if (po->flags & OPF_RMD)
3183 #define assert_operand_cnt(n_) \
3184 if (po->operand_cnt != n_) \
3185 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3187 // conditional/flag using op?
3188 if (po->flags & OPF_CC)
3193 pfo = split_cond(po, po->op, &is_inv);
3196 // we go through all this trouble to avoid using parsed_flag_op,
3197 // which makes generated code much nicer
3198 if (delayed_flag_op != NULL)
3200 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3203 else if (last_arith_dst != NULL
3204 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3205 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3208 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3209 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3210 last_arith_dst->lmod, buf3);
3213 else if (tmp_op != NULL) {
3214 // use preprocessed flag calc results
3215 if (!(tmp_op->pfomask & (1 << pfo)))
3216 ferr(po, "not prepared for pfo %d\n", pfo);
3218 // note: is_inv was not yet applied
3219 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3220 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3223 ferr(po, "all methods of finding comparison failed\n");
3226 if (po->flags & OPF_JMP) {
3227 fprintf(fout, " if %s\n", buf1);
3229 else if (po->op == OP_ADC || po->op == OP_SBB) {
3231 fprintf(fout, " cond_%s = %s;\n",
3232 parsed_flag_op_names[pfo], buf1);
3234 else if (po->flags & OPF_DATA) { // SETcc
3235 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3236 fprintf(fout, " %s = %s;", buf2, buf1);
3239 ferr(po, "unhandled conditional op\n");
3243 pfomask = po->pfomask;
3248 assert_operand_cnt(2);
3249 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3250 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3251 fprintf(fout, " %s = %s;", buf1,
3252 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3253 po->operand[0].is_ptr ? "(void *)" : "", 0));
3257 assert_operand_cnt(2);
3258 po->operand[1].lmod = OPLM_DWORD; // always
3259 fprintf(fout, " %s = %s;",
3260 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3261 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3266 assert_operand_cnt(2);
3267 fprintf(fout, " %s = %s;",
3268 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3269 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3273 assert_operand_cnt(2);
3274 switch (po->operand[1].lmod) {
3276 strcpy(buf3, "(s8)");
3279 strcpy(buf3, "(s16)");
3282 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3284 fprintf(fout, " %s = %s;",
3285 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3286 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3291 assert_operand_cnt(1);
3292 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3293 fprintf(fout, " %s = ~%s;", buf1, buf1);
3297 assert_operand_cnt(2);
3298 fprintf(fout, " %s = (s32)%s >> 31;",
3299 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3300 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3301 strcpy(g_comment, "cdq");
3306 assert_operand_cnt(3);
3307 if (po->flags & OPF_REP) {
3308 fprintf(fout, " for (; ecx != 0; ecx--, edi += %d)\n",
3309 lmod_bytes(po, po->operand[0].lmod));
3310 fprintf(fout, " %sedi = eax;",
3311 lmod_cast_u_ptr(po, po->operand[0].lmod));
3312 strcpy(g_comment, "rep stos");
3315 fprintf(fout, " %sedi = eax; edi += %d;",
3316 lmod_cast_u_ptr(po, po->operand[0].lmod),
3317 lmod_bytes(po, po->operand[0].lmod));
3318 strcpy(g_comment, "stos");
3324 assert_operand_cnt(3);
3325 j = lmod_bytes(po, po->operand[0].lmod);
3326 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3327 if (po->flags & OPF_REP) {
3329 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3332 " %sedi = %sesi;", buf1, buf1);
3333 strcpy(g_comment, "rep movs");
3336 fprintf(fout, " %sedi = %sesi; edi += %d; esi += %d;",
3338 strcpy(g_comment, "movs");
3344 // repe ~ repeat while ZF=1
3345 assert_operand_cnt(3);
3346 j = lmod_bytes(po, po->operand[0].lmod);
3347 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3348 if (po->flags & OPF_REP) {
3350 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3353 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3354 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3357 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3358 (po->flags & OPF_REPZ) ? "e" : "ne");
3362 " cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3364 strcpy(g_comment, "cmps");
3366 pfomask &= ~(1 << PFO_Z);
3367 last_arith_dst = NULL;
3368 delayed_flag_op = NULL;
3371 // arithmetic w/flags
3376 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3379 assert_operand_cnt(2);
3380 fprintf(fout, " %s %s= %s;",
3381 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3383 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3384 output_std_flags(fout, po, &pfomask, buf1);
3385 last_arith_dst = &po->operand[0];
3386 delayed_flag_op = NULL;
3391 assert_operand_cnt(2);
3392 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3393 if (pfomask & (1 << PFO_C)) {
3394 if (po->operand[1].type == OPT_CONST) {
3395 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3396 j = po->operand[1].val;
3399 if (po->op == OP_SHL)
3403 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3407 ferr(po, "zero shift?\n");
3411 pfomask &= ~(1 << PFO_C);
3413 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3414 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3415 output_std_flags(fout, po, &pfomask, buf1);
3416 last_arith_dst = &po->operand[0];
3417 delayed_flag_op = NULL;
3421 assert_operand_cnt(2);
3422 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3423 fprintf(fout, " %s = %s%s >> %s;", buf1,
3424 lmod_cast_s(po, po->operand[0].lmod), buf1,
3425 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3426 output_std_flags(fout, po, &pfomask, buf1);
3427 last_arith_dst = &po->operand[0];
3428 delayed_flag_op = NULL;
3433 assert_operand_cnt(2);
3434 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3435 if (po->operand[1].type == OPT_CONST) {
3436 j = po->operand[1].val;
3437 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3438 fprintf(fout, po->op == OP_ROL ?
3439 " %s = (%s << %d) | (%s >> %d);" :
3440 " %s = (%s >> %d) | (%s << %d);",
3441 buf1, buf1, j, buf1,
3442 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3446 output_std_flags(fout, po, &pfomask, buf1);
3447 last_arith_dst = &po->operand[0];
3448 delayed_flag_op = NULL;
3452 assert_operand_cnt(2);
3453 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3454 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3455 // special case for XOR
3456 fprintf(fout, " %s = 0;",
3457 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3458 last_arith_dst = &po->operand[0];
3459 delayed_flag_op = NULL;
3466 assert_operand_cnt(2);
3467 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3468 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3469 if (po->op == OP_SBB
3470 && IS(po->operand[0].name, po->operand[1].name))
3472 // avoid use of unitialized var
3473 fprintf(fout, " %s = -cond_c;", buf1);
3474 // carry remains what it was
3475 pfomask &= ~(1 << PFO_C);
3478 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3479 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3481 output_std_flags(fout, po, &pfomask, buf1);
3482 last_arith_dst = &po->operand[0];
3483 delayed_flag_op = NULL;
3488 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3489 if (po->operand[0].type == OPT_REG) {
3490 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3491 fprintf(fout, " %s%s;", buf1, buf2);
3494 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3495 fprintf(fout, " %s %s= 1;", buf1, buf2);
3497 output_std_flags(fout, po, &pfomask, buf1);
3498 last_arith_dst = &po->operand[0];
3499 delayed_flag_op = NULL;
3503 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3504 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3505 fprintf(fout, " %s = -%s%s;", buf1,
3506 lmod_cast_s(po, po->operand[0].lmod), buf2);
3507 last_arith_dst = &po->operand[0];
3508 delayed_flag_op = NULL;
3509 if (pfomask & (1 << PFO_C)) {
3510 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3511 pfomask &= ~(1 << PFO_C);
3516 if (po->operand_cnt == 2) {
3517 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3520 if (po->operand_cnt == 3)
3521 ferr(po, "TODO imul3\n");
3524 assert_operand_cnt(1);
3525 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3526 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3527 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3528 fprintf(fout, " edx = mul_tmp >> 32;\n");
3529 fprintf(fout, " eax = mul_tmp;");
3530 last_arith_dst = NULL;
3531 delayed_flag_op = NULL;
3536 assert_operand_cnt(1);
3537 if (po->operand[0].lmod != OPLM_DWORD)
3538 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3540 // 32bit division is common, look for it
3541 if (po->op == OP_DIV)
3542 ret = scan_for_reg_clear(i, xDX);
3544 ret = scan_for_cdq_edx(i);
3546 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3547 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3548 po->op == OP_IDIV));
3549 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3550 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3553 ferr(po, "TODO 64bit divident\n");
3554 last_arith_dst = NULL;
3555 delayed_flag_op = NULL;
3560 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3562 for (j = 0; j < 8; j++) {
3563 if (pfomask & (1 << j)) {
3564 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3565 fprintf(fout, " cond_%s = %s;",
3566 parsed_flag_op_names[j], buf1);
3573 last_arith_dst = NULL;
3574 delayed_flag_op = po;
3577 // note: we reuse OP_Jcc for SETcc, only flags differ
3578 case OP_JO ... OP_JG:
3579 if (po->flags & OPF_JMP)
3580 fprintf(fout, " goto %s;", po->operand[0].name);
3581 // else SETcc - should already be handled
3585 assert_operand_cnt(1);
3586 last_arith_dst = NULL;
3587 delayed_flag_op = NULL;
3589 if (po->operand[0].type == OPT_REGMEM) {
3590 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3593 ferr(po, "parse failure for jmp '%s'\n",
3594 po->operand[0].name);
3595 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
3598 else if (po->operand[0].type != OPT_LABEL)
3599 ferr(po, "unhandled jmp type\n");
3601 fprintf(fout, " goto %s;", po->operand[0].name);
3605 assert_operand_cnt(1);
3608 ferr(po, "NULL pp\n");
3610 if (po->operand[0].type != OPT_LABEL)
3611 fprintf(fout, " icall%d = %s;\n", i,
3612 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
3616 if (strstr(pp->ret_type.name, "int64")) {
3617 if (po->flags & OPF_TAIL)
3618 ferr(po, "int64 and tail?\n");
3619 fprintf(fout, "mul_tmp = ");
3621 else if (!IS(pp->ret_type.name, "void")) {
3622 if (po->flags & OPF_TAIL) {
3623 if (!IS(g_func_pp->ret_type.name, "void")) {
3624 fprintf(fout, "return ");
3625 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3626 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3630 fprintf(fout, "eax = ");
3631 if (pp->ret_type.is_ptr)
3632 fprintf(fout, "(u32)");
3636 if (po->operand[0].type != OPT_LABEL) {
3637 fprintf(fout, "icall%d(", i);
3640 if (pp->name[0] == 0)
3641 ferr(po, "missing pp->name\n");
3642 fprintf(fout, "%s%s(", pp->name,
3643 pp->has_structarg ? "_sa" : "");
3646 for (arg = 0; arg < pp->argc; arg++) {
3648 fprintf(fout, ", ");
3651 if (pp->arg[arg].type.is_ptr)
3652 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3654 if (pp->arg[arg].reg != NULL) {
3655 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3660 tmp_op = pp->arg[arg].datap;
3662 ferr(po, "parsed_op missing for arg%d\n", arg);
3663 if (tmp_op->argnum != 0) {
3664 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3668 out_src_opr(buf1, sizeof(buf1),
3669 tmp_op, &tmp_op->operand[0], cast, 0));
3672 fprintf(fout, ");");
3674 if (strstr(pp->ret_type.name, "int64")) {
3675 fprintf(fout, "\n");
3676 fprintf(fout, " edx = mul_tmp >> 32;\n");
3677 fprintf(fout, " eax = mul_tmp;");
3680 if (po->flags & OPF_TAIL) {
3681 strcpy(g_comment, "tailcall");
3685 else if (IS(pp->ret_type.name, "void"))
3687 else if (IS(g_func_pp->ret_type.name, "void"))
3689 // else already handled as 'return f()'
3692 if (!IS(g_func_pp->ret_type.name, "void"))
3693 ferr(po, "int func -> void func tailcall?\n");
3694 fprintf(fout, "\n return;");
3695 strcpy(g_comment, "^ tailcall");
3698 delayed_flag_op = NULL;
3699 last_arith_dst = NULL;
3703 if (g_func_pp->is_vararg)
3704 fprintf(fout, " va_end(ap);\n");
3706 if (IS(g_func_pp->ret_type.name, "void")) {
3707 if (i != opcnt - 1 || label_pending)
3708 fprintf(fout, " return;");
3710 else if (g_func_pp->ret_type.is_ptr) {
3711 fprintf(fout, " return (%s)eax;",
3712 g_func_pp->ret_type.name);
3715 fprintf(fout, " return eax;");
3717 last_arith_dst = NULL;
3718 delayed_flag_op = NULL;
3722 if (po->argnum != 0) {
3723 // special case - saved func arg
3724 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3725 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
3728 else if (po->flags & OPF_RSAVE) {
3729 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3730 fprintf(fout, " s_%s = %s;", buf1, buf1);
3733 if (!(g_ida_func_attr & IDAFA_NORETURN))
3734 ferr(po, "stray push encountered\n");
3739 if (po->flags & OPF_RSAVE) {
3740 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3741 fprintf(fout, " %s = s_%s;", buf1, buf1);
3744 ferr(po, "stray pop encountered\n");
3753 ferr(po, "unhandled op type %d, flags %x\n",
3758 if (g_comment[0] != 0) {
3759 fprintf(fout, " // %s", g_comment);
3764 fprintf(fout, "\n");
3766 // some sanity checking
3767 if ((po->flags & OPF_REP) && po->op != OP_STOS
3768 && po->op != OP_MOVS && po->op != OP_CMPS)
3769 ferr(po, "unexpected rep\n");
3770 if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3771 ferr(po, "unexpected repz/repnz\n");
3774 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3776 // see is delayed flag stuff is still valid
3777 if (delayed_flag_op != NULL && delayed_flag_op != po) {
3778 if (is_any_opr_modified(delayed_flag_op, po))
3779 delayed_flag_op = NULL;
3782 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3783 if (is_opr_modified(last_arith_dst, po))
3784 last_arith_dst = NULL;
3790 if (g_stack_fsz && !g_stack_frame_used)
3791 fprintf(fout, " (void)sf;\n");
3793 fprintf(fout, "}\n\n");
3796 for (i = 0; i < opcnt; i++) {
3797 struct label_ref *lr, *lr_del;
3799 lr = g_label_refs[i].next;
3800 while (lr != NULL) {
3805 g_label_refs[i].i = -1;
3806 g_label_refs[i].next = NULL;
3808 if (ops[i].op == OP_CALL) {
3817 static void set_label(int i, const char *name)
3823 p = strchr(name, ':');
3827 if (len > sizeof(g_labels[0]) - 1)
3828 aerr("label '%s' too long: %d\n", name, len);
3829 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
3830 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
3831 memcpy(g_labels[i], name, len);
3832 g_labels[i][len] = 0;
3835 // '=' needs special treatment..
3836 static char *next_word_s(char *w, size_t wsize, char *s)
3842 for (i = 0; i < wsize - 1; i++) {
3843 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
3849 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
3850 printf("warning: '%s' truncated\n", w);
3861 static struct chunk_item *func_chunks;
3862 static int func_chunk_cnt;
3863 static int func_chunk_alloc;
3865 static void add_func_chunk(FILE *fasm, const char *name, int line)
3867 if (func_chunk_cnt >= func_chunk_alloc) {
3868 func_chunk_alloc *= 2;
3869 func_chunks = realloc(func_chunks,
3870 func_chunk_alloc * sizeof(func_chunks[0]));
3871 my_assert_not(func_chunks, NULL);
3873 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
3874 func_chunks[func_chunk_cnt].name = strdup(name);
3875 func_chunks[func_chunk_cnt].asmln = line;
3879 static int cmp_chunks(const void *p1, const void *p2)
3881 const struct chunk_item *c1 = p1, *c2 = p2;
3882 return strcmp(c1->name, c2->name);
3885 static int cmpstringp(const void *p1, const void *p2)
3887 return strcmp(*(char * const *)p1, *(char * const *)p2);
3890 static void scan_ahead(FILE *fasm)
3900 oldpos = ftell(fasm);
3903 while (fgets(line, sizeof(line), fasm))
3914 // get rid of random tabs
3915 for (i = 0; line[i] != 0; i++)
3916 if (line[i] == '\t')
3919 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3922 next_word(words[0], sizeof(words[0]), p);
3923 if (words[0][0] == 0)
3924 aerr("missing name for func chunk?\n");
3926 add_func_chunk(fasm, words[0], asmln);
3931 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3932 words[wordc][0] = 0;
3933 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3934 if (*p == 0 || *p == ';') {
3940 if (wordc == 2 && IS(words[1], "ends"))
3944 fseek(fasm, oldpos, SEEK_SET);
3948 int main(int argc, char *argv[])
3950 FILE *fout, *fasm, *frlist;
3951 struct parsed_data *pd = NULL;
3953 char **rlist = NULL;
3955 int rlist_alloc = 0;
3956 int func_chunks_used = 0;
3957 int func_chunks_sorted = 0;
3958 int func_chunk_i = -1;
3959 long func_chunk_ret = 0;
3960 int func_chunk_ret_ln = 0;
3961 int scanned_ahead = 0;
3963 char words[20][256];
3964 enum opr_lenmod lmod;
3966 int pending_endp = 0;
3968 int skip_warned = 0;
3979 if (argv[1] && IS(argv[1], "-v")) {
3984 if (argc < arg + 3) {
3985 printf("usage:\n%s [-v] <.c> <.asm> <hdrf> [rlist]*\n",
3992 asmfn = argv[arg++];
3993 fasm = fopen(asmfn, "r");
3994 my_assert_not(fasm, NULL);
3996 hdrfn = argv[arg++];
3997 g_fhdr = fopen(hdrfn, "r");
3998 my_assert_not(g_fhdr, NULL);
4001 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4002 my_assert_not(rlist, NULL);
4003 // needs special handling..
4004 rlist[rlist_len++] = "__alloca_probe";
4006 func_chunk_alloc = 32;
4007 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4008 my_assert_not(func_chunks, NULL);
4010 memset(words, 0, sizeof(words));
4012 for (; arg < argc; arg++) {
4013 frlist = fopen(argv[arg], "r");
4014 my_assert_not(frlist, NULL);
4016 while (fgets(line, sizeof(line), frlist)) {
4018 if (*p == 0 || *p == ';')
4021 if (IS_START(p, "#if 0"))
4023 else if (IS_START(p, "#endif"))
4030 p = next_word(words[0], sizeof(words[0]), p);
4031 if (words[0][0] == 0)
4034 if (rlist_len >= rlist_alloc) {
4035 rlist_alloc = rlist_alloc * 2 + 64;
4036 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4037 my_assert_not(rlist, NULL);
4039 rlist[rlist_len++] = strdup(words[0]);
4048 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4050 fout = fopen(argv[arg_out], "w");
4051 my_assert_not(fout, NULL);
4054 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4055 my_assert_not(g_eqs, NULL);
4057 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4058 g_label_refs[i].i = -1;
4059 g_label_refs[i].next = NULL;
4062 while (fgets(line, sizeof(line), fasm))
4071 // get rid of random tabs
4072 for (i = 0; line[i] != 0; i++)
4073 if (line[i] == '\t')
4078 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4079 goto do_pending_endp; // eww..
4081 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4083 static const char *attrs[] = {
4092 // parse IDA's attribute-list comment
4093 g_ida_func_attr = 0;
4096 for (; *p != 0; p = sskip(p)) {
4097 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4098 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4099 g_ida_func_attr |= 1 << i;
4100 p += strlen(attrs[i]);
4104 if (i == ARRAY_SIZE(attrs)) {
4105 anote("unparsed IDA attr: %s\n", p);
4108 if (IS(attrs[i], "fpd=")) {
4109 p = next_word(words[0], sizeof(words[0]), p);
4114 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4117 next_word(words[0], sizeof(words[0]), p);
4118 if (words[0][0] == 0)
4119 aerr("missing name for func chunk?\n");
4121 if (!scanned_ahead) {
4122 add_func_chunk(fasm, words[0], asmln);
4123 func_chunks_sorted = 0;
4126 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4128 if (func_chunk_i >= 0) {
4129 if (func_chunk_i < func_chunk_cnt
4130 && IS(func_chunks[func_chunk_i].name, g_func))
4132 // move on to next chunk
4133 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4135 aerr("seek failed for '%s' chunk #%d\n",
4136 g_func, func_chunk_i);
4137 asmln = func_chunks[func_chunk_i].asmln;
4141 if (func_chunk_ret == 0)
4142 aerr("no return from chunk?\n");
4143 fseek(fasm, func_chunk_ret, SEEK_SET);
4144 asmln = func_chunk_ret_ln;
4150 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4151 func_chunks_used = 1;
4153 if (IS_START(g_func, "sub_")) {
4154 unsigned long addr = strtoul(p, NULL, 16);
4155 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4156 if (addr > f_addr && !scanned_ahead) {
4157 anote("scan_ahead caused by '%s', addr %lx\n",
4161 func_chunks_sorted = 0;
4169 for (i = wordc; i < ARRAY_SIZE(words); i++)
4171 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4172 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4173 if (*p == 0 || *p == ';') {
4178 if (*p != 0 && *p != ';')
4179 aerr("too many words\n");
4181 // alow asm patches in comments
4182 if (*p == ';' && IS_START(p, "; sctpatch:")) {
4184 if (*p == 0 || *p == ';')
4186 goto parse_words; // lame
4191 awarn("wordc == 0?\n");
4195 // don't care about this:
4196 if (words[0][0] == '.'
4197 || IS(words[0], "include")
4198 || IS(words[0], "assume") || IS(words[1], "segment")
4199 || IS(words[0], "align"))
4205 // do delayed endp processing to collect switch jumptables
4207 if (in_func && !skip_func && wordc >= 2
4208 && ((words[0][0] == 'd' && words[0][2] == 0)
4209 || (words[1][0] == 'd' && words[1][2] == 0)))
4212 if (words[1][0] == 'd' && words[1][2] == 0) {
4214 if (g_func_pd_cnt >= pd_alloc) {
4215 pd_alloc = pd_alloc * 2 + 16;
4216 g_func_pd = realloc(g_func_pd,
4217 sizeof(g_func_pd[0]) * pd_alloc);
4218 my_assert_not(g_func_pd, NULL);
4220 pd = &g_func_pd[g_func_pd_cnt];
4222 memset(pd, 0, sizeof(*pd));
4223 strcpy(pd->label, words[0]);
4224 pd->type = OPT_CONST;
4225 pd->lmod = lmod_from_directive(words[1]);
4229 lmod = lmod_from_directive(words[0]);
4230 if (lmod != pd->lmod)
4231 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4234 if (pd->count_alloc < pd->count + wordc) {
4235 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4236 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4237 my_assert_not(pd->d, NULL);
4239 for (; i < wordc; i++) {
4240 if (IS(words[i], "offset")) {
4241 pd->type = OPT_OFFSET;
4244 p = strchr(words[i], ',');
4247 if (pd->type == OPT_OFFSET)
4248 pd->d[pd->count].u.label = strdup(words[i]);
4250 pd->d[pd->count].u.val = parse_number(words[i]);
4251 pd->d[pd->count].bt_i = -1;
4257 if (in_func && !skip_func)
4258 gen_func(fout, g_fhdr, g_func, pi);
4262 g_ida_func_attr = 0;
4266 func_chunks_used = 0;
4269 memset(&ops, 0, pi * sizeof(ops[0]));
4270 memset(g_labels, 0, pi * sizeof(g_labels[0]));
4274 for (i = 0; i < g_func_pd_cnt; i++) {
4276 if (pd->type == OPT_OFFSET) {
4277 for (j = 0; j < pd->count; j++)
4278 free(pd->d[j].u.label);
4289 if (IS(words[1], "proc")) {
4291 aerr("proc '%s' while in_func '%s'?\n",
4294 if ((g_ida_func_attr & IDAFA_THUNK)
4295 || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4297 strcpy(g_func, words[0]);
4298 set_label(0, words[0]);
4303 if (IS(words[1], "endp"))
4306 aerr("endp '%s' while not in_func?\n", words[0]);
4307 if (!IS(g_func, words[0]))
4308 aerr("endp '%s' while in_func '%s'?\n",
4311 if (!skip_func && func_chunks_used) {
4312 // start processing chunks
4313 struct chunk_item *ci, key = { g_func, 0 };
4315 func_chunk_ret = ftell(fasm);
4316 func_chunk_ret_ln = asmln;
4317 if (!func_chunks_sorted) {
4318 qsort(func_chunks, func_chunk_cnt,
4319 sizeof(func_chunks[0]), cmp_chunks);
4320 func_chunks_sorted = 1;
4322 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4323 sizeof(func_chunks[0]), cmp_chunks);
4325 aerr("'%s' needs chunks, but none found\n", g_func);
4326 func_chunk_i = ci - func_chunks;
4327 for (; func_chunk_i > 0; func_chunk_i--)
4328 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4331 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4333 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4334 asmln = func_chunks[func_chunk_i].asmln;
4342 if (wordc == 2 && IS(words[1], "ends"))
4345 p = strchr(words[0], ':');
4347 set_label(pi, words[0]);
4351 if (!in_func || skip_func) {
4352 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4354 anote("skipping from '%s'\n", g_labels[pi]);
4357 g_labels[pi][0] = 0;
4361 if (wordc > 1 && IS(words[1], "=")) {
4363 aerr("unhandled equ, wc=%d\n", wordc);
4364 if (g_eqcnt >= eq_alloc) {
4366 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4367 my_assert_not(g_eqs, NULL);
4370 len = strlen(words[0]);
4371 if (len > sizeof(g_eqs[0].name) - 1)
4372 aerr("equ name too long: %d\n", len);
4373 strcpy(g_eqs[g_eqcnt].name, words[0]);
4375 if (!IS(words[3], "ptr"))
4376 aerr("unhandled equ\n");
4377 if (IS(words[2], "dword"))
4378 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4379 else if (IS(words[2], "word"))
4380 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4381 else if (IS(words[2], "byte"))
4382 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4384 aerr("bad lmod: '%s'\n", words[2]);
4386 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4391 if (pi >= ARRAY_SIZE(ops))
4392 aerr("too many ops\n");
4394 parse_op(&ops[pi], words, wordc);
4405 // vim:ts=2:shiftwidth=2:expandtab