9 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
10 #define IS(w, y) !strcmp(w, y)
11 #define IS_START(w, y) !strncmp(w, y, strlen(y))
13 #include "protoparse.h"
15 static const char *asmfn;
19 #define anote(fmt, ...) \
20 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
21 #define awarn(fmt, ...) \
22 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
23 #define aerr(fmt, ...) do { \
24 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
30 OPF_RMD = (1 << 0), /* removed or optimized out */
31 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
32 OPF_FLAGS = (1 << 2), /* sets flags */
33 OPF_JMP = (1 << 3), /* branches, ret and call */
34 OPF_CC = (1 << 4), /* uses flags */
35 OPF_TAIL = (1 << 5), /* ret or tail call */
36 OPF_RSAVE = (1 << 6), /* push/pop is local reg save/load */
37 OPF_REP = (1 << 7), /* prefixed by rep */
38 OPF_REPZ = (1 << 8), /* rep is repe/repz */
39 OPF_REPNZ = (1 << 9), /* rep is repne/repnz */
40 OPF_FARG = (1 << 10), /* push collected as func arg (no reuse) */
41 OPF_EBP_S = (1 << 11), /* ebp used as scratch, not BP */
109 // must be sorted (larger len must be further in enum)
117 #define MAX_OPERANDS 3
121 enum opr_lenmod lmod;
122 unsigned int is_ptr:1; // pointer in C
123 unsigned int is_array:1; // array in C
124 unsigned int type_from_var:1; // .. in header, sometimes wrong
125 unsigned int size_mismatch:1; // type override differs from C
126 unsigned int size_lt:1; // type override is larger than C
134 struct parsed_opr operand[MAX_OPERANDS];
137 int regmask_src; // all referensed regs
139 int pfomask; // flagop: parsed_flag_op that can't be delayed
140 int argnum; // push: altered before call arg #
141 int cc_scratch; // scratch storage during analysis
142 int bt_i; // branch target for branches
143 struct parsed_data *btj;// branch targets for jumptables
148 // OP_CALL - ptr to parsed_proto
149 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
153 enum opr_lenmod lmod;
160 enum opr_lenmod lmod;
174 struct label_ref *next;
178 IDAFA_BP_FRAME = (1 << 0),
179 IDAFA_LIB_FUNC = (1 << 1),
180 IDAFA_STATIC = (1 << 2),
181 IDAFA_NORETURN = (1 << 3),
182 IDAFA_THUNK = (1 << 4),
183 IDAFA_FPD = (1 << 5),
188 static struct parsed_op ops[MAX_OPS];
189 static struct parsed_equ *g_eqs;
191 static char g_labels[MAX_OPS][32];
192 static struct label_ref g_label_refs[MAX_OPS];
193 static const struct parsed_proto *g_func_pp;
194 static struct parsed_data *g_func_pd;
195 static int g_func_pd_cnt;
196 static char g_func[256];
197 static char g_comment[256];
198 static int g_bp_frame;
199 static int g_sp_frame;
200 static int g_stack_frame_used;
201 static int g_stack_fsz;
202 static int g_ida_func_attr;
203 #define ferr(op_, fmt, ...) do { \
204 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
205 dump_op(op_), ##__VA_ARGS__); \
209 #define fnote(op_, fmt, ...) \
210 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
211 dump_op(op_), ##__VA_ARGS__)
215 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
216 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
217 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
218 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
220 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
222 // possible basic comparison types (without inversion)
223 enum parsed_flag_op {
227 PFO_BE, // 6 CF=1||ZF=1
231 PFO_LE, // e ZF=1||SF!=OF
234 static const char *parsed_flag_op_names[] = {
235 "o", "c", "z", "be", "s", "p", "l", "le"
238 static int char_array_i(const char *array[], size_t len, const char *s)
242 for (i = 0; i < len; i++)
249 static void printf_number(char *buf, size_t buf_size,
250 unsigned long number)
252 // output in C-friendly form
253 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
256 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
260 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
262 *reg_lmod = OPLM_DWORD;
265 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
267 *reg_lmod = OPLM_WORD;
270 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
272 *reg_lmod = OPLM_BYTE;
275 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
277 *reg_lmod = OPLM_BYTE;
284 static unsigned long parse_number(const char *number)
286 int len = strlen(number);
287 const char *p = number;
297 if (len > 1 && *p == '0')
299 if (number[len - 1] == 'h') {
300 ret = strtoul(p, &endp, 16);
301 bad = (*endp != 'h');
304 ret = strtoul(p, &endp, 10);
308 aerr("number parsing failed\n");
314 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
316 enum opr_lenmod lmod;
329 while (my_isblank(*s))
331 for (; my_issep(*s); d++, s++)
333 while (my_isblank(*s))
338 if (IS_START(s, "ds:"))
341 s = next_idt(w, sizeof(w), s);
346 reg = parse_reg(&lmod, w);
348 *regmask |= 1 << reg;
352 if ('0' <= w[0] && w[0] <= '9') {
353 number = parse_number(w);
354 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
358 // probably some label/identifier - pass
361 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
365 strcpy(name, cvtbuf);
370 static int is_reg_in_str(const char *s)
374 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
377 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
378 if (!strncmp(s, regs_r32[i], 3))
384 static const char *parse_stack_el(const char *name, char *extra_reg)
386 const char *p, *p2, *s;
393 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
395 if (extra_reg != NULL) {
396 strncpy(extra_reg, name, 3);
401 if (IS_START(p, "ebp+")) {
405 if (p2 != NULL && is_reg_in_str(p)) {
406 if (extra_reg != NULL) {
407 strncpy(extra_reg, p, p2 - p);
408 extra_reg[p2 - p] = 0;
413 if (!('0' <= *p && *p <= '9'))
419 if (!IS_START(name, "esp+"))
422 p = strchr(name + 4, '+');
424 // must be a number after esp+, already converted to 0x..
426 if (!('0' <= *s && *s <= '9')) {
427 aerr("%s nan?\n", __func__);
430 if (s[0] == '0' && s[1] == 'x')
433 if (len < sizeof(buf) - 1) {
434 strncpy(buf, s, len);
436 val = strtol(buf, &endp, 16);
437 if (val == 0 || *endp != 0) {
438 aerr("%s num parse fail for '%s'\n", __func__, buf);
447 if ('0' <= *p && *p <= '9')
453 static int guess_lmod_from_name(struct parsed_opr *opr)
455 if (!strncmp(opr->name, "dword_", 6)) {
456 opr->lmod = OPLM_DWORD;
459 if (!strncmp(opr->name, "word_", 5)) {
460 opr->lmod = OPLM_WORD;
463 if (!strncmp(opr->name, "byte_", 5)) {
464 opr->lmod = OPLM_BYTE;
470 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
471 const struct parsed_type *c_type)
473 static const char *dword_types[] = {
474 "int", "_DWORD", "UINT_PTR",
475 "DWORD", "HANDLE", "HWND", "HMODULE",
476 "WPARAM", "LPARAM", "UINT",
478 static const char *word_types[] = {
479 "uint16_t", "int16_t",
480 "unsigned __int16", "__int16",
482 static const char *byte_types[] = {
483 "uint8_t", "int8_t", "char",
484 "unsigned __int8", "__int8", "BYTE",
490 if (c_type->is_ptr) {
495 n = skip_type_mod(c_type->name);
497 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
498 if (IS(n, dword_types[i])) {
504 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
505 if (IS(n, word_types[i])) {
511 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
512 if (IS(n, byte_types[i])) {
521 static enum opr_type lmod_from_directive(const char *d)
525 else if (IS(d, "dw"))
527 else if (IS(d, "db"))
530 aerr("unhandled directive: '%s'\n", d);
534 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
540 *regmask |= 1 << reg;
543 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
546 static int parse_operand(struct parsed_opr *opr,
547 int *regmask, int *regmask_indirect,
548 char words[16][256], int wordc, int w, unsigned int op_flags)
550 const struct parsed_proto *pp;
551 enum opr_lenmod tmplmod;
552 unsigned long number;
559 aerr("parse_operand w %d, wordc %d\n", w, wordc);
563 for (i = w; i < wordc; i++) {
564 len = strlen(words[i]);
565 if (words[i][len - 1] == ',') {
566 words[i][len - 1] = 0;
572 wordc_in = wordc - w;
574 if ((op_flags & OPF_JMP) && wordc_in > 0
575 && !('0' <= words[w][0] && words[w][0] <= '9'))
577 const char *label = NULL;
579 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
580 && IS(words[w + 1], "ptr"))
581 label = words[w + 2];
582 else if (wordc_in == 2 && IS(words[w], "short"))
583 label = words[w + 1];
584 else if (wordc_in == 1
585 && strchr(words[w], '[') == NULL
586 && parse_reg(&tmplmod, words[w]) < 0)
590 opr->type = OPT_LABEL;
591 if (IS_START(label, "ds:"))
593 strcpy(opr->name, label);
599 if (IS(words[w + 1], "ptr")) {
600 if (IS(words[w], "dword"))
601 opr->lmod = OPLM_DWORD;
602 else if (IS(words[w], "word"))
603 opr->lmod = OPLM_WORD;
604 else if (IS(words[w], "byte"))
605 opr->lmod = OPLM_BYTE;
607 aerr("type parsing failed\n");
609 wordc_in = wordc - w;
614 if (IS(words[w], "offset")) {
615 opr->type = OPT_OFFSET;
616 strcpy(opr->name, words[w + 1]);
619 if (IS(words[w], "(offset")) {
620 char *p = strchr(words[w + 1], ')');
622 aerr("parse of bracketed offset failed\n");
624 opr->type = OPT_OFFSET;
625 strcpy(opr->name, words[w + 1]);
631 aerr("parse_operand 1 word expected\n");
634 if (IS_START(tmp, "ds:"))
636 strcpy(opr->name, tmp);
638 if (words[w][0] == '[') {
639 opr->type = OPT_REGMEM;
640 ret = sscanf(words[w], "[%[^]]]", opr->name);
642 aerr("[] parse failure\n");
644 parse_indmode(opr->name, regmask_indirect, 1);
645 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
647 struct parsed_equ *eq =
648 equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
650 opr->lmod = eq->lmod;
654 else if (strchr(words[w], '[')) {
656 opr->type = OPT_REGMEM;
657 if (opr->lmod == OPLM_UNSPEC)
658 guess_lmod_from_name(opr);
659 parse_indmode(strchr(words[w], '['), regmask_indirect, 0);
662 else if (('0' <= words[w][0] && words[w][0] <= '9')
663 || words[w][0] == '-')
665 number = parse_number(words[w]);
666 opr->type = OPT_CONST;
668 printf_number(opr->name, sizeof(opr->name), number);
672 ret = parse_reg(&tmplmod, opr->name);
674 setup_reg_opr(opr, ret, tmplmod, regmask);
678 // most likely var in data segment
679 opr->type = OPT_LABEL;
681 pp = proto_parse(g_fhdr, opr->name);
684 opr->lmod = OPLM_DWORD;
688 tmplmod = OPLM_UNSPEC;
689 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
690 anote("unhandled C type '%s' for '%s'\n",
691 pp->type.name, opr->name);
693 if (opr->lmod == OPLM_UNSPEC) {
695 opr->type_from_var = 1;
697 else if (opr->lmod != tmplmod) {
698 opr->size_mismatch = 1;
699 if (tmplmod < opr->lmod)
702 opr->is_ptr = pp->type.is_ptr;
704 opr->is_array = pp->type.is_array;
707 if (opr->lmod == OPLM_UNSPEC)
708 guess_lmod_from_name(opr);
712 static const struct {
717 { "repe", OPF_REP|OPF_REPZ },
718 { "repz", OPF_REP|OPF_REPZ },
719 { "repne", OPF_REP|OPF_REPNZ },
720 { "repnz", OPF_REP|OPF_REPNZ },
723 static const struct {
730 { "nop", OP_NOP, 0, 0, 0 },
731 { "push", OP_PUSH, 1, 1, 0 },
732 { "pop", OP_POP, 1, 1, OPF_DATA },
733 { "mov" , OP_MOV, 2, 2, OPF_DATA },
734 { "lea", OP_LEA, 2, 2, OPF_DATA },
735 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
736 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
737 { "not", OP_NOT, 1, 1, OPF_DATA },
738 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
739 { "stosb",OP_STOS, 0, 0, OPF_DATA },
740 { "stosw",OP_STOS, 0, 0, OPF_DATA },
741 { "stosd",OP_STOS, 0, 0, OPF_DATA },
742 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
743 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
744 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
745 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
746 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
747 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
748 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
749 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
750 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
751 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
752 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
753 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
754 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
755 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
756 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
757 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
758 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
759 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
760 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
761 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
762 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
763 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
764 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
765 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
766 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
767 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
768 { "test", OP_TEST, 2, 2, OPF_FLAGS },
769 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
770 { "retn", OP_RET, 0, 1, OPF_TAIL },
771 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
772 { "jmp", OP_JMP, 1, 1, OPF_JMP },
773 { "jo", OP_JO, 1, 1, OPF_JMP|OPF_CC }, // 70 OF=1
774 { "jno", OP_JNO, 1, 1, OPF_JMP|OPF_CC }, // 71 OF=0
775 { "jc", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72 CF=1
776 { "jb", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72
777 { "jnc", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73 CF=0
778 { "jnb", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
779 { "jae", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
780 { "jz", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74 ZF=1
781 { "je", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74
782 { "jnz", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75 ZF=0
783 { "jne", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75
784 { "jbe", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76 CF=1 || ZF=1
785 { "jna", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76
786 { "ja", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77 CF=0 && ZF=0
787 { "jnbe", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77
788 { "js", OP_JS, 1, 1, OPF_JMP|OPF_CC }, // 78 SF=1
789 { "jns", OP_JNS, 1, 1, OPF_JMP|OPF_CC }, // 79 SF=0
790 { "jp", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a PF=1
791 { "jpe", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a
792 { "jnp", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b PF=0
793 { "jpo", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b
794 { "jl", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c SF!=OF
795 { "jnge", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c
796 { "jge", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d SF=OF
797 { "jnl", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d
798 { "jle", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e ZF=1 || SF!=OF
799 { "jng", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e
800 { "jg", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f ZF=0 && SF=OF
801 { "jnle", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f
802 { "seto", OP_JO, 1, 1, OPF_DATA|OPF_CC },
803 { "setno", OP_JNO, 1, 1, OPF_DATA|OPF_CC },
804 { "setc", OP_JC, 1, 1, OPF_DATA|OPF_CC },
805 { "setb", OP_JC, 1, 1, OPF_DATA|OPF_CC },
806 { "setnc", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
807 { "setae", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
808 { "setz", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
809 { "sete", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
810 { "setnz", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
811 { "setne", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
812 { "setbe", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
813 { "setna", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
814 { "seta", OP_JA, 1, 1, OPF_DATA|OPF_CC },
815 { "setnbe", OP_JA, 1, 1, OPF_DATA|OPF_CC },
816 { "sets", OP_JS, 1, 1, OPF_DATA|OPF_CC },
817 { "setns", OP_JNS, 1, 1, OPF_DATA|OPF_CC },
818 { "setp", OP_JP, 1, 1, OPF_DATA|OPF_CC },
819 { "setpe", OP_JP, 1, 1, OPF_DATA|OPF_CC },
820 { "setnp", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
821 { "setpo", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
822 { "setl", OP_JL, 1, 1, OPF_DATA|OPF_CC },
823 { "setnge", OP_JL, 1, 1, OPF_DATA|OPF_CC },
824 { "setge", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
825 { "setnl", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
826 { "setle", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
827 { "setng", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
828 { "setg", OP_JG, 1, 1, OPF_DATA|OPF_CC },
829 { "setnle", OP_JG, 1, 1, OPF_DATA|OPF_CC },
832 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
834 enum opr_lenmod lmod = OPLM_UNSPEC;
835 int prefix_flags = 0;
843 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
844 if (IS(words[w], pref_table[i].name)) {
845 prefix_flags = pref_table[i].flags;
852 aerr("lone prefix: '%s'\n", words[0]);
857 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
858 if (IS(words[w], op_table[i].name))
862 if (i == ARRAY_SIZE(op_table))
863 aerr("unhandled op: '%s'\n", words[0]);
866 op->op = op_table[i].op;
867 op->flags = op_table[i].flags | prefix_flags;
868 op->regmask_src = op->regmask_dst = 0;
870 for (opr = 0; opr < op_table[i].minopr; opr++) {
871 regmask = regmask_ind = 0;
872 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
873 words, wordc, w, op->flags);
875 if (opr == 0 && (op->flags & OPF_DATA))
876 op->regmask_dst = regmask;
877 // for now, mark dst as src too
878 op->regmask_src |= regmask | regmask_ind;
881 for (; w < wordc && opr < op_table[i].maxopr; opr++) {
882 w = parse_operand(&op->operand[opr],
883 &op->regmask_src, &op->regmask_src,
884 words, wordc, w, op->flags);
888 aerr("parse_op %s incomplete: %d/%d\n",
892 op->operand_cnt = opr;
893 if (!strncmp(op_table[i].name, "set", 3))
894 op->operand[0].lmod = OPLM_BYTE;
896 // ops with implicit argumets
900 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
901 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
905 if (op->operand_cnt != 0)
907 if (IS(words[op_w], "stosb"))
909 else if (IS(words[op_w], "stosw"))
911 else if (IS(words[op_w], "stosd"))
914 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
915 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
916 op->regmask_dst = op->regmask_src;
917 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
922 if (op->operand_cnt != 0)
924 if (words[op_w][4] == 'b')
926 else if (words[op_w][4] == 'w')
928 else if (words[op_w][4] == 'd')
931 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
932 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
933 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
934 op->regmask_dst = op->regmask_src;
938 if (op->operand_cnt != 1)
943 op->regmask_dst = (1 << xDX) | (1 << xAX);
944 op->regmask_src |= (1 << xAX);
945 if (op->operand[0].lmod == OPLM_UNSPEC)
946 op->operand[0].lmod = OPLM_DWORD;
951 // we could set up operands for edx:eax, but there is no real need to
952 // (see is_opr_modified())
953 regmask = (1 << xDX) | (1 << xAX);
954 op->regmask_dst = regmask;
955 op->regmask_src |= regmask;
956 if (op->operand[0].lmod == OPLM_UNSPEC)
957 op->operand[0].lmod = OPLM_DWORD;
965 if (op->operand[1].lmod == OPLM_UNSPEC)
966 op->operand[1].lmod = OPLM_BYTE;
970 if (op->operand[0].lmod == OPLM_UNSPEC
971 && (op->operand[0].type == OPT_CONST
972 || op->operand[0].type == OPT_OFFSET
973 || op->operand[0].type == OPT_LABEL))
974 op->operand[0].lmod = OPLM_DWORD;
979 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
980 && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
982 op->flags |= OPF_RMD;
987 if (op->operand[0].type == OPT_REG
988 && op->operand[1].type == OPT_REGMEM)
991 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
992 if (IS(buf, op->operand[1].name))
993 op->flags |= OPF_RMD;
1002 static const char *op_name(enum op_op op)
1006 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1007 if (op_table[i].op == op)
1008 return op_table[i].name;
1014 static const char *dump_op(struct parsed_op *po)
1016 static char out[128];
1023 snprintf(out, sizeof(out), "%s", op_name(po->op));
1024 for (i = 0; i < po->operand_cnt; i++) {
1028 snprintf(p, sizeof(out) - (p - out),
1029 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1030 po->operand[i].name);
1036 static const char *lmod_type_u(struct parsed_op *po,
1037 enum opr_lenmod lmod)
1047 ferr(po, "invalid lmod: %d\n", lmod);
1048 return "(_invalid_)";
1052 static const char *lmod_cast_u(struct parsed_op *po,
1053 enum opr_lenmod lmod)
1063 ferr(po, "invalid lmod: %d\n", lmod);
1064 return "(_invalid_)";
1068 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1069 enum opr_lenmod lmod)
1079 ferr(po, "invalid lmod: %d\n", lmod);
1080 return "(_invalid_)";
1084 static const char *lmod_cast_s(struct parsed_op *po,
1085 enum opr_lenmod lmod)
1095 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1096 return "(_invalid_)";
1100 static const char *lmod_cast(struct parsed_op *po,
1101 enum opr_lenmod lmod, int is_signed)
1104 lmod_cast_s(po, lmod) :
1105 lmod_cast_u(po, lmod);
1108 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1118 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1123 static const char *opr_name(struct parsed_op *po, int opr_num)
1125 if (opr_num >= po->operand_cnt)
1126 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1127 return po->operand[opr_num].name;
1130 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1132 if (opr_num >= po->operand_cnt)
1133 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1134 if (po->operand[opr_num].type != OPT_CONST)
1135 ferr(po, "opr %d: const expected\n", opr_num);
1136 return po->operand[opr_num].val;
1139 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1141 if ((unsigned int)popr->reg >= MAX_REGS)
1142 ferr(po, "invalid reg: %d\n", popr->reg);
1143 return regs_r32[popr->reg];
1146 // cast1 is the "final" cast
1147 static const char *simplify_cast(const char *cast1, const char *cast2)
1149 static char buf[256];
1155 if (IS(cast1, cast2))
1157 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1159 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1161 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1163 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1166 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1170 static const char *simplify_cast_num(const char *cast, unsigned int val)
1172 if (IS(cast, "(u8)") && val < 0x100)
1174 if (IS(cast, "(s8)") && val < 0x80)
1176 if (IS(cast, "(u16)") && val < 0x10000)
1178 if (IS(cast, "(s16)") && val < 0x8000)
1180 if (IS(cast, "(s32)") && val < 0x80000000)
1186 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1195 namelen = strlen(name);
1197 p = strchr(name, '+');
1201 ferr(po, "equ parse failed for '%s'\n", name);
1203 if (IS_START(p, "0x"))
1205 *extra_offs = strtol(p, &endp, 16);
1207 ferr(po, "equ parse failed for '%s'\n", name);
1210 for (i = 0; i < g_eqcnt; i++)
1211 if (strncmp(g_eqs[i].name, name, namelen) == 0
1212 && g_eqs[i].name[namelen] == 0)
1216 ferr(po, "unresolved equ name: '%s'\n", name);
1223 static void stack_frame_access(struct parsed_op *po,
1224 struct parsed_opr *popr, char *buf, size_t buf_size,
1225 const char *name, const char *cast, int is_src, int is_lea)
1227 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1228 const char *prefix = "";
1229 const char *bp_arg = NULL;
1230 char ofs_reg[16] = { 0, };
1231 struct parsed_equ *eq;
1234 int i, arg_i, arg_s;
1241 if (po->flags & OPF_EBP_S)
1242 ferr(po, "stack_frame_access while ebp is scratch\n");
1244 if (IS_START(name, "ebp-")
1245 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1248 if (IS_START(p, "0x"))
1250 offset = strtoul(p, &endp, 16);
1254 ferr(po, "ebp- parse of '%s' failed\n", name);
1257 bp_arg = parse_stack_el(name, ofs_reg);
1258 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1259 eq = equ_find(po, bp_arg, &offset);
1261 ferr(po, "detected but missing eq\n");
1262 offset += eq->offset;
1265 if (!strncmp(name, "ebp", 3))
1268 if (ofs_reg[0] == 0 && stack_ra <= offset && offset < stack_ra + 4)
1269 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
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);
1381 if (g_stack_fsz == 0)
1382 ferr(po, "stack var access without stackframe\n");
1383 g_stack_frame_used = 1;
1385 sf_ofs = g_stack_fsz + offset;
1386 lim = (ofs_reg[0] != 0) ? -4 : 0;
1387 if (offset > 0 || sf_ofs < lim)
1388 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1398 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1399 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1403 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1404 // known unaligned or possibly unaligned
1405 strcat(g_comment, " unaligned");
1407 prefix = "*(u16 *)&";
1408 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1409 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1412 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1416 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1417 // known unaligned or possibly unaligned
1418 strcat(g_comment, " unaligned");
1420 prefix = "*(u32 *)&";
1421 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1422 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1425 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1429 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1434 static void check_label_read_ref(struct parsed_op *po, const char *name)
1436 const struct parsed_proto *pp;
1438 pp = proto_parse(g_fhdr, name);
1440 ferr(po, "proto_parse failed for ref '%s'\n", name);
1442 // currently we can take __cdecl and __stdcall
1443 if (pp->is_func && pp->argc_reg != 0)
1444 ferr(po, "reg-arg func reference?\n");
1447 static char *out_src_opr(char *buf, size_t buf_size,
1448 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1451 char tmp1[256], tmp2[256];
1459 switch (popr->type) {
1462 ferr(po, "lea from reg?\n");
1464 switch (popr->lmod) {
1466 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1469 snprintf(buf, buf_size, "%s%s",
1470 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1473 if (popr->name[1] == 'h') // XXX..
1474 snprintf(buf, buf_size, "%s(%s >> 8)",
1475 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1477 snprintf(buf, buf_size, "%s%s",
1478 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1481 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1486 if (parse_stack_el(popr->name, NULL)
1487 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1488 && IS_START(popr->name, "ebp")))
1490 stack_frame_access(po, popr, buf, buf_size,
1491 popr->name, cast, 1, is_lea);
1495 strcpy(expr, popr->name);
1496 if (strchr(expr, '[')) {
1497 // special case: '[' can only be left for label[reg] form
1498 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1500 ferr(po, "parse failure for '%s'\n", expr);
1501 if (tmp1[0] == '(') {
1502 // (off_4FFF50+3)[eax]
1503 p = strchr(tmp1 + 1, ')');
1504 if (p == NULL || p[1] != 0)
1505 ferr(po, "parse failure (2) for '%s'\n", expr);
1507 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1509 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1512 // XXX: do we need more parsing?
1514 snprintf(buf, buf_size, "%s", expr);
1518 snprintf(buf, buf_size, "%s(%s)",
1519 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1523 check_label_read_ref(po, popr->name);
1524 if (cast[0] == 0 && popr->is_ptr)
1528 snprintf(buf, buf_size, "(u32)&%s", popr->name);
1529 else if (popr->size_lt)
1530 snprintf(buf, buf_size, "%s%s%s%s", cast,
1531 lmod_cast_u_ptr(po, popr->lmod),
1532 popr->is_array ? "" : "&",
1535 snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1536 popr->is_array ? "[0]" : "");
1540 check_label_read_ref(po, popr->name);
1544 ferr(po, "lea an offset?\n");
1545 snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1550 ferr(po, "lea from const?\n");
1552 printf_number(tmp1, sizeof(tmp1), popr->val);
1553 snprintf(buf, buf_size, "%s%s",
1554 simplify_cast_num(cast, popr->val), tmp1);
1558 ferr(po, "invalid src type: %d\n", popr->type);
1564 // note: may set is_ptr (we find that out late for ebp frame..)
1565 static char *out_dst_opr(char *buf, size_t buf_size,
1566 struct parsed_op *po, struct parsed_opr *popr)
1568 switch (popr->type) {
1570 switch (popr->lmod) {
1572 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1576 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1580 if (popr->name[1] == 'h') // XXX..
1581 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1583 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1586 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1591 if (parse_stack_el(popr->name, NULL)
1592 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1593 && IS_START(popr->name, "ebp")))
1595 stack_frame_access(po, popr, buf, buf_size,
1596 popr->name, "", 0, 0);
1600 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1603 if (popr->size_mismatch)
1604 snprintf(buf, buf_size, "%s%s%s",
1605 lmod_cast_u_ptr(po, popr->lmod),
1606 popr->is_array ? "" : "&", popr->name);
1608 snprintf(buf, buf_size, "%s%s", popr->name,
1609 popr->is_array ? "[0]" : "");
1613 ferr(po, "invalid dst type: %d\n", popr->type);
1619 static char *out_src_opr_u32(char *buf, size_t buf_size,
1620 struct parsed_op *po, struct parsed_opr *popr)
1622 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1625 static enum parsed_flag_op split_cond(struct parsed_op *po,
1626 enum op_op op, int *is_inv)
1678 ferr(po, "split_cond: bad op %d\n", op);
1683 static void out_test_for_cc(char *buf, size_t buf_size,
1684 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1685 enum opr_lenmod lmod, const char *expr)
1687 const char *cast, *scast;
1689 cast = lmod_cast_u(po, lmod);
1690 scast = lmod_cast_s(po, lmod);
1694 case PFO_BE: // CF=1||ZF=1; CF=0
1695 snprintf(buf, buf_size, "(%s%s %s 0)",
1696 cast, expr, is_inv ? "!=" : "==");
1700 case PFO_L: // SF!=OF; OF=0
1701 snprintf(buf, buf_size, "(%s%s %s 0)",
1702 scast, expr, is_inv ? ">=" : "<");
1705 case PFO_LE: // ZF=1||SF!=OF; OF=0
1706 snprintf(buf, buf_size, "(%s%s %s 0)",
1707 scast, expr, is_inv ? ">" : "<=");
1711 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1715 static void out_cmp_for_cc(char *buf, size_t buf_size,
1716 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1718 const char *cast, *scast, *cast_use;
1719 char buf1[256], buf2[256];
1720 enum opr_lenmod lmod;
1722 if (po->operand[0].lmod != po->operand[1].lmod)
1723 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1724 po->operand[0].lmod, po->operand[1].lmod);
1725 lmod = po->operand[0].lmod;
1727 cast = lmod_cast_u(po, lmod);
1728 scast = lmod_cast_s(po, lmod);
1744 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1747 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1748 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1752 // note: must be unsigned compare
1753 snprintf(buf, buf_size, "(%s %s %s)",
1754 buf1, is_inv ? ">=" : "<", buf2);
1758 snprintf(buf, buf_size, "(%s %s %s)",
1759 buf1, is_inv ? "!=" : "==", buf2);
1763 // note: must be unsigned compare
1764 snprintf(buf, buf_size, "(%s %s %s)",
1765 buf1, is_inv ? ">" : "<=", buf2);
1768 if (is_inv && lmod == OPLM_BYTE
1769 && po->operand[1].type == OPT_CONST
1770 && po->operand[1].val == 0xff)
1772 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1773 snprintf(buf, buf_size, "(0)");
1777 // note: must be signed compare
1779 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1780 scast, buf1, buf2, is_inv ? ">=" : "<");
1784 snprintf(buf, buf_size, "(%s %s %s)",
1785 buf1, is_inv ? ">=" : "<", buf2);
1789 snprintf(buf, buf_size, "(%s %s %s)",
1790 buf1, is_inv ? ">" : "<=", buf2);
1798 static void out_cmp_test(char *buf, size_t buf_size,
1799 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1801 char buf1[256], buf2[256], buf3[256];
1803 if (po->op == OP_TEST) {
1804 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1805 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1808 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1809 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1810 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1812 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1813 po->operand[0].lmod, buf3);
1815 else if (po->op == OP_CMP) {
1816 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1819 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1822 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1823 struct parsed_opr *popr2)
1825 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1826 ferr(po, "missing lmod for both operands\n");
1828 if (popr1->lmod == OPLM_UNSPEC)
1829 popr1->lmod = popr2->lmod;
1830 else if (popr2->lmod == OPLM_UNSPEC)
1831 popr2->lmod = popr1->lmod;
1832 else if (popr1->lmod != popr2->lmod) {
1833 if (popr1->type_from_var) {
1834 popr1->size_mismatch = 1;
1835 if (popr1->lmod < popr2->lmod)
1837 popr1->lmod = popr2->lmod;
1839 else if (popr2->type_from_var) {
1840 popr2->size_mismatch = 1;
1841 if (popr2->lmod < popr1->lmod)
1843 popr2->lmod = popr1->lmod;
1846 ferr(po, "conflicting lmods: %d vs %d\n",
1847 popr1->lmod, popr2->lmod);
1851 static const char *op_to_c(struct parsed_op *po)
1875 ferr(po, "op_to_c was supplied with %d\n", po->op);
1879 static void op_set_clear_flag(struct parsed_op *po,
1880 enum op_flags flag_set, enum op_flags flag_clear)
1882 po->flags |= flag_set;
1883 po->flags &= ~flag_clear;
1886 // last op in stream - unconditional branch or ret
1887 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1888 || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1890 static int scan_for_pop(int i, int opcnt, const char *reg,
1891 int magic, int depth, int *maxdepth, int do_flags)
1893 struct parsed_op *po;
1897 for (; i < opcnt; i++) {
1899 if (po->cc_scratch == magic)
1900 break; // already checked
1901 po->cc_scratch = magic;
1903 if (po->flags & OPF_TAIL)
1904 return -1; // deadend
1906 if ((po->flags & OPF_RMD)
1907 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1910 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1911 if (po->btj != NULL) {
1913 for (j = 0; j < po->btj->count - 1; j++) {
1914 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1915 depth, maxdepth, do_flags);
1917 return ret; // dead end
1919 // follow last jumptable entry
1920 i = po->btj->d[j].bt_i - 1;
1925 ferr(po, "dead branch\n");
1929 if (po->flags & OPF_CC) {
1930 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1931 depth, maxdepth, do_flags);
1933 return ret; // dead end
1941 if ((po->op == OP_POP || po->op == OP_PUSH)
1942 && po->operand[0].type == OPT_REG
1943 && IS(po->operand[0].name, reg))
1945 if (po->op == OP_PUSH) {
1947 if (depth > *maxdepth)
1950 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1952 else if (depth == 0) {
1954 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1959 if (depth < 0) // should not happen
1960 ferr(po, "fail with depth\n");
1962 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1970 // scan for pop starting from 'ret' op (all paths)
1971 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
1977 for (; i < opcnt; i++) {
1978 if (!(ops[i].flags & OPF_TAIL))
1981 for (j = i - 1; j >= 0; j--) {
1982 if (ops[j].flags & OPF_RMD)
1984 if (ops[j].flags & OPF_JMP)
1987 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
1988 && IS(ops[j].operand[0].name, reg))
1991 ops[j].flags |= flag_set;
1995 if (g_labels[j][0] != 0)
2000 return found ? 0 : -1;
2003 // is operand 'opr modified' by parsed_op 'po'?
2004 static int is_opr_modified(const struct parsed_opr *opr,
2005 const struct parsed_op *po)
2007 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2010 if (opr->type == OPT_REG && po->operand[0].type == OPT_REG) {
2011 if (po->regmask_dst & (1 << opr->reg))
2017 return IS(po->operand[0].name, opr->name);
2020 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2021 static int is_any_opr_modified(const struct parsed_op *po_test,
2022 const struct parsed_op *po)
2026 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2029 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2032 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2035 // in reality, it can wreck any register, but in decompiled C
2036 // version it can only overwrite eax or edx:eax
2037 if (po->op == OP_CALL
2038 && ((po_test->regmask_src | po_test->regmask_dst)
2039 & ((1 << xAX)|(1 << xDX))))
2042 for (i = 0; i < po_test->operand_cnt; i++)
2043 if (IS(po_test->operand[i].name, po->operand[0].name))
2049 // scan for any po_test operand modification in range given
2050 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt)
2052 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2055 for (; i < opcnt; i++) {
2056 if (is_any_opr_modified(po_test, &ops[i]))
2063 // scan for po_test operand[0] modification in range given
2064 static int scan_for_mod_opr0(struct parsed_op *po_test,
2067 for (; i < opcnt; i++) {
2068 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2075 static int scan_for_flag_set(int i, int magic, int *branched,
2076 int *setters, int *setter_cnt)
2078 struct label_ref *lr;
2082 if (ops[i].cc_scratch == magic) {
2083 ferr(&ops[i], "%s looped\n", __func__);
2086 ops[i].cc_scratch = magic;
2088 if (g_labels[i][0] != 0) {
2091 lr = &g_label_refs[i];
2092 for (; lr->next; lr = lr->next) {
2093 ret = scan_for_flag_set(lr->i, magic,
2094 branched, setters, setter_cnt);
2099 if (i > 0 && LAST_OP(i - 1)) {
2103 ret = scan_for_flag_set(lr->i, magic,
2104 branched, setters, setter_cnt);
2110 if (ops[i].flags & OPF_FLAGS) {
2111 setters[*setter_cnt] = i;
2116 if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2123 // scan back for cdq, if anything modifies edx, fail
2124 static int scan_for_cdq_edx(int i)
2127 if (g_labels[i][0] != 0) {
2128 if (g_label_refs[i].next != NULL)
2130 if (i > 0 && LAST_OP(i - 1)) {
2131 i = g_label_refs[i].i;
2138 if (ops[i].op == OP_CDQ)
2141 if (ops[i].regmask_dst & (1 << xDX))
2143 if (g_labels[i][0] != 0)
2150 static int scan_for_reg_clear(int i, int reg)
2153 if (g_labels[i][0] != 0) {
2154 if (g_label_refs[i].next != NULL)
2156 if (i > 0 && LAST_OP(i - 1)) {
2157 i = g_label_refs[i].i;
2164 if (ops[i].op == OP_XOR
2165 && ops[i].operand[0].lmod == OPLM_DWORD
2166 && ops[i].operand[0].reg == ops[i].operand[1].reg
2167 && ops[i].operand[0].reg == reg)
2170 if (ops[i].regmask_dst & (1 << reg))
2172 if (g_labels[i][0] != 0)
2179 // scan for positive, constant esp adjust
2180 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2182 struct parsed_op *po;
2186 for (; i < opcnt; i++) {
2189 if (g_labels[i][0] != 0)
2192 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2193 if (po->operand[1].type != OPT_CONST)
2194 ferr(&ops[i], "non-const esp adjust?\n");
2195 *adj += po->operand[1].val;
2197 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2200 else if (po->op == OP_PUSH)
2201 *adj -= lmod_bytes(po, po->operand[0].lmod);
2202 else if (po->op == OP_POP)
2203 *adj += lmod_bytes(po, po->operand[0].lmod);
2204 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2205 if (po->op != OP_CALL)
2207 if (po->operand[0].type != OPT_LABEL)
2209 // TODO: should only allow combining __cdecl calls..
2213 if (*adj == 4 && ops[i_first].op == OP_POP
2214 && ops[i_first].operand[0].type == OPT_REG
2215 && ops[i_first].operand[0].reg == xCX)
2217 // probably 'pop ecx' was used..
2224 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2226 struct parsed_op *po;
2230 ferr(ops, "%s: followed bad branch?\n", __func__);
2232 for (; i < opcnt; i++) {
2234 if (po->cc_scratch == magic)
2236 po->cc_scratch = magic;
2239 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2240 if (po->btj != NULL) {
2242 for (j = 0; j < po->btj->count; j++)
2243 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2247 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2248 if (!(po->flags & OPF_CC))
2251 if (po->flags & OPF_TAIL)
2256 static int collect_call_args(struct parsed_op *po, int i,
2257 struct parsed_proto *pp, int *save_arg_vars, int arg,
2258 int magic, int need_op_saving, int may_reuse)
2260 struct parsed_proto *pp_tmp;
2261 struct label_ref *lr;
2262 int need_to_save_current;
2267 ferr(po, "dead label encountered\n");
2271 for (; arg < pp->argc; arg++)
2272 if (pp->arg[arg].reg == NULL)
2274 magic = (magic & 0xffffff) | (arg << 24);
2276 for (j = i; j >= 0 && arg < pp->argc; )
2278 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2279 if (ops[j].cc_scratch != magic) {
2280 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2284 // ok: have already been here
2287 ops[j].cc_scratch = magic;
2289 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2290 lr = &g_label_refs[j];
2291 if (lr->next != NULL)
2293 for (; lr->next; lr = lr->next) {
2294 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2296 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2297 arg, magic, need_op_saving, may_reuse);
2302 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2304 if (j > 0 && LAST_OP(j - 1)) {
2305 // follow last branch in reverse
2310 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2311 arg, magic, need_op_saving, may_reuse);
2317 if (ops[j].op == OP_CALL)
2319 pp_tmp = ops[j].datap;
2321 ferr(po, "arg collect hit unparsed call '%s'\n",
2322 ops[j].operand[0].name);
2323 if (may_reuse && pp_tmp->argc_stack > 0)
2324 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2325 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2327 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2328 ferr(po, "arg collect %d/%d hit esp adjust\n",
2331 else if (ops[j].op == OP_POP) {
2332 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2334 else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2338 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2340 pp->arg[arg].datap = &ops[j];
2341 need_to_save_current = 0;
2342 if (!need_op_saving) {
2343 ret = scan_for_mod(&ops[j], j + 1, i);
2344 need_to_save_current = (ret >= 0);
2346 if (need_op_saving || need_to_save_current) {
2347 // mark this push as one that needs operand saving
2348 ops[j].flags &= ~OPF_RMD;
2349 if (ops[j].argnum == 0) {
2350 ops[j].argnum = arg + 1;
2351 *save_arg_vars |= 1 << arg;
2353 else if (ops[j].argnum < arg + 1)
2354 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2355 ops[j].argnum, arg + 1, pp->name);
2357 else if (ops[j].argnum == 0)
2358 ops[j].flags |= OPF_RMD;
2360 // some PUSHes are reused by different calls on other branches,
2361 // but that can't happen if we didn't branch, so they
2362 // can be removed from future searches (handles nested calls)
2364 ops[j].flags |= OPF_FARG;
2367 for (arg++; arg < pp->argc; arg++)
2368 if (pp->arg[arg].reg == NULL)
2370 magic = (magic & 0xffffff) | (arg << 24);
2374 if (arg < pp->argc) {
2375 ferr(po, "arg collect failed for '%s': %d/%d\n",
2376 pp->name, arg, pp->argc);
2382 static void add_label_ref(struct label_ref *lr, int op_i)
2384 struct label_ref *lr_new;
2391 lr_new = calloc(1, sizeof(*lr_new));
2393 lr_new->next = lr->next;
2397 static void output_std_flags(FILE *fout, struct parsed_op *po,
2398 int *pfomask, const char *dst_opr_text)
2400 if (*pfomask & (1 << PFO_Z)) {
2401 fprintf(fout, "\n cond_z = (%s%s == 0);",
2402 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2403 *pfomask &= ~(1 << PFO_Z);
2405 if (*pfomask & (1 << PFO_S)) {
2406 fprintf(fout, "\n cond_s = (%s%s < 0);",
2407 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2408 *pfomask &= ~(1 << PFO_S);
2412 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2414 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2415 struct parsed_opr *last_arith_dst = NULL;
2416 char buf1[256], buf2[256], buf3[256], cast[64];
2417 const struct parsed_proto *pp_c;
2418 struct parsed_proto *pp, *pp_tmp;
2419 struct parsed_data *pd;
2420 const char *tmpname;
2421 enum parsed_flag_op pfo;
2422 int save_arg_vars = 0;
2423 int cmp_result_vars = 0;
2424 int need_mul_var = 0;
2425 int have_func_ret = 0;
2426 int have_normal_ret = 0;
2428 int label_pending = 0;
2429 int regmask_save = 0;
2430 int regmask_arg = 0;
2431 int regmask_now = 0;
2443 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2444 g_stack_frame_used = 0;
2446 g_func_pp = proto_parse(fhdr, funcn);
2447 if (g_func_pp == NULL)
2448 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2450 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2451 if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2452 fprintf(fout, "__stdcall ");
2453 if (g_ida_func_attr & IDAFA_NORETURN)
2454 fprintf(fout, "noreturn ");
2455 fprintf(fout, "%s(", funcn);
2457 for (i = 0; i < g_func_pp->argc; i++) {
2459 fprintf(fout, ", ");
2460 if (g_func_pp->arg[i].fptr != NULL) {
2462 pp = g_func_pp->arg[i].fptr;
2463 fprintf(fout, "%s (", pp->ret_type.name);
2464 if (pp->is_stdcall && pp->argc_reg == 0)
2465 fprintf(fout, "__stdcall ");
2466 fprintf(fout, "*a%d)(", i + 1);
2467 for (j = 0; j < pp->argc; j++) {
2469 fprintf(fout, ", ");
2470 if (pp->arg[j].fptr)
2471 ferr(ops, "nested fptr\n");
2472 fprintf(fout, "%s", pp->arg[j].type.name);
2477 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2480 if (g_func_pp->is_vararg) {
2482 fprintf(fout, ", ");
2483 fprintf(fout, "...");
2486 fprintf(fout, ")\n{\n");
2489 // - handle ebp/esp frame, remove ops related to it
2490 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2491 && ops[1].op == OP_MOV
2492 && IS(opr_name(&ops[1], 0), "ebp")
2493 && IS(opr_name(&ops[1], 1), "esp"))
2498 ops[0].flags |= OPF_RMD;
2499 ops[1].flags |= OPF_RMD;
2502 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2503 g_stack_fsz = opr_const(&ops[2], 1);
2504 ops[2].flags |= OPF_RMD;
2508 // another way msvc builds stack frame..
2510 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2512 ops[i].flags |= OPF_RMD;
2516 // and another way..
2517 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2518 && ops[i].operand[1].type == OPT_CONST
2519 && ops[i + 1].op == OP_CALL
2520 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2522 g_stack_fsz += ops[i].operand[1].val;
2523 ops[i].flags |= OPF_RMD;
2525 ops[i].flags |= OPF_RMD;
2532 for (; i < opcnt; i++)
2533 if (ops[i].op == OP_RET)
2535 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2538 if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2539 ops[i - 1].flags |= OPF_RMD;
2540 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2541 ferr(&ops[i - 1], "'pop ebp' expected\n");
2543 if (g_stack_fsz != 0) {
2544 if (ops[i - 2].op == OP_MOV
2545 && IS(opr_name(&ops[i - 2], 0), "esp")
2546 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2548 ops[i - 2].flags |= OPF_RMD;
2550 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2551 ferr(&ops[i - 2], "esp restore expected\n");
2553 if (ecx_push && ops[i - 3].op == OP_POP
2554 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2556 ferr(&ops[i - 3], "unexpected ecx pop\n");
2562 } while (i < opcnt);
2565 for (i = 0; i < opcnt; i++) {
2566 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2568 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2569 && ops[i].operand[1].type == OPT_CONST)
2578 g_stack_fsz = ops[i].operand[1].val;
2579 ops[i].flags |= OPF_RMD;
2583 for (; i < opcnt; i++)
2584 if (ops[i].op == OP_RET)
2586 if (ops[i - 1].op != OP_ADD
2587 || !IS(opr_name(&ops[i - 1], 0), "esp")
2588 || ops[i - 1].operand[1].type != OPT_CONST
2589 || ops[i - 1].operand[1].val != g_stack_fsz)
2590 ferr(&ops[i - 1], "'add esp' expected\n");
2591 ops[i - 1].flags |= OPF_RMD;
2594 } while (i < opcnt);
2599 // - parse calls with labels
2600 // - resolve all branches
2601 for (i = 0; i < opcnt; i++)
2607 if (po->flags & OPF_RMD)
2610 if (po->op == OP_CALL) {
2611 if (po->operand[0].type == OPT_LABEL) {
2612 tmpname = opr_name(po, 0);
2613 pp_c = proto_parse(fhdr, tmpname);
2615 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2616 if (pp_c->is_fptr && pp_c->argc_reg != 0)
2617 ferr(po, "fptr call with reg arg\n");
2618 pp = proto_clone(pp_c);
2619 my_assert_not(pp, NULL);
2625 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2628 if (po->operand[0].type == OPT_REGMEM) {
2629 char *p = strchr(po->operand[0].name, '[');
2631 ferr(po, "unhandled indirect branch\n");
2632 ret = p - po->operand[0].name;
2633 strncpy(buf1, po->operand[0].name, ret);
2636 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2637 if (IS(g_func_pd[j].label, buf1)) {
2643 //ferr(po, "label '%s' not parsed?\n", buf1);
2645 if (pd->type != OPT_OFFSET)
2646 ferr(po, "label '%s' with non-offset data?\n", buf1);
2648 // find all labels, link
2649 for (j = 0; j < pd->count; j++) {
2650 for (l = 0; l < opcnt; l++) {
2651 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2652 add_label_ref(&g_label_refs[l], i);
2663 for (l = 0; l < opcnt; l++) {
2664 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2665 add_label_ref(&g_label_refs[l], i);
2674 if (po->operand[0].type == OPT_LABEL)
2678 ferr(po, "unhandled branch\n");
2682 po->flags |= OPF_TAIL;
2687 // - remove dead labels
2689 for (i = 0; i < opcnt; i++)
2691 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
2695 if (po->flags & OPF_RMD)
2698 if (po->op == OP_CALL)
2700 tmpname = opr_name(po, 0);
2705 pp = calloc(1, sizeof(*pp));
2706 my_assert_not(pp, NULL);
2707 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2709 ferr(po, "non-__cdecl indirect call unhandled yet\n");
2711 if (j > ARRAY_SIZE(pp->arg))
2712 ferr(po, "esp adjust too large?\n");
2713 pp->ret_type.name = strdup("int");
2714 pp->argc = pp->argc_stack = j;
2715 for (arg = 0; arg < pp->argc; arg++)
2716 pp->arg[arg].type.name = strdup("int");
2720 // look for and make use of esp adjust
2722 if (!pp->is_stdcall && pp->argc_stack > 0)
2723 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2725 if (pp->is_vararg) {
2726 if (j / 4 < pp->argc_stack)
2727 ferr(po, "esp adjust is too small: %x < %x\n",
2728 j, pp->argc_stack * 4);
2729 // modify pp to make it have varargs as normal args
2731 pp->argc += j / 4 - pp->argc_stack;
2732 for (; arg < pp->argc; arg++) {
2733 pp->arg[arg].type.name = strdup("int");
2736 if (pp->argc > ARRAY_SIZE(pp->arg))
2737 ferr(po, "too many args for '%s'\n", tmpname);
2739 if (pp->argc_stack != j / 4)
2740 ferr(po, "stack tracking failed for '%s': %x %x\n",
2741 tmpname, pp->argc_stack * 4, j);
2743 ops[ret].flags |= OPF_RMD;
2744 // a bit of a hack, but deals with use of
2745 // single adj for multiple calls
2746 ops[ret].operand[1].val -= j;
2748 else if (pp->is_vararg)
2749 ferr(po, "missing esp_adjust for vararg func '%s'\n",
2752 // can't call functions with non-__cdecl callbacks yet
2753 for (arg = 0; arg < pp->argc; arg++) {
2754 if (pp->arg[arg].fptr != NULL) {
2755 pp_tmp = pp->arg[arg].fptr;
2756 if (pp_tmp->is_stdcall || pp_tmp->argc != pp_tmp->argc_stack)
2757 ferr(po, "'%s' has a non-__cdecl callback\n", tmpname);
2761 collect_call_args(po, i, pp, &save_arg_vars,
2762 0, i + opcnt * 2, 0, 0);
2764 if (strstr(pp->ret_type.name, "int64"))
2766 if (!(po->flags & OPF_TAIL) && !IS(pp->ret_type.name, "void"))
2772 // - find POPs for PUSHes, rm both
2773 // - scan for all used registers
2774 // - find flag set ops for their users
2775 // - declare indirect functions
2776 for (i = 0; i < opcnt; i++) {
2778 if (po->flags & OPF_RMD)
2781 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
2782 reg = po->operand[0].reg;
2783 if (!(regmask & (1 << reg)))
2784 // not a reg save after all, rerun scan_for_pop
2785 po->flags &= ~OPF_RSAVE;
2787 regmask_save |= 1 << reg;
2790 if (po->op == OP_PUSH
2791 && po->argnum == 0 && !(po->flags & OPF_RSAVE)
2792 && po->operand[0].type == OPT_REG)
2794 reg = po->operand[0].reg;
2796 ferr(po, "reg not set for push?\n");
2799 ret = scan_for_pop(i + 1, opcnt,
2800 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
2803 ferr(po, "too much depth: %d\n", depth);
2805 po->flags |= OPF_RMD;
2806 scan_for_pop(i + 1, opcnt, po->operand[0].name,
2807 i + opcnt * 4, 0, &depth, 1);
2810 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
2813 if (regmask & (1 << reg)) {
2814 if (regmask_save & (1 << reg))
2815 ferr(po, "%s already saved?\n", po->operand[0].name);
2819 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
2824 regmask_now = po->regmask_src | po->regmask_dst;
2825 if (regmask_now & (1 << xBP)) {
2826 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
2827 if (po->regmask_dst & (1 << xBP))
2828 // compiler decided to drop bp frame and use ebp as scratch
2829 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
2831 regmask_now &= ~(1 << xBP);
2835 regmask |= regmask_now;
2837 if (po->flags & OPF_CC)
2839 int setters[16], cnt = 0, branched = 0;
2841 ret = scan_for_flag_set(i, i + opcnt * 6,
2842 &branched, setters, &cnt);
2843 if (ret < 0 || cnt <= 0)
2844 ferr(po, "unable to trace flag setter(s)\n");
2845 if (cnt > ARRAY_SIZE(setters))
2846 ferr(po, "too many flag setters\n");
2848 pfo = split_cond(po, po->op, &dummy);
2849 for (j = 0; j < cnt; j++)
2851 tmp_op = &ops[setters[j]]; // flag setter
2854 // to get nicer code, we try to delay test and cmp;
2855 // if we can't because of operand modification, or if we
2856 // have math op, or branch, make it calculate flags explicitly
2857 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
2858 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i) >= 0)
2861 else if (tmp_op->op == OP_CMPS) {
2862 pfomask = 1 << PFO_Z;
2865 // see if we'll be able to handle based on op result
2866 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
2867 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
2869 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
2873 tmp_op->pfomask |= pfomask;
2874 cmp_result_vars |= pfomask;
2876 // note: may overwrite, currently not a problem
2880 if (po->op == OP_ADC || po->op == OP_SBB)
2881 cmp_result_vars |= 1 << PFO_C;
2883 else if (po->op == OP_MUL
2884 || (po->op == OP_IMUL && po->operand_cnt == 1))
2888 else if (po->op == OP_CALL && po->operand[0].type != OPT_LABEL) {
2890 my_assert_not(pp, NULL);
2891 fprintf(fout, " %s (*icall%d)(", pp->ret_type.name, i);
2892 for (j = 0; j < pp->argc; j++) {
2894 fprintf(fout, ", ");
2895 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
2897 fprintf(fout, ");\n");
2899 else if (po->op == OP_RET)
2900 have_normal_ret = 1;
2903 // output LUTs/jumptables
2904 for (i = 0; i < g_func_pd_cnt; i++) {
2906 fprintf(fout, " static const ");
2907 if (pd->type == OPT_OFFSET) {
2908 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
2910 for (j = 0; j < pd->count; j++) {
2912 fprintf(fout, ", ");
2913 fprintf(fout, "&&%s", pd->d[j].u.label);
2917 fprintf(fout, "%s %s[] =\n { ",
2918 lmod_type_u(ops, pd->lmod), pd->label);
2920 for (j = 0; j < pd->count; j++) {
2922 fprintf(fout, ", ");
2923 fprintf(fout, "%u", pd->d[j].u.val);
2926 fprintf(fout, " };\n");
2929 // declare stack frame, va_arg
2931 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
2932 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
2934 if (g_func_pp->is_vararg)
2935 fprintf(fout, " va_list ap;\n");
2937 // declare arg-registers
2938 for (i = 0; i < g_func_pp->argc; i++) {
2939 if (g_func_pp->arg[i].reg != NULL) {
2940 reg = char_array_i(regs_r32,
2941 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2943 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2945 regmask_arg |= 1 << reg;
2946 fprintf(fout, " u32 %s = (u32)a%d;\n",
2947 g_func_pp->arg[i].reg, i + 1);
2952 // declare other regs - special case for eax
2953 if (!((regmask | regmask_arg) & 1)
2954 && (have_func_ret || have_normal_ret)
2955 && !IS(g_func_pp->ret_type.name, "void"))
2957 fprintf(fout, " u32 eax = 0;\n");
2961 regmask &= ~regmask_arg;
2962 regmask &= ~(1 << xSP);
2964 for (reg = 0; reg < 8; reg++) {
2965 if (regmask & (1 << reg)) {
2966 fprintf(fout, " u32 %s;\n", regs_r32[reg]);
2973 for (reg = 0; reg < 8; reg++) {
2974 if (regmask_save & (1 << reg)) {
2975 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
2981 if (save_arg_vars) {
2982 for (reg = 0; reg < 32; reg++) {
2983 if (save_arg_vars & (1 << reg)) {
2984 fprintf(fout, " u32 s_a%d;\n", reg + 1);
2990 if (cmp_result_vars) {
2991 for (i = 0; i < 8; i++) {
2992 if (cmp_result_vars & (1 << i)) {
2993 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3000 fprintf(fout, " u64 mul_tmp;\n");
3005 fprintf(fout, "\n");
3007 if (g_func_pp->is_vararg) {
3008 if (g_func_pp->argc_stack == 0)
3009 ferr(ops, "vararg func without stack args?\n");
3010 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3014 for (i = 0; i < opcnt; i++)
3016 if (g_labels[i][0] != 0) {
3017 fprintf(fout, "\n%s:\n", g_labels[i]);
3020 delayed_flag_op = NULL;
3021 last_arith_dst = NULL;
3025 if (po->flags & OPF_RMD)
3030 #define assert_operand_cnt(n_) \
3031 if (po->operand_cnt != n_) \
3032 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3034 // conditional/flag using op?
3035 if (po->flags & OPF_CC)
3040 pfo = split_cond(po, po->op, &is_inv);
3043 // we go through all this trouble to avoid using parsed_flag_op,
3044 // which makes generated code much nicer
3045 if (delayed_flag_op != NULL)
3047 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3050 else if (last_arith_dst != NULL
3051 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3052 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3055 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3056 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3057 last_arith_dst->lmod, buf3);
3060 else if (tmp_op != NULL) {
3061 // use preprocessed flag calc results
3062 if (!(tmp_op->pfomask & (1 << pfo)))
3063 ferr(po, "not prepared for pfo %d\n", pfo);
3065 // note: is_inv was not yet applied
3066 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3067 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3070 ferr(po, "all methods of finding comparison failed\n");
3073 if (po->flags & OPF_JMP) {
3074 fprintf(fout, " if %s\n", buf1);
3076 else if (po->op == OP_ADC || po->op == OP_SBB) {
3078 fprintf(fout, " cond_%s = %s;\n",
3079 parsed_flag_op_names[pfo], buf1);
3081 else if (po->flags & OPF_DATA) { // SETcc
3082 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3083 fprintf(fout, " %s = %s;", buf2, buf1);
3086 ferr(po, "unhandled conditional op\n");
3090 pfomask = po->pfomask;
3095 assert_operand_cnt(2);
3096 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3097 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3098 fprintf(fout, " %s = %s;", buf1,
3099 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3100 po->operand[0].is_ptr ? "(void *)" : "", 0));
3104 assert_operand_cnt(2);
3105 po->operand[1].lmod = OPLM_DWORD; // always
3106 fprintf(fout, " %s = %s;",
3107 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3108 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3113 assert_operand_cnt(2);
3114 fprintf(fout, " %s = %s;",
3115 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3116 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3120 assert_operand_cnt(2);
3121 switch (po->operand[1].lmod) {
3123 strcpy(buf3, "(s8)");
3126 strcpy(buf3, "(s16)");
3129 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3131 fprintf(fout, " %s = %s;",
3132 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3133 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3138 assert_operand_cnt(1);
3139 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3140 fprintf(fout, " %s = ~%s;", buf1, buf1);
3144 assert_operand_cnt(2);
3145 fprintf(fout, " %s = (s32)%s >> 31;",
3146 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3147 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3148 strcpy(g_comment, "cdq");
3153 assert_operand_cnt(3);
3154 if (po->flags & OPF_REP) {
3155 fprintf(fout, " for (; ecx != 0; ecx--, edi += %d)\n",
3156 lmod_bytes(po, po->operand[0].lmod));
3157 fprintf(fout, " %sedi = eax;",
3158 lmod_cast_u_ptr(po, po->operand[0].lmod));
3159 strcpy(g_comment, "rep stos");
3162 fprintf(fout, " %sedi = eax; edi += %d;",
3163 lmod_cast_u_ptr(po, po->operand[0].lmod),
3164 lmod_bytes(po, po->operand[0].lmod));
3165 strcpy(g_comment, "stos");
3171 assert_operand_cnt(3);
3172 j = lmod_bytes(po, po->operand[0].lmod);
3173 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3174 if (po->flags & OPF_REP) {
3176 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3179 " %sedi = %sesi;", buf1, buf1);
3180 strcpy(g_comment, "rep movs");
3183 fprintf(fout, " %sedi = %sesi; edi += %d; esi += %d;",
3185 strcpy(g_comment, "movs");
3191 // repe ~ repeat while ZF=1
3192 assert_operand_cnt(3);
3193 j = lmod_bytes(po, po->operand[0].lmod);
3194 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3195 if (po->flags & OPF_REP) {
3197 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3200 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3201 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3204 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3205 (po->flags & OPF_REPZ) ? "e" : "ne");
3209 " cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3211 strcpy(g_comment, "cmps");
3213 pfomask &= ~(1 << PFO_Z);
3214 last_arith_dst = NULL;
3215 delayed_flag_op = NULL;
3218 // arithmetic w/flags
3223 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3226 assert_operand_cnt(2);
3227 fprintf(fout, " %s %s= %s;",
3228 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3230 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3231 output_std_flags(fout, po, &pfomask, buf1);
3232 last_arith_dst = &po->operand[0];
3233 delayed_flag_op = NULL;
3238 assert_operand_cnt(2);
3239 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3240 if (pfomask & (1 << PFO_C)) {
3241 if (po->operand[1].type == OPT_CONST) {
3242 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3243 j = po->operand[1].val;
3246 if (po->op == OP_SHL)
3250 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3254 ferr(po, "zero shift?\n");
3258 pfomask &= ~(1 << PFO_C);
3260 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3261 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3262 output_std_flags(fout, po, &pfomask, buf1);
3263 last_arith_dst = &po->operand[0];
3264 delayed_flag_op = NULL;
3268 assert_operand_cnt(2);
3269 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3270 fprintf(fout, " %s = %s%s >> %s;", buf1,
3271 lmod_cast_s(po, po->operand[0].lmod), buf1,
3272 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3273 output_std_flags(fout, po, &pfomask, buf1);
3274 last_arith_dst = &po->operand[0];
3275 delayed_flag_op = NULL;
3280 assert_operand_cnt(2);
3281 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3282 if (po->operand[1].type == OPT_CONST) {
3283 j = po->operand[1].val;
3284 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3285 fprintf(fout, po->op == OP_ROL ?
3286 " %s = (%s << %d) | (%s >> %d);" :
3287 " %s = (%s >> %d) | (%s << %d);",
3288 buf1, buf1, j, buf1,
3289 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3293 output_std_flags(fout, po, &pfomask, buf1);
3294 last_arith_dst = &po->operand[0];
3295 delayed_flag_op = NULL;
3299 assert_operand_cnt(2);
3300 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3301 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3302 // special case for XOR
3303 fprintf(fout, " %s = 0;",
3304 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3305 last_arith_dst = &po->operand[0];
3306 delayed_flag_op = NULL;
3313 assert_operand_cnt(2);
3314 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3315 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3316 if (po->op == OP_SBB
3317 && IS(po->operand[0].name, po->operand[1].name))
3319 // avoid use of unitialized var
3320 fprintf(fout, " %s = -cond_c;", buf1);
3321 // carry remains what it was
3322 pfomask &= ~(1 << PFO_C);
3325 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3326 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3328 output_std_flags(fout, po, &pfomask, buf1);
3329 last_arith_dst = &po->operand[0];
3330 delayed_flag_op = NULL;
3335 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3336 if (po->operand[0].type == OPT_REG) {
3337 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3338 fprintf(fout, " %s%s;", buf1, buf2);
3341 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3342 fprintf(fout, " %s %s= 1;", buf1, buf2);
3344 output_std_flags(fout, po, &pfomask, buf1);
3345 last_arith_dst = &po->operand[0];
3346 delayed_flag_op = NULL;
3350 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3351 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3352 fprintf(fout, " %s = -%s%s;", buf1,
3353 lmod_cast_s(po, po->operand[0].lmod), buf2);
3354 last_arith_dst = &po->operand[0];
3355 delayed_flag_op = NULL;
3356 if (pfomask & (1 << PFO_C)) {
3357 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3358 pfomask &= ~(1 << PFO_C);
3363 if (po->operand_cnt == 2) {
3364 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3367 if (po->operand_cnt == 3)
3368 ferr(po, "TODO imul3\n");
3371 assert_operand_cnt(1);
3372 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3373 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3374 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3375 fprintf(fout, " edx = mul_tmp >> 32;\n");
3376 fprintf(fout, " eax = mul_tmp;");
3377 last_arith_dst = NULL;
3378 delayed_flag_op = NULL;
3383 assert_operand_cnt(1);
3384 if (po->operand[0].lmod != OPLM_DWORD)
3385 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3387 // 32bit division is common, look for it
3388 if (po->op == OP_DIV)
3389 ret = scan_for_reg_clear(i, xDX);
3391 ret = scan_for_cdq_edx(i);
3393 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3394 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3395 po->op == OP_IDIV));
3396 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3397 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3400 ferr(po, "TODO 64bit divident\n");
3401 last_arith_dst = NULL;
3402 delayed_flag_op = NULL;
3407 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3409 for (j = 0; j < 8; j++) {
3410 if (pfomask & (1 << j)) {
3411 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3412 fprintf(fout, " cond_%s = %s;",
3413 parsed_flag_op_names[j], buf1);
3420 last_arith_dst = NULL;
3421 delayed_flag_op = po;
3424 // note: we reuse OP_Jcc for SETcc, only flags differ
3425 case OP_JO ... OP_JG:
3426 if (po->flags & OPF_JMP)
3427 fprintf(fout, " goto %s;", po->operand[0].name);
3428 // else SETcc - should already be handled
3432 assert_operand_cnt(1);
3433 last_arith_dst = NULL;
3434 delayed_flag_op = NULL;
3436 if (po->operand[0].type == OPT_REGMEM) {
3437 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3440 ferr(po, "parse failure for jmp '%s'\n",
3441 po->operand[0].name);
3442 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
3445 else if (po->operand[0].type != OPT_LABEL)
3446 ferr(po, "unhandled jmp type\n");
3448 fprintf(fout, " goto %s;", po->operand[0].name);
3452 assert_operand_cnt(1);
3455 ferr(po, "NULL pp\n");
3457 if (po->operand[0].type != OPT_LABEL)
3458 fprintf(fout, " icall%d = (void *)%s;\n", i,
3459 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]));
3462 if (strstr(pp->ret_type.name, "int64")) {
3463 if (po->flags & OPF_TAIL)
3464 ferr(po, "int64 and tail?\n");
3465 fprintf(fout, "mul_tmp = ");
3467 else if (!IS(pp->ret_type.name, "void")) {
3468 if (po->flags & OPF_TAIL) {
3469 if (!IS(g_func_pp->ret_type.name, "void")) {
3470 fprintf(fout, "return ");
3471 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3472 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3476 fprintf(fout, "eax = ");
3477 if (pp->ret_type.is_ptr)
3478 fprintf(fout, "(u32)");
3482 if (po->operand[0].type != OPT_LABEL) {
3483 fprintf(fout, "icall%d(", i);
3486 if (pp->name[0] == 0)
3487 ferr(po, "missing pp->name\n");
3488 fprintf(fout, "%s%s(", pp->name,
3489 pp->has_structarg ? "_sa" : "");
3492 for (arg = 0; arg < pp->argc; arg++) {
3494 fprintf(fout, ", ");
3497 if (pp->arg[arg].type.is_ptr)
3498 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3500 if (pp->arg[arg].reg != NULL) {
3501 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3506 tmp_op = pp->arg[arg].datap;
3508 ferr(po, "parsed_op missing for arg%d\n", arg);
3509 if (tmp_op->argnum != 0) {
3510 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3514 out_src_opr(buf1, sizeof(buf1),
3515 tmp_op, &tmp_op->operand[0], cast, 0));
3518 fprintf(fout, ");");
3520 if (strstr(pp->ret_type.name, "int64")) {
3521 fprintf(fout, "\n");
3522 fprintf(fout, " edx = mul_tmp >> 32;\n");
3523 fprintf(fout, " eax = mul_tmp;");
3526 if (po->flags & OPF_TAIL) {
3527 strcpy(g_comment, "tailcall");
3531 else if (IS(pp->ret_type.name, "void"))
3533 else if (IS(g_func_pp->ret_type.name, "void"))
3535 // else already handled as 'return f()'
3538 if (!IS(g_func_pp->ret_type.name, "void"))
3539 ferr(po, "int func -> void func tailcall?\n");
3540 fprintf(fout, "\n return;");
3541 strcpy(g_comment, "^ tailcall");
3544 delayed_flag_op = NULL;
3545 last_arith_dst = NULL;
3549 if (g_func_pp->is_vararg)
3550 fprintf(fout, " va_end(ap);\n");
3552 if (IS(g_func_pp->ret_type.name, "void")) {
3553 if (i != opcnt - 1 || label_pending)
3554 fprintf(fout, " return;");
3556 else if (g_func_pp->ret_type.is_ptr) {
3557 fprintf(fout, " return (%s)eax;",
3558 g_func_pp->ret_type.name);
3561 fprintf(fout, " return eax;");
3563 last_arith_dst = NULL;
3564 delayed_flag_op = NULL;
3568 if (po->argnum != 0) {
3569 // special case - saved func arg
3570 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3571 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
3574 else if (po->flags & OPF_RSAVE) {
3575 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3576 fprintf(fout, " s_%s = %s;", buf1, buf1);
3579 if (!(g_ida_func_attr & IDAFA_NORETURN))
3580 ferr(po, "stray push encountered\n");
3585 if (po->flags & OPF_RSAVE) {
3586 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3587 fprintf(fout, " %s = s_%s;", buf1, buf1);
3590 ferr(po, "stray pop encountered\n");
3599 ferr(po, "unhandled op type %d, flags %x\n",
3604 if (g_comment[0] != 0) {
3605 fprintf(fout, " // %s", g_comment);
3610 fprintf(fout, "\n");
3612 // some sanity checking
3613 if ((po->flags & OPF_REP) && po->op != OP_STOS
3614 && po->op != OP_MOVS && po->op != OP_CMPS)
3615 ferr(po, "unexpected rep\n");
3616 if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3617 ferr(po, "unexpected repz/repnz\n");
3620 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3622 // see is delayed flag stuff is still valid
3623 if (delayed_flag_op != NULL && delayed_flag_op != po) {
3624 if (is_any_opr_modified(delayed_flag_op, po))
3625 delayed_flag_op = NULL;
3628 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3629 if (is_opr_modified(last_arith_dst, po))
3630 last_arith_dst = NULL;
3636 if (g_stack_fsz && !g_stack_frame_used)
3637 fprintf(fout, " (void)sf;\n");
3639 fprintf(fout, "}\n\n");
3642 for (i = 0; i < opcnt; i++) {
3643 struct label_ref *lr, *lr_del;
3645 lr = g_label_refs[i].next;
3646 while (lr != NULL) {
3651 g_label_refs[i].i = -1;
3652 g_label_refs[i].next = NULL;
3654 if (ops[i].op == OP_CALL) {
3663 static void set_label(int i, const char *name)
3669 p = strchr(name, ':');
3673 if (len > sizeof(g_labels[0]) - 1)
3674 aerr("label '%s' too long: %d\n", name, len);
3675 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
3676 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
3677 memcpy(g_labels[i], name, len);
3678 g_labels[i][len] = 0;
3681 // '=' needs special treatment..
3682 static char *next_word_s(char *w, size_t wsize, char *s)
3688 for (i = 0; i < wsize - 1; i++) {
3689 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
3695 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
3696 printf("warning: '%s' truncated\n", w);
3707 static struct chunk_item *func_chunks;
3708 static int func_chunk_cnt;
3709 static int func_chunk_alloc;
3711 static void add_func_chunk(FILE *fasm, const char *name, int line)
3713 if (func_chunk_cnt >= func_chunk_alloc) {
3714 func_chunk_alloc *= 2;
3715 func_chunks = realloc(func_chunks,
3716 func_chunk_alloc * sizeof(func_chunks[0]));
3717 my_assert_not(func_chunks, NULL);
3719 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
3720 func_chunks[func_chunk_cnt].name = strdup(name);
3721 func_chunks[func_chunk_cnt].asmln = line;
3725 static int cmp_chunks(const void *p1, const void *p2)
3727 const struct chunk_item *c1 = p1, *c2 = p2;
3728 return strcmp(c1->name, c2->name);
3731 static int cmpstringp(const void *p1, const void *p2)
3733 return strcmp(*(char * const *)p1, *(char * const *)p2);
3736 static void scan_ahead(FILE *fasm)
3746 oldpos = ftell(fasm);
3749 while (fgets(line, sizeof(line), fasm))
3760 // get rid of random tabs
3761 for (i = 0; line[i] != 0; i++)
3762 if (line[i] == '\t')
3765 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3768 next_word(words[0], sizeof(words[0]), p);
3769 if (words[0][0] == 0)
3770 aerr("missing name for func chunk?\n");
3772 add_func_chunk(fasm, words[0], asmln);
3777 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3778 words[wordc][0] = 0;
3779 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3780 if (*p == 0 || *p == ';') {
3786 if (wordc == 2 && IS(words[1], "ends"))
3790 fseek(fasm, oldpos, SEEK_SET);
3794 int main(int argc, char *argv[])
3796 FILE *fout, *fasm, *frlist;
3797 struct parsed_data *pd = NULL;
3799 char **rlist = NULL;
3801 int rlist_alloc = 0;
3802 int func_chunks_used = 0;
3803 int func_chunks_sorted = 0;
3804 int func_chunk_i = -1;
3805 long func_chunk_ret = 0;
3806 int func_chunk_ret_ln = 0;
3807 int scanned_ahead = 0;
3809 char words[20][256];
3810 enum opr_lenmod lmod;
3812 int pending_endp = 0;
3814 int skip_warned = 0;
3825 if (argv[1] && IS(argv[1], "-v")) {
3830 if (argc < arg + 3) {
3831 printf("usage:\n%s [-v] <.c> <.asm> <hdrf> [rlist]*\n",
3838 asmfn = argv[arg++];
3839 fasm = fopen(asmfn, "r");
3840 my_assert_not(fasm, NULL);
3842 hdrfn = argv[arg++];
3843 g_fhdr = fopen(hdrfn, "r");
3844 my_assert_not(g_fhdr, NULL);
3847 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
3848 my_assert_not(rlist, NULL);
3849 // needs special handling..
3850 rlist[rlist_len++] = "__alloca_probe";
3852 func_chunk_alloc = 32;
3853 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
3854 my_assert_not(func_chunks, NULL);
3856 memset(words, 0, sizeof(words));
3858 for (; arg < argc; arg++) {
3859 frlist = fopen(argv[arg], "r");
3860 my_assert_not(frlist, NULL);
3862 while (fgets(line, sizeof(line), frlist)) {
3864 if (*p == 0 || *p == ';' || *p == '#')
3867 p = next_word(words[0], sizeof(words[0]), p);
3868 if (words[0][0] == 0)
3871 if (rlist_len >= rlist_alloc) {
3872 rlist_alloc = rlist_alloc * 2 + 64;
3873 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
3874 my_assert_not(rlist, NULL);
3876 rlist[rlist_len++] = strdup(words[0]);
3884 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
3886 fout = fopen(argv[arg_out], "w");
3887 my_assert_not(fout, NULL);
3890 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
3891 my_assert_not(g_eqs, NULL);
3893 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
3894 g_label_refs[i].i = -1;
3895 g_label_refs[i].next = NULL;
3898 while (fgets(line, sizeof(line), fasm))
3907 // get rid of random tabs
3908 for (i = 0; line[i] != 0; i++)
3909 if (line[i] == '\t')
3914 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
3915 goto do_pending_endp; // eww..
3917 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
3919 static const char *attrs[] = {
3928 // parse IDA's attribute-list comment
3929 g_ida_func_attr = 0;
3932 for (; *p != 0; p = sskip(p)) {
3933 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
3934 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
3935 g_ida_func_attr |= 1 << i;
3936 p += strlen(attrs[i]);
3940 if (i == ARRAY_SIZE(attrs)) {
3941 anote("unparsed IDA attr: %s\n", p);
3944 if (IS(attrs[i], "fpd=")) {
3945 p = next_word(words[0], sizeof(words[0]), p);
3950 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3953 next_word(words[0], sizeof(words[0]), p);
3954 if (words[0][0] == 0)
3955 aerr("missing name for func chunk?\n");
3957 if (!scanned_ahead) {
3958 add_func_chunk(fasm, words[0], asmln);
3959 func_chunks_sorted = 0;
3962 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
3964 if (func_chunk_i >= 0) {
3965 if (func_chunk_i < func_chunk_cnt
3966 && IS(func_chunks[func_chunk_i].name, g_func))
3968 // move on to next chunk
3969 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
3971 aerr("seek failed for '%s' chunk #%d\n",
3972 g_func, func_chunk_i);
3973 asmln = func_chunks[func_chunk_i].asmln;
3977 if (func_chunk_ret == 0)
3978 aerr("no return from chunk?\n");
3979 fseek(fasm, func_chunk_ret, SEEK_SET);
3980 asmln = func_chunk_ret_ln;
3986 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
3987 func_chunks_used = 1;
3989 if (IS_START(g_func, "sub_")) {
3990 unsigned long addr = strtoul(p, NULL, 16);
3991 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
3992 if (addr > f_addr && !scanned_ahead) {
3993 anote("scan_ahead caused by '%s', addr %lx\n",
3997 func_chunks_sorted = 0;
4005 for (i = wordc; i < ARRAY_SIZE(words); i++)
4007 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4008 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4009 if (*p == 0 || *p == ';') {
4014 if (*p != 0 && *p != ';')
4015 aerr("too many words\n");
4017 // alow asm patches in comments
4018 if (*p == ';' && IS_START(p, "; sctpatch:")) {
4020 if (*p == 0 || *p == ';')
4022 goto parse_words; // lame
4027 awarn("wordc == 0?\n");
4031 // don't care about this:
4032 if (words[0][0] == '.'
4033 || IS(words[0], "include")
4034 || IS(words[0], "assume") || IS(words[1], "segment")
4035 || IS(words[0], "align"))
4041 // do delayed endp processing to collect switch jumptables
4043 if (in_func && !skip_func && wordc >= 2
4044 && ((words[0][0] == 'd' && words[0][2] == 0)
4045 || (words[1][0] == 'd' && words[1][2] == 0)))
4048 if (words[1][0] == 'd' && words[1][2] == 0) {
4050 if (g_func_pd_cnt >= pd_alloc) {
4051 pd_alloc = pd_alloc * 2 + 16;
4052 g_func_pd = realloc(g_func_pd,
4053 sizeof(g_func_pd[0]) * pd_alloc);
4054 my_assert_not(g_func_pd, NULL);
4056 pd = &g_func_pd[g_func_pd_cnt];
4058 memset(pd, 0, sizeof(*pd));
4059 strcpy(pd->label, words[0]);
4060 pd->type = OPT_CONST;
4061 pd->lmod = lmod_from_directive(words[1]);
4065 lmod = lmod_from_directive(words[0]);
4066 if (lmod != pd->lmod)
4067 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4070 if (pd->count_alloc < pd->count + wordc) {
4071 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4072 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4073 my_assert_not(pd->d, NULL);
4075 for (; i < wordc; i++) {
4076 if (IS(words[i], "offset")) {
4077 pd->type = OPT_OFFSET;
4080 p = strchr(words[i], ',');
4083 if (pd->type == OPT_OFFSET)
4084 pd->d[pd->count].u.label = strdup(words[i]);
4086 pd->d[pd->count].u.val = parse_number(words[i]);
4087 pd->d[pd->count].bt_i = -1;
4093 if (in_func && !skip_func)
4094 gen_func(fout, g_fhdr, g_func, pi);
4098 g_ida_func_attr = 0;
4102 func_chunks_used = 0;
4105 memset(&ops, 0, pi * sizeof(ops[0]));
4106 memset(g_labels, 0, pi * sizeof(g_labels[0]));
4110 for (i = 0; i < g_func_pd_cnt; i++) {
4112 if (pd->type == OPT_OFFSET) {
4113 for (j = 0; j < pd->count; j++)
4114 free(pd->d[j].u.label);
4125 if (IS(words[1], "proc")) {
4127 aerr("proc '%s' while in_func '%s'?\n",
4130 if ((g_ida_func_attr & IDAFA_THUNK)
4131 || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4133 strcpy(g_func, words[0]);
4134 set_label(0, words[0]);
4139 if (IS(words[1], "endp"))
4142 aerr("endp '%s' while not in_func?\n", words[0]);
4143 if (!IS(g_func, words[0]))
4144 aerr("endp '%s' while in_func '%s'?\n",
4147 if (!skip_func && func_chunks_used) {
4148 // start processing chunks
4149 struct chunk_item *ci, key = { g_func, 0 };
4151 func_chunk_ret = ftell(fasm);
4152 func_chunk_ret_ln = asmln;
4153 if (!func_chunks_sorted) {
4154 qsort(func_chunks, func_chunk_cnt,
4155 sizeof(func_chunks[0]), cmp_chunks);
4156 func_chunks_sorted = 1;
4158 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4159 sizeof(func_chunks[0]), cmp_chunks);
4161 aerr("'%s' needs chunks, but none found\n", g_func);
4162 func_chunk_i = ci - func_chunks;
4163 for (; func_chunk_i > 0; func_chunk_i--)
4164 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4167 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4169 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4170 asmln = func_chunks[func_chunk_i].asmln;
4178 if (wordc == 2 && IS(words[1], "ends"))
4181 p = strchr(words[0], ':');
4183 set_label(pi, words[0]);
4187 if (!in_func || skip_func) {
4188 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4190 anote("skipping from '%s'\n", g_labels[pi]);
4193 g_labels[pi][0] = 0;
4197 if (wordc > 1 && IS(words[1], "=")) {
4199 aerr("unhandled equ, wc=%d\n", wordc);
4200 if (g_eqcnt >= eq_alloc) {
4202 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4203 my_assert_not(g_eqs, NULL);
4206 len = strlen(words[0]);
4207 if (len > sizeof(g_eqs[0].name) - 1)
4208 aerr("equ name too long: %d\n", len);
4209 strcpy(g_eqs[g_eqcnt].name, words[0]);
4211 if (!IS(words[3], "ptr"))
4212 aerr("unhandled equ\n");
4213 if (IS(words[2], "dword"))
4214 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4215 else if (IS(words[2], "word"))
4216 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4217 else if (IS(words[2], "byte"))
4218 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4220 aerr("bad lmod: '%s'\n", words[2]);
4222 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4227 if (pi >= ARRAY_SIZE(ops))
4228 aerr("too many ops\n");
4230 parse_op(&ops[pi], words, wordc);
4241 // vim:ts=2:shiftwidth=2:expandtab