9 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
10 #define IS(w, y) !strcmp(w, y)
11 #define IS_START(w, y) !strncmp(w, y, strlen(y))
13 #include "protoparse.h"
15 static const char *asmfn;
19 #define anote(fmt, ...) \
20 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
21 #define awarn(fmt, ...) \
22 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
23 #define aerr(fmt, ...) do { \
24 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
30 OPF_RMD = (1 << 0), /* removed or optimized out */
31 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
32 OPF_FLAGS = (1 << 2), /* sets flags */
33 OPF_JMP = (1 << 3), /* branches, ret and call */
34 OPF_CC = (1 << 4), /* uses flags */
35 OPF_TAIL = (1 << 5), /* ret or tail call */
36 OPF_RSAVE = (1 << 6), /* push/pop is local reg save/load */
37 OPF_REP = (1 << 7), /* prefixed by rep */
38 OPF_REPZ = (1 << 8), /* rep is repe/repz */
39 OPF_REPNZ = (1 << 9), /* rep is repne/repnz */
40 OPF_FARG = (1 << 10), /* push collected as func arg (no reuse) */
41 OPF_EBP_S = (1 << 11), /* ebp used as scratch, not BP */
109 // must be sorted (larger len must be further in enum)
117 #define MAX_OPERANDS 3
121 enum opr_lenmod lmod;
122 unsigned int is_ptr:1; // pointer in C
123 unsigned int is_array:1; // array in C
124 unsigned int type_from_var:1; // .. in header, sometimes wrong
125 unsigned int size_mismatch:1; // type override differs from C
126 unsigned int size_lt:1; // type override is larger than C
134 struct parsed_opr operand[MAX_OPERANDS];
137 int regmask_src; // all referensed regs
139 int pfomask; // flagop: parsed_flag_op that can't be delayed
140 int argnum; // push: altered before call arg #
141 int cc_scratch; // scratch storage during analysis
142 int bt_i; // branch target for branches
143 struct parsed_data *btj;// branch targets for jumptables
148 // OP_CALL - ptr to parsed_proto
149 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
153 enum opr_lenmod lmod;
160 enum opr_lenmod lmod;
174 struct label_ref *next;
178 IDAFA_BP_FRAME = (1 << 0),
179 IDAFA_LIB_FUNC = (1 << 1),
180 IDAFA_STATIC = (1 << 2),
181 IDAFA_NORETURN = (1 << 3),
182 IDAFA_THUNK = (1 << 4),
183 IDAFA_FPD = (1 << 5),
188 static struct parsed_op ops[MAX_OPS];
189 static struct parsed_equ *g_eqs;
191 static char g_labels[MAX_OPS][32];
192 static struct label_ref g_label_refs[MAX_OPS];
193 static const struct parsed_proto *g_func_pp;
194 static struct parsed_data *g_func_pd;
195 static int g_func_pd_cnt;
196 static char g_func[256];
197 static char g_comment[256];
198 static int g_bp_frame;
199 static int g_sp_frame;
200 static int g_stack_fsz;
201 static int g_ida_func_attr;
202 #define ferr(op_, fmt, ...) do { \
203 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
204 dump_op(op_), ##__VA_ARGS__); \
208 #define fnote(op_, fmt, ...) \
209 printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
210 dump_op(op_), ##__VA_ARGS__)
214 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
215 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
216 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
217 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
219 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
221 // possible basic comparison types (without inversion)
222 enum parsed_flag_op {
226 PFO_BE, // 6 CF=1||ZF=1
230 PFO_LE, // e ZF=1||SF!=OF
233 static const char *parsed_flag_op_names[] = {
234 "o", "c", "z", "be", "s", "p", "l", "le"
237 static int char_array_i(const char *array[], size_t len, const char *s)
241 for (i = 0; i < len; i++)
248 static void printf_number(char *buf, size_t buf_size,
249 unsigned long number)
251 // output in C-friendly form
252 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
255 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
259 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
261 *reg_lmod = OPLM_DWORD;
264 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
266 *reg_lmod = OPLM_WORD;
269 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
271 *reg_lmod = OPLM_BYTE;
274 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
276 *reg_lmod = OPLM_BYTE;
283 static unsigned long parse_number(const char *number)
285 int len = strlen(number);
286 const char *p = number;
296 if (len > 1 && *p == '0')
298 if (number[len - 1] == 'h') {
299 ret = strtoul(p, &endp, 16);
300 bad = (*endp != 'h');
303 ret = strtoul(p, &endp, 10);
307 aerr("number parsing failed\n");
313 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
315 enum opr_lenmod lmod;
328 while (my_isblank(*s))
330 for (; my_issep(*s); d++, s++)
332 while (my_isblank(*s))
337 if (IS_START(s, "ds:"))
340 s = next_idt(w, sizeof(w), s);
345 reg = parse_reg(&lmod, w);
347 *regmask |= 1 << reg;
351 if ('0' <= w[0] && w[0] <= '9') {
352 number = parse_number(w);
353 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
357 // probably some label/identifier - pass
360 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
364 strcpy(name, cvtbuf);
369 static int is_reg_in_str(const char *s)
373 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
376 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
377 if (!strncmp(s, regs_r32[i], 3))
383 static const char *parse_stack_el(const char *name, char *extra_reg)
385 const char *p, *p2, *s;
392 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
394 if (extra_reg != NULL) {
395 strncpy(extra_reg, name, 3);
400 if (IS_START(p, "ebp+")) {
404 if (p2 != NULL && is_reg_in_str(p)) {
405 if (extra_reg != NULL) {
406 strncpy(extra_reg, p, p2 - p);
407 extra_reg[p2 - p] = 0;
412 if (!('0' <= *p && *p <= '9'))
418 if (!IS_START(name, "esp+"))
421 p = strchr(name + 4, '+');
423 // must be a number after esp+, already converted to 0x..
425 if (!('0' <= *s && *s <= '9')) {
426 aerr("%s nan?\n", __func__);
429 if (s[0] == '0' && s[1] == 'x')
432 if (len < sizeof(buf) - 1) {
433 strncpy(buf, s, len);
435 val = strtol(buf, &endp, 16);
436 if (val == 0 || *endp != 0) {
437 aerr("%s num parse fail for '%s'\n", __func__, buf);
446 if ('0' <= *p && *p <= '9')
452 static int guess_lmod_from_name(struct parsed_opr *opr)
454 if (!strncmp(opr->name, "dword_", 6)) {
455 opr->lmod = OPLM_DWORD;
458 if (!strncmp(opr->name, "word_", 5)) {
459 opr->lmod = OPLM_WORD;
462 if (!strncmp(opr->name, "byte_", 5)) {
463 opr->lmod = OPLM_BYTE;
469 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
470 const struct parsed_type *c_type)
472 static const char *dword_types[] = {
473 "int", "_DWORD", "UINT_PTR",
474 "DWORD", "HANDLE", "HWND", "HMODULE",
475 "WPARAM", "LPARAM", "UINT",
477 static const char *word_types[] = {
478 "uint16_t", "int16_t",
479 "unsigned __int16", "__int16",
481 static const char *byte_types[] = {
482 "uint8_t", "int8_t", "char",
483 "unsigned __int8", "__int8", "BYTE",
489 if (c_type->is_ptr) {
494 n = skip_type_mod(c_type->name);
496 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
497 if (IS(n, dword_types[i])) {
503 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
504 if (IS(n, word_types[i])) {
510 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
511 if (IS(n, byte_types[i])) {
520 static enum opr_type lmod_from_directive(const char *d)
524 else if (IS(d, "dw"))
526 else if (IS(d, "db"))
529 aerr("unhandled directive: '%s'\n", d);
533 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
539 *regmask |= 1 << reg;
542 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
545 static int parse_operand(struct parsed_opr *opr,
546 int *regmask, int *regmask_indirect,
547 char words[16][256], int wordc, int w, unsigned int op_flags)
549 const struct parsed_proto *pp;
550 enum opr_lenmod tmplmod;
551 unsigned long number;
558 aerr("parse_operand w %d, wordc %d\n", w, wordc);
562 for (i = w; i < wordc; i++) {
563 len = strlen(words[i]);
564 if (words[i][len - 1] == ',') {
565 words[i][len - 1] = 0;
571 wordc_in = wordc - w;
573 if ((op_flags & OPF_JMP) && wordc_in > 0
574 && !('0' <= words[w][0] && words[w][0] <= '9'))
576 const char *label = NULL;
578 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
579 && IS(words[w + 1], "ptr"))
580 label = words[w + 2];
581 else if (wordc_in == 2 && IS(words[w], "short"))
582 label = words[w + 1];
583 else if (wordc_in == 1
584 && strchr(words[w], '[') == NULL
585 && parse_reg(&tmplmod, words[w]) < 0)
589 opr->type = OPT_LABEL;
590 if (IS_START(label, "ds:"))
592 strcpy(opr->name, label);
598 if (IS(words[w + 1], "ptr")) {
599 if (IS(words[w], "dword"))
600 opr->lmod = OPLM_DWORD;
601 else if (IS(words[w], "word"))
602 opr->lmod = OPLM_WORD;
603 else if (IS(words[w], "byte"))
604 opr->lmod = OPLM_BYTE;
606 aerr("type parsing failed\n");
608 wordc_in = wordc - w;
613 if (IS(words[w], "offset")) {
614 opr->type = OPT_OFFSET;
615 strcpy(opr->name, words[w + 1]);
618 if (IS(words[w], "(offset")) {
619 char *p = strchr(words[w + 1], ')');
621 aerr("parse of bracketed offset failed\n");
623 opr->type = OPT_OFFSET;
624 strcpy(opr->name, words[w + 1]);
630 aerr("parse_operand 1 word expected\n");
633 if (IS_START(tmp, "ds:"))
635 strcpy(opr->name, tmp);
637 if (words[w][0] == '[') {
638 opr->type = OPT_REGMEM;
639 ret = sscanf(words[w], "[%[^]]]", opr->name);
641 aerr("[] parse failure\n");
643 parse_indmode(opr->name, regmask_indirect, 1);
644 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
646 struct parsed_equ *eq =
647 equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
649 opr->lmod = eq->lmod;
653 else if (strchr(words[w], '[')) {
655 opr->type = OPT_REGMEM;
656 if (opr->lmod == OPLM_UNSPEC)
657 guess_lmod_from_name(opr);
658 parse_indmode(strchr(words[w], '['), regmask_indirect, 0);
661 else if (('0' <= words[w][0] && words[w][0] <= '9')
662 || words[w][0] == '-')
664 number = parse_number(words[w]);
665 opr->type = OPT_CONST;
667 printf_number(opr->name, sizeof(opr->name), number);
671 ret = parse_reg(&tmplmod, opr->name);
673 setup_reg_opr(opr, ret, tmplmod, regmask);
677 // most likely var in data segment
678 opr->type = OPT_LABEL;
680 pp = proto_parse(g_fhdr, opr->name);
683 opr->lmod = OPLM_DWORD;
687 tmplmod = OPLM_UNSPEC;
688 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
689 anote("unhandled C type '%s' for '%s'\n",
690 pp->type.name, opr->name);
692 if (opr->lmod == OPLM_UNSPEC) {
694 opr->type_from_var = 1;
696 else if (opr->lmod != tmplmod) {
697 opr->size_mismatch = 1;
698 if (tmplmod < opr->lmod)
701 opr->is_ptr = pp->type.is_ptr;
703 opr->is_array = pp->type.is_array;
706 if (opr->lmod == OPLM_UNSPEC)
707 guess_lmod_from_name(opr);
711 static const struct {
716 { "repe", OPF_REP|OPF_REPZ },
717 { "repz", OPF_REP|OPF_REPZ },
718 { "repne", OPF_REP|OPF_REPNZ },
719 { "repnz", OPF_REP|OPF_REPNZ },
722 static const struct {
729 { "nop", OP_NOP, 0, 0, 0 },
730 { "push", OP_PUSH, 1, 1, 0 },
731 { "pop", OP_POP, 1, 1, OPF_DATA },
732 { "mov" , OP_MOV, 2, 2, OPF_DATA },
733 { "lea", OP_LEA, 2, 2, OPF_DATA },
734 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
735 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
736 { "not", OP_NOT, 1, 1, OPF_DATA },
737 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
738 { "stosb",OP_STOS, 0, 0, OPF_DATA },
739 { "stosw",OP_STOS, 0, 0, OPF_DATA },
740 { "stosd",OP_STOS, 0, 0, OPF_DATA },
741 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
742 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
743 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
744 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
745 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
746 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
747 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
748 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
749 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
750 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
751 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
752 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
753 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
754 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
755 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
756 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
757 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
758 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
759 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
760 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
761 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
762 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
763 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
764 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
765 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
766 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
767 { "test", OP_TEST, 2, 2, OPF_FLAGS },
768 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
769 { "retn", OP_RET, 0, 1, OPF_TAIL },
770 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
771 { "jmp", OP_JMP, 1, 1, OPF_JMP },
772 { "jo", OP_JO, 1, 1, OPF_JMP|OPF_CC }, // 70 OF=1
773 { "jno", OP_JNO, 1, 1, OPF_JMP|OPF_CC }, // 71 OF=0
774 { "jc", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72 CF=1
775 { "jb", OP_JC, 1, 1, OPF_JMP|OPF_CC }, // 72
776 { "jnc", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73 CF=0
777 { "jnb", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
778 { "jae", OP_JNC, 1, 1, OPF_JMP|OPF_CC }, // 73
779 { "jz", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74 ZF=1
780 { "je", OP_JZ, 1, 1, OPF_JMP|OPF_CC }, // 74
781 { "jnz", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75 ZF=0
782 { "jne", OP_JNZ, 1, 1, OPF_JMP|OPF_CC }, // 75
783 { "jbe", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76 CF=1 || ZF=1
784 { "jna", OP_JBE, 1, 1, OPF_JMP|OPF_CC }, // 76
785 { "ja", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77 CF=0 && ZF=0
786 { "jnbe", OP_JA, 1, 1, OPF_JMP|OPF_CC }, // 77
787 { "js", OP_JS, 1, 1, OPF_JMP|OPF_CC }, // 78 SF=1
788 { "jns", OP_JNS, 1, 1, OPF_JMP|OPF_CC }, // 79 SF=0
789 { "jp", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a PF=1
790 { "jpe", OP_JP, 1, 1, OPF_JMP|OPF_CC }, // 7a
791 { "jnp", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b PF=0
792 { "jpo", OP_JNP, 1, 1, OPF_JMP|OPF_CC }, // 7b
793 { "jl", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c SF!=OF
794 { "jnge", OP_JL, 1, 1, OPF_JMP|OPF_CC }, // 7c
795 { "jge", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d SF=OF
796 { "jnl", OP_JGE, 1, 1, OPF_JMP|OPF_CC }, // 7d
797 { "jle", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e ZF=1 || SF!=OF
798 { "jng", OP_JLE, 1, 1, OPF_JMP|OPF_CC }, // 7e
799 { "jg", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f ZF=0 && SF=OF
800 { "jnle", OP_JG, 1, 1, OPF_JMP|OPF_CC }, // 7f
801 { "seto", OP_JO, 1, 1, OPF_DATA|OPF_CC },
802 { "setno", OP_JNO, 1, 1, OPF_DATA|OPF_CC },
803 { "setc", OP_JC, 1, 1, OPF_DATA|OPF_CC },
804 { "setb", OP_JC, 1, 1, OPF_DATA|OPF_CC },
805 { "setnc", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
806 { "setae", OP_JNC, 1, 1, OPF_DATA|OPF_CC },
807 { "setz", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
808 { "sete", OP_JZ, 1, 1, OPF_DATA|OPF_CC },
809 { "setnz", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
810 { "setne", OP_JNZ, 1, 1, OPF_DATA|OPF_CC },
811 { "setbe", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
812 { "setna", OP_JBE, 1, 1, OPF_DATA|OPF_CC },
813 { "seta", OP_JA, 1, 1, OPF_DATA|OPF_CC },
814 { "setnbe", OP_JA, 1, 1, OPF_DATA|OPF_CC },
815 { "sets", OP_JS, 1, 1, OPF_DATA|OPF_CC },
816 { "setns", OP_JNS, 1, 1, OPF_DATA|OPF_CC },
817 { "setp", OP_JP, 1, 1, OPF_DATA|OPF_CC },
818 { "setpe", OP_JP, 1, 1, OPF_DATA|OPF_CC },
819 { "setnp", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
820 { "setpo", OP_JNP, 1, 1, OPF_DATA|OPF_CC },
821 { "setl", OP_JL, 1, 1, OPF_DATA|OPF_CC },
822 { "setnge", OP_JL, 1, 1, OPF_DATA|OPF_CC },
823 { "setge", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
824 { "setnl", OP_JGE, 1, 1, OPF_DATA|OPF_CC },
825 { "setle", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
826 { "setng", OP_JLE, 1, 1, OPF_DATA|OPF_CC },
827 { "setg", OP_JG, 1, 1, OPF_DATA|OPF_CC },
828 { "setnle", OP_JG, 1, 1, OPF_DATA|OPF_CC },
831 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
833 enum opr_lenmod lmod = OPLM_UNSPEC;
834 int prefix_flags = 0;
842 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
843 if (IS(words[w], pref_table[i].name)) {
844 prefix_flags = pref_table[i].flags;
851 aerr("lone prefix: '%s'\n", words[0]);
856 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
857 if (IS(words[w], op_table[i].name))
861 if (i == ARRAY_SIZE(op_table))
862 aerr("unhandled op: '%s'\n", words[0]);
865 op->op = op_table[i].op;
866 op->flags = op_table[i].flags | prefix_flags;
867 op->regmask_src = op->regmask_dst = 0;
869 for (opr = 0; opr < op_table[i].minopr; opr++) {
870 regmask = regmask_ind = 0;
871 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
872 words, wordc, w, op->flags);
874 if (opr == 0 && (op->flags & OPF_DATA))
875 op->regmask_dst = regmask;
876 // for now, mark dst as src too
877 op->regmask_src |= regmask | regmask_ind;
880 for (; w < wordc && opr < op_table[i].maxopr; opr++) {
881 w = parse_operand(&op->operand[opr],
882 &op->regmask_src, &op->regmask_src,
883 words, wordc, w, op->flags);
887 aerr("parse_op %s incomplete: %d/%d\n",
891 op->operand_cnt = opr;
892 if (!strncmp(op_table[i].name, "set", 3))
893 op->operand[0].lmod = OPLM_BYTE;
895 // ops with implicit argumets
899 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
900 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
904 if (op->operand_cnt != 0)
906 if (IS(words[op_w], "stosb"))
908 else if (IS(words[op_w], "stosw"))
910 else if (IS(words[op_w], "stosd"))
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;
937 if (op->operand_cnt != 1)
942 op->regmask_dst = (1 << xDX) | (1 << xAX);
943 op->regmask_src |= (1 << xAX);
944 if (op->operand[0].lmod == OPLM_UNSPEC)
945 op->operand[0].lmod = OPLM_DWORD;
950 // we could set up operands for edx:eax, but there is no real need to
951 // (see is_opr_modified())
952 regmask = (1 << xDX) | (1 << xAX);
953 op->regmask_dst = regmask;
954 op->regmask_src |= regmask;
955 if (op->operand[0].lmod == OPLM_UNSPEC)
956 op->operand[0].lmod = OPLM_DWORD;
964 if (op->operand[1].lmod == OPLM_UNSPEC)
965 op->operand[1].lmod = OPLM_BYTE;
969 if (op->operand[0].lmod == OPLM_UNSPEC
970 && (op->operand[0].type == OPT_CONST
971 || op->operand[0].type == OPT_OFFSET
972 || op->operand[0].type == OPT_LABEL))
973 op->operand[0].lmod = OPLM_DWORD;
978 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
979 && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
981 op->flags |= OPF_RMD;
986 if (op->operand[0].type == OPT_REG
987 && op->operand[1].type == OPT_REGMEM)
990 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
991 if (IS(buf, op->operand[1].name))
992 op->flags |= OPF_RMD;
1001 static const char *op_name(enum op_op op)
1005 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1006 if (op_table[i].op == op)
1007 return op_table[i].name;
1013 static const char *dump_op(struct parsed_op *po)
1015 static char out[128];
1022 snprintf(out, sizeof(out), "%s", op_name(po->op));
1023 for (i = 0; i < po->operand_cnt; i++) {
1027 snprintf(p, sizeof(out) - (p - out),
1028 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1029 po->operand[i].name);
1035 static const char *lmod_type_u(struct parsed_op *po,
1036 enum opr_lenmod lmod)
1046 ferr(po, "invalid lmod: %d\n", lmod);
1047 return "(_invalid_)";
1051 static const char *lmod_cast_u(struct parsed_op *po,
1052 enum opr_lenmod lmod)
1062 ferr(po, "invalid lmod: %d\n", lmod);
1063 return "(_invalid_)";
1067 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1068 enum opr_lenmod lmod)
1078 ferr(po, "invalid lmod: %d\n", lmod);
1079 return "(_invalid_)";
1083 static const char *lmod_cast_s(struct parsed_op *po,
1084 enum opr_lenmod lmod)
1094 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1095 return "(_invalid_)";
1099 static const char *lmod_cast(struct parsed_op *po,
1100 enum opr_lenmod lmod, int is_signed)
1103 lmod_cast_s(po, lmod) :
1104 lmod_cast_u(po, lmod);
1107 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1117 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1122 static const char *opr_name(struct parsed_op *po, int opr_num)
1124 if (opr_num >= po->operand_cnt)
1125 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1126 return po->operand[opr_num].name;
1129 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1131 if (opr_num >= po->operand_cnt)
1132 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1133 if (po->operand[opr_num].type != OPT_CONST)
1134 ferr(po, "opr %d: const expected\n", opr_num);
1135 return po->operand[opr_num].val;
1138 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1140 if ((unsigned int)popr->reg >= MAX_REGS)
1141 ferr(po, "invalid reg: %d\n", popr->reg);
1142 return regs_r32[popr->reg];
1145 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1154 namelen = strlen(name);
1156 p = strchr(name, '+');
1160 ferr(po, "equ parse failed for '%s'\n", name);
1162 if (IS_START(p, "0x"))
1164 *extra_offs = strtol(p, &endp, 16);
1166 ferr(po, "equ parse failed for '%s'\n", name);
1169 for (i = 0; i < g_eqcnt; i++)
1170 if (strncmp(g_eqs[i].name, name, namelen) == 0
1171 && g_eqs[i].name[namelen] == 0)
1175 ferr(po, "unresolved equ name: '%s'\n", name);
1182 static void stack_frame_access(struct parsed_op *po,
1183 struct parsed_opr *popr, char *buf, size_t buf_size,
1184 const char *name, const char *cast, int is_src, int is_lea)
1186 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1187 const char *prefix = "";
1188 const char *bp_arg = NULL;
1189 char ofs_reg[16] = { 0, };
1190 struct parsed_equ *eq;
1193 int i, arg_i, arg_s;
1200 if (po->flags & OPF_EBP_S)
1201 ferr(po, "stack_frame_access while ebp is scratch\n");
1203 if (IS_START(name, "ebp-")
1204 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1207 if (IS_START(p, "0x"))
1209 offset = strtoul(p, &endp, 16);
1213 ferr(po, "ebp- parse of '%s' failed\n", name);
1216 bp_arg = parse_stack_el(name, ofs_reg);
1217 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1218 eq = equ_find(po, bp_arg, &offset);
1220 ferr(po, "detected but missing eq\n");
1221 offset += eq->offset;
1224 if (!strncmp(name, "ebp", 3))
1227 if (stack_ra <= offset && offset < stack_ra + 4)
1228 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1230 if (offset > stack_ra)
1232 arg_i = (offset - stack_ra - 4) / 4;
1233 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1235 if (g_func_pp->is_vararg
1236 && arg_i == g_func_pp->argc_stack && is_lea)
1238 // should be va_list
1241 snprintf(buf, buf_size, "%sap", cast);
1244 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1245 offset, bp_arg, arg_i);
1247 if (ofs_reg[0] != 0)
1248 ferr(po, "offset reg on arg access?\n");
1250 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1251 if (g_func_pp->arg[i].reg != NULL)
1257 if (i == g_func_pp->argc)
1258 ferr(po, "arg %d not in prototype?\n", arg_i);
1260 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1266 ferr(po, "lea/byte to arg?\n");
1267 if (is_src && (offset & 3) == 0)
1268 snprintf(buf, buf_size, "(u8)a%d", i + 1);
1270 snprintf(buf, buf_size, "BYTE%d(a%d)", offset & 3, i + 1);
1275 ferr(po, "lea/word to arg?\n");
1280 ferr(po, "problematic arg store\n");
1281 snprintf(buf, buf_size, "*(u16 *)((char *)&a%d + 1)", i + 1);
1284 ferr(po, "unaligned arg word load\n");
1286 else if (is_src && (offset & 2) == 0)
1287 snprintf(buf, buf_size, "(u16)a%d", i + 1);
1289 snprintf(buf, buf_size, "%sWORD(a%d)",
1290 (offset & 2) ? "HI" : "LO", i + 1);
1302 snprintf(buf, buf_size, "(u32)&a%d + %d",
1305 ferr(po, "unaligned arg store\n");
1307 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1308 snprintf(buf, buf_size, "%s(a%d >> %d)",
1309 prefix, i + 1, (offset & 3) * 8);
1313 snprintf(buf, buf_size, "%s%sa%d",
1314 prefix, is_lea ? "&" : "", i + 1);
1319 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1323 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1326 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1327 if (unaligned && tmp_lmod != OPLM_DWORD)
1328 ferr(po, "bp_arg arg/w offset %d and type '%s'\n",
1329 offset, g_func_pp->arg[i].type.name);
1333 if (g_stack_fsz == 0)
1334 ferr(po, "stack var access without stackframe\n");
1336 sf_ofs = g_stack_fsz + offset;
1337 lim = (ofs_reg[0] != 0) ? -4 : 0;
1338 if (offset > 0 || sf_ofs < lim)
1339 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1349 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1350 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1354 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1355 // known unaligned or possibly unaligned
1356 strcat(g_comment, " unaligned");
1358 prefix = "*(u16 *)&";
1359 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1360 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1363 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1367 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1368 // known unaligned or possibly unaligned
1369 strcat(g_comment, " unaligned");
1371 prefix = "*(u32 *)&";
1372 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1373 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1376 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1380 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1385 static void check_label_read_ref(struct parsed_op *po, const char *name)
1387 const struct parsed_proto *pp;
1389 pp = proto_parse(g_fhdr, name);
1391 ferr(po, "proto_parse failed for ref '%s'\n", name);
1393 // currently we can take __cdecl and __stdcall
1394 if (pp->is_func && pp->argc_reg != 0)
1395 ferr(po, "reg-arg func reference?\n");
1398 static char *out_src_opr(char *buf, size_t buf_size,
1399 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1402 char tmp1[256], tmp2[256];
1409 switch (popr->type) {
1412 ferr(po, "lea from reg?\n");
1414 switch (popr->lmod) {
1416 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1419 snprintf(buf, buf_size, "(u16)%s", opr_reg_p(po, popr));
1422 if (popr->name[1] == 'h') // XXX..
1423 snprintf(buf, buf_size, "(u8)(%s >> 8)", opr_reg_p(po, popr));
1425 snprintf(buf, buf_size, "(u8)%s", opr_reg_p(po, popr));
1428 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1433 if (parse_stack_el(popr->name, NULL)
1434 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1435 && IS_START(popr->name, "ebp")))
1437 stack_frame_access(po, popr, buf, buf_size,
1438 popr->name, cast, 1, is_lea);
1442 strcpy(expr, popr->name);
1443 if (strchr(expr, '[')) {
1444 // special case: '[' can only be left for label[reg] form
1445 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1447 ferr(po, "parse failure for '%s'\n", expr);
1448 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1451 // XXX: do we need more parsing?
1453 snprintf(buf, buf_size, "%s", expr);
1458 cast = lmod_cast_u_ptr(po, popr->lmod);
1459 snprintf(buf, buf_size, "%s(%s)", cast, expr);
1463 check_label_read_ref(po, popr->name);
1464 if (cast[0] == 0 && popr->is_ptr)
1468 snprintf(buf, buf_size, "(u32)&%s", popr->name);
1469 else if (popr->size_lt)
1470 snprintf(buf, buf_size, "%s%s%s%s", cast,
1471 lmod_cast_u_ptr(po, popr->lmod),
1472 popr->is_array ? "" : "&",
1475 snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1476 popr->is_array ? "[0]" : "");
1480 check_label_read_ref(po, popr->name);
1484 ferr(po, "lea an offset?\n");
1485 snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1490 ferr(po, "lea from const?\n");
1492 snprintf(buf, buf_size, "%s", cast);
1494 printf_number(buf + ret, buf_size - ret, popr->val);
1498 ferr(po, "invalid src type: %d\n", popr->type);
1504 // note: may set is_ptr (we find that out late for ebp frame..)
1505 static char *out_dst_opr(char *buf, size_t buf_size,
1506 struct parsed_op *po, struct parsed_opr *popr)
1508 switch (popr->type) {
1510 switch (popr->lmod) {
1512 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1516 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1520 if (popr->name[1] == 'h') // XXX..
1521 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1523 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1526 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1531 if (parse_stack_el(popr->name, NULL)
1532 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1533 && IS_START(popr->name, "ebp")))
1535 stack_frame_access(po, popr, buf, buf_size,
1536 popr->name, "", 0, 0);
1540 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1543 if (popr->size_mismatch)
1544 snprintf(buf, buf_size, "%s%s%s",
1545 lmod_cast_u_ptr(po, popr->lmod),
1546 popr->is_array ? "" : "&", popr->name);
1548 snprintf(buf, buf_size, "%s%s", popr->name,
1549 popr->is_array ? "[0]" : "");
1553 ferr(po, "invalid dst type: %d\n", popr->type);
1559 static char *out_src_opr_u32(char *buf, size_t buf_size,
1560 struct parsed_op *po, struct parsed_opr *popr)
1562 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1565 static enum parsed_flag_op split_cond(struct parsed_op *po,
1566 enum op_op op, int *is_inv)
1618 ferr(po, "split_cond: bad op %d\n", op);
1623 static void out_test_for_cc(char *buf, size_t buf_size,
1624 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1625 enum opr_lenmod lmod, const char *expr)
1627 const char *cast, *scast;
1629 cast = lmod_cast_u(po, lmod);
1630 scast = lmod_cast_s(po, lmod);
1634 case PFO_BE: // CF=1||ZF=1; CF=0
1635 snprintf(buf, buf_size, "(%s%s %s 0)",
1636 cast, expr, is_inv ? "!=" : "==");
1640 case PFO_L: // SF!=OF; OF=0
1641 snprintf(buf, buf_size, "(%s%s %s 0)",
1642 scast, expr, is_inv ? ">=" : "<");
1645 case PFO_LE: // ZF=1||SF!=OF; OF=0
1646 snprintf(buf, buf_size, "(%s%s %s 0)",
1647 scast, expr, is_inv ? ">" : "<=");
1651 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1655 static void out_cmp_for_cc(char *buf, size_t buf_size,
1656 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1657 enum opr_lenmod lmod, const char *expr1, const char *expr2)
1659 const char *cast, *scast;
1661 cast = lmod_cast_u(po, lmod);
1662 scast = lmod_cast_s(po, lmod);
1666 // note: must be unsigned compare
1667 snprintf(buf, buf_size, "(%s%s %s %s%s)",
1668 cast, expr1, is_inv ? ">=" : "<", cast, expr2);
1672 snprintf(buf, buf_size, "(%s%s %s %s%s)",
1673 cast, expr1, is_inv ? "!=" : "==", cast, expr2);
1677 // note: must be unsigned compare
1678 snprintf(buf, buf_size, "(%s%s %s %s%s)",
1679 cast, expr1, is_inv ? ">" : "<=", cast, expr2);
1682 // note: must be signed compare
1684 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1685 scast, expr1, expr2, is_inv ? ">=" : "<");
1689 snprintf(buf, buf_size, "(%s%s %s %s%s)",
1690 scast, expr1, is_inv ? ">=" : "<", scast, expr2);
1694 snprintf(buf, buf_size, "(%s%s %s %s%s)",
1695 scast, expr1, is_inv ? ">" : "<=", scast, expr2);
1699 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1703 static void out_cmp_test(char *buf, size_t buf_size,
1704 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1706 char buf1[256], buf2[256], buf3[256];
1708 if (po->op == OP_TEST) {
1709 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1710 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1713 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1714 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1715 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1717 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1718 po->operand[0].lmod, buf3);
1720 else if (po->op == OP_CMP) {
1721 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
1722 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[1]);
1723 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv,
1724 po->operand[0].lmod, buf2, buf3);
1727 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1730 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1731 struct parsed_opr *popr2)
1733 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1734 ferr(po, "missing lmod for both operands\n");
1736 if (popr1->lmod == OPLM_UNSPEC)
1737 popr1->lmod = popr2->lmod;
1738 else if (popr2->lmod == OPLM_UNSPEC)
1739 popr2->lmod = popr1->lmod;
1740 else if (popr1->lmod != popr2->lmod) {
1741 if (popr1->type_from_var) {
1742 popr1->size_mismatch = 1;
1743 if (popr1->lmod < popr2->lmod)
1745 popr1->lmod = popr2->lmod;
1747 else if (popr2->type_from_var) {
1748 popr2->size_mismatch = 1;
1749 if (popr2->lmod < popr1->lmod)
1751 popr2->lmod = popr1->lmod;
1754 ferr(po, "conflicting lmods: %d vs %d\n",
1755 popr1->lmod, popr2->lmod);
1759 static const char *op_to_c(struct parsed_op *po)
1783 ferr(po, "op_to_c was supplied with %d\n", po->op);
1787 static void set_flag_no_dup(struct parsed_op *po, enum op_flags flag,
1788 enum op_flags flag_check)
1790 if (po->flags & flag)
1791 ferr(po, "flag %x already set\n", flag);
1792 if (po->flags & flag_check)
1793 ferr(po, "flag_check %x already set\n", flag_check);
1798 // last op in stream - unconditional branch or ret
1799 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1800 || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1802 static int scan_for_pop(int i, int opcnt, const char *reg,
1803 int magic, int depth, int *maxdepth, int do_flags)
1805 struct parsed_op *po;
1809 for (; i < opcnt; i++) {
1811 if (po->cc_scratch == magic)
1812 break; // already checked
1813 po->cc_scratch = magic;
1815 if (po->flags & OPF_TAIL)
1816 return -1; // deadend
1818 if ((po->flags & OPF_RMD)
1819 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1822 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1823 if (po->btj != NULL) {
1825 for (j = 0; j < po->btj->count - 1; j++) {
1826 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1827 depth, maxdepth, do_flags);
1829 return ret; // dead end
1831 // follow last jumptable entry
1832 i = po->btj->d[j].bt_i - 1;
1837 ferr(po, "dead branch\n");
1841 if (po->flags & OPF_CC) {
1842 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1843 depth, maxdepth, do_flags);
1845 return ret; // dead end
1853 if ((po->op == OP_POP || po->op == OP_PUSH)
1854 && po->operand[0].type == OPT_REG
1855 && IS(po->operand[0].name, reg))
1857 if (po->op == OP_PUSH) {
1859 if (depth > *maxdepth)
1862 set_flag_no_dup(po, OPF_RSAVE, OPF_RMD);
1864 else if (depth == 0) {
1866 set_flag_no_dup(po, OPF_RMD, OPF_RSAVE);
1871 if (depth < 0) // should not happen
1872 ferr(po, "fail with depth\n");
1874 set_flag_no_dup(po, OPF_RSAVE, OPF_RMD);
1882 // scan for pop starting from 'ret' op (all paths)
1883 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
1889 for (; i < opcnt; i++) {
1890 if (!(ops[i].flags & OPF_TAIL))
1893 for (j = i - 1; j >= 0; j--) {
1894 if (ops[j].flags & OPF_RMD)
1896 if (ops[j].flags & OPF_JMP)
1899 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
1900 && IS(ops[j].operand[0].name, reg))
1903 ops[j].flags |= flag_set;
1907 if (g_labels[j][0] != 0)
1912 return found ? 0 : -1;
1915 // is operand 'opr modified' by parsed_op 'po'?
1916 static int is_opr_modified(const struct parsed_opr *opr,
1917 const struct parsed_op *po)
1919 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
1922 if (opr->type == OPT_REG && po->operand[0].type == OPT_REG) {
1923 if (po->regmask_dst & (1 << opr->reg))
1929 return IS(po->operand[0].name, opr->name);
1932 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
1933 static int is_any_opr_modified(const struct parsed_op *po_test,
1934 const struct parsed_op *po)
1938 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
1941 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
1944 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
1947 // in reality, it can wreck any register, but in decompiled C
1948 // version it can only overwrite eax or edx:eax
1949 if (po->op == OP_CALL
1950 && ((po_test->regmask_src | po_test->regmask_dst)
1951 & ((1 << xAX)|(1 << xDX))))
1954 for (i = 0; i < po_test->operand_cnt; i++)
1955 if (IS(po_test->operand[i].name, po->operand[0].name))
1961 // scan for any po_test operand modification in range given
1962 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt)
1964 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
1967 for (; i < opcnt; i++) {
1968 if (is_any_opr_modified(po_test, &ops[i]))
1975 // scan for po_test operand[0] modification in range given
1976 static int scan_for_mod_opr0(struct parsed_op *po_test,
1979 for (; i < opcnt; i++) {
1980 if (is_opr_modified(&po_test->operand[0], &ops[i]))
1987 static int scan_for_flag_set(int i, int magic, int *branched,
1988 int *setters, int *setter_cnt)
1990 struct label_ref *lr;
1994 if (ops[i].cc_scratch == magic) {
1995 ferr(&ops[i], "%s looped\n", __func__);
1998 ops[i].cc_scratch = magic;
2000 if (g_labels[i][0] != 0) {
2003 lr = &g_label_refs[i];
2004 for (; lr->next; lr = lr->next) {
2005 ret = scan_for_flag_set(lr->i, magic,
2006 branched, setters, setter_cnt);
2011 if (i > 0 && LAST_OP(i - 1)) {
2012 i = g_label_refs[i].i;
2015 ret = scan_for_flag_set(lr->i, magic,
2016 branched, setters, setter_cnt);
2022 if (ops[i].flags & OPF_FLAGS) {
2023 setters[*setter_cnt] = i;
2028 if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2035 // scan back for cdq, if anything modifies edx, fail
2036 static int scan_for_cdq_edx(int i)
2039 if (g_labels[i][0] != 0) {
2040 if (g_label_refs[i].next != NULL)
2042 if (i > 0 && LAST_OP(i - 1)) {
2043 i = g_label_refs[i].i;
2050 if (ops[i].op == OP_CDQ)
2053 if (ops[i].regmask_dst & (1 << xDX))
2055 if (g_labels[i][0] != 0)
2062 static int scan_for_reg_clear(int i, int reg)
2065 if (g_labels[i][0] != 0) {
2066 if (g_label_refs[i].next != NULL)
2068 if (i > 0 && LAST_OP(i - 1)) {
2069 i = g_label_refs[i].i;
2076 if (ops[i].op == OP_XOR
2077 && ops[i].operand[0].lmod == OPLM_DWORD
2078 && ops[i].operand[0].reg == ops[i].operand[1].reg
2079 && ops[i].operand[0].reg == reg)
2082 if (ops[i].regmask_dst & (1 << reg))
2084 if (g_labels[i][0] != 0)
2091 // scan for positive, constant esp adjust
2092 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2094 struct parsed_op *po;
2097 for (; i < opcnt; i++) {
2100 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2101 if (po->operand[1].type != OPT_CONST)
2102 ferr(&ops[i], "non-const esp adjust?\n");
2103 *adj += po->operand[1].val;
2105 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2108 else if (po->op == OP_PUSH)
2109 *adj -= lmod_bytes(po, po->operand[0].lmod);
2110 else if (po->op == OP_POP)
2111 *adj += lmod_bytes(po, po->operand[0].lmod);
2112 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2113 if (po->op != OP_CALL)
2115 if (po->operand[0].type != OPT_LABEL)
2117 // TODO: should only allow combining __cdecl calls..
2120 if (g_labels[i][0] != 0)
2127 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2129 struct parsed_op *po;
2133 ferr(ops, "%s: followed bad branch?\n", __func__);
2135 for (; i < opcnt; i++) {
2137 if (po->cc_scratch == magic)
2139 po->cc_scratch = magic;
2142 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2143 if (po->btj != NULL) {
2145 for (j = 0; j < po->btj->count; j++)
2146 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2150 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2151 if (!(po->flags & OPF_CC))
2154 if (po->flags & OPF_TAIL)
2159 static int collect_call_args(struct parsed_op *po, int i,
2160 struct parsed_proto *pp, int *save_arg_vars, int arg,
2161 int magic, int need_op_saving, int may_reuse)
2163 struct parsed_proto *pp_tmp;
2164 struct label_ref *lr;
2165 int need_to_save_current;
2170 ferr(po, "no refs for '%s'?\n", g_labels[i]);
2174 for (; arg < pp->argc; arg++)
2175 if (pp->arg[arg].reg == NULL)
2177 magic = (magic & 0xffffff) | (arg << 24);
2179 for (j = i; j >= 0 && arg < pp->argc; )
2181 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2182 if (ops[j].cc_scratch != magic) {
2183 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2187 // ok: have already been here
2190 ops[j].cc_scratch = magic;
2192 if (g_labels[j][0] != 0) {
2193 lr = &g_label_refs[j];
2194 if (lr->next != NULL)
2196 for (; lr->next; lr = lr->next) {
2197 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2199 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2200 arg, magic, need_op_saving, may_reuse);
2205 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2207 if (j > 0 && LAST_OP(j - 1)) {
2208 // follow last branch in reverse
2213 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2214 arg, magic, need_op_saving, may_reuse);
2220 if (ops[j].op == OP_CALL)
2222 pp_tmp = ops[j].datap;
2224 ferr(po, "arg collect hit unparsed call\n");
2225 if (may_reuse && pp_tmp->argc_stack > 0)
2226 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2227 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2229 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2230 ferr(po, "arg collect %d/%d hit esp adjust\n",
2233 else if (ops[j].op == OP_POP) {
2234 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2236 else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2240 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2242 pp->arg[arg].datap = &ops[j];
2243 need_to_save_current = 0;
2244 if (!need_op_saving) {
2245 ret = scan_for_mod(&ops[j], j + 1, i);
2246 need_to_save_current = (ret >= 0);
2248 if (need_op_saving || need_to_save_current) {
2249 // mark this push as one that needs operand saving
2250 ops[j].flags &= ~OPF_RMD;
2251 if (ops[j].argnum == 0) {
2252 ops[j].argnum = arg + 1;
2253 *save_arg_vars |= 1 << arg;
2255 else if (ops[j].argnum < arg + 1)
2256 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2257 ops[j].argnum, arg + 1, pp->name);
2259 else if (ops[j].argnum == 0)
2260 ops[j].flags |= OPF_RMD;
2262 // some PUSHes are reused by different calls on other branches,
2263 // but that can't happen if we didn't branch, so they
2264 // can be removed from future searches (handles nested calls)
2266 ops[j].flags |= OPF_FARG;
2269 for (arg++; arg < pp->argc; arg++)
2270 if (pp->arg[arg].reg == NULL)
2272 magic = (magic & 0xffffff) | (arg << 24);
2276 if (arg < pp->argc) {
2277 ferr(po, "arg collect failed for '%s': %d/%d\n",
2278 pp->name, arg, pp->argc);
2284 static void add_label_ref(struct label_ref *lr, int op_i)
2286 struct label_ref *lr_new;
2293 lr_new = calloc(1, sizeof(*lr_new));
2295 lr_new->next = lr->next;
2299 static void output_std_flags(FILE *fout, struct parsed_op *po,
2300 int *pfomask, const char *dst_opr_text)
2302 if (*pfomask & (1 << PFO_Z)) {
2303 fprintf(fout, "\n cond_z = (%s%s == 0);",
2304 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2305 *pfomask &= ~(1 << PFO_Z);
2307 if (*pfomask & (1 << PFO_S)) {
2308 fprintf(fout, "\n cond_s = (%s%s < 0);",
2309 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2310 *pfomask &= ~(1 << PFO_S);
2314 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2316 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2317 struct parsed_opr *last_arith_dst = NULL;
2318 char buf1[256], buf2[256], buf3[256], cast[64];
2319 const struct parsed_proto *pp_c;
2320 struct parsed_proto *pp, *pp_tmp;
2321 struct parsed_data *pd;
2322 const char *tmpname;
2323 enum parsed_flag_op pfo;
2324 int save_arg_vars = 0;
2325 int cmp_result_vars = 0;
2326 int need_mul_var = 0;
2327 int have_func_ret = 0;
2329 int label_pending = 0;
2330 int regmask_save = 0;
2331 int regmask_arg = 0;
2332 int regmask_now = 0;
2344 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2346 g_func_pp = proto_parse(fhdr, funcn);
2347 if (g_func_pp == NULL)
2348 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2350 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2351 if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2352 fprintf(fout, "__stdcall ");
2353 if (g_ida_func_attr & IDAFA_NORETURN)
2354 fprintf(fout, "noreturn ");
2355 fprintf(fout, "%s(", funcn);
2357 for (i = 0; i < g_func_pp->argc; i++) {
2359 fprintf(fout, ", ");
2360 if (g_func_pp->arg[i].fptr != NULL) {
2362 pp = g_func_pp->arg[i].fptr;
2363 fprintf(fout, "%s (", pp->ret_type.name);
2364 if (pp->is_stdcall && pp->argc_reg == 0)
2365 fprintf(fout, "__stdcall ");
2366 fprintf(fout, "*a%d)(", i + 1);
2367 for (j = 0; j < pp->argc; j++) {
2369 fprintf(fout, ", ");
2370 if (pp->arg[j].fptr)
2371 ferr(ops, "nested fptr\n");
2372 fprintf(fout, "%s", pp->arg[j].type.name);
2377 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2380 if (g_func_pp->is_vararg) {
2382 fprintf(fout, ", ");
2383 fprintf(fout, "...");
2386 fprintf(fout, ")\n{\n");
2389 // - handle ebp/esp frame, remove ops related to it
2390 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2391 && ops[1].op == OP_MOV
2392 && IS(opr_name(&ops[1], 0), "ebp")
2393 && IS(opr_name(&ops[1], 1), "esp"))
2398 ops[0].flags |= OPF_RMD;
2399 ops[1].flags |= OPF_RMD;
2402 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2403 g_stack_fsz = opr_const(&ops[2], 1);
2404 ops[2].flags |= OPF_RMD;
2408 // another way msvc builds stack frame..
2410 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2412 ops[i].flags |= OPF_RMD;
2416 // and another way..
2417 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2418 && ops[i].operand[1].type == OPT_CONST
2419 && ops[i + 1].op == OP_CALL
2420 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2422 g_stack_fsz += ops[i].operand[1].val;
2423 ops[i].flags |= OPF_RMD;
2425 ops[i].flags |= OPF_RMD;
2432 for (; i < opcnt; i++)
2433 if (ops[i].op == OP_RET)
2435 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2438 if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2439 ops[i - 1].flags |= OPF_RMD;
2440 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2441 ferr(&ops[i - 1], "'pop ebp' expected\n");
2443 if (g_stack_fsz != 0) {
2444 if (ops[i - 2].op == OP_MOV
2445 && IS(opr_name(&ops[i - 2], 0), "esp")
2446 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2448 ops[i - 2].flags |= OPF_RMD;
2450 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2451 ferr(&ops[i - 2], "esp restore expected\n");
2453 if (ecx_push && ops[i - 3].op == OP_POP
2454 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2456 ferr(&ops[i - 3], "unexpected ecx pop\n");
2462 } while (i < opcnt);
2465 for (i = 0; i < opcnt; i++) {
2466 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2468 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2469 && ops[i].operand[1].type == OPT_CONST)
2478 g_stack_fsz = ops[i].operand[1].val;
2479 ops[i].flags |= OPF_RMD;
2483 for (; i < opcnt; i++)
2484 if (ops[i].op == OP_RET)
2486 if (ops[i - 1].op != OP_ADD
2487 || !IS(opr_name(&ops[i - 1], 0), "esp")
2488 || ops[i - 1].operand[1].type != OPT_CONST
2489 || ops[i - 1].operand[1].val != g_stack_fsz)
2490 ferr(&ops[i - 1], "'add esp' expected\n");
2491 ops[i - 1].flags |= OPF_RMD;
2494 } while (i < opcnt);
2499 // - resolve all branches
2500 for (i = 0; i < opcnt; i++)
2506 if ((po->flags & OPF_RMD) || !(po->flags & OPF_JMP)
2507 || po->op == OP_CALL || po->op == OP_RET)
2510 if (po->operand[0].type == OPT_REGMEM) {
2511 char *p = strchr(po->operand[0].name, '[');
2513 ferr(po, "unhandled indirect branch\n");
2514 ret = p - po->operand[0].name;
2515 strncpy(buf1, po->operand[0].name, ret);
2518 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2519 if (IS(g_func_pd[j].label, buf1)) {
2525 //ferr(po, "label '%s' not parsed?\n", buf1);
2527 if (pd->type != OPT_OFFSET)
2528 ferr(po, "label '%s' with non-offset data?\n", buf1);
2530 // find all labels, link
2531 for (j = 0; j < pd->count; j++) {
2532 for (l = 0; l < opcnt; l++) {
2533 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2534 add_label_ref(&g_label_refs[l], i);
2545 for (l = 0; l < opcnt; l++) {
2546 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2547 add_label_ref(&g_label_refs[l], i);
2556 if (po->operand[0].type == OPT_LABEL)
2560 ferr(po, "unhandled branch\n");
2564 po->flags |= OPF_TAIL;
2569 for (i = 0; i < opcnt; i++)
2572 if (po->flags & OPF_RMD)
2575 if (po->op == OP_CALL)
2577 pp = calloc(1, sizeof(*pp));
2578 my_assert_not(pp, NULL);
2579 tmpname = opr_name(po, 0);
2580 if (po->operand[0].type != OPT_LABEL)
2582 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2584 ferr(po, "non-__cdecl indirect call unhandled yet\n");
2586 if (j > ARRAY_SIZE(pp->arg))
2587 ferr(po, "esp adjust too large?\n");
2588 pp->ret_type.name = strdup("int");
2589 pp->argc = pp->argc_stack = j;
2590 for (arg = 0; arg < pp->argc; arg++)
2591 pp->arg[arg].type.name = strdup("int");
2594 pp_c = proto_parse(fhdr, tmpname);
2596 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2597 if (pp_c->is_fptr && pp_c->argc_reg != 0)
2598 ferr(po, "fptr call with reg arg\n");
2599 pp = proto_clone(pp_c);
2602 // look for and make use of esp adjust
2604 if (!pp->is_stdcall && pp->argc_stack > 0)
2605 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2607 if (pp->is_vararg) {
2608 if (j / 4 < pp->argc_stack)
2609 ferr(po, "esp adjust is too small: %x < %x\n",
2610 j, pp->argc_stack * 4);
2611 // modify pp to make it have varargs as normal args
2613 pp->argc += j / 4 - pp->argc_stack;
2614 for (; arg < pp->argc; arg++) {
2615 pp->arg[arg].type.name = strdup("int");
2618 if (pp->argc > ARRAY_SIZE(pp->arg))
2619 ferr(po, "too many args for '%s'\n", tmpname);
2621 if (pp->argc_stack != j / 4)
2622 ferr(po, "stack tracking failed for '%s': %x %x\n",
2623 tmpname, pp->argc_stack * 4, j);
2625 ops[ret].flags |= OPF_RMD;
2626 // a bit of a hack, but deals with use of
2627 // single adj for multiple calls
2628 ops[ret].operand[1].val -= j;
2630 else if (pp->is_vararg)
2631 ferr(po, "missing esp_adjust for vararg func '%s'\n",
2634 // can't call functions with non-__cdecl callbacks yet
2635 for (arg = 0; arg < pp->argc; arg++) {
2636 if (pp->arg[arg].fptr != NULL) {
2637 pp_tmp = pp->arg[arg].fptr;
2638 if (pp_tmp->is_stdcall || pp_tmp->argc != pp_tmp->argc_stack)
2639 ferr(po, "'%s' has a non-__cdecl callback\n", tmpname);
2643 collect_call_args(po, i, pp, &save_arg_vars,
2644 0, i + opcnt * 2, 0, 0);
2646 if (strstr(pp->ret_type.name, "int64"))
2648 if (!(po->flags & OPF_TAIL) && !IS(pp->ret_type.name, "void"))
2655 // - find POPs for PUSHes, rm both
2656 // - scan for all used registers
2657 // - find flag set ops for their users
2658 // - declare indirect functions
2659 for (i = 0; i < opcnt; i++) {
2661 if (po->flags & OPF_RMD)
2664 if (po->op == OP_PUSH
2665 && po->argnum == 0 && !(po->flags & OPF_RSAVE)
2666 && po->operand[0].type == OPT_REG)
2668 reg = po->operand[0].reg;
2670 ferr(po, "reg not set for push?\n");
2673 ret = scan_for_pop(i + 1, opcnt,
2674 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
2677 ferr(po, "too much depth: %d\n", depth);
2679 regmask_save |= 1 << reg;
2681 po->flags |= OPF_RMD;
2682 scan_for_pop(i + 1, opcnt, po->operand[0].name,
2683 i + opcnt * 4, 0, &depth, 1);
2686 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
2689 if (regmask & (1 << reg)) {
2690 if (regmask_save & (1 << reg))
2691 ferr(po, "%s already saved?\n", po->operand[0].name);
2695 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
2700 regmask_now = po->regmask_src | po->regmask_dst;
2701 if (regmask_now & (1 << xBP)) {
2702 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
2703 if (po->regmask_dst & (1 << xBP))
2704 // compiler decided to drop bp frame and use ebp as scratch
2705 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
2707 regmask_now &= ~(1 << xBP);
2711 regmask |= regmask_now;
2713 if (po->flags & OPF_CC)
2715 int setters[16], cnt = 0, branched = 0;
2717 ret = scan_for_flag_set(i, i + opcnt * 6,
2718 &branched, setters, &cnt);
2719 if (ret < 0 || cnt <= 0)
2720 ferr(po, "unable to trace flag setter(s)\n");
2721 if (cnt > ARRAY_SIZE(setters))
2722 ferr(po, "too many flag setters\n");
2724 pfo = split_cond(po, po->op, &dummy);
2725 for (j = 0; j < cnt; j++)
2727 tmp_op = &ops[setters[j]]; // flag setter
2730 // to get nicer code, we try to delay test and cmp;
2731 // if we can't because of operand modification, or if we
2732 // have math op, or branch, make it calculate flags explicitly
2733 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
2734 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i) >= 0)
2737 else if (tmp_op->op == OP_CMPS) {
2738 pfomask = 1 << PFO_Z;
2741 // see if we'll be able to handle based on op result
2742 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
2743 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
2745 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
2749 tmp_op->pfomask |= pfomask;
2750 cmp_result_vars |= pfomask;
2752 // note: may overwrite, currently not a problem
2756 if (po->op == OP_ADC || po->op == OP_SBB)
2757 cmp_result_vars |= 1 << PFO_C;
2759 else if (po->op == OP_MUL
2760 || (po->op == OP_IMUL && po->operand_cnt == 1))
2764 else if (po->op == OP_CALL && po->operand[0].type != OPT_LABEL) {
2766 my_assert_not(pp, NULL);
2767 fprintf(fout, " %s (*icall%d)(", pp->ret_type.name, i);
2768 for (j = 0; j < pp->argc; j++) {
2770 fprintf(fout, ", ");
2771 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
2773 fprintf(fout, ");\n");
2777 // output LUTs/jumptables
2778 for (i = 0; i < g_func_pd_cnt; i++) {
2780 fprintf(fout, " static const ");
2781 if (pd->type == OPT_OFFSET) {
2782 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
2784 for (j = 0; j < pd->count; j++) {
2786 fprintf(fout, ", ");
2787 fprintf(fout, "&&%s", pd->d[j].u.label);
2791 fprintf(fout, "%s %s[] =\n { ",
2792 lmod_type_u(ops, pd->lmod), pd->label);
2794 for (j = 0; j < pd->count; j++) {
2796 fprintf(fout, ", ");
2797 fprintf(fout, "%u", pd->d[j].u.val);
2800 fprintf(fout, " };\n");
2803 // declare stack frame, va_arg
2805 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
2806 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
2808 if (g_func_pp->is_vararg)
2809 fprintf(fout, " va_list ap;\n");
2811 // declare arg-registers
2812 for (i = 0; i < g_func_pp->argc; i++) {
2813 if (g_func_pp->arg[i].reg != NULL) {
2814 reg = char_array_i(regs_r32,
2815 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2817 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2819 regmask_arg |= 1 << reg;
2820 fprintf(fout, " u32 %s = (u32)a%d;\n",
2821 g_func_pp->arg[i].reg, i + 1);
2826 // declare other regs - special case for eax
2827 if (!((regmask | regmask_arg) & 1) && have_func_ret
2828 && !IS(g_func_pp->ret_type.name, "void"))
2830 fprintf(fout, " u32 eax = 0;\n");
2834 regmask &= ~regmask_arg;
2835 regmask &= ~(1 << xSP);
2837 for (reg = 0; reg < 8; reg++) {
2838 if (regmask & (1 << reg)) {
2839 fprintf(fout, " u32 %s;\n", regs_r32[reg]);
2846 for (reg = 0; reg < 8; reg++) {
2847 if (regmask_save & (1 << reg)) {
2848 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
2854 if (save_arg_vars) {
2855 for (reg = 0; reg < 32; reg++) {
2856 if (save_arg_vars & (1 << reg)) {
2857 fprintf(fout, " u32 s_a%d;\n", reg + 1);
2863 if (cmp_result_vars) {
2864 for (i = 0; i < 8; i++) {
2865 if (cmp_result_vars & (1 << i)) {
2866 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
2873 fprintf(fout, " u64 mul_tmp;\n");
2878 fprintf(fout, "\n");
2880 if (g_func_pp->is_vararg) {
2881 if (g_func_pp->argc_stack == 0)
2882 ferr(ops, "vararg func without stack args?\n");
2883 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
2887 for (i = 0; i < opcnt; i++)
2889 if (g_labels[i][0] != 0 && g_label_refs[i].i != -1) {
2890 fprintf(fout, "\n%s:\n", g_labels[i]);
2893 delayed_flag_op = NULL;
2894 last_arith_dst = NULL;
2898 if (po->flags & OPF_RMD)
2903 #define assert_operand_cnt(n_) \
2904 if (po->operand_cnt != n_) \
2905 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
2907 // conditional/flag using op?
2908 if (po->flags & OPF_CC)
2913 pfo = split_cond(po, po->op, &is_inv);
2916 // we go through all this trouble to avoid using parsed_flag_op,
2917 // which makes generated code much nicer
2918 if (delayed_flag_op != NULL)
2920 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
2923 else if (last_arith_dst != NULL
2924 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
2925 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
2928 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
2929 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
2930 last_arith_dst->lmod, buf3);
2933 else if (tmp_op != NULL) {
2934 // use preprocessed flag calc results
2935 if (!(tmp_op->pfomask & (1 << pfo)))
2936 ferr(po, "not prepared for pfo %d\n", pfo);
2938 // note: is_inv was not yet applied
2939 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
2940 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
2943 ferr(po, "all methods of finding comparison failed\n");
2946 if (po->flags & OPF_JMP) {
2947 fprintf(fout, " if %s\n", buf1);
2949 else if (po->op == OP_ADC || po->op == OP_SBB) {
2951 fprintf(fout, " cond_%s = %s;\n",
2952 parsed_flag_op_names[pfo], buf1);
2954 else if (po->flags & OPF_DATA) { // SETcc
2955 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
2956 fprintf(fout, " %s = %s;", buf2, buf1);
2959 ferr(po, "unhandled conditional op\n");
2963 pfomask = po->pfomask;
2968 assert_operand_cnt(2);
2969 propagate_lmod(po, &po->operand[0], &po->operand[1]);
2970 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
2971 fprintf(fout, " %s = %s;", buf1,
2972 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
2973 po->operand[0].is_ptr ? "(void *)" : "", 0));
2977 assert_operand_cnt(2);
2978 po->operand[1].lmod = OPLM_DWORD; // always
2979 fprintf(fout, " %s = %s;",
2980 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
2981 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
2986 assert_operand_cnt(2);
2987 fprintf(fout, " %s = %s;",
2988 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
2989 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
2993 assert_operand_cnt(2);
2994 switch (po->operand[1].lmod) {
2996 strcpy(buf3, "(s8)");
2999 strcpy(buf3, "(s16)");
3002 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3004 fprintf(fout, " %s = %s%s;",
3005 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3007 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3011 assert_operand_cnt(1);
3012 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3013 fprintf(fout, " %s = ~%s;", buf1, buf1);
3017 assert_operand_cnt(2);
3018 fprintf(fout, " %s = (s32)%s >> 31;",
3019 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3020 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3021 strcpy(g_comment, "cdq");
3026 assert_operand_cnt(3);
3027 if (po->flags & OPF_REP) {
3028 fprintf(fout, " for (; ecx != 0; ecx--, edi += %d)\n",
3029 lmod_bytes(po, po->operand[0].lmod));
3030 fprintf(fout, " %sedi = eax;",
3031 lmod_cast_u_ptr(po, po->operand[0].lmod));
3032 strcpy(g_comment, "rep stos");
3035 fprintf(fout, " %sedi = eax; edi += %d;",
3036 lmod_cast_u_ptr(po, po->operand[0].lmod),
3037 lmod_bytes(po, po->operand[0].lmod));
3038 strcpy(g_comment, "stos");
3044 assert_operand_cnt(3);
3045 j = lmod_bytes(po, po->operand[0].lmod);
3046 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3047 if (po->flags & OPF_REP) {
3049 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3052 " %sedi = %sesi;", buf1, buf1);
3053 strcpy(g_comment, "rep movs");
3056 fprintf(fout, " %sedi = %sesi; edi += %d; esi += %d;",
3058 strcpy(g_comment, "movs");
3064 // repe ~ repeat while ZF=1
3065 assert_operand_cnt(3);
3066 j = lmod_bytes(po, po->operand[0].lmod);
3067 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3068 if (po->flags & OPF_REP) {
3070 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3073 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3074 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3077 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3078 (po->flags & OPF_REPZ) ? "e" : "ne");
3082 " cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3084 strcpy(g_comment, "cmps");
3086 pfomask &= ~(1 << PFO_Z);
3087 last_arith_dst = NULL;
3088 delayed_flag_op = NULL;
3091 // arithmetic w/flags
3096 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3099 assert_operand_cnt(2);
3100 fprintf(fout, " %s %s= %s;",
3101 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3103 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3104 output_std_flags(fout, po, &pfomask, buf1);
3105 last_arith_dst = &po->operand[0];
3106 delayed_flag_op = NULL;
3111 assert_operand_cnt(2);
3112 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3113 if (pfomask & (1 << PFO_C)) {
3114 if (po->operand[1].type == OPT_CONST) {
3115 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3116 j = po->operand[1].val;
3119 if (po->op == OP_SHL)
3123 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3127 ferr(po, "zero shift?\n");
3131 pfomask &= ~(1 << PFO_C);
3133 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3134 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3135 output_std_flags(fout, po, &pfomask, buf1);
3136 last_arith_dst = &po->operand[0];
3137 delayed_flag_op = NULL;
3141 assert_operand_cnt(2);
3142 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3143 fprintf(fout, " %s = %s%s >> %s;", buf1,
3144 lmod_cast_s(po, po->operand[0].lmod), buf1,
3145 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3146 output_std_flags(fout, po, &pfomask, buf1);
3147 last_arith_dst = &po->operand[0];
3148 delayed_flag_op = NULL;
3153 assert_operand_cnt(2);
3154 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3155 if (po->operand[1].type == OPT_CONST) {
3156 j = po->operand[1].val;
3157 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3158 fprintf(fout, po->op == OP_ROL ?
3159 " %s = (%s << %d) | (%s >> %d);" :
3160 " %s = (%s >> %d) | (%s << %d);",
3161 buf1, buf1, j, buf1,
3162 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3166 output_std_flags(fout, po, &pfomask, buf1);
3167 last_arith_dst = &po->operand[0];
3168 delayed_flag_op = NULL;
3172 assert_operand_cnt(2);
3173 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3174 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3175 // special case for XOR
3176 fprintf(fout, " %s = 0;",
3177 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3178 last_arith_dst = &po->operand[0];
3179 delayed_flag_op = NULL;
3186 assert_operand_cnt(2);
3187 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3188 if (po->op == OP_SBB
3189 && IS(po->operand[0].name, po->operand[1].name))
3191 // avoid use of unitialized var
3192 fprintf(fout, " %s = -cond_c;",
3193 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3196 fprintf(fout, " %s %s= %s + cond_c;",
3197 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3199 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3201 last_arith_dst = &po->operand[0];
3202 delayed_flag_op = NULL;
3207 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3208 if (po->operand[0].type == OPT_REG) {
3209 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3210 fprintf(fout, " %s%s;", buf1, buf2);
3213 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3214 fprintf(fout, " %s %s= 1;", buf1, buf2);
3216 last_arith_dst = &po->operand[0];
3217 delayed_flag_op = NULL;
3221 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3222 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3223 fprintf(fout, " %s = -%s%s;", buf1,
3224 lmod_cast_s(po, po->operand[0].lmod), buf2);
3225 last_arith_dst = &po->operand[0];
3226 delayed_flag_op = NULL;
3227 if (pfomask & (1 << PFO_C)) {
3228 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3229 pfomask &= ~(1 << PFO_C);
3234 if (po->operand_cnt == 2) {
3235 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3238 if (po->operand_cnt == 3)
3239 ferr(po, "TODO imul3\n");
3242 assert_operand_cnt(1);
3243 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3244 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3245 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3246 fprintf(fout, " edx = mul_tmp >> 32;\n");
3247 fprintf(fout, " eax = mul_tmp;");
3248 last_arith_dst = NULL;
3249 delayed_flag_op = NULL;
3254 assert_operand_cnt(1);
3255 if (po->operand[0].lmod != OPLM_DWORD)
3256 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3258 // 32bit division is common, look for it
3259 if (po->op == OP_DIV)
3260 ret = scan_for_reg_clear(i, xDX);
3262 ret = scan_for_cdq_edx(i);
3264 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3265 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3266 po->op == OP_IDIV));
3267 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3268 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3271 ferr(po, "TODO 64bit divident\n");
3272 last_arith_dst = NULL;
3273 delayed_flag_op = NULL;
3278 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3280 for (j = 0; j < 8; j++) {
3281 if (pfomask & (1 << j)) {
3282 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3283 fprintf(fout, " cond_%s = %s;",
3284 parsed_flag_op_names[j], buf1);
3291 last_arith_dst = NULL;
3292 delayed_flag_op = po;
3295 // note: we reuse OP_Jcc for SETcc, only flags differ
3296 case OP_JO ... OP_JG:
3297 if (po->flags & OPF_JMP)
3298 fprintf(fout, " goto %s;", po->operand[0].name);
3299 // else SETcc - should already be handled
3303 assert_operand_cnt(1);
3304 last_arith_dst = NULL;
3305 delayed_flag_op = NULL;
3307 if (po->operand[0].type == OPT_REGMEM) {
3308 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3311 ferr(po, "parse failure for jmp '%s'\n",
3312 po->operand[0].name);
3313 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
3316 else if (po->operand[0].type != OPT_LABEL)
3317 ferr(po, "unhandled jmp type\n");
3319 fprintf(fout, " goto %s;", po->operand[0].name);
3323 assert_operand_cnt(1);
3326 ferr(po, "NULL pp\n");
3328 if (po->operand[0].type != OPT_LABEL)
3329 fprintf(fout, " icall%d = (void *)%s;\n", i,
3330 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]));
3333 if (strstr(pp->ret_type.name, "int64")) {
3334 if (po->flags & OPF_TAIL)
3335 ferr(po, "int64 and tail?\n");
3336 fprintf(fout, "mul_tmp = ");
3338 else if (!IS(pp->ret_type.name, "void")) {
3339 if (po->flags & OPF_TAIL) {
3340 if (!IS(g_func_pp->ret_type.name, "void")) {
3341 fprintf(fout, "return ");
3342 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3343 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3347 fprintf(fout, "eax = ");
3348 if (pp->ret_type.is_ptr)
3349 fprintf(fout, "(u32)");
3353 if (po->operand[0].type != OPT_LABEL) {
3354 fprintf(fout, "icall%d(", i);
3357 if (pp->name[0] == 0)
3358 ferr(po, "missing pp->name\n");
3359 fprintf(fout, "%s%s(", pp->name,
3360 pp->has_structarg ? "_sa" : "");
3363 for (arg = 0; arg < pp->argc; arg++) {
3365 fprintf(fout, ", ");
3368 if (pp->arg[arg].type.is_ptr)
3369 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3371 if (pp->arg[arg].reg != NULL) {
3372 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3377 tmp_op = pp->arg[arg].datap;
3379 ferr(po, "parsed_op missing for arg%d\n", arg);
3380 if (tmp_op->argnum != 0) {
3381 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3385 out_src_opr(buf1, sizeof(buf1),
3386 tmp_op, &tmp_op->operand[0], cast, 0));
3389 fprintf(fout, ");");
3391 if (strstr(pp->ret_type.name, "int64")) {
3392 fprintf(fout, "\n");
3393 fprintf(fout, " edx = mul_tmp >> 32;\n");
3394 fprintf(fout, " eax = mul_tmp;");
3397 if (po->flags & OPF_TAIL) {
3398 strcpy(g_comment, "tailcall");
3402 else if (IS(pp->ret_type.name, "void"))
3404 else if (IS(g_func_pp->ret_type.name, "void"))
3406 // else already handled as 'return f()'
3409 fprintf(fout, "\n return;");
3410 strcpy(g_comment, "^ tailcall");
3413 delayed_flag_op = NULL;
3414 last_arith_dst = NULL;
3418 if (g_func_pp->is_vararg)
3419 fprintf(fout, " va_end(ap);\n");
3421 if (IS(g_func_pp->ret_type.name, "void")) {
3422 if (i != opcnt - 1 || label_pending)
3423 fprintf(fout, " return;");
3425 else if (g_func_pp->ret_type.is_ptr) {
3426 fprintf(fout, " return (%s)eax;",
3427 g_func_pp->ret_type.name);
3430 fprintf(fout, " return eax;");
3432 last_arith_dst = NULL;
3433 delayed_flag_op = NULL;
3437 if (po->argnum != 0) {
3438 // special case - saved func arg
3439 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3440 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
3443 else if (po->flags & OPF_RSAVE) {
3444 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3445 fprintf(fout, " s_%s = %s;", buf1, buf1);
3448 if (!(g_ida_func_attr & IDAFA_NORETURN))
3449 ferr(po, "stray push encountered\n");
3454 if (po->flags & OPF_RSAVE) {
3455 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3456 fprintf(fout, " %s = s_%s;", buf1, buf1);
3459 ferr(po, "stray pop encountered\n");
3468 ferr(po, "unhandled op type %d, flags %x\n",
3473 if (g_comment[0] != 0) {
3474 fprintf(fout, " // %s", g_comment);
3479 fprintf(fout, "\n");
3481 // some sanity checking
3482 if ((po->flags & OPF_REP) && po->op != OP_STOS
3483 && po->op != OP_MOVS && po->op != OP_CMPS)
3484 ferr(po, "unexpected rep\n");
3485 if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3486 ferr(po, "unexpected repz/repnz\n");
3489 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3491 // see is delayed flag stuff is still valid
3492 if (delayed_flag_op != NULL && delayed_flag_op != po) {
3493 if (is_any_opr_modified(delayed_flag_op, po))
3494 delayed_flag_op = NULL;
3497 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3498 if (is_opr_modified(last_arith_dst, po))
3499 last_arith_dst = NULL;
3505 fprintf(fout, "}\n\n");
3508 for (i = 0; i < opcnt; i++) {
3509 struct label_ref *lr, *lr_del;
3511 lr = g_label_refs[i].next;
3512 while (lr != NULL) {
3517 g_label_refs[i].i = -1;
3518 g_label_refs[i].next = NULL;
3520 if (ops[i].op == OP_CALL) {
3529 static void set_label(int i, const char *name)
3535 p = strchr(name, ':');
3539 if (len > sizeof(g_labels[0]) - 1)
3540 aerr("label '%s' too long: %d\n", name, len);
3541 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
3542 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
3543 memcpy(g_labels[i], name, len);
3544 g_labels[i][len] = 0;
3547 // '=' needs special treatment..
3548 static char *next_word_s(char *w, size_t wsize, char *s)
3554 for (i = 0; i < wsize - 1; i++) {
3555 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
3561 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
3562 printf("warning: '%s' truncated\n", w);
3573 static struct chunk_item *func_chunks;
3574 static int func_chunk_cnt;
3575 static int func_chunk_alloc;
3577 static void add_func_chunk(FILE *fasm, const char *name, int line)
3579 if (func_chunk_cnt >= func_chunk_alloc) {
3580 func_chunk_alloc *= 2;
3581 func_chunks = realloc(func_chunks,
3582 func_chunk_alloc * sizeof(func_chunks[0]));
3583 my_assert_not(func_chunks, NULL);
3585 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
3586 func_chunks[func_chunk_cnt].name = strdup(name);
3587 func_chunks[func_chunk_cnt].asmln = line;
3591 static int cmp_chunks(const void *p1, const void *p2)
3593 const struct chunk_item *c1 = p1, *c2 = p2;
3594 return strcmp(c1->name, c2->name);
3597 static int cmpstringp(const void *p1, const void *p2)
3599 return strcmp(*(char * const *)p1, *(char * const *)p2);
3602 static void scan_ahead(FILE *fasm)
3612 oldpos = ftell(fasm);
3615 while (fgets(line, sizeof(line), fasm))
3626 // get rid of random tabs
3627 for (i = 0; line[i] != 0; i++)
3628 if (line[i] == '\t')
3631 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3634 next_word(words[0], sizeof(words[0]), p);
3635 if (words[0][0] == 0)
3636 aerr("missing name for func chunk?\n");
3638 add_func_chunk(fasm, words[0], asmln);
3643 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3644 words[wordc][0] = 0;
3645 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3646 if (*p == 0 || *p == ';') {
3652 if (wordc == 2 && IS(words[1], "ends"))
3656 fseek(fasm, oldpos, SEEK_SET);
3660 int main(int argc, char *argv[])
3662 FILE *fout, *fasm, *frlist;
3663 struct parsed_data *pd = NULL;
3665 char **rlist = NULL;
3667 int rlist_alloc = 0;
3668 int func_chunks_used = 0;
3669 int func_chunks_sorted = 0;
3670 int func_chunk_i = -1;
3671 long func_chunk_ret = 0;
3672 int func_chunk_ret_ln = 0;
3673 int scanned_ahead = 0;
3675 char words[16][256];
3676 enum opr_lenmod lmod;
3678 int pending_endp = 0;
3680 int skip_warned = 0;
3691 if (argv[1] && IS(argv[1], "-v")) {
3696 if (argc < arg + 3) {
3697 printf("usage:\n%s [-v] <.c> <.asm> <hdrf> [rlist]*\n",
3704 asmfn = argv[arg++];
3705 fasm = fopen(asmfn, "r");
3706 my_assert_not(fasm, NULL);
3708 hdrfn = argv[arg++];
3709 g_fhdr = fopen(hdrfn, "r");
3710 my_assert_not(g_fhdr, NULL);
3713 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
3714 my_assert_not(rlist, NULL);
3715 // needs special handling..
3716 rlist[rlist_len++] = "__alloca_probe";
3718 func_chunk_alloc = 32;
3719 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
3720 my_assert_not(func_chunks, NULL);
3722 for (; arg < argc; arg++) {
3723 frlist = fopen(argv[arg], "r");
3724 my_assert_not(frlist, NULL);
3726 while (fgets(line, sizeof(line), frlist)) {
3728 if (*p == 0 || *p == ';' || *p == '#')
3731 p = next_word(words[0], sizeof(words[0]), p);
3732 if (words[0][0] == 0)
3735 if (rlist_len >= rlist_alloc) {
3736 rlist_alloc = rlist_alloc * 2 + 64;
3737 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
3738 my_assert_not(rlist, NULL);
3740 rlist[rlist_len++] = strdup(words[0]);
3748 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
3750 fout = fopen(argv[arg_out], "w");
3751 my_assert_not(fout, NULL);
3754 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
3755 my_assert_not(g_eqs, NULL);
3757 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
3758 g_label_refs[i].i = -1;
3759 g_label_refs[i].next = NULL;
3762 while (fgets(line, sizeof(line), fasm))
3771 // get rid of random tabs
3772 for (i = 0; line[i] != 0; i++)
3773 if (line[i] == '\t')
3778 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
3779 goto do_pending_endp; // eww..
3781 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
3783 static const char *attrs[] = {
3792 // parse IDA's attribute-list comment
3793 g_ida_func_attr = 0;
3796 for (; *p != 0; p = sskip(p)) {
3797 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
3798 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
3799 g_ida_func_attr |= 1 << i;
3800 p += strlen(attrs[i]);
3804 if (i == ARRAY_SIZE(attrs)) {
3805 anote("unparsed IDA attr: %s\n", p);
3808 if (IS(attrs[i], "fpd=")) {
3809 p = next_word(words[0], sizeof(words[0]), p);
3814 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3817 next_word(words[0], sizeof(words[0]), p);
3818 if (words[0][0] == 0)
3819 aerr("missing name for func chunk?\n");
3821 if (!scanned_ahead) {
3822 add_func_chunk(fasm, words[0], asmln);
3823 func_chunks_sorted = 0;
3826 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
3828 if (func_chunk_i >= 0) {
3829 if (func_chunk_i < func_chunk_cnt
3830 && IS(func_chunks[func_chunk_i].name, g_func))
3832 // move on to next chunk
3833 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
3835 aerr("seek failed for '%s' chunk #%d\n",
3836 g_func, func_chunk_i);
3837 asmln = func_chunks[func_chunk_i].asmln;
3841 if (func_chunk_ret == 0)
3842 aerr("no return from chunk?\n");
3843 fseek(fasm, func_chunk_ret, SEEK_SET);
3844 asmln = func_chunk_ret_ln;
3850 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
3851 func_chunks_used = 1;
3853 if (IS_START(g_func, "sub_")) {
3854 unsigned long addr = strtoul(p, NULL, 16);
3855 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
3856 if (addr > f_addr && !scanned_ahead) {
3857 anote("scan_ahead caused by '%s', f_addr %lx\n",
3861 func_chunks_sorted = 0;
3869 memset(words, 0, sizeof(words));
3870 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3871 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3872 if (*p == 0 || *p == ';') {
3878 // alow asm patches in comments
3879 if (*p == ';' && IS_START(p, "; sctpatch:")) {
3881 if (*p == 0 || *p == ';')
3883 goto parse_words; // lame
3888 awarn("wordc == 0?\n");
3892 // don't care about this:
3893 if (words[0][0] == '.'
3894 || IS(words[0], "include")
3895 || IS(words[0], "assume") || IS(words[1], "segment")
3896 || IS(words[0], "align"))
3902 // do delayed endp processing to collect switch jumptables
3904 if (in_func && !skip_func && wordc >= 2
3905 && ((words[0][0] == 'd' && words[0][2] == 0)
3906 || (words[1][0] == 'd' && words[1][2] == 0)))
3909 if (words[1][0] == 'd' && words[1][2] == 0) {
3911 if (g_func_pd_cnt >= pd_alloc) {
3912 pd_alloc = pd_alloc * 2 + 16;
3913 g_func_pd = realloc(g_func_pd,
3914 sizeof(g_func_pd[0]) * pd_alloc);
3915 my_assert_not(g_func_pd, NULL);
3917 pd = &g_func_pd[g_func_pd_cnt];
3919 memset(pd, 0, sizeof(*pd));
3920 strcpy(pd->label, words[0]);
3921 pd->type = OPT_CONST;
3922 pd->lmod = lmod_from_directive(words[1]);
3926 lmod = lmod_from_directive(words[0]);
3927 if (lmod != pd->lmod)
3928 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
3931 if (pd->count_alloc < pd->count + wordc) {
3932 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
3933 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
3934 my_assert_not(pd->d, NULL);
3936 for (; i < wordc; i++) {
3937 if (IS(words[i], "offset")) {
3938 pd->type = OPT_OFFSET;
3941 p = strchr(words[i], ',');
3944 if (pd->type == OPT_OFFSET)
3945 pd->d[pd->count].u.label = strdup(words[i]);
3947 pd->d[pd->count].u.val = parse_number(words[i]);
3948 pd->d[pd->count].bt_i = -1;
3954 if (in_func && !skip_func)
3955 gen_func(fout, g_fhdr, g_func, pi);
3959 g_ida_func_attr = 0;
3963 func_chunks_used = 0;
3966 memset(&ops, 0, pi * sizeof(ops[0]));
3967 memset(g_labels, 0, pi * sizeof(g_labels[0]));
3971 for (i = 0; i < g_func_pd_cnt; i++) {
3973 if (pd->type == OPT_OFFSET) {
3974 for (j = 0; j < pd->count; j++)
3975 free(pd->d[j].u.label);
3986 if (IS(words[1], "proc")) {
3988 aerr("proc '%s' while in_func '%s'?\n",
3991 if ((g_ida_func_attr & IDAFA_THUNK)
3992 || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
3994 strcpy(g_func, words[0]);
3995 set_label(0, words[0]);
4000 if (IS(words[1], "endp"))
4003 aerr("endp '%s' while not in_func?\n", words[0]);
4004 if (!IS(g_func, words[0]))
4005 aerr("endp '%s' while in_func '%s'?\n",
4008 if (!skip_func && func_chunks_used) {
4009 // start processing chunks
4010 struct chunk_item *ci, key = { g_func, 0 };
4012 func_chunk_ret = ftell(fasm);
4013 func_chunk_ret_ln = asmln;
4014 if (!func_chunks_sorted) {
4015 qsort(func_chunks, func_chunk_cnt,
4016 sizeof(func_chunks[0]), cmp_chunks);
4017 func_chunks_sorted = 1;
4019 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4020 sizeof(func_chunks[0]), cmp_chunks);
4022 aerr("'%s' needs chunks, but none found\n", g_func);
4023 func_chunk_i = ci - func_chunks;
4024 for (; func_chunk_i > 0; func_chunk_i--)
4025 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4028 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4030 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4031 asmln = func_chunks[func_chunk_i].asmln;
4039 p = strchr(words[0], ':');
4041 set_label(pi, words[0]);
4045 if (!in_func || skip_func) {
4046 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4048 anote("skipping from '%s'\n", g_labels[pi]);
4051 g_labels[pi][0] = 0;
4055 if (wordc > 1 && IS(words[1], "=")) {
4057 aerr("unhandled equ, wc=%d\n", wordc);
4058 if (g_eqcnt >= eq_alloc) {
4060 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4061 my_assert_not(g_eqs, NULL);
4064 len = strlen(words[0]);
4065 if (len > sizeof(g_eqs[0].name) - 1)
4066 aerr("equ name too long: %d\n", len);
4067 strcpy(g_eqs[g_eqcnt].name, words[0]);
4069 if (!IS(words[3], "ptr"))
4070 aerr("unhandled equ\n");
4071 if (IS(words[2], "dword"))
4072 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4073 else if (IS(words[2], "word"))
4074 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4075 else if (IS(words[2], "byte"))
4076 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4078 aerr("bad lmod: '%s'\n", words[2]);
4080 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4085 if (pi >= ARRAY_SIZE(ops))
4086 aerr("too many ops\n");
4088 parse_op(&ops[pi], words, wordc);
4099 // vim:ts=2:shiftwidth=2:expandtab