9 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
10 #define IS(w, y) !strcmp(w, y)
11 #define IS_START(w, y) !strncmp(w, y, strlen(y))
13 #include "protoparse.h"
15 static const char *asmfn;
19 #define anote(fmt, ...) \
20 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
21 #define awarn(fmt, ...) \
22 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
23 #define aerr(fmt, ...) do { \
24 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
29 #include "masm_tools.h"
32 OPF_RMD = (1 << 0), /* removed or optimized out */
33 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
34 OPF_FLAGS = (1 << 2), /* sets flags */
35 OPF_JMP = (1 << 3), /* branch, call */
36 OPF_CJMP = (1 << 4), /* cond. branch (cc or jecxz) */
37 OPF_CC = (1 << 5), /* uses flags */
38 OPF_TAIL = (1 << 6), /* ret or tail call */
39 OPF_RSAVE = (1 << 7), /* push/pop is local reg save/load */
40 OPF_REP = (1 << 8), /* prefixed by rep */
41 OPF_REPZ = (1 << 9), /* rep is repe/repz */
42 OPF_REPNZ = (1 << 10), /* rep is repne/repnz */
43 OPF_FARG = (1 << 11), /* push collected as func arg (no reuse) */
44 OPF_EBP_S = (1 << 12), /* ebp used as scratch here, not BP */
45 OPF_DF = (1 << 13), /* DF flag set */
118 // must be sorted (larger len must be further in enum)
126 #define MAX_OPERANDS 3
130 enum opr_lenmod lmod;
131 unsigned int is_ptr:1; // pointer in C
132 unsigned int is_array:1; // array in C
133 unsigned int type_from_var:1; // .. in header, sometimes wrong
134 unsigned int size_mismatch:1; // type override differs from C
135 unsigned int size_lt:1; // type override is larger than C
136 unsigned int had_ds:1; // had ds: prefix
144 struct parsed_opr operand[MAX_OPERANDS];
147 int regmask_src; // all referensed regs
149 int pfomask; // flagop: parsed_flag_op that can't be delayed
150 int argnum; // push: altered before call arg #
151 int cc_scratch; // scratch storage during analysis
152 int bt_i; // branch target for branches
153 struct parsed_data *btj;// branch targets for jumptables
158 // OP_CALL - parser proto hint (str), ptr to struct parsed_proto
159 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
160 // OP_POP - point to OP_PUSH in push/pop pair
164 enum opr_lenmod lmod;
171 enum opr_lenmod lmod;
185 struct label_ref *next;
189 IDAFA_BP_FRAME = (1 << 0),
190 IDAFA_LIB_FUNC = (1 << 1),
191 IDAFA_STATIC = (1 << 2),
192 IDAFA_NORETURN = (1 << 3),
193 IDAFA_THUNK = (1 << 4),
194 IDAFA_FPD = (1 << 5),
199 static struct parsed_op ops[MAX_OPS];
200 static struct parsed_equ *g_eqs;
202 static char g_labels[MAX_OPS][32];
203 static struct label_ref g_label_refs[MAX_OPS];
204 static const struct parsed_proto *g_func_pp;
205 static struct parsed_data *g_func_pd;
206 static int g_func_pd_cnt;
207 static char g_func[256];
208 static char g_comment[256];
209 static int g_bp_frame;
210 static int g_sp_frame;
211 static int g_stack_frame_used;
212 static int g_stack_fsz;
213 static int g_ida_func_attr;
214 static int g_allow_regfunc;
215 #define ferr(op_, fmt, ...) do { \
216 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
217 dump_op(op_), ##__VA_ARGS__); \
221 #define fnote(op_, fmt, ...) \
222 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
223 dump_op(op_), ##__VA_ARGS__)
227 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
228 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
229 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
230 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
232 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
234 // possible basic comparison types (without inversion)
235 enum parsed_flag_op {
239 PFO_BE, // 6 CF=1||ZF=1
243 PFO_LE, // e ZF=1||SF!=OF
246 static const char *parsed_flag_op_names[] = {
247 "o", "c", "z", "be", "s", "p", "l", "le"
250 static int char_array_i(const char *array[], size_t len, const char *s)
254 for (i = 0; i < len; i++)
261 static void printf_number(char *buf, size_t buf_size,
262 unsigned long number)
264 // output in C-friendly form
265 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
268 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
272 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
274 *reg_lmod = OPLM_DWORD;
277 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
279 *reg_lmod = OPLM_WORD;
282 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
284 *reg_lmod = OPLM_BYTE;
287 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
289 *reg_lmod = OPLM_BYTE;
296 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
298 enum opr_lenmod lmod;
311 while (my_isblank(*s))
313 for (; my_issep(*s); d++, s++)
315 while (my_isblank(*s))
320 if (IS_START(s, "ds:"))
323 s = next_idt(w, sizeof(w), s);
328 reg = parse_reg(&lmod, w);
330 *regmask |= 1 << reg;
334 if ('0' <= w[0] && w[0] <= '9') {
335 number = parse_number(w);
336 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
340 // probably some label/identifier - pass
343 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
347 strcpy(name, cvtbuf);
352 static int is_reg_in_str(const char *s)
356 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
359 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
360 if (!strncmp(s, regs_r32[i], 3))
366 static const char *parse_stack_el(const char *name, char *extra_reg)
368 const char *p, *p2, *s;
375 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
377 if (extra_reg != NULL) {
378 strncpy(extra_reg, name, 3);
383 if (IS_START(p, "ebp+")) {
387 if (p2 != NULL && is_reg_in_str(p)) {
388 if (extra_reg != NULL) {
389 strncpy(extra_reg, p, p2 - p);
390 extra_reg[p2 - p] = 0;
395 if (!('0' <= *p && *p <= '9'))
401 if (!IS_START(name, "esp+"))
404 p = strchr(name + 4, '+');
406 // must be a number after esp+, already converted to 0x..
408 if (!('0' <= *s && *s <= '9')) {
409 aerr("%s nan?\n", __func__);
412 if (s[0] == '0' && s[1] == 'x')
415 if (len < sizeof(buf) - 1) {
416 strncpy(buf, s, len);
418 val = strtol(buf, &endp, 16);
419 if (val == 0 || *endp != 0) {
420 aerr("%s num parse fail for '%s'\n", __func__, buf);
429 if ('0' <= *p && *p <= '9')
435 static int guess_lmod_from_name(struct parsed_opr *opr)
437 if (!strncmp(opr->name, "dword_", 6)) {
438 opr->lmod = OPLM_DWORD;
441 if (!strncmp(opr->name, "word_", 5)) {
442 opr->lmod = OPLM_WORD;
445 if (!strncmp(opr->name, "byte_", 5)) {
446 opr->lmod = OPLM_BYTE;
452 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
453 const struct parsed_type *c_type)
455 static const char *dword_types[] = {
456 "int", "_DWORD", "UINT_PTR", "DWORD",
457 "WPARAM", "LPARAM", "UINT",
460 static const char *word_types[] = {
461 "uint16_t", "int16_t", "_WORD",
462 "unsigned __int16", "__int16",
464 static const char *byte_types[] = {
465 "uint8_t", "int8_t", "char",
466 "unsigned __int8", "__int8", "BYTE", "_BYTE",
472 if (c_type->is_ptr) {
477 n = skip_type_mod(c_type->name);
479 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
480 if (IS(n, dword_types[i])) {
486 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
487 if (IS(n, word_types[i])) {
493 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
494 if (IS(n, byte_types[i])) {
503 static enum opr_type lmod_from_directive(const char *d)
507 else if (IS(d, "dw"))
509 else if (IS(d, "db"))
512 aerr("unhandled directive: '%s'\n", d);
516 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
522 *regmask |= 1 << reg;
525 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
528 static int parse_operand(struct parsed_opr *opr,
529 int *regmask, int *regmask_indirect,
530 char words[16][256], int wordc, int w, unsigned int op_flags)
532 const struct parsed_proto *pp;
533 enum opr_lenmod tmplmod;
534 unsigned long number;
542 aerr("parse_operand w %d, wordc %d\n", w, wordc);
546 for (i = w; i < wordc; i++) {
547 len = strlen(words[i]);
548 if (words[i][len - 1] == ',') {
549 words[i][len - 1] = 0;
555 wordc_in = wordc - w;
557 if ((op_flags & OPF_JMP) && wordc_in > 0
558 && !('0' <= words[w][0] && words[w][0] <= '9'))
560 const char *label = NULL;
562 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
563 && IS(words[w + 1], "ptr"))
564 label = words[w + 2];
565 else if (wordc_in == 2 && IS(words[w], "short"))
566 label = words[w + 1];
567 else if (wordc_in == 1
568 && strchr(words[w], '[') == NULL
569 && parse_reg(&tmplmod, words[w]) < 0)
573 opr->type = OPT_LABEL;
574 if (IS_START(label, "ds:")) {
578 strcpy(opr->name, label);
584 if (IS(words[w + 1], "ptr")) {
585 if (IS(words[w], "dword"))
586 opr->lmod = OPLM_DWORD;
587 else if (IS(words[w], "word"))
588 opr->lmod = OPLM_WORD;
589 else if (IS(words[w], "byte"))
590 opr->lmod = OPLM_BYTE;
592 aerr("type parsing failed\n");
594 wordc_in = wordc - w;
599 if (IS(words[w], "offset")) {
600 opr->type = OPT_OFFSET;
601 strcpy(opr->name, words[w + 1]);
604 if (IS(words[w], "(offset")) {
605 p = strchr(words[w + 1], ')');
607 aerr("parse of bracketed offset failed\n");
609 opr->type = OPT_OFFSET;
610 strcpy(opr->name, words[w + 1]);
616 aerr("parse_operand 1 word expected\n");
618 if (IS_START(words[w], "ds:")) {
620 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
622 strcpy(opr->name, words[w]);
624 if (words[w][0] == '[') {
625 opr->type = OPT_REGMEM;
626 ret = sscanf(words[w], "[%[^]]]", opr->name);
628 aerr("[] parse failure\n");
630 parse_indmode(opr->name, regmask_indirect, 1);
631 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
633 struct parsed_equ *eq =
634 equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
636 opr->lmod = eq->lmod;
640 else if (strchr(words[w], '[')) {
642 p = strchr(words[w], '[');
643 opr->type = OPT_REGMEM;
644 parse_indmode(p, regmask_indirect, 0);
645 strncpy(buf, words[w], p - words[w]);
646 buf[p - words[w]] = 0;
647 pp = proto_parse(g_fhdr, buf, 1);
650 else if (('0' <= words[w][0] && words[w][0] <= '9')
651 || words[w][0] == '-')
653 number = parse_number(words[w]);
654 opr->type = OPT_CONST;
656 printf_number(opr->name, sizeof(opr->name), number);
660 ret = parse_reg(&tmplmod, opr->name);
662 setup_reg_opr(opr, ret, tmplmod, regmask);
666 // most likely var in data segment
667 opr->type = OPT_LABEL;
668 pp = proto_parse(g_fhdr, opr->name, 0);
672 if (pp->is_fptr || pp->is_func) {
673 opr->lmod = OPLM_DWORD;
677 tmplmod = OPLM_UNSPEC;
678 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
679 anote("unhandled C type '%s' for '%s'\n",
680 pp->type.name, opr->name);
682 if (opr->lmod == OPLM_UNSPEC) {
684 opr->type_from_var = 1;
686 else if (opr->lmod != tmplmod) {
687 opr->size_mismatch = 1;
688 if (tmplmod < opr->lmod)
691 opr->is_ptr = pp->type.is_ptr;
693 opr->is_array = pp->type.is_array;
696 if (opr->lmod == OPLM_UNSPEC)
697 guess_lmod_from_name(opr);
701 static const struct {
706 { "repe", OPF_REP|OPF_REPZ },
707 { "repz", OPF_REP|OPF_REPZ },
708 { "repne", OPF_REP|OPF_REPNZ },
709 { "repnz", OPF_REP|OPF_REPNZ },
712 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
714 static const struct {
721 { "nop", OP_NOP, 0, 0, 0 },
722 { "push", OP_PUSH, 1, 1, 0 },
723 { "pop", OP_POP, 1, 1, OPF_DATA },
724 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
725 { "mov" , OP_MOV, 2, 2, OPF_DATA },
726 { "lea", OP_LEA, 2, 2, OPF_DATA },
727 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
728 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
729 { "not", OP_NOT, 1, 1, OPF_DATA },
730 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
731 { "stosb",OP_STOS, 0, 0, OPF_DATA },
732 { "stosw",OP_STOS, 0, 0, OPF_DATA },
733 { "stosd",OP_STOS, 0, 0, OPF_DATA },
734 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
735 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
736 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
737 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
738 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
739 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
740 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
741 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
742 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
743 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
744 { "cld", OP_CLD, 0, 0, OPF_DATA },
745 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
746 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
747 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
748 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
749 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
750 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
751 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
752 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
753 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
754 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
755 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
756 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
757 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
758 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
759 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
760 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
761 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
762 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
763 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
764 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
765 { "test", OP_TEST, 2, 2, OPF_FLAGS },
766 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
767 { "retn", OP_RET, 0, 1, OPF_TAIL },
768 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
769 { "jmp", OP_JMP, 1, 1, OPF_JMP },
770 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
771 { "jo", OP_JO, 1, 1, OPF_CJMP_CC }, // 70 OF=1
772 { "jno", OP_JNO, 1, 1, OPF_CJMP_CC }, // 71 OF=0
773 { "jc", OP_JC, 1, 1, OPF_CJMP_CC }, // 72 CF=1
774 { "jb", OP_JC, 1, 1, OPF_CJMP_CC }, // 72
775 { "jnc", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73 CF=0
776 { "jnb", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73
777 { "jae", OP_JNC, 1, 1, OPF_CJMP_CC }, // 73
778 { "jz", OP_JZ, 1, 1, OPF_CJMP_CC }, // 74 ZF=1
779 { "je", OP_JZ, 1, 1, OPF_CJMP_CC }, // 74
780 { "jnz", OP_JNZ, 1, 1, OPF_CJMP_CC }, // 75 ZF=0
781 { "jne", OP_JNZ, 1, 1, OPF_CJMP_CC }, // 75
782 { "jbe", OP_JBE, 1, 1, OPF_CJMP_CC }, // 76 CF=1 || ZF=1
783 { "jna", OP_JBE, 1, 1, OPF_CJMP_CC }, // 76
784 { "ja", OP_JA, 1, 1, OPF_CJMP_CC }, // 77 CF=0 && ZF=0
785 { "jnbe", OP_JA, 1, 1, OPF_CJMP_CC }, // 77
786 { "js", OP_JS, 1, 1, OPF_CJMP_CC }, // 78 SF=1
787 { "jns", OP_JNS, 1, 1, OPF_CJMP_CC }, // 79 SF=0
788 { "jp", OP_JP, 1, 1, OPF_CJMP_CC }, // 7a PF=1
789 { "jpe", OP_JP, 1, 1, OPF_CJMP_CC }, // 7a
790 { "jnp", OP_JNP, 1, 1, OPF_CJMP_CC }, // 7b PF=0
791 { "jpo", OP_JNP, 1, 1, OPF_CJMP_CC }, // 7b
792 { "jl", OP_JL, 1, 1, OPF_CJMP_CC }, // 7c SF!=OF
793 { "jnge", OP_JL, 1, 1, OPF_CJMP_CC }, // 7c
794 { "jge", OP_JGE, 1, 1, OPF_CJMP_CC }, // 7d SF=OF
795 { "jnl", OP_JGE, 1, 1, OPF_CJMP_CC }, // 7d
796 { "jle", OP_JLE, 1, 1, OPF_CJMP_CC }, // 7e ZF=1 || SF!=OF
797 { "jng", OP_JLE, 1, 1, OPF_CJMP_CC }, // 7e
798 { "jg", OP_JG, 1, 1, OPF_CJMP_CC }, // 7f ZF=0 && SF=OF
799 { "jnle", OP_JG, 1, 1, OPF_CJMP_CC }, // 7f
800 { "seto", OP_JO, 1, 1, OPF_DATA|OPF_CC },
801 { "setno", OP_JNO, 1, 1, OPF_DATA|OPF_CC },
802 { "setc", OP_JC, 1, 1, OPF_DATA|OPF_CC },
803 { "setb", OP_JC, 1, 1, OPF_DATA|OPF_CC },
804 { "setnc", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
805 { "setae", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
806 { "setz", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
807 { "sete", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
808 { "setnz", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
809 { "setne", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
810 { "setbe", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
811 { "setna", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
812 { "seta", OP_JA, 1, 1, OPF_DATA|OPF_CC },
813 { "setnbe", OP_JA, 1, 1, OPF_DATA|OPF_CC },
814 { "sets", OP_JS, 1, 1, OPF_DATA|OPF_CC },
815 { "setns", OP_JNS, 1, 1, OPF_DATA|OPF_CC },
816 { "setp", OP_JP, 1, 1, OPF_DATA|OPF_CC },
817 { "setpe", OP_JP, 1, 1, OPF_DATA|OPF_CC },
818 { "setnp", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
819 { "setpo", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
820 { "setl", OP_JL, 1, 1, OPF_DATA|OPF_CC },
821 { "setnge", OP_JL, 1, 1, OPF_DATA|OPF_CC },
822 { "setge", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
823 { "setnl", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
824 { "setle", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
825 { "setng", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
826 { "setg", OP_JG, 1, 1, OPF_DATA|OPF_CC },
827 { "setnle", OP_JG, 1, 1, OPF_DATA|OPF_CC },
830 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
832 enum opr_lenmod lmod = OPLM_UNSPEC;
833 int prefix_flags = 0;
841 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
842 if (IS(words[w], pref_table[i].name)) {
843 prefix_flags = pref_table[i].flags;
850 aerr("lone prefix: '%s'\n", words[0]);
855 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
856 if (IS(words[w], op_table[i].name))
860 if (i == ARRAY_SIZE(op_table))
861 aerr("unhandled op: '%s'\n", words[0]);
864 op->op = op_table[i].op;
865 op->flags = op_table[i].flags | prefix_flags;
866 op->regmask_src = op->regmask_dst = 0;
868 for (opr = 0; opr < op_table[i].minopr; opr++) {
869 regmask = regmask_ind = 0;
870 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
871 words, wordc, w, op->flags);
873 if (opr == 0 && (op->flags & OPF_DATA))
874 op->regmask_dst = regmask;
875 // for now, mark dst as src too
876 op->regmask_src |= regmask | regmask_ind;
879 for (; w < wordc && opr < op_table[i].maxopr; opr++) {
880 w = parse_operand(&op->operand[opr],
881 &op->regmask_src, &op->regmask_src,
882 words, wordc, w, op->flags);
886 aerr("parse_op %s incomplete: %d/%d\n",
890 op->operand_cnt = opr;
891 if (!strncmp(op_table[i].name, "set", 3))
892 op->operand[0].lmod = OPLM_BYTE;
894 // ops with implicit argumets
898 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
899 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
904 if (op->operand_cnt != 0)
906 if (words[op_w][4] == 'b')
908 else if (words[op_w][4] == 'w')
910 else if (words[op_w][4] == 'd')
913 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
914 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
915 op->regmask_dst = op->regmask_src;
916 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
921 if (op->operand_cnt != 0)
923 if (words[op_w][4] == 'b')
925 else if (words[op_w][4] == 'w')
927 else if (words[op_w][4] == 'd')
930 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
931 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
932 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
933 op->regmask_dst = op->regmask_src;
938 op->regmask_src = 1 << xCX;
939 op->operand[0].type = OPT_REG;
940 op->operand[0].reg = xCX;
941 op->operand[0].lmod = OPLM_DWORD;
945 if (op->operand_cnt != 1)
950 op->regmask_dst = (1 << xDX) | (1 << xAX);
951 op->regmask_src |= (1 << xAX);
952 if (op->operand[0].lmod == OPLM_UNSPEC)
953 op->operand[0].lmod = OPLM_DWORD;
958 // we could set up operands for edx:eax, but there is no real need to
959 // (see is_opr_modified())
960 regmask = (1 << xDX) | (1 << xAX);
961 op->regmask_dst = regmask;
962 op->regmask_src |= regmask;
963 if (op->operand[0].lmod == OPLM_UNSPEC)
964 op->operand[0].lmod = OPLM_DWORD;
972 if (op->operand[1].lmod == OPLM_UNSPEC)
973 op->operand[1].lmod = OPLM_BYTE;
977 if (op->operand[0].lmod == OPLM_UNSPEC
978 && (op->operand[0].type == OPT_CONST
979 || op->operand[0].type == OPT_OFFSET
980 || op->operand[0].type == OPT_LABEL))
981 op->operand[0].lmod = OPLM_DWORD;
986 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
987 && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
989 op->flags |= OPF_RMD;
994 if (op->operand[0].type == OPT_REG
995 && op->operand[1].type == OPT_REGMEM)
998 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
999 if (IS(buf, op->operand[1].name))
1000 op->flags |= OPF_RMD;
1005 // trashed regs must be explicitly detected later
1006 op->regmask_dst = 0;
1014 static const char *op_name(enum op_op op)
1018 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1019 if (op_table[i].op == op)
1020 return op_table[i].name;
1026 static const char *dump_op(struct parsed_op *po)
1028 static char out[128];
1035 snprintf(out, sizeof(out), "%s", op_name(po->op));
1036 for (i = 0; i < po->operand_cnt; i++) {
1040 snprintf(p, sizeof(out) - (p - out),
1041 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1042 po->operand[i].name);
1048 static const char *lmod_type_u(struct parsed_op *po,
1049 enum opr_lenmod lmod)
1059 ferr(po, "invalid lmod: %d\n", lmod);
1060 return "(_invalid_)";
1064 static const char *lmod_cast_u(struct parsed_op *po,
1065 enum opr_lenmod lmod)
1075 ferr(po, "invalid lmod: %d\n", lmod);
1076 return "(_invalid_)";
1080 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1081 enum opr_lenmod lmod)
1091 ferr(po, "invalid lmod: %d\n", lmod);
1092 return "(_invalid_)";
1096 static const char *lmod_cast_s(struct parsed_op *po,
1097 enum opr_lenmod lmod)
1107 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1108 return "(_invalid_)";
1112 static const char *lmod_cast(struct parsed_op *po,
1113 enum opr_lenmod lmod, int is_signed)
1116 lmod_cast_s(po, lmod) :
1117 lmod_cast_u(po, lmod);
1120 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1130 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1135 static const char *opr_name(struct parsed_op *po, int opr_num)
1137 if (opr_num >= po->operand_cnt)
1138 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1139 return po->operand[opr_num].name;
1142 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1144 if (opr_num >= po->operand_cnt)
1145 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1146 if (po->operand[opr_num].type != OPT_CONST)
1147 ferr(po, "opr %d: const expected\n", opr_num);
1148 return po->operand[opr_num].val;
1151 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1153 if ((unsigned int)popr->reg >= MAX_REGS)
1154 ferr(po, "invalid reg: %d\n", popr->reg);
1155 return regs_r32[popr->reg];
1158 // cast1 is the "final" cast
1159 static const char *simplify_cast(const char *cast1, const char *cast2)
1161 static char buf[256];
1167 if (IS(cast1, cast2))
1169 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1171 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1173 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1175 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1177 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1180 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1184 static const char *simplify_cast_num(const char *cast, unsigned int val)
1186 if (IS(cast, "(u8)") && val < 0x100)
1188 if (IS(cast, "(s8)") && val < 0x80)
1190 if (IS(cast, "(u16)") && val < 0x10000)
1192 if (IS(cast, "(s16)") && val < 0x8000)
1194 if (IS(cast, "(s32)") && val < 0x80000000)
1200 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1209 namelen = strlen(name);
1211 p = strchr(name, '+');
1215 ferr(po, "equ parse failed for '%s'\n", name);
1217 if (IS_START(p, "0x"))
1219 *extra_offs = strtol(p, &endp, 16);
1221 ferr(po, "equ parse failed for '%s'\n", name);
1224 for (i = 0; i < g_eqcnt; i++)
1225 if (strncmp(g_eqs[i].name, name, namelen) == 0
1226 && g_eqs[i].name[namelen] == 0)
1230 ferr(po, "unresolved equ name: '%s'\n", name);
1237 static int is_stack_access(struct parsed_op *po,
1238 const struct parsed_opr *popr)
1240 return (parse_stack_el(popr->name, NULL)
1241 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1242 && IS_START(popr->name, "ebp")));
1245 static void parse_stack_access(struct parsed_op *po,
1246 const char *name, char *ofs_reg, int *offset_out,
1247 int *stack_ra_out, const char **bp_arg_out)
1249 const char *bp_arg = "";
1250 const char *p = NULL;
1251 struct parsed_equ *eq;
1258 if (IS_START(name, "ebp-")
1259 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1262 if (IS_START(p, "0x"))
1264 offset = strtoul(p, &endp, 16);
1268 ferr(po, "ebp- parse of '%s' failed\n", name);
1271 bp_arg = parse_stack_el(name, ofs_reg);
1272 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1273 eq = equ_find(po, bp_arg, &offset);
1275 ferr(po, "detected but missing eq\n");
1276 offset += eq->offset;
1279 if (!strncmp(name, "ebp", 3))
1282 if (ofs_reg[0] == 0 && stack_ra <= offset && offset < stack_ra + 4)
1283 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1285 *offset_out = offset;
1286 *stack_ra_out = stack_ra;
1288 *bp_arg_out = bp_arg;
1291 static void stack_frame_access(struct parsed_op *po,
1292 struct parsed_opr *popr, char *buf, size_t buf_size,
1293 const char *name, const char *cast, int is_src, int is_lea)
1295 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1296 const char *prefix = "";
1297 const char *bp_arg = NULL;
1298 char ofs_reg[16] = { 0, };
1299 int i, arg_i, arg_s;
1306 if (po->flags & OPF_EBP_S)
1307 ferr(po, "stack_frame_access while ebp is scratch\n");
1309 parse_stack_access(po, name, ofs_reg, &offset, &stack_ra, &bp_arg);
1311 if (offset > stack_ra)
1313 arg_i = (offset - stack_ra - 4) / 4;
1314 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1316 if (g_func_pp->is_vararg
1317 && arg_i == g_func_pp->argc_stack && is_lea)
1319 // should be va_list
1322 snprintf(buf, buf_size, "%sap", cast);
1325 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1326 offset, bp_arg, arg_i);
1328 if (ofs_reg[0] != 0)
1329 ferr(po, "offset reg on arg access?\n");
1331 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1332 if (g_func_pp->arg[i].reg != NULL)
1338 if (i == g_func_pp->argc)
1339 ferr(po, "arg %d not in prototype?\n", arg_i);
1341 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1347 ferr(po, "lea/byte to arg?\n");
1348 if (is_src && (offset & 3) == 0)
1349 snprintf(buf, buf_size, "%sa%d",
1350 simplify_cast(cast, "(u8)"), i + 1);
1352 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1353 cast, offset & 3, i + 1);
1358 ferr(po, "lea/word to arg?\n");
1363 ferr(po, "problematic arg store\n");
1364 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1365 simplify_cast(cast, "*(u16 *)"), i + 1);
1368 ferr(po, "unaligned arg word load\n");
1370 else if (is_src && (offset & 2) == 0)
1371 snprintf(buf, buf_size, "%sa%d",
1372 simplify_cast(cast, "(u16)"), i + 1);
1374 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1375 cast, (offset & 2) ? "HI" : "LO", i + 1);
1387 snprintf(buf, buf_size, "(u32)&a%d + %d",
1390 ferr(po, "unaligned arg store\n");
1392 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1393 snprintf(buf, buf_size, "%s(a%d >> %d)",
1394 prefix, i + 1, (offset & 3) * 8);
1398 snprintf(buf, buf_size, "%s%sa%d",
1399 prefix, is_lea ? "&" : "", i + 1);
1404 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1408 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1411 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1412 if (tmp_lmod != OPLM_DWORD
1413 && (unaligned || (!is_src && tmp_lmod < popr->lmod)))
1415 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1416 i + 1, offset, g_func_pp->arg[i].type.name);
1418 if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1419 ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1423 if (g_stack_fsz == 0)
1424 ferr(po, "stack var access without stackframe\n");
1425 g_stack_frame_used = 1;
1427 sf_ofs = g_stack_fsz + offset;
1428 lim = (ofs_reg[0] != 0) ? -4 : 0;
1429 if (offset > 0 || sf_ofs < lim)
1430 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1440 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1441 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1445 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1446 // known unaligned or possibly unaligned
1447 strcat(g_comment, " unaligned");
1449 prefix = "*(u16 *)&";
1450 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1451 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1454 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1458 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1459 // known unaligned or possibly unaligned
1460 strcat(g_comment, " unaligned");
1462 prefix = "*(u32 *)&";
1463 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1464 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1467 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1471 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1476 static void check_func_pp(struct parsed_op *po,
1477 const struct parsed_proto *pp, const char *pfx)
1481 if (pp->argc_reg != 0) {
1482 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1483 pp_print(buf, sizeof(buf), pp);
1484 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1486 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1487 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1488 pfx, pp->argc_reg, pp->argc_stack);
1492 static void check_label_read_ref(struct parsed_op *po, const char *name)
1494 const struct parsed_proto *pp;
1496 pp = proto_parse(g_fhdr, name, 0);
1498 ferr(po, "proto_parse failed for ref '%s'\n", name);
1501 check_func_pp(po, pp, "ref");
1504 static char *out_src_opr(char *buf, size_t buf_size,
1505 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1508 char tmp1[256], tmp2[256];
1516 switch (popr->type) {
1519 ferr(po, "lea from reg?\n");
1521 switch (popr->lmod) {
1523 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1526 snprintf(buf, buf_size, "%s%s",
1527 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1530 if (popr->name[1] == 'h') // XXX..
1531 snprintf(buf, buf_size, "%s(%s >> 8)",
1532 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1534 snprintf(buf, buf_size, "%s%s",
1535 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1538 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1543 if (is_stack_access(po, popr)) {
1544 stack_frame_access(po, popr, buf, buf_size,
1545 popr->name, cast, 1, is_lea);
1549 strcpy(expr, popr->name);
1550 if (strchr(expr, '[')) {
1551 // special case: '[' can only be left for label[reg] form
1552 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1554 ferr(po, "parse failure for '%s'\n", expr);
1555 if (tmp1[0] == '(') {
1556 // (off_4FFF50+3)[eax]
1557 p = strchr(tmp1 + 1, ')');
1558 if (p == NULL || p[1] != 0)
1559 ferr(po, "parse failure (2) for '%s'\n", expr);
1561 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1563 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1566 // XXX: do we need more parsing?
1568 snprintf(buf, buf_size, "%s", expr);
1572 snprintf(buf, buf_size, "%s(%s)",
1573 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1577 check_label_read_ref(po, popr->name);
1578 if (cast[0] == 0 && popr->is_ptr)
1582 snprintf(buf, buf_size, "(u32)&%s", popr->name);
1583 else if (popr->size_lt)
1584 snprintf(buf, buf_size, "%s%s%s%s", cast,
1585 lmod_cast_u_ptr(po, popr->lmod),
1586 popr->is_array ? "" : "&",
1589 snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1590 popr->is_array ? "[0]" : "");
1594 check_label_read_ref(po, popr->name);
1598 ferr(po, "lea an offset?\n");
1599 snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1604 ferr(po, "lea from const?\n");
1606 printf_number(tmp1, sizeof(tmp1), popr->val);
1607 if (popr->val == 0 && strchr(cast, '*'))
1608 snprintf(buf, buf_size, "NULL");
1610 snprintf(buf, buf_size, "%s%s",
1611 simplify_cast_num(cast, popr->val), tmp1);
1615 ferr(po, "invalid src type: %d\n", popr->type);
1621 // note: may set is_ptr (we find that out late for ebp frame..)
1622 static char *out_dst_opr(char *buf, size_t buf_size,
1623 struct parsed_op *po, struct parsed_opr *popr)
1625 switch (popr->type) {
1627 switch (popr->lmod) {
1629 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1633 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1637 if (popr->name[1] == 'h') // XXX..
1638 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1640 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1643 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1648 if (is_stack_access(po, popr)) {
1649 stack_frame_access(po, popr, buf, buf_size,
1650 popr->name, "", 0, 0);
1654 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1657 if (popr->size_mismatch)
1658 snprintf(buf, buf_size, "%s%s%s",
1659 lmod_cast_u_ptr(po, popr->lmod),
1660 popr->is_array ? "" : "&", popr->name);
1662 snprintf(buf, buf_size, "%s%s", popr->name,
1663 popr->is_array ? "[0]" : "");
1667 ferr(po, "invalid dst type: %d\n", popr->type);
1673 static char *out_src_opr_u32(char *buf, size_t buf_size,
1674 struct parsed_op *po, struct parsed_opr *popr)
1676 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1679 static enum parsed_flag_op split_cond(struct parsed_op *po,
1680 enum op_op op, int *is_inv)
1732 ferr(po, "split_cond: bad op %d\n", op);
1737 static void out_test_for_cc(char *buf, size_t buf_size,
1738 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1739 enum opr_lenmod lmod, const char *expr)
1741 const char *cast, *scast;
1743 cast = lmod_cast_u(po, lmod);
1744 scast = lmod_cast_s(po, lmod);
1748 case PFO_BE: // CF=1||ZF=1; CF=0
1749 snprintf(buf, buf_size, "(%s%s %s 0)",
1750 cast, expr, is_inv ? "!=" : "==");
1754 case PFO_L: // SF!=OF; OF=0
1755 snprintf(buf, buf_size, "(%s%s %s 0)",
1756 scast, expr, is_inv ? ">=" : "<");
1759 case PFO_LE: // ZF=1||SF!=OF; OF=0
1760 snprintf(buf, buf_size, "(%s%s %s 0)",
1761 scast, expr, is_inv ? ">" : "<=");
1765 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1769 static void out_cmp_for_cc(char *buf, size_t buf_size,
1770 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1772 const char *cast, *scast, *cast_use;
1773 char buf1[256], buf2[256];
1774 enum opr_lenmod lmod;
1776 if (po->operand[0].lmod != po->operand[1].lmod)
1777 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1778 po->operand[0].lmod, po->operand[1].lmod);
1779 lmod = po->operand[0].lmod;
1781 cast = lmod_cast_u(po, lmod);
1782 scast = lmod_cast_s(po, lmod);
1798 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1801 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1802 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1806 // note: must be unsigned compare
1807 snprintf(buf, buf_size, "(%s %s %s)",
1808 buf1, is_inv ? ">=" : "<", buf2);
1812 snprintf(buf, buf_size, "(%s %s %s)",
1813 buf1, is_inv ? "!=" : "==", buf2);
1817 // note: must be unsigned compare
1818 snprintf(buf, buf_size, "(%s %s %s)",
1819 buf1, is_inv ? ">" : "<=", buf2);
1822 if (is_inv && lmod == OPLM_BYTE
1823 && po->operand[1].type == OPT_CONST
1824 && po->operand[1].val == 0xff)
1826 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1827 snprintf(buf, buf_size, "(0)");
1831 // note: must be signed compare
1833 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1834 scast, buf1, buf2, is_inv ? ">=" : "<");
1838 snprintf(buf, buf_size, "(%s %s %s)",
1839 buf1, is_inv ? ">=" : "<", buf2);
1843 snprintf(buf, buf_size, "(%s %s %s)",
1844 buf1, is_inv ? ">" : "<=", buf2);
1852 static void out_cmp_test(char *buf, size_t buf_size,
1853 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1855 char buf1[256], buf2[256], buf3[256];
1857 if (po->op == OP_TEST) {
1858 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1859 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1862 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1863 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1864 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1866 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1867 po->operand[0].lmod, buf3);
1869 else if (po->op == OP_CMP) {
1870 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1873 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1876 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1877 struct parsed_opr *popr2)
1879 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1880 ferr(po, "missing lmod for both operands\n");
1882 if (popr1->lmod == OPLM_UNSPEC)
1883 popr1->lmod = popr2->lmod;
1884 else if (popr2->lmod == OPLM_UNSPEC)
1885 popr2->lmod = popr1->lmod;
1886 else if (popr1->lmod != popr2->lmod) {
1887 if (popr1->type_from_var) {
1888 popr1->size_mismatch = 1;
1889 if (popr1->lmod < popr2->lmod)
1891 popr1->lmod = popr2->lmod;
1893 else if (popr2->type_from_var) {
1894 popr2->size_mismatch = 1;
1895 if (popr2->lmod < popr1->lmod)
1897 popr2->lmod = popr1->lmod;
1900 ferr(po, "conflicting lmods: %d vs %d\n",
1901 popr1->lmod, popr2->lmod);
1905 static const char *op_to_c(struct parsed_op *po)
1929 ferr(po, "op_to_c was supplied with %d\n", po->op);
1933 static void op_set_clear_flag(struct parsed_op *po,
1934 enum op_flags flag_set, enum op_flags flag_clear)
1936 po->flags |= flag_set;
1937 po->flags &= ~flag_clear;
1940 // last op in stream - unconditional branch or ret
1941 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1942 || (ops[_i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
1944 static int scan_for_pop(int i, int opcnt, const char *reg,
1945 int magic, int depth, int *maxdepth, int do_flags)
1947 const struct parsed_proto *pp;
1948 struct parsed_op *po;
1952 for (; i < opcnt; i++) {
1954 if (po->cc_scratch == magic)
1955 break; // already checked
1956 po->cc_scratch = magic;
1958 if (po->flags & OPF_TAIL) {
1959 if (po->op == OP_CALL) {
1960 pp = proto_parse(g_fhdr, po->operand[0].name, 0);
1961 if (pp != NULL && pp->is_noreturn)
1962 // no stack cleanup for noreturn
1965 return -1; // deadend
1968 if ((po->flags & OPF_RMD)
1969 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1972 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1973 if (po->btj != NULL) {
1975 for (j = 0; j < po->btj->count; j++) {
1976 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1977 depth, maxdepth, do_flags);
1979 return ret; // dead end
1985 ferr(po, "dead branch\n");
1989 if (po->flags & OPF_CJMP) {
1990 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1991 depth, maxdepth, do_flags);
1993 return ret; // dead end
2001 if ((po->op == OP_POP || po->op == OP_PUSH)
2002 && po->operand[0].type == OPT_REG
2003 && IS(po->operand[0].name, reg))
2005 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
2007 if (depth > *maxdepth)
2010 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2012 else if (po->op == OP_POP) {
2015 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2020 if (depth < 0) // should not happen
2021 ferr(po, "fail with depth\n");
2023 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2032 // scan for pop starting from 'ret' op (all paths)
2033 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2039 for (; i < opcnt; i++) {
2040 if (!(ops[i].flags & OPF_TAIL))
2043 for (j = i - 1; j >= 0; j--) {
2044 if (ops[j].flags & OPF_RMD)
2046 if (ops[j].flags & OPF_JMP)
2049 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2050 && IS(ops[j].operand[0].name, reg))
2053 ops[j].flags |= flag_set;
2057 if (g_labels[j][0] != 0)
2062 return found ? 0 : -1;
2065 static void scan_propagate_df(int i, int opcnt)
2067 struct parsed_op *po = &ops[i];
2070 for (; i < opcnt; i++) {
2072 if (po->flags & OPF_DF)
2073 return; // already resolved
2074 po->flags |= OPF_DF;
2076 if (po->op == OP_CALL)
2077 ferr(po, "call with DF set?\n");
2079 if (po->flags & OPF_JMP) {
2080 if (po->btj != NULL) {
2082 for (j = 0; j < po->btj->count; j++)
2083 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2088 ferr(po, "dead branch\n");
2092 if (po->flags & OPF_CJMP)
2093 scan_propagate_df(po->bt_i, opcnt);
2099 if (po->flags & OPF_TAIL)
2102 if (po->op == OP_CLD) {
2103 po->flags |= OPF_RMD;
2108 ferr(po, "missing DF clear?\n");
2111 // is operand 'opr' modified by parsed_op 'po'?
2112 static int is_opr_modified(const struct parsed_opr *opr,
2113 const struct parsed_op *po)
2117 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2120 if (opr->type == OPT_REG) {
2121 if (po->op == OP_CALL) {
2122 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2123 if ((1 << opr->reg) & mask)
2129 if (po->operand[0].type == OPT_REG) {
2130 if (po->regmask_dst & (1 << opr->reg))
2137 return IS(po->operand[0].name, opr->name);
2140 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2141 static int is_any_opr_modified(const struct parsed_op *po_test,
2142 const struct parsed_op *po, int c_mode)
2147 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2150 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2153 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2156 // in reality, it can wreck any register, but in decompiled C
2157 // version it can only overwrite eax or edx:eax
2158 mask = (1 << xAX) | (1 << xDX);
2162 if (po->op == OP_CALL
2163 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2166 for (i = 0; i < po_test->operand_cnt; i++)
2167 if (IS(po_test->operand[i].name, po->operand[0].name))
2173 // scan for any po_test operand modification in range given
2174 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2177 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2180 for (; i < opcnt; i++) {
2181 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2188 // scan for po_test operand[0] modification in range given
2189 static int scan_for_mod_opr0(struct parsed_op *po_test,
2192 for (; i < opcnt; i++) {
2193 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2200 static int scan_for_flag_set(int i, int magic, int *branched,
2201 int *setters, int *setter_cnt)
2203 struct label_ref *lr;
2207 if (ops[i].cc_scratch == magic) {
2208 ferr(&ops[i], "%s looped\n", __func__);
2211 ops[i].cc_scratch = magic;
2213 if (g_labels[i][0] != 0) {
2216 lr = &g_label_refs[i];
2217 for (; lr->next; lr = lr->next) {
2218 ret = scan_for_flag_set(lr->i, magic,
2219 branched, setters, setter_cnt);
2224 if (i > 0 && LAST_OP(i - 1)) {
2228 ret = scan_for_flag_set(lr->i, magic,
2229 branched, setters, setter_cnt);
2235 if (ops[i].flags & OPF_FLAGS) {
2236 setters[*setter_cnt] = i;
2241 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2248 // scan back for cdq, if anything modifies edx, fail
2249 static int scan_for_cdq_edx(int i)
2252 if (g_labels[i][0] != 0) {
2253 if (g_label_refs[i].next != NULL)
2255 if (i > 0 && LAST_OP(i - 1)) {
2256 i = g_label_refs[i].i;
2263 if (ops[i].op == OP_CDQ)
2266 if (ops[i].regmask_dst & (1 << xDX))
2273 static int scan_for_reg_clear(int i, int reg)
2276 if (g_labels[i][0] != 0) {
2277 if (g_label_refs[i].next != NULL)
2279 if (i > 0 && LAST_OP(i - 1)) {
2280 i = g_label_refs[i].i;
2287 if (ops[i].op == OP_XOR
2288 && ops[i].operand[0].lmod == OPLM_DWORD
2289 && ops[i].operand[0].reg == ops[i].operand[1].reg
2290 && ops[i].operand[0].reg == reg)
2293 if (ops[i].regmask_dst & (1 << reg))
2300 // scan for positive, constant esp adjust
2301 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2303 const struct parsed_proto *pp;
2304 struct parsed_op *po;
2308 for (; i < opcnt; i++) {
2311 if (g_labels[i][0] != 0)
2314 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2315 if (po->operand[1].type != OPT_CONST)
2316 ferr(&ops[i], "non-const esp adjust?\n");
2317 *adj += po->operand[1].val;
2319 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2322 else if (po->op == OP_PUSH) {
2323 //if (first_pop == -1)
2324 // first_pop = -2; // none
2325 *adj -= lmod_bytes(po, po->operand[0].lmod);
2327 else if (po->op == OP_POP && !(po->flags & OPF_RMD)) {
2328 if (first_pop == -1 && *adj >= 0)
2330 *adj += lmod_bytes(po, po->operand[0].lmod);
2332 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2333 if (po->op != OP_CALL)
2335 if (po->operand[0].type != OPT_LABEL)
2338 if (pp != NULL && pp->is_stdcall)
2343 if (*adj <= 8 && first_pop >= 0 && ops[first_pop].op == OP_POP
2344 && ops[first_pop].operand[0].type == OPT_REG
2345 && ops[first_pop].operand[0].reg == xCX)
2347 // probably 'pop ecx' was used..
2354 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2356 struct parsed_op *po;
2360 ferr(ops, "%s: followed bad branch?\n", __func__);
2362 for (; i < opcnt; i++) {
2364 if (po->cc_scratch == magic)
2366 po->cc_scratch = magic;
2369 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2370 if (po->btj != NULL) {
2372 for (j = 0; j < po->btj->count; j++)
2373 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2377 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2378 if (!(po->flags & OPF_CJMP))
2381 if (po->flags & OPF_TAIL)
2386 static const struct parsed_proto *try_recover_pp(
2387 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2389 const struct parsed_proto *pp = NULL;
2393 // maybe an arg of g_func?
2394 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2396 char ofs_reg[16] = { 0, };
2397 int arg, arg_s, arg_i;
2401 parse_stack_access(po, opr->name, ofs_reg,
2402 &offset, &stack_ra, NULL);
2403 if (ofs_reg[0] != 0)
2404 ferr(po, "offset reg on arg access?\n");
2405 if (offset <= stack_ra) {
2406 // search who set the stack var instead
2407 if (search_instead != NULL)
2408 *search_instead = 1;
2412 arg_i = (offset - stack_ra - 4) / 4;
2413 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2414 if (g_func_pp->arg[arg].reg != NULL)
2420 if (arg == g_func_pp->argc)
2421 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2423 pp = g_func_pp->arg[arg].fptr;
2425 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2426 check_func_pp(po, pp, "icall arg");
2428 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2430 p = strchr(opr->name + 1, '[');
2431 memcpy(buf, opr->name, p - opr->name);
2432 buf[p - opr->name] = 0;
2433 pp = proto_parse(g_fhdr, buf, 0);
2435 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2436 pp = proto_parse(g_fhdr, opr->name, 0);
2438 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2439 check_func_pp(po, pp, "reg-fptr ref");
2445 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2446 int magic, const struct parsed_proto **pp_found, int *multi)
2448 const struct parsed_proto *pp = NULL;
2449 struct parsed_op *po;
2450 struct label_ref *lr;
2453 if (ops[i].cc_scratch == magic)
2455 ops[i].cc_scratch = magic;
2457 if (g_labels[i][0] != 0) {
2458 lr = &g_label_refs[i];
2459 for (; lr != NULL; lr = lr->next)
2460 scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2461 if (i > 0 && LAST_OP(i - 1))
2466 if (!(ops[i].flags & OPF_DATA))
2468 if (!is_opr_modified(opr, &ops[i]))
2470 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2471 // most probably trashed by some processing
2476 opr = &ops[i].operand[1];
2477 if (opr->type != OPT_REG)
2481 po = (i >= 0) ? &ops[i] : ops;
2484 // reached the top - can only be an arg-reg
2485 if (opr->type != OPT_REG)
2488 for (i = 0; i < g_func_pp->argc; i++) {
2489 if (g_func_pp->arg[i].reg == NULL)
2491 if (IS(opr->name, g_func_pp->arg[i].reg))
2494 if (i == g_func_pp->argc)
2496 pp = g_func_pp->arg[i].fptr;
2498 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2499 i + 1, g_func_pp->arg[i].reg);
2500 check_func_pp(po, pp, "icall reg-arg");
2503 pp = try_recover_pp(po, opr, NULL);
2505 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2506 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2507 || (*pp_found)->is_stdcall != pp->is_stdcall
2508 || (*pp_found)->is_fptr != pp->is_fptr
2509 || (*pp_found)->argc != pp->argc
2510 || (*pp_found)->argc_reg != pp->argc_reg
2511 || (*pp_found)->argc_stack != pp->argc_stack)
2513 ferr(po, "icall: parsed_proto mismatch\n");
2521 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2524 const struct parsed_proto *pp = NULL;
2525 int search_advice = 0;
2529 switch (ops[i].operand[0].type) {
2533 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2538 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2546 static int collect_call_args_r(struct parsed_op *po, int i,
2547 struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2548 int magic, int need_op_saving, int may_reuse)
2550 struct parsed_proto *pp_tmp;
2551 struct label_ref *lr;
2552 int need_to_save_current;
2557 ferr(po, "dead label encountered\n");
2561 for (; arg < pp->argc; arg++)
2562 if (pp->arg[arg].reg == NULL)
2564 magic = (magic & 0xffffff) | (arg << 24);
2566 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2568 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2569 if (ops[j].cc_scratch != magic) {
2570 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2574 // ok: have already been here
2577 ops[j].cc_scratch = magic;
2579 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2580 lr = &g_label_refs[j];
2581 if (lr->next != NULL)
2583 for (; lr->next; lr = lr->next) {
2584 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2586 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2587 arg, magic, need_op_saving, may_reuse);
2592 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2594 if (j > 0 && LAST_OP(j - 1)) {
2595 // follow last branch in reverse
2600 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2601 arg, magic, need_op_saving, may_reuse);
2607 if (ops[j].op == OP_CALL)
2609 if (pp->is_unresolved)
2612 pp_tmp = ops[j].datap;
2614 ferr(po, "arg collect hit unparsed call '%s'\n",
2615 ops[j].operand[0].name);
2616 if (may_reuse && pp_tmp->argc_stack > 0)
2617 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2618 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2620 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2621 if (pp->is_unresolved)
2624 ferr(po, "arg collect %d/%d hit esp adjust\n",
2627 else if (ops[j].op == OP_POP) {
2628 if (pp->is_unresolved)
2631 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2633 else if (ops[j].flags & OPF_CJMP)
2635 if (pp->is_unresolved)
2640 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2642 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2645 pp->arg[arg].datap = &ops[j];
2646 need_to_save_current = 0;
2647 if (!need_op_saving) {
2648 ret = scan_for_mod(&ops[j], j + 1, i, 1);
2649 need_to_save_current = (ret >= 0);
2651 if (need_op_saving || need_to_save_current) {
2652 // mark this push as one that needs operand saving
2653 ops[j].flags &= ~OPF_RMD;
2654 if (ops[j].argnum == 0) {
2655 ops[j].argnum = arg + 1;
2656 *save_arg_vars |= 1 << arg;
2658 else if (ops[j].argnum < arg + 1)
2659 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2660 ops[j].argnum, arg + 1, pp->name);
2662 else if (ops[j].argnum == 0)
2663 ops[j].flags |= OPF_RMD;
2665 // some PUSHes are reused by different calls on other branches,
2666 // but that can't happen if we didn't branch, so they
2667 // can be removed from future searches (handles nested calls)
2669 ops[j].flags |= OPF_FARG;
2671 ops[j].flags &= ~OPF_RSAVE;
2674 if (!pp->is_unresolved) {
2676 for (; arg < pp->argc; arg++)
2677 if (pp->arg[arg].reg == NULL)
2680 magic = (magic & 0xffffff) | (arg << 24);
2682 // tracking reg usage
2683 if (ops[j].operand[0].type == OPT_REG)
2684 *regmask |= 1 << ops[j].operand[0].reg;
2688 if (arg < pp->argc) {
2689 ferr(po, "arg collect failed for '%s': %d/%d\n",
2690 pp->name, arg, pp->argc);
2697 static int collect_call_args(struct parsed_op *po, int i,
2698 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2704 ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2709 if (pp->is_unresolved) {
2711 pp->argc_stack += ret;
2712 for (a = 0; a < pp->argc; a++)
2713 if (pp->arg[a].type.name == NULL)
2714 pp->arg[a].type.name = strdup("int");
2720 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2724 for (i = 0; i < pp->argc; i++)
2725 if (pp->arg[i].reg == NULL)
2729 memmove(&pp->arg[i + 1], &pp->arg[i],
2730 sizeof(pp->arg[0]) * pp->argc_stack);
2731 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2732 pp->arg[i].reg = strdup(reg);
2733 pp->arg[i].type.name = strdup("int");
2738 static void add_label_ref(struct label_ref *lr, int op_i)
2740 struct label_ref *lr_new;
2747 lr_new = calloc(1, sizeof(*lr_new));
2749 lr_new->next = lr->next;
2753 static void output_std_flags(FILE *fout, struct parsed_op *po,
2754 int *pfomask, const char *dst_opr_text)
2756 if (*pfomask & (1 << PFO_Z)) {
2757 fprintf(fout, "\n cond_z = (%s%s == 0);",
2758 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2759 *pfomask &= ~(1 << PFO_Z);
2761 if (*pfomask & (1 << PFO_S)) {
2762 fprintf(fout, "\n cond_s = (%s%s < 0);",
2763 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2764 *pfomask &= ~(1 << PFO_S);
2768 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
2771 if (pp->is_fastcall)
2772 fprintf(fout, "__fastcall ");
2773 else if (pp->is_stdcall && pp->argc_reg == 0)
2774 fprintf(fout, "__stdcall ");
2775 if (pp->is_noreturn || is_noreturn)
2776 fprintf(fout, "noreturn ");
2779 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2781 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2782 struct parsed_opr *last_arith_dst = NULL;
2783 char buf1[256], buf2[256], buf3[256], cast[64];
2784 const struct parsed_proto *pp_c;
2785 struct parsed_proto *pp, *pp_tmp;
2786 struct parsed_data *pd;
2787 const char *tmpname;
2788 enum parsed_flag_op pfo;
2789 int save_arg_vars = 0;
2790 int cmp_result_vars = 0;
2791 int need_mul_var = 0;
2793 int label_pending = 0;
2794 int regmask_save = 0;
2795 int regmask_arg = 0;
2796 int regmask_now = 0;
2797 int regmask_init = 0;
2809 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2810 g_stack_frame_used = 0;
2812 g_func_pp = proto_parse(fhdr, funcn, 0);
2813 if (g_func_pp == NULL)
2814 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2816 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2817 output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
2818 fprintf(fout, "%s(", funcn);
2820 for (i = 0; i < g_func_pp->argc; i++) {
2822 fprintf(fout, ", ");
2823 if (g_func_pp->arg[i].fptr != NULL) {
2825 pp = g_func_pp->arg[i].fptr;
2826 fprintf(fout, "%s (", pp->ret_type.name);
2827 output_pp_attrs(fout, pp, 0);
2828 fprintf(fout, "*a%d)(", i + 1);
2829 for (j = 0; j < pp->argc; j++) {
2831 fprintf(fout, ", ");
2832 if (pp->arg[j].fptr)
2833 ferr(ops, "nested fptr\n");
2834 fprintf(fout, "%s", pp->arg[j].type.name);
2839 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2841 if (g_func_pp->arg[i].reg != NULL) {
2842 reg = char_array_i(regs_r32,
2843 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2845 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2846 regmask_arg |= 1 << reg;
2849 if (g_func_pp->is_vararg) {
2851 fprintf(fout, ", ");
2852 fprintf(fout, "...");
2855 fprintf(fout, ")\n{\n");
2858 // - handle ebp/esp frame, remove ops related to it
2859 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2860 && ops[1].op == OP_MOV
2861 && IS(opr_name(&ops[1], 0), "ebp")
2862 && IS(opr_name(&ops[1], 1), "esp"))
2867 ops[0].flags |= OPF_RMD;
2868 ops[1].flags |= OPF_RMD;
2871 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2872 g_stack_fsz = opr_const(&ops[2], 1);
2873 ops[2].flags |= OPF_RMD;
2877 // another way msvc builds stack frame..
2879 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2881 ops[i].flags |= OPF_RMD;
2885 // and another way..
2886 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2887 && ops[i].operand[1].type == OPT_CONST
2888 && ops[i + 1].op == OP_CALL
2889 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2891 g_stack_fsz += ops[i].operand[1].val;
2892 ops[i].flags |= OPF_RMD;
2894 ops[i].flags |= OPF_RMD;
2901 for (; i < opcnt; i++)
2902 if (ops[i].op == OP_RET)
2904 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2907 if ((ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2908 || ops[i - 1].op == OP_LEAVE)
2910 ops[i - 1].flags |= OPF_RMD;
2912 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2913 ferr(&ops[i - 1], "'pop ebp' expected\n");
2915 if (g_stack_fsz != 0) {
2916 if (ops[i - 2].op == OP_MOV
2917 && IS(opr_name(&ops[i - 2], 0), "esp")
2918 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2920 ops[i - 2].flags |= OPF_RMD;
2922 else if (ops[i - 1].op != OP_LEAVE
2923 && !(g_ida_func_attr & IDAFA_NORETURN))
2925 ferr(&ops[i - 2], "esp restore expected\n");
2928 if (ecx_push && ops[i - 3].op == OP_POP
2929 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2931 ferr(&ops[i - 3], "unexpected ecx pop\n");
2937 } while (i < opcnt);
2940 for (i = 0; i < opcnt; i++) {
2941 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2943 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2944 && ops[i].operand[1].type == OPT_CONST)
2953 g_stack_fsz = ops[i].operand[1].val;
2954 ops[i].flags |= OPF_RMD;
2958 for (; i < opcnt; i++)
2959 if (ops[i].op == OP_RET)
2961 if (ops[i - 1].op != OP_ADD
2962 || !IS(opr_name(&ops[i - 1], 0), "esp")
2963 || ops[i - 1].operand[1].type != OPT_CONST
2964 || ops[i - 1].operand[1].val != g_stack_fsz)
2965 ferr(&ops[i - 1], "'add esp' expected\n");
2966 ops[i - 1].flags |= OPF_RMD;
2969 } while (i < opcnt);
2974 // - parse calls with labels
2975 // - resolve all branches
2976 for (i = 0; i < opcnt; i++)
2982 if (po->flags & OPF_RMD)
2985 if (po->op == OP_CALL) {
2988 if (po->operand[0].type == OPT_LABEL) {
2989 tmpname = opr_name(po, 0);
2990 if (IS_START(tmpname, "loc_"))
2991 ferr(po, "call to loc_*\n");
2992 pp_c = proto_parse(fhdr, tmpname, 0);
2994 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2996 pp = proto_clone(pp_c);
2997 my_assert_not(pp, NULL);
2999 else if (po->datap != NULL) {
3000 pp = calloc(1, sizeof(*pp));
3001 my_assert_not(pp, NULL);
3003 ret = parse_protostr(po->datap, pp);
3005 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3012 check_func_pp(po, pp, "fptr var call");
3013 if (pp->is_noreturn)
3014 po->flags |= OPF_TAIL;
3020 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3023 if (po->operand[0].type == OPT_REGMEM) {
3024 char *p = strchr(po->operand[0].name, '[');
3027 ret = p - po->operand[0].name;
3028 strncpy(buf1, po->operand[0].name, ret);
3031 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3032 if (IS(g_func_pd[j].label, buf1)) {
3038 //ferr(po, "label '%s' not parsed?\n", buf1);
3040 if (pd->type != OPT_OFFSET)
3041 ferr(po, "label '%s' with non-offset data?\n", buf1);
3043 // find all labels, link
3044 for (j = 0; j < pd->count; j++) {
3045 for (l = 0; l < opcnt; l++) {
3046 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
3047 add_label_ref(&g_label_refs[l], i);
3058 for (l = 0; l < opcnt; l++) {
3059 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
3060 add_label_ref(&g_label_refs[l], i);
3069 if (po->operand[0].type == OPT_LABEL)
3073 ferr(po, "unhandled branch\n");
3077 po->flags |= OPF_TAIL;
3082 // - remove dead labels
3084 for (i = 0; i < opcnt; i++)
3086 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3090 if (po->flags & OPF_RMD)
3093 if (po->op == OP_CALL)
3095 tmpname = opr_name(po, 0);
3100 pp_c = resolve_icall(i, opcnt, &l);
3102 pp = proto_clone(pp_c);
3103 my_assert_not(pp, NULL);
3105 // not resolved just to single func
3109 pp = calloc(1, sizeof(*pp));
3110 my_assert_not(pp, NULL);
3112 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3114 if (!g_allow_regfunc)
3115 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3116 pp->is_unresolved = 1;
3120 if (j > ARRAY_SIZE(pp->arg))
3121 ferr(po, "esp adjust too large: %d\n", j);
3122 pp->ret_type.name = strdup("int");
3123 pp->argc = pp->argc_stack = j;
3124 for (arg = 0; arg < pp->argc; arg++)
3125 pp->arg[arg].type.name = strdup("int");
3130 // look for and make use of esp adjust
3132 if (!pp->is_stdcall && pp->argc_stack > 0)
3133 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3135 if (pp->is_vararg) {
3136 if (j / 4 < pp->argc_stack)
3137 ferr(po, "esp adjust is too small: %x < %x\n",
3138 j, pp->argc_stack * 4);
3139 // modify pp to make it have varargs as normal args
3141 pp->argc += j / 4 - pp->argc_stack;
3142 for (; arg < pp->argc; arg++) {
3143 pp->arg[arg].type.name = strdup("int");
3146 if (pp->argc > ARRAY_SIZE(pp->arg))
3147 ferr(po, "too many args for '%s'\n", tmpname);
3149 if (pp->argc_stack != j / 4)
3150 ferr(po, "stack tracking failed for '%s': %x %x\n",
3151 tmpname, pp->argc_stack * 4, j);
3153 ops[ret].flags |= OPF_RMD;
3154 if (ops[ret].op == OP_POP && j > 4) {
3155 // deal with multi-pop stack adjust
3157 while (ops[ret].op == OP_POP && j > 0 && ret < opcnt) {
3158 ops[ret].flags |= OPF_RMD;
3164 // a bit of a hack, but deals with use of
3165 // single adj for multiple calls
3166 ops[ret].operand[1].val -= j;
3169 else if (pp->is_vararg)
3170 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3173 if (!pp->is_unresolved) {
3174 // since we know the args, collect them
3175 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3179 if (strstr(pp->ret_type.name, "int64"))
3185 // - find POPs for PUSHes, rm both
3186 // - scan for STD/CLD, propagate DF
3187 // - scan for all used registers
3188 // - find flag set ops for their users
3189 // - do unreselved calls
3190 // - declare indirect functions
3191 for (i = 0; i < opcnt; i++) {
3193 if (po->flags & OPF_RMD)
3196 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3197 reg = po->operand[0].reg;
3198 if (!(regmask & (1 << reg)))
3199 // not a reg save after all, rerun scan_for_pop
3200 po->flags &= ~OPF_RSAVE;
3202 regmask_save |= 1 << reg;
3205 if (po->op == OP_PUSH && po->argnum == 0
3206 && !(po->flags & OPF_RSAVE))
3208 if (po->operand[0].type == OPT_REG)
3210 reg = po->operand[0].reg;
3212 ferr(po, "reg not set for push?\n");
3215 ret = scan_for_pop(i + 1, opcnt,
3216 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3219 ferr(po, "too much depth: %d\n", depth);
3221 po->flags |= OPF_RMD;
3222 scan_for_pop(i + 1, opcnt, po->operand[0].name,
3223 i + opcnt * 4, 0, &depth, 1);
3226 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3229 if (regmask & (1 << reg)) {
3230 if (regmask_save & (1 << reg))
3231 ferr(po, "%s already saved?\n", po->operand[0].name);
3235 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3239 else if (po->operand[0].type == OPT_CONST) {
3240 for (j = i + 1; j < opcnt; j++) {
3241 if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
3242 || ops[j].op == OP_PUSH || g_labels[i][0] != 0)
3247 if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
3249 po->flags |= OPF_RMD;
3257 if (po->op == OP_STD) {
3258 po->flags |= OPF_DF | OPF_RMD;
3259 scan_propagate_df(i + 1, opcnt);
3262 regmask_now = po->regmask_src | po->regmask_dst;
3263 if (regmask_now & (1 << xBP)) {
3264 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3265 if (po->regmask_dst & (1 << xBP))
3266 // compiler decided to drop bp frame and use ebp as scratch
3267 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
3269 regmask_now &= ~(1 << xBP);
3273 regmask |= regmask_now;
3275 if (po->flags & OPF_CC)
3277 int setters[16], cnt = 0, branched = 0;
3279 ret = scan_for_flag_set(i, i + opcnt * 6,
3280 &branched, setters, &cnt);
3281 if (ret < 0 || cnt <= 0)
3282 ferr(po, "unable to trace flag setter(s)\n");
3283 if (cnt > ARRAY_SIZE(setters))
3284 ferr(po, "too many flag setters\n");
3286 pfo = split_cond(po, po->op, &dummy);
3287 for (j = 0; j < cnt; j++)
3289 tmp_op = &ops[setters[j]]; // flag setter
3292 // to get nicer code, we try to delay test and cmp;
3293 // if we can't because of operand modification, or if we
3294 // have arith op, or branch, make it calculate flags explicitly
3295 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
3297 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3300 else if (tmp_op->op == OP_SCAS) {
3303 else if (tmp_op->op == OP_CMPS) {
3304 pfomask = 1 << PFO_Z;
3307 // see if we'll be able to handle based on op result
3308 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3309 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3311 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3315 tmp_op->pfomask |= pfomask;
3316 cmp_result_vars |= pfomask;
3318 // note: may overwrite, currently not a problem
3322 if (po->op == OP_ADC || po->op == OP_SBB)
3323 cmp_result_vars |= 1 << PFO_C;
3325 else if (po->op == OP_CMPS || po->op == OP_SCAS) {
3326 cmp_result_vars |= 1 << PFO_Z;
3328 else if (po->op == OP_MUL
3329 || (po->op == OP_IMUL && po->operand_cnt == 1))
3333 else if (po->op == OP_CALL) {
3336 ferr(po, "NULL pp\n");
3338 if (pp->is_unresolved) {
3339 int regmask_stack = 0;
3340 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3343 // this is pretty rough guess:
3344 // see ecx and edx were pushed (and not their saved versions)
3345 for (arg = 0; arg < pp->argc; arg++) {
3346 if (pp->arg[arg].reg != NULL)
3349 tmp_op = pp->arg[arg].datap;
3351 ferr(po, "parsed_op missing for arg%d\n", arg);
3352 if (tmp_op->argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3353 regmask_stack |= 1 << tmp_op->operand[0].reg;
3356 if (!((regmask_stack & (1 << xCX))
3357 && (regmask_stack & (1 << xDX))))
3359 if (pp->argc_stack != 0
3360 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3362 pp_insert_reg_arg(pp, "ecx");
3363 pp->is_fastcall = 1;
3364 regmask_init |= 1 << xCX;
3365 regmask |= 1 << xCX;
3367 if (pp->argc_stack != 0
3368 || ((regmask | regmask_arg) & (1 << xDX)))
3370 pp_insert_reg_arg(pp, "edx");
3371 regmask_init |= 1 << xDX;
3372 regmask |= 1 << xDX;
3376 // note: __cdecl doesn't fall into is_unresolved category
3377 if (pp->argc_stack > 0)
3381 for (arg = 0; arg < pp->argc; arg++) {
3382 if (pp->arg[arg].reg != NULL) {
3383 reg = char_array_i(regs_r32,
3384 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3386 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3387 if (!(regmask & (1 << reg))) {
3388 regmask_init |= 1 << reg;
3389 regmask |= 1 << reg;
3395 if (pp->name[0] != 0) {
3396 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3397 memcpy(pp->name, "i_", 2);
3399 // might be declared already
3401 for (j = 0; j < i; j++) {
3402 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].datap)) {
3403 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3413 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3415 fprintf(fout, " %s (", pp->ret_type.name);
3416 output_pp_attrs(fout, pp, 0);
3417 fprintf(fout, "*%s)(", pp->name);
3418 for (j = 0; j < pp->argc; j++) {
3420 fprintf(fout, ", ");
3421 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3423 fprintf(fout, ");\n");
3426 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3427 regmask |= 1 << xAX;
3431 // - confirm regmask_save, it might have been reduced
3432 if (regmask_save != 0)
3435 for (i = 0; i < opcnt; i++) {
3437 if (po->flags & OPF_RMD)
3440 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3441 regmask_save |= 1 << po->operand[0].reg;
3446 // output LUTs/jumptables
3447 for (i = 0; i < g_func_pd_cnt; i++) {
3449 fprintf(fout, " static const ");
3450 if (pd->type == OPT_OFFSET) {
3451 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3453 for (j = 0; j < pd->count; j++) {
3455 fprintf(fout, ", ");
3456 fprintf(fout, "&&%s", pd->d[j].u.label);
3460 fprintf(fout, "%s %s[] =\n { ",
3461 lmod_type_u(ops, pd->lmod), pd->label);
3463 for (j = 0; j < pd->count; j++) {
3465 fprintf(fout, ", ");
3466 fprintf(fout, "%u", pd->d[j].u.val);
3469 fprintf(fout, " };\n");
3472 // declare stack frame, va_arg
3474 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3475 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3477 if (g_func_pp->is_vararg)
3478 fprintf(fout, " va_list ap;\n");
3480 // declare arg-registers
3481 for (i = 0; i < g_func_pp->argc; i++) {
3482 if (g_func_pp->arg[i].reg != NULL) {
3483 reg = char_array_i(regs_r32,
3484 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3485 if (regmask & (1 << reg)) {
3486 fprintf(fout, " u32 %s = (u32)a%d;\n",
3487 g_func_pp->arg[i].reg, i + 1);
3490 fprintf(fout, " // %s = a%d; // unused\n",
3491 g_func_pp->arg[i].reg, i + 1);
3496 regmask_now = regmask & ~regmask_arg;
3497 regmask_now &= ~(1 << xSP);
3499 for (reg = 0; reg < 8; reg++) {
3500 if (regmask_now & (1 << reg)) {
3501 fprintf(fout, " u32 %s", regs_r32[reg]);
3502 if (regmask_init & (1 << reg))
3503 fprintf(fout, " = 0");
3504 fprintf(fout, ";\n");
3511 for (reg = 0; reg < 8; reg++) {
3512 if (regmask_save & (1 << reg)) {
3513 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3519 if (save_arg_vars) {
3520 for (reg = 0; reg < 32; reg++) {
3521 if (save_arg_vars & (1 << reg)) {
3522 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3528 if (cmp_result_vars) {
3529 for (i = 0; i < 8; i++) {
3530 if (cmp_result_vars & (1 << i)) {
3531 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3538 fprintf(fout, " u64 mul_tmp;\n");
3543 fprintf(fout, "\n");
3545 if (g_func_pp->is_vararg) {
3546 if (g_func_pp->argc_stack == 0)
3547 ferr(ops, "vararg func without stack args?\n");
3548 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3552 for (i = 0; i < opcnt; i++)
3554 if (g_labels[i][0] != 0) {
3555 fprintf(fout, "\n%s:\n", g_labels[i]);
3558 delayed_flag_op = NULL;
3559 last_arith_dst = NULL;
3563 if (po->flags & OPF_RMD)
3568 #define assert_operand_cnt(n_) \
3569 if (po->operand_cnt != n_) \
3570 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3572 // conditional/flag using op?
3573 if (po->flags & OPF_CC)
3578 pfo = split_cond(po, po->op, &is_inv);
3581 // we go through all this trouble to avoid using parsed_flag_op,
3582 // which makes generated code much nicer
3583 if (delayed_flag_op != NULL)
3585 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3588 else if (last_arith_dst != NULL
3589 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3590 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3593 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3594 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3595 last_arith_dst->lmod, buf3);
3598 else if (tmp_op != NULL) {
3599 // use preprocessed flag calc results
3600 if (!(tmp_op->pfomask & (1 << pfo)))
3601 ferr(po, "not prepared for pfo %d\n", pfo);
3603 // note: is_inv was not yet applied
3604 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3605 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3608 ferr(po, "all methods of finding comparison failed\n");
3611 if (po->flags & OPF_JMP) {
3612 fprintf(fout, " if %s\n", buf1);
3614 else if (po->op == OP_ADC || po->op == OP_SBB) {
3616 fprintf(fout, " cond_%s = %s;\n",
3617 parsed_flag_op_names[pfo], buf1);
3619 else if (po->flags & OPF_DATA) { // SETcc
3620 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3621 fprintf(fout, " %s = %s;", buf2, buf1);
3624 ferr(po, "unhandled conditional op\n");
3628 pfomask = po->pfomask;
3633 assert_operand_cnt(2);
3634 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3635 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3636 fprintf(fout, " %s = %s;", buf1,
3637 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3638 po->operand[0].is_ptr ? "(void *)" : "", 0));
3642 assert_operand_cnt(2);
3643 po->operand[1].lmod = OPLM_DWORD; // always
3644 fprintf(fout, " %s = %s;",
3645 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3646 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3651 assert_operand_cnt(2);
3652 fprintf(fout, " %s = %s;",
3653 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3654 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3658 assert_operand_cnt(2);
3659 switch (po->operand[1].lmod) {
3661 strcpy(buf3, "(s8)");
3664 strcpy(buf3, "(s16)");
3667 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3669 fprintf(fout, " %s = %s;",
3670 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3671 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3676 assert_operand_cnt(1);
3677 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3678 fprintf(fout, " %s = ~%s;", buf1, buf1);
3682 assert_operand_cnt(2);
3683 fprintf(fout, " %s = (s32)%s >> 31;",
3684 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3685 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3686 strcpy(g_comment, "cdq");
3690 assert_operand_cnt(3);
3691 if (po->flags & OPF_REP) {
3692 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
3693 (po->flags & OPF_DF) ? '-' : '+',
3694 lmod_bytes(po, po->operand[0].lmod));
3695 fprintf(fout, " %sedi = eax;",
3696 lmod_cast_u_ptr(po, po->operand[0].lmod));
3697 strcpy(g_comment, "rep stos");
3700 fprintf(fout, " %sedi = eax; edi %c= %d;",
3701 lmod_cast_u_ptr(po, po->operand[0].lmod),
3702 (po->flags & OPF_DF) ? '-' : '+',
3703 lmod_bytes(po, po->operand[0].lmod));
3704 strcpy(g_comment, "stos");
3709 assert_operand_cnt(3);
3710 j = lmod_bytes(po, po->operand[0].lmod);
3711 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3712 l = (po->flags & OPF_DF) ? '-' : '+';
3713 if (po->flags & OPF_REP) {
3715 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
3718 " %sedi = %sesi;", buf1, buf1);
3719 strcpy(g_comment, "rep movs");
3722 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
3723 buf1, buf1, l, j, l, j);
3724 strcpy(g_comment, "movs");
3729 // repe ~ repeat while ZF=1
3730 assert_operand_cnt(3);
3731 j = lmod_bytes(po, po->operand[0].lmod);
3732 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3733 l = (po->flags & OPF_DF) ? '-' : '+';
3734 if (po->flags & OPF_REP) {
3736 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
3739 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3740 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3743 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3744 (po->flags & OPF_REPZ) ? "e" : "ne");
3748 " cond_z = (%sedi = %sesi); edi %c= %d; esi %c= %d;",
3749 buf1, buf1, l, j, l, j);
3750 strcpy(g_comment, "cmps");
3752 pfomask &= ~(1 << PFO_Z);
3753 last_arith_dst = NULL;
3754 delayed_flag_op = NULL;
3758 // only does ZF (for now)
3759 // repe ~ repeat while ZF=1
3760 assert_operand_cnt(3);
3761 j = lmod_bytes(po, po->operand[0].lmod);
3762 l = (po->flags & OPF_DF) ? '-' : '+';
3763 if (po->flags & OPF_REP) {
3765 " for (; ecx != 0; ecx--, edi %c= %d)\n", l, j);
3767 " if ((cond_z = (%seax == %sedi)) %s 0)\n",
3768 lmod_cast_u(po, po->operand[0].lmod),
3769 lmod_cast_u_ptr(po, po->operand[0].lmod),
3770 (po->flags & OPF_REPZ) ? "==" : "!=");
3773 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
3774 (po->flags & OPF_REPZ) ? "e" : "ne");
3777 fprintf(fout, " cond_z = (%seax = %sedi); edi %c= %d;",
3778 lmod_cast_u(po, po->operand[0].lmod),
3779 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
3780 strcpy(g_comment, "scas");
3782 pfomask &= ~(1 << PFO_Z);
3783 last_arith_dst = NULL;
3784 delayed_flag_op = NULL;
3787 // arithmetic w/flags
3792 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3795 assert_operand_cnt(2);
3796 fprintf(fout, " %s %s= %s;",
3797 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3799 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3800 output_std_flags(fout, po, &pfomask, buf1);
3801 last_arith_dst = &po->operand[0];
3802 delayed_flag_op = NULL;
3807 assert_operand_cnt(2);
3808 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3809 if (pfomask & (1 << PFO_C)) {
3810 if (po->operand[1].type == OPT_CONST) {
3811 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3812 j = po->operand[1].val;
3815 if (po->op == OP_SHL)
3819 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3823 ferr(po, "zero shift?\n");
3827 pfomask &= ~(1 << PFO_C);
3829 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3830 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3831 output_std_flags(fout, po, &pfomask, buf1);
3832 last_arith_dst = &po->operand[0];
3833 delayed_flag_op = NULL;
3837 assert_operand_cnt(2);
3838 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3839 fprintf(fout, " %s = %s%s >> %s;", buf1,
3840 lmod_cast_s(po, po->operand[0].lmod), buf1,
3841 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3842 output_std_flags(fout, po, &pfomask, buf1);
3843 last_arith_dst = &po->operand[0];
3844 delayed_flag_op = NULL;
3849 assert_operand_cnt(2);
3850 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3851 if (po->operand[1].type == OPT_CONST) {
3852 j = po->operand[1].val;
3853 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3854 fprintf(fout, po->op == OP_ROL ?
3855 " %s = (%s << %d) | (%s >> %d);" :
3856 " %s = (%s >> %d) | (%s << %d);",
3857 buf1, buf1, j, buf1,
3858 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3862 output_std_flags(fout, po, &pfomask, buf1);
3863 last_arith_dst = &po->operand[0];
3864 delayed_flag_op = NULL;
3868 assert_operand_cnt(2);
3869 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3870 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3871 // special case for XOR
3872 fprintf(fout, " %s = 0;",
3873 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3874 last_arith_dst = &po->operand[0];
3875 delayed_flag_op = NULL;
3882 assert_operand_cnt(2);
3883 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3884 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3885 if (po->op == OP_SBB
3886 && IS(po->operand[0].name, po->operand[1].name))
3888 // avoid use of unitialized var
3889 fprintf(fout, " %s = -cond_c;", buf1);
3890 // carry remains what it was
3891 pfomask &= ~(1 << PFO_C);
3894 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3895 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3897 output_std_flags(fout, po, &pfomask, buf1);
3898 last_arith_dst = &po->operand[0];
3899 delayed_flag_op = NULL;
3904 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3905 if (po->operand[0].type == OPT_REG) {
3906 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3907 fprintf(fout, " %s%s;", buf1, buf2);
3910 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3911 fprintf(fout, " %s %s= 1;", buf1, buf2);
3913 output_std_flags(fout, po, &pfomask, buf1);
3914 last_arith_dst = &po->operand[0];
3915 delayed_flag_op = NULL;
3919 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3920 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3921 fprintf(fout, " %s = -%s%s;", buf1,
3922 lmod_cast_s(po, po->operand[0].lmod), buf2);
3923 last_arith_dst = &po->operand[0];
3924 delayed_flag_op = NULL;
3925 if (pfomask & (1 << PFO_C)) {
3926 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3927 pfomask &= ~(1 << PFO_C);
3932 if (po->operand_cnt == 2) {
3933 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3936 if (po->operand_cnt == 3)
3937 ferr(po, "TODO imul3\n");
3940 assert_operand_cnt(1);
3941 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3942 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3943 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3944 fprintf(fout, " edx = mul_tmp >> 32;\n");
3945 fprintf(fout, " eax = mul_tmp;");
3946 last_arith_dst = NULL;
3947 delayed_flag_op = NULL;
3952 assert_operand_cnt(1);
3953 if (po->operand[0].lmod != OPLM_DWORD)
3954 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3956 // 32bit division is common, look for it
3957 if (po->op == OP_DIV)
3958 ret = scan_for_reg_clear(i, xDX);
3960 ret = scan_for_cdq_edx(i);
3962 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3963 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3964 po->op == OP_IDIV));
3965 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3966 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3969 ferr(po, "TODO 64bit divident\n");
3970 last_arith_dst = NULL;
3971 delayed_flag_op = NULL;
3976 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3978 for (j = 0; j < 8; j++) {
3979 if (pfomask & (1 << j)) {
3980 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3981 fprintf(fout, " cond_%s = %s;",
3982 parsed_flag_op_names[j], buf1);
3989 last_arith_dst = NULL;
3990 delayed_flag_op = po;
3993 // note: we reuse OP_Jcc for SETcc, only flags differ
3994 case OP_JO ... OP_JG:
3995 if (po->flags & OPF_JMP)
3996 fprintf(fout, " goto %s;", po->operand[0].name);
3997 // else SETcc - should already be handled
4001 fprintf(fout, " if (ecx == 0)\n");
4002 fprintf(fout, " goto %s;", po->operand[0].name);
4003 strcat(g_comment, "jecxz");
4007 assert_operand_cnt(1);
4008 last_arith_dst = NULL;
4009 delayed_flag_op = NULL;
4011 if (po->operand[0].type == OPT_REGMEM) {
4012 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
4015 ferr(po, "parse failure for jmp '%s'\n",
4016 po->operand[0].name);
4017 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
4020 else if (po->operand[0].type != OPT_LABEL)
4021 ferr(po, "unhandled jmp type\n");
4023 fprintf(fout, " goto %s;", po->operand[0].name);
4027 assert_operand_cnt(1);
4029 my_assert_not(pp, NULL);
4032 fprintf(fout, " %s = %s;\n", pp->name,
4033 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
4037 if (strstr(pp->ret_type.name, "int64")) {
4038 if (po->flags & OPF_TAIL)
4039 ferr(po, "int64 and tail?\n");
4040 fprintf(fout, "mul_tmp = ");
4042 else if (!IS(pp->ret_type.name, "void")) {
4043 if (po->flags & OPF_TAIL) {
4044 if (!IS(g_func_pp->ret_type.name, "void")) {
4045 fprintf(fout, "return ");
4046 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
4047 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
4050 else if (regmask & (1 << xAX)) {
4051 fprintf(fout, "eax = ");
4052 if (pp->ret_type.is_ptr)
4053 fprintf(fout, "(u32)");
4057 if (pp->name[0] == 0)
4058 ferr(po, "missing pp->name\n");
4059 fprintf(fout, "%s%s(", pp->name,
4060 pp->has_structarg ? "_sa" : "");
4062 for (arg = 0; arg < pp->argc; arg++) {
4064 fprintf(fout, ", ");
4067 if (pp->arg[arg].type.is_ptr)
4068 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
4070 if (pp->arg[arg].reg != NULL) {
4071 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4076 tmp_op = pp->arg[arg].datap;
4078 ferr(po, "parsed_op missing for arg%d\n", arg);
4079 if (tmp_op->argnum != 0) {
4080 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
4084 out_src_opr(buf1, sizeof(buf1),
4085 tmp_op, &tmp_op->operand[0], cast, 0));
4088 fprintf(fout, ");");
4090 if (strstr(pp->ret_type.name, "int64")) {
4091 fprintf(fout, "\n");
4092 fprintf(fout, " edx = mul_tmp >> 32;\n");
4093 fprintf(fout, " eax = mul_tmp;");
4096 if (pp->is_unresolved) {
4097 snprintf(buf3, sizeof(buf3), " unresoved %dreg",
4099 strcat(g_comment, buf3);
4102 if (po->flags & OPF_TAIL) {
4104 if (i == opcnt - 1 || pp->is_noreturn)
4106 else if (IS(pp->ret_type.name, "void"))
4108 else if (IS(g_func_pp->ret_type.name, "void"))
4110 // else already handled as 'return f()'
4113 if (!IS(g_func_pp->ret_type.name, "void")) {
4114 ferr(po, "int func -> void func tailcall?\n");
4117 fprintf(fout, "\n return;");
4118 strcat(g_comment, " ^ tailcall");
4122 strcat(g_comment, " tailcall");
4124 if (pp->is_noreturn)
4125 strcat(g_comment, " noreturn");
4126 delayed_flag_op = NULL;
4127 last_arith_dst = NULL;
4131 if (g_func_pp->is_vararg)
4132 fprintf(fout, " va_end(ap);\n");
4134 if (IS(g_func_pp->ret_type.name, "void")) {
4135 if (i != opcnt - 1 || label_pending)
4136 fprintf(fout, " return;");
4138 else if (g_func_pp->ret_type.is_ptr) {
4139 fprintf(fout, " return (%s)eax;",
4140 g_func_pp->ret_type.name);
4143 fprintf(fout, " return eax;");
4145 last_arith_dst = NULL;
4146 delayed_flag_op = NULL;
4150 if (po->argnum != 0) {
4151 // special case - saved func arg
4152 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4153 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
4156 else if (po->flags & OPF_RSAVE) {
4157 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4158 fprintf(fout, " s_%s = %s;", buf1, buf1);
4161 if (!(g_ida_func_attr & IDAFA_NORETURN))
4162 ferr(po, "stray push encountered\n");
4167 if (po->flags & OPF_RSAVE) {
4168 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4169 fprintf(fout, " %s = s_%s;", buf1, buf1);
4172 else if (po->datap != NULL) {
4175 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4176 fprintf(fout, " %s = %s;", buf1,
4177 out_src_opr(buf2, sizeof(buf2),
4178 tmp_op, &tmp_op->operand[0],
4179 po->operand[0].is_ptr ? "(void *)" : "", 0));
4182 ferr(po, "stray pop encountered\n");
4191 ferr(po, "unhandled op type %d, flags %x\n",
4196 if (g_comment[0] != 0) {
4197 char *p = g_comment;
4198 while (my_isblank(*p))
4200 fprintf(fout, " // %s", p);
4205 fprintf(fout, "\n");
4207 // some sanity checking
4208 if (po->flags & OPF_REP) {
4209 if (po->op != OP_STOS && po->op != OP_MOVS
4210 && po->op != OP_CMPS && po->op != OP_SCAS)
4211 ferr(po, "unexpected rep\n");
4212 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
4213 && (po->op == OP_CMPS || po->op == OP_SCAS))
4214 ferr(po, "cmps/scas with plain rep\n");
4216 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
4217 && po->op != OP_CMPS && po->op != OP_SCAS)
4218 ferr(po, "unexpected repz/repnz\n");
4221 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4223 // see is delayed flag stuff is still valid
4224 if (delayed_flag_op != NULL && delayed_flag_op != po) {
4225 if (is_any_opr_modified(delayed_flag_op, po, 0))
4226 delayed_flag_op = NULL;
4229 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4230 if (is_opr_modified(last_arith_dst, po))
4231 last_arith_dst = NULL;
4237 if (g_stack_fsz && !g_stack_frame_used)
4238 fprintf(fout, " (void)sf;\n");
4240 fprintf(fout, "}\n\n");
4243 for (i = 0; i < opcnt; i++) {
4244 struct label_ref *lr, *lr_del;
4246 lr = g_label_refs[i].next;
4247 while (lr != NULL) {
4252 g_label_refs[i].i = -1;
4253 g_label_refs[i].next = NULL;
4255 if (ops[i].op == OP_CALL) {
4264 static void set_label(int i, const char *name)
4270 p = strchr(name, ':');
4274 if (len > sizeof(g_labels[0]) - 1)
4275 aerr("label '%s' too long: %d\n", name, len);
4276 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4277 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4278 memcpy(g_labels[i], name, len);
4279 g_labels[i][len] = 0;
4282 // '=' needs special treatment..
4283 static char *next_word_s(char *w, size_t wsize, char *s)
4289 for (i = 0; i < wsize - 1; i++) {
4290 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4296 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4297 printf("warning: '%s' truncated\n", w);
4308 static struct chunk_item *func_chunks;
4309 static int func_chunk_cnt;
4310 static int func_chunk_alloc;
4312 static void add_func_chunk(FILE *fasm, const char *name, int line)
4314 if (func_chunk_cnt >= func_chunk_alloc) {
4315 func_chunk_alloc *= 2;
4316 func_chunks = realloc(func_chunks,
4317 func_chunk_alloc * sizeof(func_chunks[0]));
4318 my_assert_not(func_chunks, NULL);
4320 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4321 func_chunks[func_chunk_cnt].name = strdup(name);
4322 func_chunks[func_chunk_cnt].asmln = line;
4326 static int cmp_chunks(const void *p1, const void *p2)
4328 const struct chunk_item *c1 = p1, *c2 = p2;
4329 return strcmp(c1->name, c2->name);
4332 static int cmpstringp(const void *p1, const void *p2)
4334 return strcmp(*(char * const *)p1, *(char * const *)p2);
4337 static void scan_ahead(FILE *fasm)
4347 oldpos = ftell(fasm);
4350 while (fgets(line, sizeof(line), fasm))
4361 // get rid of random tabs
4362 for (i = 0; line[i] != 0; i++)
4363 if (line[i] == '\t')
4366 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4369 next_word(words[0], sizeof(words[0]), p);
4370 if (words[0][0] == 0)
4371 aerr("missing name for func chunk?\n");
4373 add_func_chunk(fasm, words[0], asmln);
4378 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4379 words[wordc][0] = 0;
4380 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4381 if (*p == 0 || *p == ';') {
4387 if (wordc == 2 && IS(words[1], "ends"))
4391 fseek(fasm, oldpos, SEEK_SET);
4395 int main(int argc, char *argv[])
4397 FILE *fout, *fasm, *frlist;
4398 struct parsed_data *pd = NULL;
4400 char **rlist = NULL;
4402 int rlist_alloc = 0;
4403 int func_chunks_used = 0;
4404 int func_chunks_sorted = 0;
4405 int func_chunk_i = -1;
4406 long func_chunk_ret = 0;
4407 int func_chunk_ret_ln = 0;
4408 int scanned_ahead = 0;
4410 char words[20][256];
4411 enum opr_lenmod lmod;
4412 char *sctproto = NULL;
4414 int pending_endp = 0;
4416 int skip_warned = 0;
4427 for (arg = 1; arg < argc; arg++) {
4428 if (IS(argv[arg], "-v"))
4430 else if (IS(argv[arg], "-rf"))
4431 g_allow_regfunc = 1;
4436 if (argc < arg + 3) {
4437 printf("usage:\n%s [-v] [-rf] <.c> <.asm> <hdrf> [rlist]*\n",
4444 asmfn = argv[arg++];
4445 fasm = fopen(asmfn, "r");
4446 my_assert_not(fasm, NULL);
4448 hdrfn = argv[arg++];
4449 g_fhdr = fopen(hdrfn, "r");
4450 my_assert_not(g_fhdr, NULL);
4453 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4454 my_assert_not(rlist, NULL);
4455 // needs special handling..
4456 rlist[rlist_len++] = "__alloca_probe";
4458 func_chunk_alloc = 32;
4459 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4460 my_assert_not(func_chunks, NULL);
4462 memset(words, 0, sizeof(words));
4464 for (; arg < argc; arg++) {
4465 frlist = fopen(argv[arg], "r");
4466 my_assert_not(frlist, NULL);
4468 while (fgets(line, sizeof(line), frlist)) {
4470 if (*p == 0 || *p == ';')
4473 if (IS_START(p, "#if 0")
4474 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4478 else if (IS_START(p, "#endif"))
4485 p = next_word(words[0], sizeof(words[0]), p);
4486 if (words[0][0] == 0)
4489 if (rlist_len >= rlist_alloc) {
4490 rlist_alloc = rlist_alloc * 2 + 64;
4491 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4492 my_assert_not(rlist, NULL);
4494 rlist[rlist_len++] = strdup(words[0]);
4503 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4505 fout = fopen(argv[arg_out], "w");
4506 my_assert_not(fout, NULL);
4509 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4510 my_assert_not(g_eqs, NULL);
4512 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4513 g_label_refs[i].i = -1;
4514 g_label_refs[i].next = NULL;
4517 while (fgets(line, sizeof(line), fasm))
4526 // get rid of random tabs
4527 for (i = 0; line[i] != 0; i++)
4528 if (line[i] == '\t')
4533 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4534 goto do_pending_endp; // eww..
4536 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4538 static const char *attrs[] = {
4547 // parse IDA's attribute-list comment
4548 g_ida_func_attr = 0;
4551 for (; *p != 0; p = sskip(p)) {
4552 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4553 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4554 g_ida_func_attr |= 1 << i;
4555 p += strlen(attrs[i]);
4559 if (i == ARRAY_SIZE(attrs)) {
4560 anote("unparsed IDA attr: %s\n", p);
4563 if (IS(attrs[i], "fpd=")) {
4564 p = next_word(words[0], sizeof(words[0]), p);
4569 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4572 next_word(words[0], sizeof(words[0]), p);
4573 if (words[0][0] == 0)
4574 aerr("missing name for func chunk?\n");
4576 if (!scanned_ahead) {
4577 add_func_chunk(fasm, words[0], asmln);
4578 func_chunks_sorted = 0;
4581 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4583 if (func_chunk_i >= 0) {
4584 if (func_chunk_i < func_chunk_cnt
4585 && IS(func_chunks[func_chunk_i].name, g_func))
4587 // move on to next chunk
4588 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4590 aerr("seek failed for '%s' chunk #%d\n",
4591 g_func, func_chunk_i);
4592 asmln = func_chunks[func_chunk_i].asmln;
4596 if (func_chunk_ret == 0)
4597 aerr("no return from chunk?\n");
4598 fseek(fasm, func_chunk_ret, SEEK_SET);
4599 asmln = func_chunk_ret_ln;
4605 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4606 func_chunks_used = 1;
4608 if (IS_START(g_func, "sub_")) {
4609 unsigned long addr = strtoul(p, NULL, 16);
4610 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4611 if (addr > f_addr && !scanned_ahead) {
4612 anote("scan_ahead caused by '%s', addr %lx\n",
4616 func_chunks_sorted = 0;
4624 for (i = wordc; i < ARRAY_SIZE(words); i++)
4626 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4627 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4628 if (*p == 0 || *p == ';') {
4633 if (*p != 0 && *p != ';')
4634 aerr("too many words\n");
4636 // alow asm patches in comments
4638 if (IS_START(p, "; sctpatch:")) {
4640 if (*p == 0 || *p == ';')
4642 goto parse_words; // lame
4644 if (IS_START(p, "; sctproto:")) {
4645 sctproto = strdup(p + 11);
4651 awarn("wordc == 0?\n");
4655 // don't care about this:
4656 if (words[0][0] == '.'
4657 || IS(words[0], "include")
4658 || IS(words[0], "assume") || IS(words[1], "segment")
4659 || IS(words[0], "align"))
4665 // do delayed endp processing to collect switch jumptables
4667 if (in_func && !skip_func && wordc >= 2
4668 && ((words[0][0] == 'd' && words[0][2] == 0)
4669 || (words[1][0] == 'd' && words[1][2] == 0)))
4672 if (words[1][0] == 'd' && words[1][2] == 0) {
4674 if (g_func_pd_cnt >= pd_alloc) {
4675 pd_alloc = pd_alloc * 2 + 16;
4676 g_func_pd = realloc(g_func_pd,
4677 sizeof(g_func_pd[0]) * pd_alloc);
4678 my_assert_not(g_func_pd, NULL);
4680 pd = &g_func_pd[g_func_pd_cnt];
4682 memset(pd, 0, sizeof(*pd));
4683 strcpy(pd->label, words[0]);
4684 pd->type = OPT_CONST;
4685 pd->lmod = lmod_from_directive(words[1]);
4691 anote("skipping alignment byte?\n");
4694 lmod = lmod_from_directive(words[0]);
4695 if (lmod != pd->lmod)
4696 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4699 if (pd->count_alloc < pd->count + wordc) {
4700 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4701 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4702 my_assert_not(pd->d, NULL);
4704 for (; i < wordc; i++) {
4705 if (IS(words[i], "offset")) {
4706 pd->type = OPT_OFFSET;
4709 p = strchr(words[i], ',');
4712 if (pd->type == OPT_OFFSET)
4713 pd->d[pd->count].u.label = strdup(words[i]);
4715 pd->d[pd->count].u.val = parse_number(words[i]);
4716 pd->d[pd->count].bt_i = -1;
4722 if (in_func && !skip_func)
4723 gen_func(fout, g_fhdr, g_func, pi);
4727 g_ida_func_attr = 0;
4731 func_chunks_used = 0;
4734 memset(&ops, 0, pi * sizeof(ops[0]));
4735 memset(g_labels, 0, pi * sizeof(g_labels[0]));
4739 for (i = 0; i < g_func_pd_cnt; i++) {
4741 if (pd->type == OPT_OFFSET) {
4742 for (j = 0; j < pd->count; j++)
4743 free(pd->d[j].u.label);
4754 if (IS(words[1], "proc")) {
4756 aerr("proc '%s' while in_func '%s'?\n",
4759 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4761 strcpy(g_func, words[0]);
4762 set_label(0, words[0]);
4767 if (IS(words[1], "endp"))
4770 aerr("endp '%s' while not in_func?\n", words[0]);
4771 if (!IS(g_func, words[0]))
4772 aerr("endp '%s' while in_func '%s'?\n",
4775 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
4776 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
4782 if (!skip_func && func_chunks_used) {
4783 // start processing chunks
4784 struct chunk_item *ci, key = { g_func, 0 };
4786 func_chunk_ret = ftell(fasm);
4787 func_chunk_ret_ln = asmln;
4788 if (!func_chunks_sorted) {
4789 qsort(func_chunks, func_chunk_cnt,
4790 sizeof(func_chunks[0]), cmp_chunks);
4791 func_chunks_sorted = 1;
4793 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4794 sizeof(func_chunks[0]), cmp_chunks);
4796 aerr("'%s' needs chunks, but none found\n", g_func);
4797 func_chunk_i = ci - func_chunks;
4798 for (; func_chunk_i > 0; func_chunk_i--)
4799 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4802 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4804 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4805 asmln = func_chunks[func_chunk_i].asmln;
4813 if (wordc == 2 && IS(words[1], "ends"))
4816 p = strchr(words[0], ':');
4818 set_label(pi, words[0]);
4822 if (!in_func || skip_func) {
4823 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4825 anote("skipping from '%s'\n", g_labels[pi]);
4828 g_labels[pi][0] = 0;
4832 if (wordc > 1 && IS(words[1], "="))
4835 aerr("unhandled equ, wc=%d\n", wordc);
4836 if (g_eqcnt >= eq_alloc) {
4838 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4839 my_assert_not(g_eqs, NULL);
4842 len = strlen(words[0]);
4843 if (len > sizeof(g_eqs[0].name) - 1)
4844 aerr("equ name too long: %d\n", len);
4845 strcpy(g_eqs[g_eqcnt].name, words[0]);
4847 if (!IS(words[3], "ptr"))
4848 aerr("unhandled equ\n");
4849 if (IS(words[2], "dword"))
4850 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4851 else if (IS(words[2], "word"))
4852 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4853 else if (IS(words[2], "byte"))
4854 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4856 aerr("bad lmod: '%s'\n", words[2]);
4858 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4863 if (pi >= ARRAY_SIZE(ops))
4864 aerr("too many ops\n");
4866 parse_op(&ops[pi], words, wordc);
4868 if (sctproto != NULL) {
4869 if (ops[pi].op == OP_CALL)
4870 ops[pi].datap = sctproto;
4883 // vim:ts=2:shiftwidth=2:expandtab