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 (ofs_reg[0] == 0 && 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 op_set_clear_flag(struct parsed_op *po,
1788 enum op_flags flag_set, enum op_flags flag_clear)
1790 po->flags |= flag_set;
1791 po->flags &= ~flag_clear;
1794 // last op in stream - unconditional branch or ret
1795 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1796 || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1798 static int scan_for_pop(int i, int opcnt, const char *reg,
1799 int magic, int depth, int *maxdepth, int do_flags)
1801 struct parsed_op *po;
1805 for (; i < opcnt; i++) {
1807 if (po->cc_scratch == magic)
1808 break; // already checked
1809 po->cc_scratch = magic;
1811 if (po->flags & OPF_TAIL)
1812 return -1; // deadend
1814 if ((po->flags & OPF_RMD)
1815 || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1818 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1819 if (po->btj != NULL) {
1821 for (j = 0; j < po->btj->count - 1; j++) {
1822 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1823 depth, maxdepth, do_flags);
1825 return ret; // dead end
1827 // follow last jumptable entry
1828 i = po->btj->d[j].bt_i - 1;
1833 ferr(po, "dead branch\n");
1837 if (po->flags & OPF_CC) {
1838 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1839 depth, maxdepth, do_flags);
1841 return ret; // dead end
1849 if ((po->op == OP_POP || po->op == OP_PUSH)
1850 && po->operand[0].type == OPT_REG
1851 && IS(po->operand[0].name, reg))
1853 if (po->op == OP_PUSH) {
1855 if (depth > *maxdepth)
1858 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1860 else if (depth == 0) {
1862 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1867 if (depth < 0) // should not happen
1868 ferr(po, "fail with depth\n");
1870 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1878 // scan for pop starting from 'ret' op (all paths)
1879 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
1885 for (; i < opcnt; i++) {
1886 if (!(ops[i].flags & OPF_TAIL))
1889 for (j = i - 1; j >= 0; j--) {
1890 if (ops[j].flags & OPF_RMD)
1892 if (ops[j].flags & OPF_JMP)
1895 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
1896 && IS(ops[j].operand[0].name, reg))
1899 ops[j].flags |= flag_set;
1903 if (g_labels[j][0] != 0)
1908 return found ? 0 : -1;
1911 // is operand 'opr modified' by parsed_op 'po'?
1912 static int is_opr_modified(const struct parsed_opr *opr,
1913 const struct parsed_op *po)
1915 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
1918 if (opr->type == OPT_REG && po->operand[0].type == OPT_REG) {
1919 if (po->regmask_dst & (1 << opr->reg))
1925 return IS(po->operand[0].name, opr->name);
1928 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
1929 static int is_any_opr_modified(const struct parsed_op *po_test,
1930 const struct parsed_op *po)
1934 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
1937 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
1940 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
1943 // in reality, it can wreck any register, but in decompiled C
1944 // version it can only overwrite eax or edx:eax
1945 if (po->op == OP_CALL
1946 && ((po_test->regmask_src | po_test->regmask_dst)
1947 & ((1 << xAX)|(1 << xDX))))
1950 for (i = 0; i < po_test->operand_cnt; i++)
1951 if (IS(po_test->operand[i].name, po->operand[0].name))
1957 // scan for any po_test operand modification in range given
1958 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt)
1960 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
1963 for (; i < opcnt; i++) {
1964 if (is_any_opr_modified(po_test, &ops[i]))
1971 // scan for po_test operand[0] modification in range given
1972 static int scan_for_mod_opr0(struct parsed_op *po_test,
1975 for (; i < opcnt; i++) {
1976 if (is_opr_modified(&po_test->operand[0], &ops[i]))
1983 static int scan_for_flag_set(int i, int magic, int *branched,
1984 int *setters, int *setter_cnt)
1986 struct label_ref *lr;
1990 if (ops[i].cc_scratch == magic) {
1991 ferr(&ops[i], "%s looped\n", __func__);
1994 ops[i].cc_scratch = magic;
1996 if (g_labels[i][0] != 0) {
1999 lr = &g_label_refs[i];
2000 for (; lr->next; lr = lr->next) {
2001 ret = scan_for_flag_set(lr->i, magic,
2002 branched, setters, setter_cnt);
2007 if (i > 0 && LAST_OP(i - 1)) {
2011 ret = scan_for_flag_set(lr->i, magic,
2012 branched, setters, setter_cnt);
2018 if (ops[i].flags & OPF_FLAGS) {
2019 setters[*setter_cnt] = i;
2024 if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2031 // scan back for cdq, if anything modifies edx, fail
2032 static int scan_for_cdq_edx(int i)
2035 if (g_labels[i][0] != 0) {
2036 if (g_label_refs[i].next != NULL)
2038 if (i > 0 && LAST_OP(i - 1)) {
2039 i = g_label_refs[i].i;
2046 if (ops[i].op == OP_CDQ)
2049 if (ops[i].regmask_dst & (1 << xDX))
2051 if (g_labels[i][0] != 0)
2058 static int scan_for_reg_clear(int i, int reg)
2061 if (g_labels[i][0] != 0) {
2062 if (g_label_refs[i].next != NULL)
2064 if (i > 0 && LAST_OP(i - 1)) {
2065 i = g_label_refs[i].i;
2072 if (ops[i].op == OP_XOR
2073 && ops[i].operand[0].lmod == OPLM_DWORD
2074 && ops[i].operand[0].reg == ops[i].operand[1].reg
2075 && ops[i].operand[0].reg == reg)
2078 if (ops[i].regmask_dst & (1 << reg))
2080 if (g_labels[i][0] != 0)
2087 // scan for positive, constant esp adjust
2088 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2090 struct parsed_op *po;
2093 for (; i < opcnt; i++) {
2096 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2097 if (po->operand[1].type != OPT_CONST)
2098 ferr(&ops[i], "non-const esp adjust?\n");
2099 *adj += po->operand[1].val;
2101 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2104 else if (po->op == OP_PUSH)
2105 *adj -= lmod_bytes(po, po->operand[0].lmod);
2106 else if (po->op == OP_POP)
2107 *adj += lmod_bytes(po, po->operand[0].lmod);
2108 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2109 if (po->op != OP_CALL)
2111 if (po->operand[0].type != OPT_LABEL)
2113 // TODO: should only allow combining __cdecl calls..
2116 if (g_labels[i][0] != 0)
2123 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2125 struct parsed_op *po;
2129 ferr(ops, "%s: followed bad branch?\n", __func__);
2131 for (; i < opcnt; i++) {
2133 if (po->cc_scratch == magic)
2135 po->cc_scratch = magic;
2138 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2139 if (po->btj != NULL) {
2141 for (j = 0; j < po->btj->count; j++)
2142 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2146 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2147 if (!(po->flags & OPF_CC))
2150 if (po->flags & OPF_TAIL)
2155 static int collect_call_args(struct parsed_op *po, int i,
2156 struct parsed_proto *pp, int *save_arg_vars, int arg,
2157 int magic, int need_op_saving, int may_reuse)
2159 struct parsed_proto *pp_tmp;
2160 struct label_ref *lr;
2161 int need_to_save_current;
2166 ferr(po, "no refs for '%s'?\n", g_labels[i]);
2170 for (; arg < pp->argc; arg++)
2171 if (pp->arg[arg].reg == NULL)
2173 magic = (magic & 0xffffff) | (arg << 24);
2175 for (j = i; j >= 0 && arg < pp->argc; )
2177 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2178 if (ops[j].cc_scratch != magic) {
2179 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2183 // ok: have already been here
2186 ops[j].cc_scratch = magic;
2188 if (g_labels[j][0] != 0) {
2189 lr = &g_label_refs[j];
2190 if (lr->next != NULL)
2192 for (; lr->next; lr = lr->next) {
2193 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2195 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2196 arg, magic, need_op_saving, may_reuse);
2201 if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2203 if (j > 0 && LAST_OP(j - 1)) {
2204 // follow last branch in reverse
2209 ret = collect_call_args(po, lr->i, pp, save_arg_vars,
2210 arg, magic, need_op_saving, may_reuse);
2216 if (ops[j].op == OP_CALL)
2218 pp_tmp = ops[j].datap;
2220 ferr(po, "arg collect hit unparsed call '%s'\n",
2221 ops[j].operand[0].name);
2222 if (may_reuse && pp_tmp->argc_stack > 0)
2223 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2224 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2226 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2227 ferr(po, "arg collect %d/%d hit esp adjust\n",
2230 else if (ops[j].op == OP_POP) {
2231 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2233 else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2237 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2239 pp->arg[arg].datap = &ops[j];
2240 need_to_save_current = 0;
2241 if (!need_op_saving) {
2242 ret = scan_for_mod(&ops[j], j + 1, i);
2243 need_to_save_current = (ret >= 0);
2245 if (need_op_saving || need_to_save_current) {
2246 // mark this push as one that needs operand saving
2247 ops[j].flags &= ~OPF_RMD;
2248 if (ops[j].argnum == 0) {
2249 ops[j].argnum = arg + 1;
2250 *save_arg_vars |= 1 << arg;
2252 else if (ops[j].argnum < arg + 1)
2253 ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2254 ops[j].argnum, arg + 1, pp->name);
2256 else if (ops[j].argnum == 0)
2257 ops[j].flags |= OPF_RMD;
2259 // some PUSHes are reused by different calls on other branches,
2260 // but that can't happen if we didn't branch, so they
2261 // can be removed from future searches (handles nested calls)
2263 ops[j].flags |= OPF_FARG;
2266 for (arg++; arg < pp->argc; arg++)
2267 if (pp->arg[arg].reg == NULL)
2269 magic = (magic & 0xffffff) | (arg << 24);
2273 if (arg < pp->argc) {
2274 ferr(po, "arg collect failed for '%s': %d/%d\n",
2275 pp->name, arg, pp->argc);
2281 static void add_label_ref(struct label_ref *lr, int op_i)
2283 struct label_ref *lr_new;
2290 lr_new = calloc(1, sizeof(*lr_new));
2292 lr_new->next = lr->next;
2296 static void output_std_flags(FILE *fout, struct parsed_op *po,
2297 int *pfomask, const char *dst_opr_text)
2299 if (*pfomask & (1 << PFO_Z)) {
2300 fprintf(fout, "\n cond_z = (%s%s == 0);",
2301 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2302 *pfomask &= ~(1 << PFO_Z);
2304 if (*pfomask & (1 << PFO_S)) {
2305 fprintf(fout, "\n cond_s = (%s%s < 0);",
2306 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2307 *pfomask &= ~(1 << PFO_S);
2311 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2313 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2314 struct parsed_opr *last_arith_dst = NULL;
2315 char buf1[256], buf2[256], buf3[256], cast[64];
2316 const struct parsed_proto *pp_c;
2317 struct parsed_proto *pp, *pp_tmp;
2318 struct parsed_data *pd;
2319 const char *tmpname;
2320 enum parsed_flag_op pfo;
2321 int save_arg_vars = 0;
2322 int cmp_result_vars = 0;
2323 int need_mul_var = 0;
2324 int have_func_ret = 0;
2326 int label_pending = 0;
2327 int regmask_save = 0;
2328 int regmask_arg = 0;
2329 int regmask_now = 0;
2341 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2343 g_func_pp = proto_parse(fhdr, funcn);
2344 if (g_func_pp == NULL)
2345 ferr(ops, "proto_parse failed for '%s'\n", funcn);
2347 fprintf(fout, "%s ", g_func_pp->ret_type.name);
2348 if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2349 fprintf(fout, "__stdcall ");
2350 if (g_ida_func_attr & IDAFA_NORETURN)
2351 fprintf(fout, "noreturn ");
2352 fprintf(fout, "%s(", funcn);
2354 for (i = 0; i < g_func_pp->argc; i++) {
2356 fprintf(fout, ", ");
2357 if (g_func_pp->arg[i].fptr != NULL) {
2359 pp = g_func_pp->arg[i].fptr;
2360 fprintf(fout, "%s (", pp->ret_type.name);
2361 if (pp->is_stdcall && pp->argc_reg == 0)
2362 fprintf(fout, "__stdcall ");
2363 fprintf(fout, "*a%d)(", i + 1);
2364 for (j = 0; j < pp->argc; j++) {
2366 fprintf(fout, ", ");
2367 if (pp->arg[j].fptr)
2368 ferr(ops, "nested fptr\n");
2369 fprintf(fout, "%s", pp->arg[j].type.name);
2374 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2377 if (g_func_pp->is_vararg) {
2379 fprintf(fout, ", ");
2380 fprintf(fout, "...");
2383 fprintf(fout, ")\n{\n");
2386 // - handle ebp/esp frame, remove ops related to it
2387 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2388 && ops[1].op == OP_MOV
2389 && IS(opr_name(&ops[1], 0), "ebp")
2390 && IS(opr_name(&ops[1], 1), "esp"))
2395 ops[0].flags |= OPF_RMD;
2396 ops[1].flags |= OPF_RMD;
2399 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2400 g_stack_fsz = opr_const(&ops[2], 1);
2401 ops[2].flags |= OPF_RMD;
2405 // another way msvc builds stack frame..
2407 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2409 ops[i].flags |= OPF_RMD;
2413 // and another way..
2414 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2415 && ops[i].operand[1].type == OPT_CONST
2416 && ops[i + 1].op == OP_CALL
2417 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2419 g_stack_fsz += ops[i].operand[1].val;
2420 ops[i].flags |= OPF_RMD;
2422 ops[i].flags |= OPF_RMD;
2429 for (; i < opcnt; i++)
2430 if (ops[i].op == OP_RET)
2432 if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2435 if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2436 ops[i - 1].flags |= OPF_RMD;
2437 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2438 ferr(&ops[i - 1], "'pop ebp' expected\n");
2440 if (g_stack_fsz != 0) {
2441 if (ops[i - 2].op == OP_MOV
2442 && IS(opr_name(&ops[i - 2], 0), "esp")
2443 && IS(opr_name(&ops[i - 2], 1), "ebp"))
2445 ops[i - 2].flags |= OPF_RMD;
2447 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2448 ferr(&ops[i - 2], "esp restore expected\n");
2450 if (ecx_push && ops[i - 3].op == OP_POP
2451 && IS(opr_name(&ops[i - 3], 0), "ecx"))
2453 ferr(&ops[i - 3], "unexpected ecx pop\n");
2459 } while (i < opcnt);
2462 for (i = 0; i < opcnt; i++) {
2463 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2465 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2466 && ops[i].operand[1].type == OPT_CONST)
2475 g_stack_fsz = ops[i].operand[1].val;
2476 ops[i].flags |= OPF_RMD;
2480 for (; i < opcnt; i++)
2481 if (ops[i].op == OP_RET)
2483 if (ops[i - 1].op != OP_ADD
2484 || !IS(opr_name(&ops[i - 1], 0), "esp")
2485 || ops[i - 1].operand[1].type != OPT_CONST
2486 || ops[i - 1].operand[1].val != g_stack_fsz)
2487 ferr(&ops[i - 1], "'add esp' expected\n");
2488 ops[i - 1].flags |= OPF_RMD;
2491 } while (i < opcnt);
2496 // - parse calls with labels
2497 // - resolve all branches
2498 for (i = 0; i < opcnt; i++)
2504 if (po->flags & OPF_RMD)
2507 if (po->op == OP_CALL) {
2508 if (po->operand[0].type == OPT_LABEL) {
2509 tmpname = opr_name(po, 0);
2510 pp_c = proto_parse(fhdr, tmpname);
2512 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2513 if (pp_c->is_fptr && pp_c->argc_reg != 0)
2514 ferr(po, "fptr call with reg arg\n");
2515 pp = proto_clone(pp_c);
2516 my_assert_not(pp, NULL);
2522 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2525 if (po->operand[0].type == OPT_REGMEM) {
2526 char *p = strchr(po->operand[0].name, '[');
2528 ferr(po, "unhandled indirect branch\n");
2529 ret = p - po->operand[0].name;
2530 strncpy(buf1, po->operand[0].name, ret);
2533 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2534 if (IS(g_func_pd[j].label, buf1)) {
2540 //ferr(po, "label '%s' not parsed?\n", buf1);
2542 if (pd->type != OPT_OFFSET)
2543 ferr(po, "label '%s' with non-offset data?\n", buf1);
2545 // find all labels, link
2546 for (j = 0; j < pd->count; j++) {
2547 for (l = 0; l < opcnt; l++) {
2548 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2549 add_label_ref(&g_label_refs[l], i);
2560 for (l = 0; l < opcnt; l++) {
2561 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2562 add_label_ref(&g_label_refs[l], i);
2571 if (po->operand[0].type == OPT_LABEL)
2575 ferr(po, "unhandled branch\n");
2579 po->flags |= OPF_TAIL;
2585 for (i = 0; i < opcnt; i++)
2588 if (po->flags & OPF_RMD)
2591 if (po->op == OP_CALL)
2593 tmpname = opr_name(po, 0);
2598 pp = calloc(1, sizeof(*pp));
2599 my_assert_not(pp, NULL);
2600 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2602 ferr(po, "non-__cdecl indirect call unhandled yet\n");
2604 if (j > ARRAY_SIZE(pp->arg))
2605 ferr(po, "esp adjust too large?\n");
2606 pp->ret_type.name = strdup("int");
2607 pp->argc = pp->argc_stack = j;
2608 for (arg = 0; arg < pp->argc; arg++)
2609 pp->arg[arg].type.name = strdup("int");
2613 // look for and make use of esp adjust
2615 if (!pp->is_stdcall && pp->argc_stack > 0)
2616 ret = scan_for_esp_adjust(i + 1, opcnt, &j);
2618 if (pp->is_vararg) {
2619 if (j / 4 < pp->argc_stack)
2620 ferr(po, "esp adjust is too small: %x < %x\n",
2621 j, pp->argc_stack * 4);
2622 // modify pp to make it have varargs as normal args
2624 pp->argc += j / 4 - pp->argc_stack;
2625 for (; arg < pp->argc; arg++) {
2626 pp->arg[arg].type.name = strdup("int");
2629 if (pp->argc > ARRAY_SIZE(pp->arg))
2630 ferr(po, "too many args for '%s'\n", tmpname);
2632 if (pp->argc_stack != j / 4)
2633 ferr(po, "stack tracking failed for '%s': %x %x\n",
2634 tmpname, pp->argc_stack * 4, j);
2636 ops[ret].flags |= OPF_RMD;
2637 // a bit of a hack, but deals with use of
2638 // single adj for multiple calls
2639 ops[ret].operand[1].val -= j;
2641 else if (pp->is_vararg)
2642 ferr(po, "missing esp_adjust for vararg func '%s'\n",
2645 // can't call functions with non-__cdecl callbacks yet
2646 for (arg = 0; arg < pp->argc; arg++) {
2647 if (pp->arg[arg].fptr != NULL) {
2648 pp_tmp = pp->arg[arg].fptr;
2649 if (pp_tmp->is_stdcall || pp_tmp->argc != pp_tmp->argc_stack)
2650 ferr(po, "'%s' has a non-__cdecl callback\n", tmpname);
2654 collect_call_args(po, i, pp, &save_arg_vars,
2655 0, i + opcnt * 2, 0, 0);
2657 if (strstr(pp->ret_type.name, "int64"))
2659 if (!(po->flags & OPF_TAIL) && !IS(pp->ret_type.name, "void"))
2665 // - find POPs for PUSHes, rm both
2666 // - scan for all used registers
2667 // - find flag set ops for their users
2668 // - declare indirect functions
2669 for (i = 0; i < opcnt; i++) {
2671 if (po->flags & OPF_RMD)
2674 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
2675 reg = po->operand[0].reg;
2676 if (!(regmask & (1 << reg)))
2677 // not a reg save after all, rerun scan_for_pop
2678 po->flags &= ~OPF_RSAVE;
2680 regmask_save |= 1 << reg;
2683 if (po->op == OP_PUSH
2684 && po->argnum == 0 && !(po->flags & OPF_RSAVE)
2685 && po->operand[0].type == OPT_REG)
2687 reg = po->operand[0].reg;
2689 ferr(po, "reg not set for push?\n");
2692 ret = scan_for_pop(i + 1, opcnt,
2693 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
2696 ferr(po, "too much depth: %d\n", depth);
2698 po->flags |= OPF_RMD;
2699 scan_for_pop(i + 1, opcnt, po->operand[0].name,
2700 i + opcnt * 4, 0, &depth, 1);
2703 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
2706 if (regmask & (1 << reg)) {
2707 if (regmask_save & (1 << reg))
2708 ferr(po, "%s already saved?\n", po->operand[0].name);
2712 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
2717 regmask_now = po->regmask_src | po->regmask_dst;
2718 if (regmask_now & (1 << xBP)) {
2719 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
2720 if (po->regmask_dst & (1 << xBP))
2721 // compiler decided to drop bp frame and use ebp as scratch
2722 scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
2724 regmask_now &= ~(1 << xBP);
2728 regmask |= regmask_now;
2730 if (po->flags & OPF_CC)
2732 int setters[16], cnt = 0, branched = 0;
2734 ret = scan_for_flag_set(i, i + opcnt * 6,
2735 &branched, setters, &cnt);
2736 if (ret < 0 || cnt <= 0)
2737 ferr(po, "unable to trace flag setter(s)\n");
2738 if (cnt > ARRAY_SIZE(setters))
2739 ferr(po, "too many flag setters\n");
2741 pfo = split_cond(po, po->op, &dummy);
2742 for (j = 0; j < cnt; j++)
2744 tmp_op = &ops[setters[j]]; // flag setter
2747 // to get nicer code, we try to delay test and cmp;
2748 // if we can't because of operand modification, or if we
2749 // have math op, or branch, make it calculate flags explicitly
2750 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
2751 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i) >= 0)
2754 else if (tmp_op->op == OP_CMPS) {
2755 pfomask = 1 << PFO_Z;
2758 // see if we'll be able to handle based on op result
2759 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
2760 && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
2762 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
2766 tmp_op->pfomask |= pfomask;
2767 cmp_result_vars |= pfomask;
2769 // note: may overwrite, currently not a problem
2773 if (po->op == OP_ADC || po->op == OP_SBB)
2774 cmp_result_vars |= 1 << PFO_C;
2776 else if (po->op == OP_MUL
2777 || (po->op == OP_IMUL && po->operand_cnt == 1))
2781 else if (po->op == OP_CALL && po->operand[0].type != OPT_LABEL) {
2783 my_assert_not(pp, NULL);
2784 fprintf(fout, " %s (*icall%d)(", pp->ret_type.name, i);
2785 for (j = 0; j < pp->argc; j++) {
2787 fprintf(fout, ", ");
2788 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
2790 fprintf(fout, ");\n");
2794 // output LUTs/jumptables
2795 for (i = 0; i < g_func_pd_cnt; i++) {
2797 fprintf(fout, " static const ");
2798 if (pd->type == OPT_OFFSET) {
2799 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
2801 for (j = 0; j < pd->count; j++) {
2803 fprintf(fout, ", ");
2804 fprintf(fout, "&&%s", pd->d[j].u.label);
2808 fprintf(fout, "%s %s[] =\n { ",
2809 lmod_type_u(ops, pd->lmod), pd->label);
2811 for (j = 0; j < pd->count; j++) {
2813 fprintf(fout, ", ");
2814 fprintf(fout, "%u", pd->d[j].u.val);
2817 fprintf(fout, " };\n");
2820 // declare stack frame, va_arg
2822 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
2823 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
2825 if (g_func_pp->is_vararg)
2826 fprintf(fout, " va_list ap;\n");
2828 // declare arg-registers
2829 for (i = 0; i < g_func_pp->argc; i++) {
2830 if (g_func_pp->arg[i].reg != NULL) {
2831 reg = char_array_i(regs_r32,
2832 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2834 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2836 regmask_arg |= 1 << reg;
2837 fprintf(fout, " u32 %s = (u32)a%d;\n",
2838 g_func_pp->arg[i].reg, i + 1);
2843 // declare other regs - special case for eax
2844 if (!((regmask | regmask_arg) & 1) && have_func_ret
2845 && !IS(g_func_pp->ret_type.name, "void"))
2847 fprintf(fout, " u32 eax = 0;\n");
2851 regmask &= ~regmask_arg;
2852 regmask &= ~(1 << xSP);
2854 for (reg = 0; reg < 8; reg++) {
2855 if (regmask & (1 << reg)) {
2856 fprintf(fout, " u32 %s;\n", regs_r32[reg]);
2863 for (reg = 0; reg < 8; reg++) {
2864 if (regmask_save & (1 << reg)) {
2865 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
2871 if (save_arg_vars) {
2872 for (reg = 0; reg < 32; reg++) {
2873 if (save_arg_vars & (1 << reg)) {
2874 fprintf(fout, " u32 s_a%d;\n", reg + 1);
2880 if (cmp_result_vars) {
2881 for (i = 0; i < 8; i++) {
2882 if (cmp_result_vars & (1 << i)) {
2883 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
2890 fprintf(fout, " u64 mul_tmp;\n");
2895 fprintf(fout, "\n");
2897 if (g_func_pp->is_vararg) {
2898 if (g_func_pp->argc_stack == 0)
2899 ferr(ops, "vararg func without stack args?\n");
2900 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
2904 for (i = 0; i < opcnt; i++)
2906 if (g_labels[i][0] != 0 && g_label_refs[i].i != -1) {
2907 fprintf(fout, "\n%s:\n", g_labels[i]);
2910 delayed_flag_op = NULL;
2911 last_arith_dst = NULL;
2915 if (po->flags & OPF_RMD)
2920 #define assert_operand_cnt(n_) \
2921 if (po->operand_cnt != n_) \
2922 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
2924 // conditional/flag using op?
2925 if (po->flags & OPF_CC)
2930 pfo = split_cond(po, po->op, &is_inv);
2933 // we go through all this trouble to avoid using parsed_flag_op,
2934 // which makes generated code much nicer
2935 if (delayed_flag_op != NULL)
2937 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
2940 else if (last_arith_dst != NULL
2941 && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
2942 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
2945 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
2946 out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
2947 last_arith_dst->lmod, buf3);
2950 else if (tmp_op != NULL) {
2951 // use preprocessed flag calc results
2952 if (!(tmp_op->pfomask & (1 << pfo)))
2953 ferr(po, "not prepared for pfo %d\n", pfo);
2955 // note: is_inv was not yet applied
2956 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
2957 is_inv ? "!" : "", parsed_flag_op_names[pfo]);
2960 ferr(po, "all methods of finding comparison failed\n");
2963 if (po->flags & OPF_JMP) {
2964 fprintf(fout, " if %s\n", buf1);
2966 else if (po->op == OP_ADC || po->op == OP_SBB) {
2968 fprintf(fout, " cond_%s = %s;\n",
2969 parsed_flag_op_names[pfo], buf1);
2971 else if (po->flags & OPF_DATA) { // SETcc
2972 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
2973 fprintf(fout, " %s = %s;", buf2, buf1);
2976 ferr(po, "unhandled conditional op\n");
2980 pfomask = po->pfomask;
2985 assert_operand_cnt(2);
2986 propagate_lmod(po, &po->operand[0], &po->operand[1]);
2987 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
2988 fprintf(fout, " %s = %s;", buf1,
2989 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
2990 po->operand[0].is_ptr ? "(void *)" : "", 0));
2994 assert_operand_cnt(2);
2995 po->operand[1].lmod = OPLM_DWORD; // always
2996 fprintf(fout, " %s = %s;",
2997 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
2998 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3003 assert_operand_cnt(2);
3004 fprintf(fout, " %s = %s;",
3005 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3006 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3010 assert_operand_cnt(2);
3011 switch (po->operand[1].lmod) {
3013 strcpy(buf3, "(s8)");
3016 strcpy(buf3, "(s16)");
3019 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3021 fprintf(fout, " %s = %s%s;",
3022 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3024 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3028 assert_operand_cnt(1);
3029 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3030 fprintf(fout, " %s = ~%s;", buf1, buf1);
3034 assert_operand_cnt(2);
3035 fprintf(fout, " %s = (s32)%s >> 31;",
3036 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3037 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3038 strcpy(g_comment, "cdq");
3043 assert_operand_cnt(3);
3044 if (po->flags & OPF_REP) {
3045 fprintf(fout, " for (; ecx != 0; ecx--, edi += %d)\n",
3046 lmod_bytes(po, po->operand[0].lmod));
3047 fprintf(fout, " %sedi = eax;",
3048 lmod_cast_u_ptr(po, po->operand[0].lmod));
3049 strcpy(g_comment, "rep stos");
3052 fprintf(fout, " %sedi = eax; edi += %d;",
3053 lmod_cast_u_ptr(po, po->operand[0].lmod),
3054 lmod_bytes(po, po->operand[0].lmod));
3055 strcpy(g_comment, "stos");
3061 assert_operand_cnt(3);
3062 j = lmod_bytes(po, po->operand[0].lmod);
3063 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3064 if (po->flags & OPF_REP) {
3066 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3069 " %sedi = %sesi;", buf1, buf1);
3070 strcpy(g_comment, "rep movs");
3073 fprintf(fout, " %sedi = %sesi; edi += %d; esi += %d;",
3075 strcpy(g_comment, "movs");
3081 // repe ~ repeat while ZF=1
3082 assert_operand_cnt(3);
3083 j = lmod_bytes(po, po->operand[0].lmod);
3084 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3085 if (po->flags & OPF_REP) {
3087 " for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3090 " if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3091 buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3094 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3095 (po->flags & OPF_REPZ) ? "e" : "ne");
3099 " cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3101 strcpy(g_comment, "cmps");
3103 pfomask &= ~(1 << PFO_Z);
3104 last_arith_dst = NULL;
3105 delayed_flag_op = NULL;
3108 // arithmetic w/flags
3113 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3116 assert_operand_cnt(2);
3117 fprintf(fout, " %s %s= %s;",
3118 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3120 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3121 output_std_flags(fout, po, &pfomask, buf1);
3122 last_arith_dst = &po->operand[0];
3123 delayed_flag_op = NULL;
3128 assert_operand_cnt(2);
3129 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3130 if (pfomask & (1 << PFO_C)) {
3131 if (po->operand[1].type == OPT_CONST) {
3132 l = lmod_bytes(po, po->operand[0].lmod) * 8;
3133 j = po->operand[1].val;
3136 if (po->op == OP_SHL)
3140 fprintf(fout, " cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3144 ferr(po, "zero shift?\n");
3148 pfomask &= ~(1 << PFO_C);
3150 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
3151 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3152 output_std_flags(fout, po, &pfomask, buf1);
3153 last_arith_dst = &po->operand[0];
3154 delayed_flag_op = NULL;
3158 assert_operand_cnt(2);
3159 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3160 fprintf(fout, " %s = %s%s >> %s;", buf1,
3161 lmod_cast_s(po, po->operand[0].lmod), buf1,
3162 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3163 output_std_flags(fout, po, &pfomask, buf1);
3164 last_arith_dst = &po->operand[0];
3165 delayed_flag_op = NULL;
3170 assert_operand_cnt(2);
3171 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3172 if (po->operand[1].type == OPT_CONST) {
3173 j = po->operand[1].val;
3174 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3175 fprintf(fout, po->op == OP_ROL ?
3176 " %s = (%s << %d) | (%s >> %d);" :
3177 " %s = (%s >> %d) | (%s << %d);",
3178 buf1, buf1, j, buf1,
3179 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3183 output_std_flags(fout, po, &pfomask, buf1);
3184 last_arith_dst = &po->operand[0];
3185 delayed_flag_op = NULL;
3189 assert_operand_cnt(2);
3190 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3191 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3192 // special case for XOR
3193 fprintf(fout, " %s = 0;",
3194 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3195 last_arith_dst = &po->operand[0];
3196 delayed_flag_op = NULL;
3203 assert_operand_cnt(2);
3204 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3205 if (po->op == OP_SBB
3206 && IS(po->operand[0].name, po->operand[1].name))
3208 // avoid use of unitialized var
3209 fprintf(fout, " %s = -cond_c;",
3210 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3211 // carry remains what it was
3212 pfomask &= ~(1 << PFO_C);
3215 fprintf(fout, " %s %s= %s + cond_c;",
3216 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3218 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3220 last_arith_dst = &po->operand[0];
3221 delayed_flag_op = NULL;
3226 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3227 if (po->operand[0].type == OPT_REG) {
3228 strcpy(buf2, po->op == OP_INC ? "++" : "--");
3229 fprintf(fout, " %s%s;", buf1, buf2);
3232 strcpy(buf2, po->op == OP_INC ? "+" : "-");
3233 fprintf(fout, " %s %s= 1;", buf1, buf2);
3235 last_arith_dst = &po->operand[0];
3236 delayed_flag_op = NULL;
3240 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3241 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3242 fprintf(fout, " %s = -%s%s;", buf1,
3243 lmod_cast_s(po, po->operand[0].lmod), buf2);
3244 last_arith_dst = &po->operand[0];
3245 delayed_flag_op = NULL;
3246 if (pfomask & (1 << PFO_C)) {
3247 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
3248 pfomask &= ~(1 << PFO_C);
3253 if (po->operand_cnt == 2) {
3254 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3257 if (po->operand_cnt == 3)
3258 ferr(po, "TODO imul3\n");
3261 assert_operand_cnt(1);
3262 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3263 fprintf(fout, " mul_tmp = %seax * %s%s;\n", buf1, buf1,
3264 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3265 fprintf(fout, " edx = mul_tmp >> 32;\n");
3266 fprintf(fout, " eax = mul_tmp;");
3267 last_arith_dst = NULL;
3268 delayed_flag_op = NULL;
3273 assert_operand_cnt(1);
3274 if (po->operand[0].lmod != OPLM_DWORD)
3275 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3277 // 32bit division is common, look for it
3278 if (po->op == OP_DIV)
3279 ret = scan_for_reg_clear(i, xDX);
3281 ret = scan_for_cdq_edx(i);
3283 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3284 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3285 po->op == OP_IDIV));
3286 fprintf(fout, " edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3287 fprintf(fout, " eax = %seax / %s%s;", buf2, buf2, buf1);
3290 ferr(po, "TODO 64bit divident\n");
3291 last_arith_dst = NULL;
3292 delayed_flag_op = NULL;
3297 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3299 for (j = 0; j < 8; j++) {
3300 if (pfomask & (1 << j)) {
3301 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3302 fprintf(fout, " cond_%s = %s;",
3303 parsed_flag_op_names[j], buf1);
3310 last_arith_dst = NULL;
3311 delayed_flag_op = po;
3314 // note: we reuse OP_Jcc for SETcc, only flags differ
3315 case OP_JO ... OP_JG:
3316 if (po->flags & OPF_JMP)
3317 fprintf(fout, " goto %s;", po->operand[0].name);
3318 // else SETcc - should already be handled
3322 assert_operand_cnt(1);
3323 last_arith_dst = NULL;
3324 delayed_flag_op = NULL;
3326 if (po->operand[0].type == OPT_REGMEM) {
3327 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3330 ferr(po, "parse failure for jmp '%s'\n",
3331 po->operand[0].name);
3332 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
3335 else if (po->operand[0].type != OPT_LABEL)
3336 ferr(po, "unhandled jmp type\n");
3338 fprintf(fout, " goto %s;", po->operand[0].name);
3342 assert_operand_cnt(1);
3345 ferr(po, "NULL pp\n");
3347 if (po->operand[0].type != OPT_LABEL)
3348 fprintf(fout, " icall%d = (void *)%s;\n", i,
3349 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]));
3352 if (strstr(pp->ret_type.name, "int64")) {
3353 if (po->flags & OPF_TAIL)
3354 ferr(po, "int64 and tail?\n");
3355 fprintf(fout, "mul_tmp = ");
3357 else if (!IS(pp->ret_type.name, "void")) {
3358 if (po->flags & OPF_TAIL) {
3359 if (!IS(g_func_pp->ret_type.name, "void")) {
3360 fprintf(fout, "return ");
3361 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3362 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3366 fprintf(fout, "eax = ");
3367 if (pp->ret_type.is_ptr)
3368 fprintf(fout, "(u32)");
3372 if (po->operand[0].type != OPT_LABEL) {
3373 fprintf(fout, "icall%d(", i);
3376 if (pp->name[0] == 0)
3377 ferr(po, "missing pp->name\n");
3378 fprintf(fout, "%s%s(", pp->name,
3379 pp->has_structarg ? "_sa" : "");
3382 for (arg = 0; arg < pp->argc; arg++) {
3384 fprintf(fout, ", ");
3387 if (pp->arg[arg].type.is_ptr)
3388 snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3390 if (pp->arg[arg].reg != NULL) {
3391 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3396 tmp_op = pp->arg[arg].datap;
3398 ferr(po, "parsed_op missing for arg%d\n", arg);
3399 if (tmp_op->argnum != 0) {
3400 fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3404 out_src_opr(buf1, sizeof(buf1),
3405 tmp_op, &tmp_op->operand[0], cast, 0));
3408 fprintf(fout, ");");
3410 if (strstr(pp->ret_type.name, "int64")) {
3411 fprintf(fout, "\n");
3412 fprintf(fout, " edx = mul_tmp >> 32;\n");
3413 fprintf(fout, " eax = mul_tmp;");
3416 if (po->flags & OPF_TAIL) {
3417 strcpy(g_comment, "tailcall");
3421 else if (IS(pp->ret_type.name, "void"))
3423 else if (IS(g_func_pp->ret_type.name, "void"))
3425 // else already handled as 'return f()'
3428 fprintf(fout, "\n return;");
3429 strcpy(g_comment, "^ tailcall");
3432 delayed_flag_op = NULL;
3433 last_arith_dst = NULL;
3437 if (g_func_pp->is_vararg)
3438 fprintf(fout, " va_end(ap);\n");
3440 if (IS(g_func_pp->ret_type.name, "void")) {
3441 if (i != opcnt - 1 || label_pending)
3442 fprintf(fout, " return;");
3444 else if (g_func_pp->ret_type.is_ptr) {
3445 fprintf(fout, " return (%s)eax;",
3446 g_func_pp->ret_type.name);
3449 fprintf(fout, " return eax;");
3451 last_arith_dst = NULL;
3452 delayed_flag_op = NULL;
3456 if (po->argnum != 0) {
3457 // special case - saved func arg
3458 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3459 fprintf(fout, " s_a%d = %s;", po->argnum, buf1);
3462 else if (po->flags & OPF_RSAVE) {
3463 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3464 fprintf(fout, " s_%s = %s;", buf1, buf1);
3467 if (!(g_ida_func_attr & IDAFA_NORETURN))
3468 ferr(po, "stray push encountered\n");
3473 if (po->flags & OPF_RSAVE) {
3474 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3475 fprintf(fout, " %s = s_%s;", buf1, buf1);
3478 ferr(po, "stray pop encountered\n");
3487 ferr(po, "unhandled op type %d, flags %x\n",
3492 if (g_comment[0] != 0) {
3493 fprintf(fout, " // %s", g_comment);
3498 fprintf(fout, "\n");
3500 // some sanity checking
3501 if ((po->flags & OPF_REP) && po->op != OP_STOS
3502 && po->op != OP_MOVS && po->op != OP_CMPS)
3503 ferr(po, "unexpected rep\n");
3504 if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3505 ferr(po, "unexpected repz/repnz\n");
3508 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3510 // see is delayed flag stuff is still valid
3511 if (delayed_flag_op != NULL && delayed_flag_op != po) {
3512 if (is_any_opr_modified(delayed_flag_op, po))
3513 delayed_flag_op = NULL;
3516 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3517 if (is_opr_modified(last_arith_dst, po))
3518 last_arith_dst = NULL;
3524 fprintf(fout, "}\n\n");
3527 for (i = 0; i < opcnt; i++) {
3528 struct label_ref *lr, *lr_del;
3530 lr = g_label_refs[i].next;
3531 while (lr != NULL) {
3536 g_label_refs[i].i = -1;
3537 g_label_refs[i].next = NULL;
3539 if (ops[i].op == OP_CALL) {
3548 static void set_label(int i, const char *name)
3554 p = strchr(name, ':');
3558 if (len > sizeof(g_labels[0]) - 1)
3559 aerr("label '%s' too long: %d\n", name, len);
3560 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
3561 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
3562 memcpy(g_labels[i], name, len);
3563 g_labels[i][len] = 0;
3566 // '=' needs special treatment..
3567 static char *next_word_s(char *w, size_t wsize, char *s)
3573 for (i = 0; i < wsize - 1; i++) {
3574 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
3580 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
3581 printf("warning: '%s' truncated\n", w);
3592 static struct chunk_item *func_chunks;
3593 static int func_chunk_cnt;
3594 static int func_chunk_alloc;
3596 static void add_func_chunk(FILE *fasm, const char *name, int line)
3598 if (func_chunk_cnt >= func_chunk_alloc) {
3599 func_chunk_alloc *= 2;
3600 func_chunks = realloc(func_chunks,
3601 func_chunk_alloc * sizeof(func_chunks[0]));
3602 my_assert_not(func_chunks, NULL);
3604 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
3605 func_chunks[func_chunk_cnt].name = strdup(name);
3606 func_chunks[func_chunk_cnt].asmln = line;
3610 static int cmp_chunks(const void *p1, const void *p2)
3612 const struct chunk_item *c1 = p1, *c2 = p2;
3613 return strcmp(c1->name, c2->name);
3616 static int cmpstringp(const void *p1, const void *p2)
3618 return strcmp(*(char * const *)p1, *(char * const *)p2);
3621 static void scan_ahead(FILE *fasm)
3631 oldpos = ftell(fasm);
3634 while (fgets(line, sizeof(line), fasm))
3645 // get rid of random tabs
3646 for (i = 0; line[i] != 0; i++)
3647 if (line[i] == '\t')
3650 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3653 next_word(words[0], sizeof(words[0]), p);
3654 if (words[0][0] == 0)
3655 aerr("missing name for func chunk?\n");
3657 add_func_chunk(fasm, words[0], asmln);
3662 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3663 words[wordc][0] = 0;
3664 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3665 if (*p == 0 || *p == ';') {
3671 if (wordc == 2 && IS(words[1], "ends"))
3675 fseek(fasm, oldpos, SEEK_SET);
3679 int main(int argc, char *argv[])
3681 FILE *fout, *fasm, *frlist;
3682 struct parsed_data *pd = NULL;
3684 char **rlist = NULL;
3686 int rlist_alloc = 0;
3687 int func_chunks_used = 0;
3688 int func_chunks_sorted = 0;
3689 int func_chunk_i = -1;
3690 long func_chunk_ret = 0;
3691 int func_chunk_ret_ln = 0;
3692 int scanned_ahead = 0;
3694 char words[16][256];
3695 enum opr_lenmod lmod;
3697 int pending_endp = 0;
3699 int skip_warned = 0;
3710 if (argv[1] && IS(argv[1], "-v")) {
3715 if (argc < arg + 3) {
3716 printf("usage:\n%s [-v] <.c> <.asm> <hdrf> [rlist]*\n",
3723 asmfn = argv[arg++];
3724 fasm = fopen(asmfn, "r");
3725 my_assert_not(fasm, NULL);
3727 hdrfn = argv[arg++];
3728 g_fhdr = fopen(hdrfn, "r");
3729 my_assert_not(g_fhdr, NULL);
3732 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
3733 my_assert_not(rlist, NULL);
3734 // needs special handling..
3735 rlist[rlist_len++] = "__alloca_probe";
3737 func_chunk_alloc = 32;
3738 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
3739 my_assert_not(func_chunks, NULL);
3741 for (; arg < argc; arg++) {
3742 frlist = fopen(argv[arg], "r");
3743 my_assert_not(frlist, NULL);
3745 while (fgets(line, sizeof(line), frlist)) {
3747 if (*p == 0 || *p == ';' || *p == '#')
3750 p = next_word(words[0], sizeof(words[0]), p);
3751 if (words[0][0] == 0)
3754 if (rlist_len >= rlist_alloc) {
3755 rlist_alloc = rlist_alloc * 2 + 64;
3756 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
3757 my_assert_not(rlist, NULL);
3759 rlist[rlist_len++] = strdup(words[0]);
3767 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
3769 fout = fopen(argv[arg_out], "w");
3770 my_assert_not(fout, NULL);
3773 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
3774 my_assert_not(g_eqs, NULL);
3776 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
3777 g_label_refs[i].i = -1;
3778 g_label_refs[i].next = NULL;
3781 while (fgets(line, sizeof(line), fasm))
3790 // get rid of random tabs
3791 for (i = 0; line[i] != 0; i++)
3792 if (line[i] == '\t')
3797 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
3798 goto do_pending_endp; // eww..
3800 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
3802 static const char *attrs[] = {
3811 // parse IDA's attribute-list comment
3812 g_ida_func_attr = 0;
3815 for (; *p != 0; p = sskip(p)) {
3816 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
3817 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
3818 g_ida_func_attr |= 1 << i;
3819 p += strlen(attrs[i]);
3823 if (i == ARRAY_SIZE(attrs)) {
3824 anote("unparsed IDA attr: %s\n", p);
3827 if (IS(attrs[i], "fpd=")) {
3828 p = next_word(words[0], sizeof(words[0]), p);
3833 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
3836 next_word(words[0], sizeof(words[0]), p);
3837 if (words[0][0] == 0)
3838 aerr("missing name for func chunk?\n");
3840 if (!scanned_ahead) {
3841 add_func_chunk(fasm, words[0], asmln);
3842 func_chunks_sorted = 0;
3845 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
3847 if (func_chunk_i >= 0) {
3848 if (func_chunk_i < func_chunk_cnt
3849 && IS(func_chunks[func_chunk_i].name, g_func))
3851 // move on to next chunk
3852 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
3854 aerr("seek failed for '%s' chunk #%d\n",
3855 g_func, func_chunk_i);
3856 asmln = func_chunks[func_chunk_i].asmln;
3860 if (func_chunk_ret == 0)
3861 aerr("no return from chunk?\n");
3862 fseek(fasm, func_chunk_ret, SEEK_SET);
3863 asmln = func_chunk_ret_ln;
3869 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
3870 func_chunks_used = 1;
3872 if (IS_START(g_func, "sub_")) {
3873 unsigned long addr = strtoul(p, NULL, 16);
3874 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
3875 if (addr > f_addr && !scanned_ahead) {
3876 anote("scan_ahead caused by '%s', addr %lx\n",
3880 func_chunks_sorted = 0;
3888 memset(words, 0, sizeof(words));
3889 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
3890 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
3891 if (*p == 0 || *p == ';') {
3897 // alow asm patches in comments
3898 if (*p == ';' && IS_START(p, "; sctpatch:")) {
3900 if (*p == 0 || *p == ';')
3902 goto parse_words; // lame
3907 awarn("wordc == 0?\n");
3911 // don't care about this:
3912 if (words[0][0] == '.'
3913 || IS(words[0], "include")
3914 || IS(words[0], "assume") || IS(words[1], "segment")
3915 || IS(words[0], "align"))
3921 // do delayed endp processing to collect switch jumptables
3923 if (in_func && !skip_func && wordc >= 2
3924 && ((words[0][0] == 'd' && words[0][2] == 0)
3925 || (words[1][0] == 'd' && words[1][2] == 0)))
3928 if (words[1][0] == 'd' && words[1][2] == 0) {
3930 if (g_func_pd_cnt >= pd_alloc) {
3931 pd_alloc = pd_alloc * 2 + 16;
3932 g_func_pd = realloc(g_func_pd,
3933 sizeof(g_func_pd[0]) * pd_alloc);
3934 my_assert_not(g_func_pd, NULL);
3936 pd = &g_func_pd[g_func_pd_cnt];
3938 memset(pd, 0, sizeof(*pd));
3939 strcpy(pd->label, words[0]);
3940 pd->type = OPT_CONST;
3941 pd->lmod = lmod_from_directive(words[1]);
3945 lmod = lmod_from_directive(words[0]);
3946 if (lmod != pd->lmod)
3947 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
3950 if (pd->count_alloc < pd->count + wordc) {
3951 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
3952 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
3953 my_assert_not(pd->d, NULL);
3955 for (; i < wordc; i++) {
3956 if (IS(words[i], "offset")) {
3957 pd->type = OPT_OFFSET;
3960 p = strchr(words[i], ',');
3963 if (pd->type == OPT_OFFSET)
3964 pd->d[pd->count].u.label = strdup(words[i]);
3966 pd->d[pd->count].u.val = parse_number(words[i]);
3967 pd->d[pd->count].bt_i = -1;
3973 if (in_func && !skip_func)
3974 gen_func(fout, g_fhdr, g_func, pi);
3978 g_ida_func_attr = 0;
3982 func_chunks_used = 0;
3985 memset(&ops, 0, pi * sizeof(ops[0]));
3986 memset(g_labels, 0, pi * sizeof(g_labels[0]));
3990 for (i = 0; i < g_func_pd_cnt; i++) {
3992 if (pd->type == OPT_OFFSET) {
3993 for (j = 0; j < pd->count; j++)
3994 free(pd->d[j].u.label);
4005 if (IS(words[1], "proc")) {
4007 aerr("proc '%s' while in_func '%s'?\n",
4010 if ((g_ida_func_attr & IDAFA_THUNK)
4011 || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4013 strcpy(g_func, words[0]);
4014 set_label(0, words[0]);
4019 if (IS(words[1], "endp"))
4022 aerr("endp '%s' while not in_func?\n", words[0]);
4023 if (!IS(g_func, words[0]))
4024 aerr("endp '%s' while in_func '%s'?\n",
4027 if (!skip_func && func_chunks_used) {
4028 // start processing chunks
4029 struct chunk_item *ci, key = { g_func, 0 };
4031 func_chunk_ret = ftell(fasm);
4032 func_chunk_ret_ln = asmln;
4033 if (!func_chunks_sorted) {
4034 qsort(func_chunks, func_chunk_cnt,
4035 sizeof(func_chunks[0]), cmp_chunks);
4036 func_chunks_sorted = 1;
4038 ci = bsearch(&key, func_chunks, func_chunk_cnt,
4039 sizeof(func_chunks[0]), cmp_chunks);
4041 aerr("'%s' needs chunks, but none found\n", g_func);
4042 func_chunk_i = ci - func_chunks;
4043 for (; func_chunk_i > 0; func_chunk_i--)
4044 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4047 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4049 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4050 asmln = func_chunks[func_chunk_i].asmln;
4058 p = strchr(words[0], ':');
4060 set_label(pi, words[0]);
4064 if (!in_func || skip_func) {
4065 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4067 anote("skipping from '%s'\n", g_labels[pi]);
4070 g_labels[pi][0] = 0;
4074 if (wordc > 1 && IS(words[1], "=")) {
4076 aerr("unhandled equ, wc=%d\n", wordc);
4077 if (g_eqcnt >= eq_alloc) {
4079 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4080 my_assert_not(g_eqs, NULL);
4083 len = strlen(words[0]);
4084 if (len > sizeof(g_eqs[0].name) - 1)
4085 aerr("equ name too long: %d\n", len);
4086 strcpy(g_eqs[g_eqcnt].name, words[0]);
4088 if (!IS(words[3], "ptr"))
4089 aerr("unhandled equ\n");
4090 if (IS(words[2], "dword"))
4091 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4092 else if (IS(words[2], "word"))
4093 g_eqs[g_eqcnt].lmod = OPLM_WORD;
4094 else if (IS(words[2], "byte"))
4095 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4097 aerr("bad lmod: '%s'\n", words[2]);
4099 g_eqs[g_eqcnt].offset = parse_number(words[4]);
4104 if (pi >= ARRAY_SIZE(ops))
4105 aerr("too many ops\n");
4107 parse_op(&ops[pi], words, wordc);
4118 // vim:ts=2:shiftwidth=2:expandtab