5 * This work is licensed under the terms of 3-clause BSD license.
6 * See COPYING file in the top-level directory.
14 #include "my_assert.h"
17 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
18 #define IS(w, y) !strcmp(w, y)
19 #define IS_START(w, y) !strncmp(w, y, strlen(y))
21 #include "protoparse.h"
23 static const char *asmfn;
27 #define anote(fmt, ...) \
28 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
29 #define awarn(fmt, ...) \
30 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
31 #define aerr(fmt, ...) do { \
32 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
37 #include "masm_tools.h"
40 OPF_RMD = (1 << 0), /* removed or optimized out */
41 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
42 OPF_FLAGS = (1 << 2), /* sets flags */
43 OPF_JMP = (1 << 3), /* branch, call */
44 OPF_CJMP = (1 << 4), /* cond. branch (cc or jecxz) */
45 OPF_CC = (1 << 5), /* uses flags */
46 OPF_TAIL = (1 << 6), /* ret or tail call */
47 OPF_RSAVE = (1 << 7), /* push/pop is local reg save/load */
48 OPF_REP = (1 << 8), /* prefixed by rep */
49 OPF_REPZ = (1 << 9), /* rep is repe/repz */
50 OPF_REPNZ = (1 << 10), /* rep is repne/repnz */
51 OPF_FARG = (1 << 11), /* push collected as func arg (no reuse) */
52 OPF_EBP_S = (1 << 12), /* ebp used as scratch here, not BP */
53 OPF_DF = (1 << 13), /* DF flag set */
54 OPF_ATAIL = (1 << 14), /* tail call with reused arg frame */
55 OPF_32BIT = (1 << 15), /* 32bit division */
56 OPF_LOCK = (1 << 16), /* op has lock prefix */
57 OPF_VAPUSH = (1 << 17), /* vararg ptr push (as call arg) */
125 // must be sorted (larger len must be further in enum)
134 #define MAX_OPERANDS 3
138 enum opr_lenmod lmod;
139 unsigned int is_ptr:1; // pointer in C
140 unsigned int is_array:1; // array in C
141 unsigned int type_from_var:1; // .. in header, sometimes wrong
142 unsigned int size_mismatch:1; // type override differs from C
143 unsigned int size_lt:1; // type override is larger than C
144 unsigned int had_ds:1; // had ds: prefix
145 const struct parsed_proto *pp; // for OPT_LABEL
153 struct parsed_opr operand[MAX_OPERANDS];
156 unsigned char pfo_inv;
157 unsigned char operand_cnt;
158 unsigned char p_argnum; // push: altered before call arg #
159 unsigned char p_argpass;// push: arg of host func
160 unsigned char pad[3];
161 int regmask_src; // all referensed regs
163 int pfomask; // flagop: parsed_flag_op that can't be delayed
164 int cc_scratch; // scratch storage during analysis
165 int bt_i; // branch target for branches
166 struct parsed_data *btj;// branch targets for jumptables
167 struct parsed_proto *pp;// parsed_proto for OP_CALL
173 // OP_CALL - parser proto hint (str)
174 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
175 // OP_POP - point to OP_PUSH in push/pop pair
179 enum opr_lenmod lmod;
186 enum opr_lenmod lmod;
200 struct label_ref *next;
204 IDAFA_BP_FRAME = (1 << 0),
205 IDAFA_LIB_FUNC = (1 << 1),
206 IDAFA_STATIC = (1 << 2),
207 IDAFA_NORETURN = (1 << 3),
208 IDAFA_THUNK = (1 << 4),
209 IDAFA_FPD = (1 << 5),
214 static struct parsed_op ops[MAX_OPS];
215 static struct parsed_equ *g_eqs;
217 static char g_labels[MAX_OPS][48];
218 static struct label_ref g_label_refs[MAX_OPS];
219 static const struct parsed_proto *g_func_pp;
220 static struct parsed_data *g_func_pd;
221 static int g_func_pd_cnt;
222 static char g_func[256];
223 static char g_comment[256];
224 static int g_bp_frame;
225 static int g_sp_frame;
226 static int g_stack_frame_used;
227 static int g_stack_fsz;
228 static int g_ida_func_attr;
229 static int g_allow_regfunc;
230 #define ferr(op_, fmt, ...) do { \
231 printf("%s:%d: error: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
232 dump_op(op_), ##__VA_ARGS__); \
236 #define fnote(op_, fmt, ...) \
237 printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
238 dump_op(op_), ##__VA_ARGS__)
240 const char *regs_r32[] = {
241 "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
242 // not r32, but list here for easy parsing and printing
243 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
245 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
246 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
247 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
249 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
251 // possible basic comparison types (without inversion)
252 enum parsed_flag_op {
256 PFO_BE, // 6 CF=1||ZF=1
260 PFO_LE, // e ZF=1||SF!=OF
263 #define PFOB_O (1 << PFO_O)
264 #define PFOB_C (1 << PFO_C)
265 #define PFOB_Z (1 << PFO_Z)
266 #define PFOB_S (1 << PFO_S)
268 static const char *parsed_flag_op_names[] = {
269 "o", "c", "z", "be", "s", "p", "l", "le"
272 static int char_array_i(const char *array[], size_t len, const char *s)
276 for (i = 0; i < len; i++)
283 static void printf_number(char *buf, size_t buf_size,
284 unsigned long number)
286 // output in C-friendly form
287 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
290 static int check_segment_prefix(const char *s)
292 if (s[0] == 0 || s[1] != 's' || s[2] != ':')
306 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
310 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
312 *reg_lmod = OPLM_QWORD;
316 *reg_lmod = OPLM_DWORD;
319 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
321 *reg_lmod = OPLM_WORD;
324 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
326 *reg_lmod = OPLM_BYTE;
329 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
331 *reg_lmod = OPLM_BYTE;
338 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
340 enum opr_lenmod lmod;
353 while (my_isblank(*s))
355 for (; my_issep(*s); d++, s++)
357 while (my_isblank(*s))
361 // skip '?s:' prefixes
362 if (check_segment_prefix(s))
365 s = next_idt(w, sizeof(w), s);
370 reg = parse_reg(&lmod, w);
372 *regmask |= 1 << reg;
376 if ('0' <= w[0] && w[0] <= '9') {
377 number = parse_number(w);
378 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
382 // probably some label/identifier - pass
385 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
389 strcpy(name, cvtbuf);
394 static int is_reg_in_str(const char *s)
398 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
401 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
402 if (!strncmp(s, regs_r32[i], 3))
408 static const char *parse_stack_el(const char *name, char *extra_reg,
411 const char *p, *p2, *s;
417 if (g_bp_frame || early_try)
420 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
422 if (extra_reg != NULL) {
423 strncpy(extra_reg, name, 3);
428 if (IS_START(p, "ebp+")) {
432 if (p2 != NULL && is_reg_in_str(p)) {
433 if (extra_reg != NULL) {
434 strncpy(extra_reg, p, p2 - p);
435 extra_reg[p2 - p] = 0;
440 if (!('0' <= *p && *p <= '9'))
447 if (!IS_START(name, "esp+"))
453 if (is_reg_in_str(s)) {
454 if (extra_reg != NULL) {
455 strncpy(extra_reg, s, p - s);
456 extra_reg[p - s] = 0;
461 aerr("%s IDA stackvar not set?\n", __func__);
463 if (!('0' <= *s && *s <= '9')) {
464 aerr("%s IDA stackvar offset not set?\n", __func__);
467 if (s[0] == '0' && s[1] == 'x')
470 if (len < sizeof(buf) - 1) {
471 strncpy(buf, s, len);
473 val = strtol(buf, &endp, 16);
474 if (val == 0 || *endp != 0) {
475 aerr("%s num parse fail for '%s'\n", __func__, buf);
484 if ('0' <= *p && *p <= '9')
490 static int guess_lmod_from_name(struct parsed_opr *opr)
492 if (!strncmp(opr->name, "dword_", 6)) {
493 opr->lmod = OPLM_DWORD;
496 if (!strncmp(opr->name, "word_", 5)) {
497 opr->lmod = OPLM_WORD;
500 if (!strncmp(opr->name, "byte_", 5)) {
501 opr->lmod = OPLM_BYTE;
504 if (!strncmp(opr->name, "qword_", 6)) {
505 opr->lmod = OPLM_QWORD;
511 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
512 const struct parsed_type *c_type)
514 static const char *dword_types[] = {
515 "int", "_DWORD", "UINT_PTR", "DWORD",
516 "WPARAM", "LPARAM", "UINT", "__int32",
517 "LONG", "HIMC", "BOOL", "size_t",
520 static const char *word_types[] = {
521 "uint16_t", "int16_t", "_WORD", "WORD",
522 "unsigned __int16", "__int16",
524 static const char *byte_types[] = {
525 "uint8_t", "int8_t", "char",
526 "unsigned __int8", "__int8", "BYTE", "_BYTE",
528 // structures.. deal the same as with _UNKNOWN for now
534 if (c_type->is_ptr) {
539 n = skip_type_mod(c_type->name);
541 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
542 if (IS(n, dword_types[i])) {
548 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
549 if (IS(n, word_types[i])) {
555 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
556 if (IS(n, byte_types[i])) {
565 static char *default_cast_to(char *buf, size_t buf_size,
566 struct parsed_opr *opr)
572 if (opr->pp == NULL || opr->pp->type.name == NULL
575 snprintf(buf, buf_size, "%s", "(void *)");
579 snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
583 static enum opr_type lmod_from_directive(const char *d)
587 else if (IS(d, "dw"))
589 else if (IS(d, "db"))
592 aerr("unhandled directive: '%s'\n", d);
596 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
602 *regmask |= 1 << reg;
605 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
608 static int parse_operand(struct parsed_opr *opr,
609 int *regmask, int *regmask_indirect,
610 char words[16][256], int wordc, int w, unsigned int op_flags)
612 const struct parsed_proto *pp;
613 enum opr_lenmod tmplmod;
614 unsigned long number;
622 aerr("parse_operand w %d, wordc %d\n", w, wordc);
626 for (i = w; i < wordc; i++) {
627 len = strlen(words[i]);
628 if (words[i][len - 1] == ',') {
629 words[i][len - 1] = 0;
635 wordc_in = wordc - w;
637 if ((op_flags & OPF_JMP) && wordc_in > 0
638 && !('0' <= words[w][0] && words[w][0] <= '9'))
640 const char *label = NULL;
642 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
643 && IS(words[w + 1], "ptr"))
644 label = words[w + 2];
645 else if (wordc_in == 2 && IS(words[w], "short"))
646 label = words[w + 1];
647 else if (wordc_in == 1
648 && strchr(words[w], '[') == NULL
649 && parse_reg(&tmplmod, words[w]) < 0)
653 opr->type = OPT_LABEL;
654 ret = check_segment_prefix(label);
657 aerr("fs/gs used\n");
661 strcpy(opr->name, label);
667 if (IS(words[w + 1], "ptr")) {
668 if (IS(words[w], "dword"))
669 opr->lmod = OPLM_DWORD;
670 else if (IS(words[w], "word"))
671 opr->lmod = OPLM_WORD;
672 else if (IS(words[w], "byte"))
673 opr->lmod = OPLM_BYTE;
674 else if (IS(words[w], "qword"))
675 opr->lmod = OPLM_QWORD;
677 aerr("type parsing failed\n");
679 wordc_in = wordc - w;
684 if (IS(words[w], "offset")) {
685 opr->type = OPT_OFFSET;
686 opr->lmod = OPLM_DWORD;
687 strcpy(opr->name, words[w + 1]);
688 pp = proto_parse(g_fhdr, opr->name, 1);
691 if (IS(words[w], "(offset")) {
692 p = strchr(words[w + 1], ')');
694 aerr("parse of bracketed offset failed\n");
696 opr->type = OPT_OFFSET;
697 strcpy(opr->name, words[w + 1]);
703 aerr("parse_operand 1 word expected\n");
705 ret = check_segment_prefix(words[w]);
708 aerr("fs/gs used\n");
710 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
712 strcpy(opr->name, words[w]);
714 if (words[w][0] == '[') {
715 opr->type = OPT_REGMEM;
716 ret = sscanf(words[w], "[%[^]]]", opr->name);
718 aerr("[] parse failure\n");
720 parse_indmode(opr->name, regmask_indirect, 1);
721 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
724 struct parsed_equ *eq =
725 equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
727 opr->lmod = eq->lmod;
731 else if (strchr(words[w], '[')) {
733 p = strchr(words[w], '[');
734 opr->type = OPT_REGMEM;
735 parse_indmode(p, regmask_indirect, 0);
736 strncpy(buf, words[w], p - words[w]);
737 buf[p - words[w]] = 0;
738 pp = proto_parse(g_fhdr, buf, 1);
741 else if (('0' <= words[w][0] && words[w][0] <= '9')
742 || words[w][0] == '-')
744 number = parse_number(words[w]);
745 opr->type = OPT_CONST;
747 printf_number(opr->name, sizeof(opr->name), number);
751 ret = parse_reg(&tmplmod, opr->name);
753 setup_reg_opr(opr, ret, tmplmod, regmask);
757 // most likely var in data segment
758 opr->type = OPT_LABEL;
759 pp = proto_parse(g_fhdr, opr->name, 0);
763 if (pp->is_fptr || pp->is_func) {
764 opr->lmod = OPLM_DWORD;
768 tmplmod = OPLM_UNSPEC;
769 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
770 anote("unhandled C type '%s' for '%s'\n",
771 pp->type.name, opr->name);
773 if (opr->lmod == OPLM_UNSPEC) {
775 opr->type_from_var = 1;
777 else if (opr->lmod != tmplmod) {
778 opr->size_mismatch = 1;
779 if (tmplmod < opr->lmod)
782 opr->is_ptr = pp->type.is_ptr;
784 opr->is_array = pp->type.is_array;
788 if (opr->lmod == OPLM_UNSPEC)
789 guess_lmod_from_name(opr);
793 static const struct {
798 { "repe", OPF_REP|OPF_REPZ },
799 { "repz", OPF_REP|OPF_REPZ },
800 { "repne", OPF_REP|OPF_REPNZ },
801 { "repnz", OPF_REP|OPF_REPNZ },
802 { "lock", OPF_LOCK }, // ignored for now..
805 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
807 static const struct {
810 unsigned short minopr;
811 unsigned short maxopr;
814 unsigned char pfo_inv;
816 { "nop", OP_NOP, 0, 0, 0 },
817 { "push", OP_PUSH, 1, 1, 0 },
818 { "pop", OP_POP, 1, 1, OPF_DATA },
819 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
820 { "mov" , OP_MOV, 2, 2, OPF_DATA },
821 { "lea", OP_LEA, 2, 2, OPF_DATA },
822 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
823 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
824 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
825 { "not", OP_NOT, 1, 1, OPF_DATA },
826 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
827 { "lodsb",OP_LODS, 0, 0, OPF_DATA },
828 { "lodsw",OP_LODS, 0, 0, OPF_DATA },
829 { "lodsd",OP_LODS, 0, 0, OPF_DATA },
830 { "stosb",OP_STOS, 0, 0, OPF_DATA },
831 { "stosw",OP_STOS, 0, 0, OPF_DATA },
832 { "stosd",OP_STOS, 0, 0, OPF_DATA },
833 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
834 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
835 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
836 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
837 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
838 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
839 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
840 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
841 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
842 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
843 { "cld", OP_CLD, 0, 0, OPF_DATA },
844 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
845 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
846 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
847 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
848 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
849 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
850 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
851 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
852 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
853 { "shrd", OP_SHRD, 3, 3, OPF_DATA|OPF_FLAGS },
854 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
855 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
856 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
857 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
858 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
859 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
860 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
861 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
862 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
863 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
864 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
865 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
866 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
867 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
868 { "test", OP_TEST, 2, 2, OPF_FLAGS },
869 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
870 { "retn", OP_RET, 0, 1, OPF_TAIL },
871 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
872 { "jmp", OP_JMP, 1, 1, OPF_JMP },
873 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
874 { "jo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 0 }, // 70 OF=1
875 { "jno", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 1 }, // 71 OF=0
876 { "jc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72 CF=1
877 { "jb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72
878 { "jnc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73 CF=0
879 { "jnb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
880 { "jae", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
881 { "jz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74 ZF=1
882 { "je", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74
883 { "jnz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75 ZF=0
884 { "jne", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75
885 { "jbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
886 { "jna", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
887 { "ja", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
888 { "jnbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
889 { "js", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 0 }, // 78 SF=1
890 { "jns", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 1 }, // 79 SF=0
891 { "jp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a PF=1
892 { "jpe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a
893 { "jnp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b PF=0
894 { "jpo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b
895 { "jl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c SF!=OF
896 { "jnge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c
897 { "jge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d SF=OF
898 { "jnl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d
899 { "jle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
900 { "jng", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
901 { "jg", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
902 { "jnle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
903 { "seto", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 0 },
904 { "setno", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 1 },
905 { "setc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
906 { "setb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
907 { "setnc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
908 { "setae", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
909 { "setnb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
910 { "setz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
911 { "sete", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
912 { "setnz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
913 { "setne", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
914 { "setbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
915 { "setna", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
916 { "seta", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
917 { "setnbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
918 { "sets", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 0 },
919 { "setns", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 1 },
920 { "setp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
921 { "setpe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
922 { "setnp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
923 { "setpo", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
924 { "setl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
925 { "setnge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
926 { "setge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
927 { "setnl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
928 { "setle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
929 { "setng", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
930 { "setg", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
931 { "setnle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
934 { "emms", OP_EMMS, 0, 0, OPF_DATA },
935 { "movq", OP_MOV, 2, 2, OPF_DATA },
938 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
940 enum opr_lenmod lmod = OPLM_UNSPEC;
941 int prefix_flags = 0;
949 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
950 if (IS(words[w], pref_table[i].name)) {
951 prefix_flags = pref_table[i].flags;
958 aerr("lone prefix: '%s'\n", words[0]);
963 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
964 if (IS(words[w], op_table[i].name))
968 if (i == ARRAY_SIZE(op_table))
969 aerr("unhandled op: '%s'\n", words[0]);
972 op->op = op_table[i].op;
973 op->flags = op_table[i].flags | prefix_flags;
974 op->pfo = op_table[i].pfo;
975 op->pfo_inv = op_table[i].pfo_inv;
976 op->regmask_src = op->regmask_dst = 0;
979 for (opr = 0; opr < op_table[i].minopr; opr++) {
980 regmask = regmask_ind = 0;
981 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
982 words, wordc, w, op->flags);
984 if (opr == 0 && (op->flags & OPF_DATA))
985 op->regmask_dst = regmask;
986 // for now, mark dst as src too
987 op->regmask_src |= regmask | regmask_ind;
990 for (; w < wordc && opr < op_table[i].maxopr; opr++) {
991 w = parse_operand(&op->operand[opr],
992 &op->regmask_src, &op->regmask_src,
993 words, wordc, w, op->flags);
997 aerr("parse_op %s incomplete: %d/%d\n",
1001 op->operand_cnt = opr;
1002 if (!strncmp(op_table[i].name, "set", 3))
1003 op->operand[0].lmod = OPLM_BYTE;
1005 // ops with implicit argumets
1008 op->operand_cnt = 2;
1009 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1010 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1016 if (op->operand_cnt != 0)
1018 if (words[op_w][4] == 'b')
1020 else if (words[op_w][4] == 'w')
1022 else if (words[op_w][4] == 'd')
1024 op->operand_cnt = 3;
1025 setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1026 lmod, &op->regmask_src);
1027 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1028 op->regmask_dst = op->regmask_src;
1029 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1030 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1035 if (op->operand_cnt != 0)
1037 if (words[op_w][4] == 'b')
1039 else if (words[op_w][4] == 'w')
1041 else if (words[op_w][4] == 'd')
1043 op->operand_cnt = 3;
1044 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1045 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1046 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1047 op->regmask_dst = op->regmask_src;
1051 op->regmask_src |= op->regmask_dst;
1052 op->regmask_dst |= op->regmask_src;
1056 op->operand_cnt = 1;
1057 op->regmask_src = 1 << xCX;
1058 op->operand[0].type = OPT_REG;
1059 op->operand[0].reg = xCX;
1060 op->operand[0].lmod = OPLM_DWORD;
1064 if (op->operand_cnt != 1)
1069 op->regmask_dst = (1 << xDX) | (1 << xAX);
1070 op->regmask_src |= (1 << xAX);
1071 if (op->operand[0].lmod == OPLM_UNSPEC)
1072 op->operand[0].lmod = OPLM_DWORD;
1077 // we could set up operands for edx:eax, but there is no real need to
1078 // (see is_opr_modified())
1079 regmask = (1 << xDX) | (1 << xAX);
1080 op->regmask_dst = regmask;
1081 op->regmask_src |= regmask;
1082 if (op->operand[0].lmod == OPLM_UNSPEC)
1083 op->operand[0].lmod = OPLM_DWORD;
1091 if (op->operand[1].lmod == OPLM_UNSPEC)
1092 op->operand[1].lmod = OPLM_BYTE;
1096 if (op->operand[2].lmod == OPLM_UNSPEC)
1097 op->operand[2].lmod = OPLM_BYTE;
1101 if (op->operand[0].lmod == OPLM_UNSPEC
1102 && (op->operand[0].type == OPT_CONST
1103 || op->operand[0].type == OPT_OFFSET
1104 || op->operand[0].type == OPT_LABEL))
1105 op->operand[0].lmod = OPLM_DWORD;
1111 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1112 && op->operand[0].lmod == op->operand[1].lmod
1113 && op->operand[0].reg == op->operand[1].reg
1114 && IS(op->operand[0].name, op->operand[1].name)) // ah, al..
1116 op->flags |= OPF_RMD;
1117 op->regmask_src = op->regmask_dst = 0;
1122 if (op->operand[0].type == OPT_REG
1123 && op->operand[1].type == OPT_REGMEM)
1126 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1127 if (IS(buf, op->operand[1].name))
1128 op->flags |= OPF_RMD;
1133 // trashed regs must be explicitly detected later
1134 op->regmask_dst = 0;
1142 static const char *op_name(struct parsed_op *po)
1144 static char buf[16];
1148 if (po->op == OP_JCC || po->op == OP_SCC) {
1150 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1153 strcpy(p, parsed_flag_op_names[po->pfo]);
1157 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1158 if (op_table[i].op == po->op)
1159 return op_table[i].name;
1165 static const char *dump_op(struct parsed_op *po)
1167 static char out[128];
1174 snprintf(out, sizeof(out), "%s", op_name(po));
1175 for (i = 0; i < po->operand_cnt; i++) {
1179 snprintf(p, sizeof(out) - (p - out),
1180 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1181 po->operand[i].name);
1187 static const char *lmod_type_u(struct parsed_op *po,
1188 enum opr_lenmod lmod)
1200 ferr(po, "invalid lmod: %d\n", lmod);
1201 return "(_invalid_)";
1205 static const char *lmod_cast_u(struct parsed_op *po,
1206 enum opr_lenmod lmod)
1218 ferr(po, "invalid lmod: %d\n", lmod);
1219 return "(_invalid_)";
1223 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1224 enum opr_lenmod lmod)
1236 ferr(po, "invalid lmod: %d\n", lmod);
1237 return "(_invalid_)";
1241 static const char *lmod_cast_s(struct parsed_op *po,
1242 enum opr_lenmod lmod)
1254 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1255 return "(_invalid_)";
1259 static const char *lmod_cast(struct parsed_op *po,
1260 enum opr_lenmod lmod, int is_signed)
1263 lmod_cast_s(po, lmod) :
1264 lmod_cast_u(po, lmod);
1267 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1279 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1284 static const char *opr_name(struct parsed_op *po, int opr_num)
1286 if (opr_num >= po->operand_cnt)
1287 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1288 return po->operand[opr_num].name;
1291 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1293 if (opr_num >= po->operand_cnt)
1294 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1295 if (po->operand[opr_num].type != OPT_CONST)
1296 ferr(po, "opr %d: const expected\n", opr_num);
1297 return po->operand[opr_num].val;
1300 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1302 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1303 ferr(po, "invalid reg: %d\n", popr->reg);
1304 return regs_r32[popr->reg];
1307 // cast1 is the "final" cast
1308 static const char *simplify_cast(const char *cast1, const char *cast2)
1310 static char buf[256];
1316 if (IS(cast1, cast2))
1318 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1320 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1322 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1324 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1326 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1329 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1333 static const char *simplify_cast_num(const char *cast, unsigned int val)
1335 if (IS(cast, "(u8)") && val < 0x100)
1337 if (IS(cast, "(s8)") && val < 0x80)
1339 if (IS(cast, "(u16)") && val < 0x10000)
1341 if (IS(cast, "(s16)") && val < 0x8000)
1343 if (IS(cast, "(s32)") && val < 0x80000000)
1349 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1358 namelen = strlen(name);
1360 p = strchr(name, '+');
1364 ferr(po, "equ parse failed for '%s'\n", name);
1366 if (IS_START(p, "0x"))
1368 *extra_offs = strtol(p, &endp, 16);
1370 ferr(po, "equ parse failed for '%s'\n", name);
1373 for (i = 0; i < g_eqcnt; i++)
1374 if (strncmp(g_eqs[i].name, name, namelen) == 0
1375 && g_eqs[i].name[namelen] == 0)
1379 ferr(po, "unresolved equ name: '%s'\n", name);
1386 static int is_stack_access(struct parsed_op *po,
1387 const struct parsed_opr *popr)
1389 return (parse_stack_el(popr->name, NULL, 0)
1390 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1391 && IS_START(popr->name, "ebp")));
1394 static void parse_stack_access(struct parsed_op *po,
1395 const char *name, char *ofs_reg, int *offset_out,
1396 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1398 const char *bp_arg = "";
1399 const char *p = NULL;
1400 struct parsed_equ *eq;
1407 if (IS_START(name, "ebp-")
1408 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1411 if (IS_START(p, "0x"))
1413 offset = strtoul(p, &endp, 16);
1417 ferr(po, "ebp- parse of '%s' failed\n", name);
1420 bp_arg = parse_stack_el(name, ofs_reg, 0);
1421 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1422 eq = equ_find(po, bp_arg, &offset);
1424 ferr(po, "detected but missing eq\n");
1425 offset += eq->offset;
1428 if (!strncmp(name, "ebp", 3))
1431 // yes it sometimes LEAs ra for compares..
1432 if (!is_lea && ofs_reg[0] == 0
1433 && stack_ra <= offset && offset < stack_ra + 4)
1435 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1438 *offset_out = offset;
1439 *stack_ra_out = stack_ra;
1441 *bp_arg_out = bp_arg;
1444 static int stack_frame_access(struct parsed_op *po,
1445 struct parsed_opr *popr, char *buf, size_t buf_size,
1446 const char *name, const char *cast, int is_src, int is_lea)
1448 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1449 const char *prefix = "";
1450 const char *bp_arg = NULL;
1451 char ofs_reg[16] = { 0, };
1452 int i, arg_i, arg_s;
1460 if (po->flags & OPF_EBP_S)
1461 ferr(po, "stack_frame_access while ebp is scratch\n");
1463 parse_stack_access(po, name, ofs_reg, &offset,
1464 &stack_ra, &bp_arg, is_lea);
1466 if (offset > stack_ra)
1468 arg_i = (offset - stack_ra - 4) / 4;
1469 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1471 if (g_func_pp->is_vararg
1472 && arg_i == g_func_pp->argc_stack && is_lea)
1474 // should be va_list
1477 snprintf(buf, buf_size, "%sap", cast);
1480 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1481 offset, bp_arg, arg_i);
1483 if (ofs_reg[0] != 0)
1484 ferr(po, "offset reg on arg access?\n");
1486 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1487 if (g_func_pp->arg[i].reg != NULL)
1493 if (i == g_func_pp->argc)
1494 ferr(po, "arg %d not in prototype?\n", arg_i);
1496 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1503 ferr(po, "lea/byte to arg?\n");
1504 if (is_src && (offset & 3) == 0)
1505 snprintf(buf, buf_size, "%sa%d",
1506 simplify_cast(cast, "(u8)"), i + 1);
1508 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1509 cast, offset & 3, i + 1);
1514 ferr(po, "lea/word to arg?\n");
1519 ferr(po, "problematic arg store\n");
1520 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1521 simplify_cast(cast, "*(u16 *)"), i + 1);
1524 ferr(po, "unaligned arg word load\n");
1526 else if (is_src && (offset & 2) == 0)
1527 snprintf(buf, buf_size, "%sa%d",
1528 simplify_cast(cast, "(u16)"), i + 1);
1530 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1531 cast, (offset & 2) ? "HI" : "LO", i + 1);
1543 snprintf(buf, buf_size, "(u32)&a%d + %d",
1546 ferr(po, "unaligned arg store\n");
1548 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1549 snprintf(buf, buf_size, "%s(a%d >> %d)",
1550 prefix, i + 1, (offset & 3) * 8);
1554 snprintf(buf, buf_size, "%s%sa%d",
1555 prefix, is_lea ? "&" : "", i + 1);
1560 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1564 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1567 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1568 if (tmp_lmod != OPLM_DWORD
1569 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1570 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1572 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1573 i + 1, offset, g_func_pp->arg[i].type.name);
1575 // can't check this because msvc likes to reuse
1576 // arg space for scratch..
1577 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1578 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1582 if (g_stack_fsz == 0)
1583 ferr(po, "stack var access without stackframe\n");
1584 g_stack_frame_used = 1;
1586 sf_ofs = g_stack_fsz + offset;
1587 lim = (ofs_reg[0] != 0) ? -4 : 0;
1588 if (offset > 0 || sf_ofs < lim)
1589 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1599 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1600 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1604 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1605 // known unaligned or possibly unaligned
1606 strcat(g_comment, " unaligned");
1608 prefix = "*(u16 *)&";
1609 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1610 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1613 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1617 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1618 // known unaligned or possibly unaligned
1619 strcat(g_comment, " unaligned");
1621 prefix = "*(u32 *)&";
1622 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1623 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1626 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1630 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1637 static void check_func_pp(struct parsed_op *po,
1638 const struct parsed_proto *pp, const char *pfx)
1640 enum opr_lenmod tmp_lmod;
1644 if (pp->argc_reg != 0) {
1645 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1646 pp_print(buf, sizeof(buf), pp);
1647 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1649 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1650 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1651 pfx, pp->argc_reg, pp->argc_stack);
1654 // fptrs must use 32bit args, callsite might have no information and
1655 // lack a cast to smaller types, which results in incorrectly masked
1656 // args passed (callee may assume masked args, it does on ARM)
1657 if (!pp->is_oslib) {
1658 for (i = 0; i < pp->argc; i++) {
1659 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1660 if (ret && tmp_lmod != OPLM_DWORD)
1661 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1662 i + 1, pp->arg[i].type.name);
1667 static const char *check_label_read_ref(struct parsed_op *po,
1670 const struct parsed_proto *pp;
1672 pp = proto_parse(g_fhdr, name, 0);
1674 ferr(po, "proto_parse failed for ref '%s'\n", name);
1677 check_func_pp(po, pp, "ref");
1682 static char *out_src_opr(char *buf, size_t buf_size,
1683 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1686 char tmp1[256], tmp2[256];
1695 switch (popr->type) {
1698 ferr(po, "lea from reg?\n");
1700 switch (popr->lmod) {
1702 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1705 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1708 snprintf(buf, buf_size, "%s%s",
1709 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1712 if (popr->name[1] == 'h') // XXX..
1713 snprintf(buf, buf_size, "%s(%s >> 8)",
1714 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1716 snprintf(buf, buf_size, "%s%s",
1717 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1720 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1725 if (is_stack_access(po, popr)) {
1726 stack_frame_access(po, popr, buf, buf_size,
1727 popr->name, cast, 1, is_lea);
1731 strcpy(expr, popr->name);
1732 if (strchr(expr, '[')) {
1733 // special case: '[' can only be left for label[reg] form
1734 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1736 ferr(po, "parse failure for '%s'\n", expr);
1737 if (tmp1[0] == '(') {
1738 // (off_4FFF50+3)[eax]
1739 p = strchr(tmp1 + 1, ')');
1740 if (p == NULL || p[1] != 0)
1741 ferr(po, "parse failure (2) for '%s'\n", expr);
1743 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1745 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1748 // XXX: do we need more parsing?
1750 snprintf(buf, buf_size, "%s", expr);
1754 snprintf(buf, buf_size, "%s(%s)",
1755 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1759 name = check_label_read_ref(po, popr->name);
1760 if (cast[0] == 0 && popr->is_ptr)
1764 snprintf(buf, buf_size, "(u32)&%s", name);
1765 else if (popr->size_lt)
1766 snprintf(buf, buf_size, "%s%s%s%s", cast,
1767 lmod_cast_u_ptr(po, popr->lmod),
1768 popr->is_array ? "" : "&", name);
1770 snprintf(buf, buf_size, "%s%s%s", cast, name,
1771 popr->is_array ? "[0]" : "");
1775 name = check_label_read_ref(po, popr->name);
1779 ferr(po, "lea an offset?\n");
1780 snprintf(buf, buf_size, "%s&%s", cast, name);
1785 ferr(po, "lea from const?\n");
1787 printf_number(tmp1, sizeof(tmp1), popr->val);
1788 if (popr->val == 0 && strchr(cast, '*'))
1789 snprintf(buf, buf_size, "NULL");
1791 snprintf(buf, buf_size, "%s%s",
1792 simplify_cast_num(cast, popr->val), tmp1);
1796 ferr(po, "invalid src type: %d\n", popr->type);
1802 // note: may set is_ptr (we find that out late for ebp frame..)
1803 static char *out_dst_opr(char *buf, size_t buf_size,
1804 struct parsed_op *po, struct parsed_opr *popr)
1806 switch (popr->type) {
1808 switch (popr->lmod) {
1810 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1813 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1817 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1821 if (popr->name[1] == 'h') // XXX..
1822 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1824 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1827 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1832 if (is_stack_access(po, popr)) {
1833 stack_frame_access(po, popr, buf, buf_size,
1834 popr->name, "", 0, 0);
1838 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1841 if (popr->size_mismatch)
1842 snprintf(buf, buf_size, "%s%s%s",
1843 lmod_cast_u_ptr(po, popr->lmod),
1844 popr->is_array ? "" : "&", popr->name);
1846 snprintf(buf, buf_size, "%s%s", popr->name,
1847 popr->is_array ? "[0]" : "");
1851 ferr(po, "invalid dst type: %d\n", popr->type);
1857 static char *out_src_opr_u32(char *buf, size_t buf_size,
1858 struct parsed_op *po, struct parsed_opr *popr)
1860 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1863 static void out_test_for_cc(char *buf, size_t buf_size,
1864 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1865 enum opr_lenmod lmod, const char *expr)
1867 const char *cast, *scast;
1869 cast = lmod_cast_u(po, lmod);
1870 scast = lmod_cast_s(po, lmod);
1874 case PFO_BE: // CF=1||ZF=1; CF=0
1875 snprintf(buf, buf_size, "(%s%s %s 0)",
1876 cast, expr, is_inv ? "!=" : "==");
1880 case PFO_L: // SF!=OF; OF=0
1881 snprintf(buf, buf_size, "(%s%s %s 0)",
1882 scast, expr, is_inv ? ">=" : "<");
1885 case PFO_LE: // ZF=1||SF!=OF; OF=0
1886 snprintf(buf, buf_size, "(%s%s %s 0)",
1887 scast, expr, is_inv ? ">" : "<=");
1891 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1895 static void out_cmp_for_cc(char *buf, size_t buf_size,
1896 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1898 const char *cast, *scast, *cast_use;
1899 char buf1[256], buf2[256];
1900 enum opr_lenmod lmod;
1902 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
1903 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1904 po->operand[0].lmod, po->operand[1].lmod);
1905 lmod = po->operand[0].lmod;
1907 cast = lmod_cast_u(po, lmod);
1908 scast = lmod_cast_s(po, lmod);
1924 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1927 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1928 if (po->op == OP_DEC)
1929 snprintf(buf2, sizeof(buf2), "1");
1931 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1935 // note: must be unsigned compare
1936 snprintf(buf, buf_size, "(%s %s %s)",
1937 buf1, is_inv ? ">=" : "<", buf2);
1941 snprintf(buf, buf_size, "(%s %s %s)",
1942 buf1, is_inv ? "!=" : "==", buf2);
1946 // note: must be unsigned compare
1947 snprintf(buf, buf_size, "(%s %s %s)",
1948 buf1, is_inv ? ">" : "<=", buf2);
1951 if (is_inv && lmod == OPLM_BYTE
1952 && po->operand[1].type == OPT_CONST
1953 && po->operand[1].val == 0xff)
1955 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1956 snprintf(buf, buf_size, "(0)");
1960 // note: must be signed compare
1962 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1963 scast, buf1, buf2, is_inv ? ">=" : "<");
1967 snprintf(buf, buf_size, "(%s %s %s)",
1968 buf1, is_inv ? ">=" : "<", buf2);
1972 snprintf(buf, buf_size, "(%s %s %s)",
1973 buf1, is_inv ? ">" : "<=", buf2);
1981 static void out_cmp_test(char *buf, size_t buf_size,
1982 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1984 char buf1[256], buf2[256], buf3[256];
1986 if (po->op == OP_TEST) {
1987 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1988 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1991 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1992 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1993 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1995 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1996 po->operand[0].lmod, buf3);
1998 else if (po->op == OP_CMP) {
1999 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2002 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2005 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2006 struct parsed_opr *popr2)
2008 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2009 ferr(po, "missing lmod for both operands\n");
2011 if (popr1->lmod == OPLM_UNSPEC)
2012 popr1->lmod = popr2->lmod;
2013 else if (popr2->lmod == OPLM_UNSPEC)
2014 popr2->lmod = popr1->lmod;
2015 else if (popr1->lmod != popr2->lmod) {
2016 if (popr1->type_from_var) {
2017 popr1->size_mismatch = 1;
2018 if (popr1->lmod < popr2->lmod)
2020 popr1->lmod = popr2->lmod;
2022 else if (popr2->type_from_var) {
2023 popr2->size_mismatch = 1;
2024 if (popr2->lmod < popr1->lmod)
2026 popr2->lmod = popr1->lmod;
2029 ferr(po, "conflicting lmods: %d vs %d\n",
2030 popr1->lmod, popr2->lmod);
2034 static const char *op_to_c(struct parsed_op *po)
2058 ferr(po, "op_to_c was supplied with %d\n", po->op);
2062 static void op_set_clear_flag(struct parsed_op *po,
2063 enum op_flags flag_set, enum op_flags flag_clear)
2065 po->flags |= flag_set;
2066 po->flags &= ~flag_clear;
2069 // last op in stream - unconditional branch or ret
2070 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2071 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2072 && ops[_i].op != OP_CALL))
2074 static int scan_for_pop(int i, int opcnt, const char *reg,
2075 int magic, int depth, int *maxdepth, int do_flags)
2077 const struct parsed_proto *pp;
2078 struct parsed_op *po;
2082 for (; i < opcnt; i++) {
2084 if (po->cc_scratch == magic)
2085 break; // already checked
2086 po->cc_scratch = magic;
2088 if (po->flags & OPF_TAIL) {
2089 if (po->op == OP_CALL) {
2090 pp = proto_parse(g_fhdr, po->operand[0].name, 0);
2091 if (pp != NULL && pp->is_noreturn)
2092 // no stack cleanup for noreturn
2095 return -1; // deadend
2098 if ((po->flags & OPF_RMD)
2099 || (po->op == OP_PUSH && po->p_argnum != 0)) // arg push
2102 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2103 if (po->btj != NULL) {
2105 for (j = 0; j < po->btj->count; j++) {
2106 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2107 depth, maxdepth, do_flags);
2109 return ret; // dead end
2115 ferr(po, "dead branch\n");
2119 if (po->flags & OPF_CJMP) {
2120 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2121 depth, maxdepth, do_flags);
2123 return ret; // dead end
2131 if ((po->op == OP_POP || po->op == OP_PUSH)
2132 && po->operand[0].type == OPT_REG
2133 && IS(po->operand[0].name, reg))
2135 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
2137 if (depth > *maxdepth)
2140 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2142 else if (po->op == OP_POP) {
2145 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2150 if (depth < 0) // should not happen
2151 ferr(po, "fail with depth\n");
2153 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2162 // scan for pop starting from 'ret' op (all paths)
2163 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2169 for (; i < opcnt; i++) {
2170 if (!(ops[i].flags & OPF_TAIL))
2173 for (j = i - 1; j >= 0; j--) {
2174 if (ops[j].flags & OPF_RMD)
2176 if (ops[j].flags & OPF_JMP)
2179 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2180 && IS(ops[j].operand[0].name, reg))
2183 ops[j].flags |= flag_set;
2187 if (g_labels[j][0] != 0)
2192 return found ? 0 : -1;
2195 static void scan_propagate_df(int i, int opcnt)
2197 struct parsed_op *po = &ops[i];
2200 for (; i < opcnt; i++) {
2202 if (po->flags & OPF_DF)
2203 return; // already resolved
2204 po->flags |= OPF_DF;
2206 if (po->op == OP_CALL)
2207 ferr(po, "call with DF set?\n");
2209 if (po->flags & OPF_JMP) {
2210 if (po->btj != NULL) {
2212 for (j = 0; j < po->btj->count; j++)
2213 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2218 ferr(po, "dead branch\n");
2222 if (po->flags & OPF_CJMP)
2223 scan_propagate_df(po->bt_i, opcnt);
2229 if (po->flags & OPF_TAIL)
2232 if (po->op == OP_CLD) {
2233 po->flags |= OPF_RMD;
2238 ferr(po, "missing DF clear?\n");
2241 // is operand 'opr' modified by parsed_op 'po'?
2242 static int is_opr_modified(const struct parsed_opr *opr,
2243 const struct parsed_op *po)
2247 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2250 if (opr->type == OPT_REG) {
2251 if (po->op == OP_CALL) {
2252 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2253 if ((1 << opr->reg) & mask)
2259 if (po->operand[0].type == OPT_REG) {
2260 if (po->regmask_dst & (1 << opr->reg))
2267 return IS(po->operand[0].name, opr->name);
2270 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2271 static int is_any_opr_modified(const struct parsed_op *po_test,
2272 const struct parsed_op *po, int c_mode)
2277 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2280 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2283 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2286 // in reality, it can wreck any register, but in decompiled C
2287 // version it can only overwrite eax or edx:eax
2288 mask = (1 << xAX) | (1 << xDX);
2292 if (po->op == OP_CALL
2293 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2296 for (i = 0; i < po_test->operand_cnt; i++)
2297 if (IS(po_test->operand[i].name, po->operand[0].name))
2303 // scan for any po_test operand modification in range given
2304 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2307 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2310 for (; i < opcnt; i++) {
2311 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2318 // scan for po_test operand[0] modification in range given
2319 static int scan_for_mod_opr0(struct parsed_op *po_test,
2322 for (; i < opcnt; i++) {
2323 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2330 static int scan_for_flag_set(int i, int magic, int *branched,
2331 int *setters, int *setter_cnt)
2333 struct label_ref *lr;
2337 if (ops[i].cc_scratch == magic) {
2338 ferr(&ops[i], "%s looped\n", __func__);
2341 ops[i].cc_scratch = magic;
2343 if (g_labels[i][0] != 0) {
2346 lr = &g_label_refs[i];
2347 for (; lr->next; lr = lr->next) {
2348 ret = scan_for_flag_set(lr->i, magic,
2349 branched, setters, setter_cnt);
2354 if (i > 0 && LAST_OP(i - 1)) {
2358 ret = scan_for_flag_set(lr->i, magic,
2359 branched, setters, setter_cnt);
2365 if (ops[i].flags & OPF_FLAGS) {
2366 setters[*setter_cnt] = i;
2371 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2378 // scan back for cdq, if anything modifies edx, fail
2379 static int scan_for_cdq_edx(int i)
2382 if (g_labels[i][0] != 0) {
2383 if (g_label_refs[i].next != NULL)
2385 if (i > 0 && LAST_OP(i - 1)) {
2386 i = g_label_refs[i].i;
2393 if (ops[i].op == OP_CDQ)
2396 if (ops[i].regmask_dst & (1 << xDX))
2403 static int scan_for_reg_clear(int i, int reg)
2406 if (g_labels[i][0] != 0) {
2407 if (g_label_refs[i].next != NULL)
2409 if (i > 0 && LAST_OP(i - 1)) {
2410 i = g_label_refs[i].i;
2417 if (ops[i].op == OP_XOR
2418 && ops[i].operand[0].lmod == OPLM_DWORD
2419 && ops[i].operand[0].reg == ops[i].operand[1].reg
2420 && ops[i].operand[0].reg == reg)
2423 if (ops[i].regmask_dst & (1 << reg))
2430 // scan for positive, constant esp adjust
2431 static int scan_for_esp_adjust(int i, int opcnt, int *adj,
2434 struct parsed_op *po;
2437 *adj = *multipath = 0;
2439 for (; i < opcnt; i++) {
2442 if (g_labels[i][0] != 0)
2445 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2446 if (po->operand[1].type != OPT_CONST)
2447 ferr(&ops[i], "non-const esp adjust?\n");
2448 *adj += po->operand[1].val;
2450 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2453 else if (po->op == OP_PUSH && !(po->flags & OPF_RMD)) {
2454 //if (first_pop == -1)
2455 // first_pop = -2; // none
2456 *adj -= lmod_bytes(po, po->operand[0].lmod);
2458 else if (po->op == OP_POP && !(po->flags & OPF_RMD)) {
2459 // seems like msvc only uses 'pop ecx' for stack realignment..
2460 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2462 if (first_pop == -1 && *adj >= 0)
2464 *adj += lmod_bytes(po, po->operand[0].lmod);
2466 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2467 if (po->op == OP_JMP && po->btj == NULL) {
2471 if (po->op != OP_CALL)
2473 if (po->operand[0].type != OPT_LABEL)
2475 if (po->pp != NULL && po->pp->is_stdcall)
2480 if (first_pop >= 0) {
2481 // probably 'pop ecx' was used..
2488 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2490 struct parsed_op *po;
2494 ferr(ops, "%s: followed bad branch?\n", __func__);
2496 for (; i < opcnt; i++) {
2498 if (po->cc_scratch == magic)
2500 po->cc_scratch = magic;
2503 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2504 if (po->btj != NULL) {
2506 for (j = 0; j < po->btj->count; j++)
2507 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2511 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2512 if (!(po->flags & OPF_CJMP))
2515 if (po->flags & OPF_TAIL)
2520 static const struct parsed_proto *try_recover_pp(
2521 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2523 const struct parsed_proto *pp = NULL;
2527 // maybe an arg of g_func?
2528 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2530 char ofs_reg[16] = { 0, };
2531 int arg, arg_s, arg_i;
2535 parse_stack_access(po, opr->name, ofs_reg,
2536 &offset, &stack_ra, NULL, 0);
2537 if (ofs_reg[0] != 0)
2538 ferr(po, "offset reg on arg access?\n");
2539 if (offset <= stack_ra) {
2540 // search who set the stack var instead
2541 if (search_instead != NULL)
2542 *search_instead = 1;
2546 arg_i = (offset - stack_ra - 4) / 4;
2547 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2548 if (g_func_pp->arg[arg].reg != NULL)
2554 if (arg == g_func_pp->argc)
2555 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2557 pp = g_func_pp->arg[arg].fptr;
2559 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2560 check_func_pp(po, pp, "icall arg");
2562 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2564 p = strchr(opr->name + 1, '[');
2565 memcpy(buf, opr->name, p - opr->name);
2566 buf[p - opr->name] = 0;
2567 pp = proto_parse(g_fhdr, buf, 0);
2569 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2570 pp = proto_parse(g_fhdr, opr->name, 0);
2572 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2573 check_func_pp(po, pp, "reg-fptr ref");
2579 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2580 int magic, const struct parsed_proto **pp_found, int *multi)
2582 const struct parsed_proto *pp = NULL;
2583 struct parsed_op *po;
2584 struct label_ref *lr;
2586 ops[i].cc_scratch = magic;
2589 if (g_labels[i][0] != 0) {
2590 lr = &g_label_refs[i];
2591 for (; lr != NULL; lr = lr->next)
2592 scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2593 if (i > 0 && LAST_OP(i - 1))
2601 if (ops[i].cc_scratch == magic)
2603 ops[i].cc_scratch = magic;
2605 if (!(ops[i].flags & OPF_DATA))
2607 if (!is_opr_modified(opr, &ops[i]))
2609 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2610 // most probably trashed by some processing
2615 opr = &ops[i].operand[1];
2616 if (opr->type != OPT_REG)
2620 po = (i >= 0) ? &ops[i] : ops;
2623 // reached the top - can only be an arg-reg
2624 if (opr->type != OPT_REG)
2627 for (i = 0; i < g_func_pp->argc; i++) {
2628 if (g_func_pp->arg[i].reg == NULL)
2630 if (IS(opr->name, g_func_pp->arg[i].reg))
2633 if (i == g_func_pp->argc)
2635 pp = g_func_pp->arg[i].fptr;
2637 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2638 i + 1, g_func_pp->arg[i].reg);
2639 check_func_pp(po, pp, "icall reg-arg");
2642 pp = try_recover_pp(po, opr, NULL);
2644 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2645 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2646 || (*pp_found)->is_stdcall != pp->is_stdcall
2647 || (*pp_found)->is_fptr != pp->is_fptr
2648 || (*pp_found)->argc != pp->argc
2649 || (*pp_found)->argc_reg != pp->argc_reg
2650 || (*pp_found)->argc_stack != pp->argc_stack)
2652 ferr(po, "icall: parsed_proto mismatch\n");
2660 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2663 const struct parsed_proto *pp = NULL;
2664 int search_advice = 0;
2668 switch (ops[i].operand[0].type) {
2672 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2677 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2685 // find an instruction that changed opr before i op
2686 // *op_i must be set to -1
2687 static int resolve_origin(int i, const struct parsed_opr *opr,
2688 int magic, int *op_i)
2690 struct label_ref *lr;
2693 ops[i].cc_scratch = magic;
2696 if (g_labels[i][0] != 0) {
2697 lr = &g_label_refs[i];
2698 for (; lr != NULL; lr = lr->next)
2699 ret |= resolve_origin(lr->i, opr, magic, op_i);
2700 if (i > 0 && LAST_OP(i - 1))
2708 if (ops[i].cc_scratch == magic)
2710 ops[i].cc_scratch = magic;
2712 if (!(ops[i].flags & OPF_DATA))
2714 if (!is_opr_modified(opr, &ops[i]))
2720 // XXX: could check if the other op does the same
2729 static int try_resolve_const(int i, const struct parsed_opr *opr,
2730 int magic, unsigned int *val)
2735 ret = resolve_origin(i, opr, magic, &s_i);
2738 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
2741 *val = ops[i].operand[1].val;
2748 static int collect_call_args_r(struct parsed_op *po, int i,
2749 struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2750 int magic, int need_op_saving, int may_reuse)
2752 struct parsed_proto *pp_tmp;
2753 struct label_ref *lr;
2754 int need_to_save_current;
2762 ferr(po, "dead label encountered\n");
2766 for (; arg < pp->argc; arg++)
2767 if (pp->arg[arg].reg == NULL)
2769 magic = (magic & 0xffffff) | (arg << 24);
2771 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2773 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2774 if (ops[j].cc_scratch != magic) {
2775 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2779 // ok: have already been here
2782 ops[j].cc_scratch = magic;
2784 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2785 lr = &g_label_refs[j];
2786 if (lr->next != NULL)
2788 for (; lr->next; lr = lr->next) {
2789 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2791 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2792 arg, magic, need_op_saving, may_reuse);
2797 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2799 if (j > 0 && LAST_OP(j - 1)) {
2800 // follow last branch in reverse
2805 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2806 arg, magic, need_op_saving, may_reuse);
2812 if (ops[j].op == OP_CALL)
2814 if (pp->is_unresolved)
2819 ferr(po, "arg collect hit unparsed call '%s'\n",
2820 ops[j].operand[0].name);
2821 if (may_reuse && pp_tmp->argc_stack > 0)
2822 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2823 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2825 // esp adjust of 0 means we collected it before
2826 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
2827 && (ops[j].operand[1].type != OPT_CONST
2828 || ops[j].operand[1].val != 0))
2830 if (pp->is_unresolved)
2833 ferr(po, "arg collect %d/%d hit esp adjust of %d\n",
2834 arg, pp->argc, ops[j].operand[1].val);
2836 else if (ops[j].op == OP_POP) {
2837 if (pp->is_unresolved)
2840 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2842 else if (ops[j].flags & OPF_CJMP)
2844 if (pp->is_unresolved)
2849 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2851 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2854 pp->arg[arg].datap = &ops[j];
2855 need_to_save_current = 0;
2858 if (ops[j].operand[0].type == OPT_REG)
2859 reg = ops[j].operand[0].reg;
2861 if (!need_op_saving) {
2862 ret = scan_for_mod(&ops[j], j + 1, i, 1);
2863 need_to_save_current = (ret >= 0);
2865 if (need_op_saving || need_to_save_current) {
2866 // mark this push as one that needs operand saving
2867 ops[j].flags &= ~OPF_RMD;
2868 if (ops[j].p_argnum == 0) {
2869 ops[j].p_argnum = arg + 1;
2870 save_args |= 1 << arg;
2872 else if (ops[j].p_argnum < arg + 1) {
2873 // XXX: might kill valid var..
2874 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
2875 ops[j].p_argnum = arg + 1;
2876 save_args |= 1 << arg;
2879 else if (ops[j].p_argnum == 0)
2880 ops[j].flags |= OPF_RMD;
2882 // some PUSHes are reused by different calls on other branches,
2883 // but that can't happen if we didn't branch, so they
2884 // can be removed from future searches (handles nested calls)
2886 ops[j].flags |= OPF_FARG;
2888 ops[j].flags &= ~OPF_RSAVE;
2890 // check for __VALIST
2891 if (!pp->is_unresolved && pp->arg[arg].type.is_va_list) {
2893 ret = resolve_origin(j, &ops[j].operand[0], magic + 1, &k);
2894 if (ret == 1 && k >= 0)
2896 if (ops[k].op == OP_LEA) {
2897 snprintf(buf, sizeof(buf), "arg_%X",
2898 g_func_pp->argc_stack * 4);
2899 if (!g_func_pp->is_vararg
2900 || strstr(ops[k].operand[1].name, buf))
2902 ops[k].flags |= OPF_RMD;
2903 ops[j].flags |= OPF_RMD | OPF_VAPUSH;
2904 save_args &= ~(1 << arg);
2908 ferr(&ops[j], "lea va_list used, but no vararg?\n");
2910 // check for va_list from g_func_pp arg too
2911 else if (ops[k].op == OP_MOV
2912 && is_stack_access(&ops[k], &ops[k].operand[1]))
2914 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
2915 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
2917 ops[k].flags |= OPF_RMD;
2918 ops[j].flags |= OPF_RMD;
2919 ops[j].p_argpass = ret + 1;
2920 save_args &= ~(1 << arg);
2927 *save_arg_vars |= save_args;
2929 // tracking reg usage
2931 *regmask |= 1 << reg;
2934 if (!pp->is_unresolved) {
2936 for (; arg < pp->argc; arg++)
2937 if (pp->arg[arg].reg == NULL)
2940 magic = (magic & 0xffffff) | (arg << 24);
2944 if (arg < pp->argc) {
2945 ferr(po, "arg collect failed for '%s': %d/%d\n",
2946 pp->name, arg, pp->argc);
2953 static int collect_call_args(struct parsed_op *po, int i,
2954 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2960 ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2965 if (pp->is_unresolved) {
2967 pp->argc_stack += ret;
2968 for (a = 0; a < pp->argc; a++)
2969 if (pp->arg[a].type.name == NULL)
2970 pp->arg[a].type.name = strdup("int");
2976 // early check for tail call or branch back
2977 static int is_like_tailjmp(int j)
2979 if (!(ops[j].flags & OPF_JMP))
2982 if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2983 // probably local branch back..
2985 if (ops[j].op == OP_CALL)
2986 // probably noreturn call..
2992 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2996 for (i = 0; i < pp->argc; i++)
2997 if (pp->arg[i].reg == NULL)
3001 memmove(&pp->arg[i + 1], &pp->arg[i],
3002 sizeof(pp->arg[0]) * pp->argc_stack);
3003 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
3004 pp->arg[i].reg = strdup(reg);
3005 pp->arg[i].type.name = strdup("int");
3010 static void add_label_ref(struct label_ref *lr, int op_i)
3012 struct label_ref *lr_new;
3019 lr_new = calloc(1, sizeof(*lr_new));
3021 lr_new->next = lr->next;
3025 static void output_std_flags(FILE *fout, struct parsed_op *po,
3026 int *pfomask, const char *dst_opr_text)
3028 if (*pfomask & (1 << PFO_Z)) {
3029 fprintf(fout, "\n cond_z = (%s%s == 0);",
3030 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
3031 *pfomask &= ~(1 << PFO_Z);
3033 if (*pfomask & (1 << PFO_S)) {
3034 fprintf(fout, "\n cond_s = (%s%s < 0);",
3035 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
3036 *pfomask &= ~(1 << PFO_S);
3040 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
3043 if (pp->is_fastcall)
3044 fprintf(fout, "__fastcall ");
3045 else if (pp->is_stdcall && pp->argc_reg == 0)
3046 fprintf(fout, "__stdcall ");
3047 if (pp->is_noreturn || is_noreturn)
3048 fprintf(fout, "noreturn ");
3051 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
3053 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
3054 struct parsed_opr *last_arith_dst = NULL;
3055 char buf1[256], buf2[256], buf3[256], cast[64];
3056 const struct parsed_proto *pp_c;
3057 struct parsed_proto *pp, *pp_tmp;
3058 struct parsed_data *pd;
3059 const char *tmpname;
3061 int save_arg_vars = 0;
3063 int need_tmp_var = 0;
3066 int label_pending = 0;
3067 int regmask_save = 0;
3068 int regmask_arg = 0;
3069 int regmask_now = 0;
3070 int regmask_init = 0;
3081 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
3082 g_stack_frame_used = 0;
3084 g_func_pp = proto_parse(fhdr, funcn, 0);
3085 if (g_func_pp == NULL)
3086 ferr(ops, "proto_parse failed for '%s'\n", funcn);
3088 for (i = 0; i < g_func_pp->argc; i++) {
3089 if (g_func_pp->arg[i].reg != NULL) {
3090 reg = char_array_i(regs_r32,
3091 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3093 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
3094 regmask_arg |= 1 << reg;
3099 // - handle ebp/esp frame, remove ops related to it
3100 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
3101 && ops[1].op == OP_MOV
3102 && IS(opr_name(&ops[1], 0), "ebp")
3103 && IS(opr_name(&ops[1], 1), "esp"))
3108 ops[0].flags |= OPF_RMD;
3109 ops[1].flags |= OPF_RMD;
3112 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
3113 g_stack_fsz = opr_const(&ops[2], 1);
3114 ops[2].flags |= OPF_RMD;
3118 // another way msvc builds stack frame..
3120 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3122 ops[i].flags |= OPF_RMD;
3126 // and another way..
3127 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3128 && ops[i].operand[1].type == OPT_CONST
3129 && ops[i + 1].op == OP_CALL
3130 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3132 g_stack_fsz += ops[i].operand[1].val;
3133 ops[i].flags |= OPF_RMD;
3135 ops[i].flags |= OPF_RMD;
3142 for (; i < opcnt; i++)
3143 if (ops[i].op == OP_RET)
3146 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3147 if (found && is_like_tailjmp(j))
3152 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3153 || ops[j].op == OP_LEAVE)
3155 ops[j].flags |= OPF_RMD;
3157 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3158 ferr(&ops[j], "'pop ebp' expected\n");
3160 if (g_stack_fsz != 0) {
3161 if (ops[j - 1].op == OP_MOV
3162 && IS(opr_name(&ops[j - 1], 0), "esp")
3163 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3165 ops[j - 1].flags |= OPF_RMD;
3167 else if (ops[j].op != OP_LEAVE
3168 && !(g_ida_func_attr & IDAFA_NORETURN))
3170 ferr(&ops[j - 1], "esp restore expected\n");
3173 if (ecx_push && ops[j - 2].op == OP_POP
3174 && IS(opr_name(&ops[j - 2], 0), "ecx"))
3176 ferr(&ops[j - 2], "unexpected ecx pop\n");
3182 } while (i < opcnt);
3185 int ecx_push = 0, esp_sub = 0;
3188 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3189 ops[i].flags |= OPF_RMD;
3195 for (; i < opcnt; i++) {
3196 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3198 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3199 && ops[i].operand[1].type == OPT_CONST)
3201 g_stack_fsz = ops[i].operand[1].val;
3202 ops[i].flags |= OPF_RMD;
3209 if (ecx_push || esp_sub)
3215 for (; i < opcnt; i++)
3216 if (ops[i].op == OP_RET)
3219 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3220 if (found && is_like_tailjmp(j))
3226 for (l = 0; l < ecx_push; l++) {
3227 if (ops[j].op != OP_POP
3228 || !IS(opr_name(&ops[j], 0), "ecx"))
3230 ferr(&ops[j], "'pop ecx' expected\n");
3232 ops[j].flags |= OPF_RMD;
3240 if (ops[j].op != OP_ADD
3241 || !IS(opr_name(&ops[j], 0), "esp")
3242 || ops[j].operand[1].type != OPT_CONST
3243 || ops[j].operand[1].val != g_stack_fsz)
3244 ferr(&ops[j], "'add esp' expected\n");
3245 ops[j].flags |= OPF_RMD;
3251 } while (i < opcnt);
3256 // - parse calls with labels
3257 // - resolve all branches
3258 for (i = 0; i < opcnt; i++)
3264 if (po->flags & OPF_RMD)
3267 if (po->op == OP_CALL) {
3270 if (po->operand[0].type == OPT_LABEL) {
3271 tmpname = opr_name(po, 0);
3272 if (IS_START(tmpname, "loc_"))
3273 ferr(po, "call to loc_*\n");
3274 pp_c = proto_parse(fhdr, tmpname, 0);
3276 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3278 pp = proto_clone(pp_c);
3279 my_assert_not(pp, NULL);
3281 else if (po->datap != NULL) {
3282 pp = calloc(1, sizeof(*pp));
3283 my_assert_not(pp, NULL);
3285 ret = parse_protostr(po->datap, pp);
3287 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3294 check_func_pp(po, pp, "fptr var call");
3295 if (pp->is_noreturn)
3296 po->flags |= OPF_TAIL;
3302 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3305 if (po->operand[0].type == OPT_REGMEM) {
3306 char *p = strchr(po->operand[0].name, '[');
3309 ret = p - po->operand[0].name;
3310 strncpy(buf1, po->operand[0].name, ret);
3313 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3314 if (IS(g_func_pd[j].label, buf1)) {
3320 //ferr(po, "label '%s' not parsed?\n", buf1);
3322 if (pd->type != OPT_OFFSET)
3323 ferr(po, "label '%s' with non-offset data?\n", buf1);
3325 // find all labels, link
3326 for (j = 0; j < pd->count; j++) {
3327 for (l = 0; l < opcnt; l++) {
3328 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
3329 add_label_ref(&g_label_refs[l], i);
3340 for (l = 0; l < opcnt; l++) {
3341 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
3342 if (l == i + 1 && po->op == OP_JMP) {
3343 // yet another alignment type..
3344 po->flags |= OPF_RMD;
3347 add_label_ref(&g_label_refs[l], i);
3353 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3356 if (po->operand[0].type == OPT_LABEL)
3360 ferr(po, "unhandled branch\n");
3364 po->flags |= OPF_TAIL;
3365 if (i > 0 && ops[i - 1].op == OP_POP)
3366 po->flags |= OPF_ATAIL;
3371 // - remove dead labels
3373 for (i = 0; i < opcnt; i++)
3375 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3379 if (po->flags & OPF_RMD)
3382 if (po->op == OP_CALL)
3384 tmpname = opr_name(po, 0);
3389 pp_c = resolve_icall(i, opcnt, &l);
3391 if (!pp_c->is_func && !pp_c->is_fptr)
3392 ferr(po, "call to non-func: %s\n", pp_c->name);
3393 pp = proto_clone(pp_c);
3394 my_assert_not(pp, NULL);
3396 // not resolved just to single func
3399 switch (po->operand[0].type) {
3401 // we resolved this call and no longer need the register
3402 po->regmask_src &= ~(1 << po->operand[0].reg);
3412 pp = calloc(1, sizeof(*pp));
3413 my_assert_not(pp, NULL);
3415 ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3417 if (!g_allow_regfunc)
3418 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3419 pp->is_unresolved = 1;
3423 if (j > ARRAY_SIZE(pp->arg))
3424 ferr(po, "esp adjust too large: %d\n", j);
3425 pp->ret_type.name = strdup("int");
3426 pp->argc = pp->argc_stack = j;
3427 for (arg = 0; arg < pp->argc; arg++)
3428 pp->arg[arg].type.name = strdup("int");
3433 // look for and make use of esp adjust
3435 if (!pp->is_stdcall && pp->argc_stack > 0)
3436 ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3438 if (pp->is_vararg) {
3439 if (j / 4 < pp->argc_stack)
3440 ferr(po, "esp adjust is too small: %x < %x\n",
3441 j, pp->argc_stack * 4);
3442 // modify pp to make it have varargs as normal args
3444 pp->argc += j / 4 - pp->argc_stack;
3445 for (; arg < pp->argc; arg++) {
3446 pp->arg[arg].type.name = strdup("int");
3449 if (pp->argc > ARRAY_SIZE(pp->arg))
3450 ferr(po, "too many args for '%s'\n", tmpname);
3452 if (pp->argc_stack != j / 4)
3453 ferr(po, "stack tracking failed for '%s': %x %x\n",
3454 tmpname, pp->argc_stack * 4, j);
3456 ops[ret].flags |= OPF_RMD;
3457 if (ops[ret].op == OP_POP && j > 4) {
3458 // deal with multi-pop stack adjust
3460 while (ops[ret].op == OP_POP && j > 0 && ret < opcnt) {
3461 ops[ret].flags |= OPF_RMD;
3467 // a bit of a hack, but deals with use of
3468 // single adj for multiple calls
3469 ops[ret].operand[1].val -= j;
3472 else if (pp->is_vararg)
3473 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3476 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3477 // since we know the args, collect them
3478 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3482 if (strstr(pp->ret_type.name, "int64"))
3488 // - find POPs for PUSHes, rm both
3489 // - scan for STD/CLD, propagate DF
3490 // - scan for all used registers
3491 // - find flag set ops for their users
3492 // - do unreselved calls
3493 // - declare indirect functions
3494 for (i = 0; i < opcnt; i++) {
3496 if (po->flags & OPF_RMD)
3499 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3500 reg = po->operand[0].reg;
3501 if (!(regmask & (1 << reg)))
3502 // not a reg save after all, rerun scan_for_pop
3503 po->flags &= ~OPF_RSAVE;
3505 regmask_save |= 1 << reg;
3508 if (po->op == OP_PUSH && po->p_argnum == 0
3509 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
3511 if (po->operand[0].type == OPT_REG)
3513 reg = po->operand[0].reg;
3515 ferr(po, "reg not set for push?\n");
3518 ret = scan_for_pop(i + 1, opcnt,
3519 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3522 ferr(po, "too much depth: %d\n", depth);
3524 po->flags |= OPF_RMD;
3525 scan_for_pop(i + 1, opcnt, po->operand[0].name,
3526 i + opcnt * 4, 0, &depth, 1);
3529 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3532 if (regmask & (1 << reg)) {
3533 if (regmask_save & (1 << reg))
3534 ferr(po, "%s already saved?\n", po->operand[0].name);
3538 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3542 else if (po->operand[0].type == OPT_CONST) {
3543 for (j = i + 1; j < opcnt; j++) {
3544 if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
3545 || ops[j].op == OP_PUSH || g_labels[i][0] != 0)
3550 if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
3552 po->flags |= OPF_RMD;
3560 if (po->op == OP_STD) {
3561 po->flags |= OPF_DF | OPF_RMD;
3562 scan_propagate_df(i + 1, opcnt);
3565 regmask_now = po->regmask_src | po->regmask_dst;
3566 if (regmask_now & (1 << xBP)) {
3567 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3568 if (po->regmask_dst & (1 << xBP))
3569 // compiler decided to drop bp frame and use ebp as scratch
3570 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
3572 regmask_now &= ~(1 << xBP);
3576 regmask |= regmask_now;
3578 if (po->flags & OPF_CC)
3580 int setters[16], cnt = 0, branched = 0;
3582 ret = scan_for_flag_set(i, i + opcnt * 6,
3583 &branched, setters, &cnt);
3584 if (ret < 0 || cnt <= 0)
3585 ferr(po, "unable to trace flag setter(s)\n");
3586 if (cnt > ARRAY_SIZE(setters))
3587 ferr(po, "too many flag setters\n");
3589 for (j = 0; j < cnt; j++)
3591 tmp_op = &ops[setters[j]]; // flag setter
3594 // to get nicer code, we try to delay test and cmp;
3595 // if we can't because of operand modification, or if we
3596 // have arith op, or branch, make it calculate flags explicitly
3597 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
3599 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3600 pfomask = 1 << po->pfo;
3602 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
3603 pfomask = 1 << po->pfo;
3606 // see if we'll be able to handle based on op result
3607 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3608 && po->pfo != PFO_Z && po->pfo != PFO_S
3609 && po->pfo != PFO_P)
3611 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3613 pfomask = 1 << po->pfo;
3616 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
3617 propagate_lmod(tmp_op, &tmp_op->operand[0],
3618 &tmp_op->operand[1]);
3619 if (tmp_op->operand[0].lmod == OPLM_DWORD)
3624 tmp_op->pfomask |= pfomask;
3625 cond_vars |= pfomask;
3627 // note: may overwrite, currently not a problem
3631 if (po->op == OP_RCL || po->op == OP_RCR
3632 || po->op == OP_ADC || po->op == OP_SBB)
3633 cond_vars |= 1 << PFO_C;
3636 if (po->op == OP_CMPS || po->op == OP_SCAS) {
3637 cond_vars |= 1 << PFO_Z;
3639 else if (po->op == OP_MUL
3640 || (po->op == OP_IMUL && po->operand_cnt == 1))
3642 if (po->operand[0].lmod == OPLM_DWORD)
3645 else if (po->op == OP_CALL) {
3648 ferr(po, "NULL pp\n");
3650 if (pp->is_unresolved) {
3651 int regmask_stack = 0;
3652 collect_call_args(po, i, pp, ®mask, &save_arg_vars,
3655 // this is pretty rough guess:
3656 // see ecx and edx were pushed (and not their saved versions)
3657 for (arg = 0; arg < pp->argc; arg++) {
3658 if (pp->arg[arg].reg != NULL)
3661 tmp_op = pp->arg[arg].datap;
3663 ferr(po, "parsed_op missing for arg%d\n", arg);
3664 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3665 regmask_stack |= 1 << tmp_op->operand[0].reg;
3668 if (!((regmask_stack & (1 << xCX))
3669 && (regmask_stack & (1 << xDX))))
3671 if (pp->argc_stack != 0
3672 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3674 pp_insert_reg_arg(pp, "ecx");
3675 pp->is_fastcall = 1;
3676 regmask_init |= 1 << xCX;
3677 regmask |= 1 << xCX;
3679 if (pp->argc_stack != 0
3680 || ((regmask | regmask_arg) & (1 << xDX)))
3682 pp_insert_reg_arg(pp, "edx");
3683 regmask_init |= 1 << xDX;
3684 regmask |= 1 << xDX;
3688 // note: __cdecl doesn't fall into is_unresolved category
3689 if (pp->argc_stack > 0)
3693 for (arg = 0; arg < pp->argc; arg++) {
3694 if (pp->arg[arg].reg != NULL) {
3695 reg = char_array_i(regs_r32,
3696 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3698 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3699 if (!(regmask & (1 << reg))) {
3700 regmask_init |= 1 << reg;
3701 regmask |= 1 << reg;
3706 else if (po->op == OP_MOV && po->operand[0].pp != NULL
3707 && po->operand[1].pp != NULL)
3709 // <var> = offset <something>
3710 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
3711 && !IS_START(po->operand[1].name, "off_"))
3713 if (!po->operand[0].pp->is_fptr)
3714 ferr(po, "%s not declared as fptr when it should be\n",
3715 po->operand[0].name);
3716 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
3717 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
3718 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
3719 fnote(po, "var: %s\n", buf1);
3720 fnote(po, "func: %s\n", buf2);
3721 ferr(po, "^ mismatch\n");
3725 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3726 regmask |= 1 << xAX;
3727 else if (po->op == OP_DIV || po->op == OP_IDIV) {
3728 // 32bit division is common, look for it
3729 if (po->op == OP_DIV)
3730 ret = scan_for_reg_clear(i, xDX);
3732 ret = scan_for_cdq_edx(i);
3734 po->flags |= OPF_32BIT;
3738 else if (po->op == OP_CLD)
3739 po->flags |= OPF_RMD;
3741 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
3747 // - confirm regmask_save, it might have been reduced
3748 if (regmask_save != 0)
3751 for (i = 0; i < opcnt; i++) {
3753 if (po->flags & OPF_RMD)
3756 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3757 regmask_save |= 1 << po->operand[0].reg;
3761 // output starts here
3763 // define userstack size
3764 if (g_func_pp->is_userstack) {
3765 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
3766 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
3767 fprintf(fout, "#endif\n");
3770 // the function itself
3771 fprintf(fout, "%s ", g_func_pp->ret_type.name);
3772 output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
3773 fprintf(fout, "%s(", g_func_pp->name);
3775 for (i = 0; i < g_func_pp->argc; i++) {
3777 fprintf(fout, ", ");
3778 if (g_func_pp->arg[i].fptr != NULL) {
3780 pp = g_func_pp->arg[i].fptr;
3781 fprintf(fout, "%s (", pp->ret_type.name);
3782 output_pp_attrs(fout, pp, 0);
3783 fprintf(fout, "*a%d)(", i + 1);
3784 for (j = 0; j < pp->argc; j++) {
3786 fprintf(fout, ", ");
3787 if (pp->arg[j].fptr)
3788 ferr(ops, "nested fptr\n");
3789 fprintf(fout, "%s", pp->arg[j].type.name);
3791 if (pp->is_vararg) {
3793 fprintf(fout, ", ");
3794 fprintf(fout, "...");
3798 else if (g_func_pp->arg[i].type.is_retreg) {
3799 fprintf(fout, "u32 *r_%s", g_func_pp->arg[i].reg);
3802 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
3805 if (g_func_pp->is_vararg) {
3807 fprintf(fout, ", ");
3808 fprintf(fout, "...");
3811 fprintf(fout, ")\n{\n");
3813 // declare indirect functions
3814 for (i = 0; i < opcnt; i++) {
3816 if (po->flags & OPF_RMD)
3819 if (po->op == OP_CALL) {
3822 ferr(po, "NULL pp\n");
3824 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
3825 if (pp->name[0] != 0) {
3826 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3827 memcpy(pp->name, "i_", 2);
3829 // might be declared already
3831 for (j = 0; j < i; j++) {
3832 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
3833 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3843 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3845 fprintf(fout, " %s (", pp->ret_type.name);
3846 output_pp_attrs(fout, pp, 0);
3847 fprintf(fout, "*%s)(", pp->name);
3848 for (j = 0; j < pp->argc; j++) {
3850 fprintf(fout, ", ");
3851 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3853 fprintf(fout, ");\n");
3858 // output LUTs/jumptables
3859 for (i = 0; i < g_func_pd_cnt; i++) {
3861 fprintf(fout, " static const ");
3862 if (pd->type == OPT_OFFSET) {
3863 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3865 for (j = 0; j < pd->count; j++) {
3867 fprintf(fout, ", ");
3868 fprintf(fout, "&&%s", pd->d[j].u.label);
3872 fprintf(fout, "%s %s[] =\n { ",
3873 lmod_type_u(ops, pd->lmod), pd->label);
3875 for (j = 0; j < pd->count; j++) {
3877 fprintf(fout, ", ");
3878 fprintf(fout, "%u", pd->d[j].u.val);
3881 fprintf(fout, " };\n");
3885 // declare stack frame, va_arg
3887 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3888 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3892 if (g_func_pp->is_userstack) {
3893 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
3894 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
3898 if (g_func_pp->is_vararg) {
3899 fprintf(fout, " va_list ap;\n");
3903 // declare arg-registers
3904 for (i = 0; i < g_func_pp->argc; i++) {
3905 if (g_func_pp->arg[i].reg != NULL) {
3906 reg = char_array_i(regs_r32,
3907 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3908 if (regmask & (1 << reg)) {
3909 if (g_func_pp->arg[i].type.is_retreg)
3910 fprintf(fout, " u32 %s = *r_%s;\n",
3911 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
3913 fprintf(fout, " u32 %s = (u32)a%d;\n",
3914 g_func_pp->arg[i].reg, i + 1);
3917 if (g_func_pp->arg[i].type.is_retreg)
3918 ferr(ops, "retreg '%s' is unused?\n",
3919 g_func_pp->arg[i].reg);
3920 fprintf(fout, " // %s = a%d; // unused\n",
3921 g_func_pp->arg[i].reg, i + 1);
3927 regmask_now = regmask & ~regmask_arg;
3928 regmask_now &= ~(1 << xSP);
3929 if (regmask_now & 0x00ff) {
3930 for (reg = 0; reg < 8; reg++) {
3931 if (regmask_now & (1 << reg)) {
3932 fprintf(fout, " u32 %s", regs_r32[reg]);
3933 if (regmask_init & (1 << reg))
3934 fprintf(fout, " = 0");
3935 fprintf(fout, ";\n");
3940 if (regmask_now & 0xff00) {
3941 for (reg = 8; reg < 16; reg++) {
3942 if (regmask_now & (1 << reg)) {
3943 fprintf(fout, " mmxr %s", regs_r32[reg]);
3944 if (regmask_init & (1 << reg))
3945 fprintf(fout, " = { 0, }");
3946 fprintf(fout, ";\n");
3953 for (reg = 0; reg < 8; reg++) {
3954 if (regmask_save & (1 << reg)) {
3955 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3961 if (save_arg_vars) {
3962 for (reg = 0; reg < 32; reg++) {
3963 if (save_arg_vars & (1 << reg)) {
3964 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3971 for (i = 0; i < 8; i++) {
3972 if (cond_vars & (1 << i)) {
3973 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3980 fprintf(fout, " u32 tmp;\n");
3985 fprintf(fout, " u64 tmp64;\n");
3990 fprintf(fout, "\n");
3992 if (g_func_pp->is_vararg) {
3993 if (g_func_pp->argc_stack == 0)
3994 ferr(ops, "vararg func without stack args?\n");
3995 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3999 for (i = 0; i < opcnt; i++)
4001 if (g_labels[i][0] != 0) {
4002 fprintf(fout, "\n%s:\n", g_labels[i]);
4005 delayed_flag_op = NULL;
4006 last_arith_dst = NULL;
4010 if (po->flags & OPF_RMD)
4015 #define assert_operand_cnt(n_) \
4016 if (po->operand_cnt != n_) \
4017 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4019 // conditional/flag using op?
4020 if (po->flags & OPF_CC)
4026 // we go through all this trouble to avoid using parsed_flag_op,
4027 // which makes generated code much nicer
4028 if (delayed_flag_op != NULL)
4030 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
4031 po->pfo, po->pfo_inv);
4034 else if (last_arith_dst != NULL
4035 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
4036 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
4039 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4040 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
4041 last_arith_dst->lmod, buf3);
4044 else if (tmp_op != NULL) {
4045 // use preprocessed flag calc results
4046 if (!(tmp_op->pfomask & (1 << po->pfo)))
4047 ferr(po, "not prepared for pfo %d\n", po->pfo);
4049 // note: pfo_inv was not yet applied
4050 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
4051 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
4054 ferr(po, "all methods of finding comparison failed\n");
4057 if (po->flags & OPF_JMP) {
4058 fprintf(fout, " if %s", buf1);
4060 else if (po->op == OP_RCL || po->op == OP_RCR
4061 || po->op == OP_ADC || po->op == OP_SBB)
4064 fprintf(fout, " cond_%s = %s;\n",
4065 parsed_flag_op_names[po->pfo], buf1);
4067 else if (po->flags & OPF_DATA) { // SETcc
4068 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
4069 fprintf(fout, " %s = %s;", buf2, buf1);
4072 ferr(po, "unhandled conditional op\n");
4076 pfomask = po->pfomask;
4078 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
4079 struct parsed_opr opr = {0,};
4082 opr.lmod = OPLM_DWORD;
4083 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
4085 if (ret != 1 || uval == 0) {
4086 // we need initial flags for ecx=0 case..
4087 if (i > 0 && ops[i - 1].op == OP_XOR
4088 && IS(ops[i - 1].operand[0].name,
4089 ops[i - 1].operand[1].name))
4091 fprintf(fout, " cond_z = ");
4092 if (pfomask & (1 << PFO_C))
4093 fprintf(fout, "cond_c = ");
4094 fprintf(fout, "0;\n");
4096 else if (last_arith_dst != NULL) {
4097 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4098 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
4099 last_arith_dst->lmod, buf3);
4100 fprintf(fout, " cond_z = %s;\n", buf1);
4103 ferr(po, "missing initial ZF\n");
4110 assert_operand_cnt(2);
4111 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4112 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4113 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
4114 fprintf(fout, " %s = %s;", buf1,
4115 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4120 assert_operand_cnt(2);
4121 po->operand[1].lmod = OPLM_DWORD; // always
4122 fprintf(fout, " %s = %s;",
4123 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4124 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4129 assert_operand_cnt(2);
4130 fprintf(fout, " %s = %s;",
4131 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4132 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4136 assert_operand_cnt(2);
4137 switch (po->operand[1].lmod) {
4139 strcpy(buf3, "(s8)");
4142 strcpy(buf3, "(s16)");
4145 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4147 fprintf(fout, " %s = %s;",
4148 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4149 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4154 assert_operand_cnt(2);
4155 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4156 fprintf(fout, " tmp = %s;",
4157 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4158 fprintf(fout, " %s = %s;",
4159 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4160 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4161 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4162 fprintf(fout, " %s = %stmp;",
4163 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4164 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
4165 snprintf(g_comment, sizeof(g_comment), "xchg");
4169 assert_operand_cnt(1);
4170 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4171 fprintf(fout, " %s = ~%s;", buf1, buf1);
4175 assert_operand_cnt(2);
4176 fprintf(fout, " %s = (s32)%s >> 31;",
4177 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4178 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4179 strcpy(g_comment, "cdq");
4183 assert_operand_cnt(3);
4184 if (po->flags & OPF_REP) {
4189 fprintf(fout, " eax = %sesi; esi %c= %d;",
4190 lmod_cast_u_ptr(po, po->operand[0].lmod),
4191 (po->flags & OPF_DF) ? '-' : '+',
4192 lmod_bytes(po, po->operand[0].lmod));
4193 strcpy(g_comment, "lods");
4198 assert_operand_cnt(3);
4199 if (po->flags & OPF_REP) {
4200 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
4201 (po->flags & OPF_DF) ? '-' : '+',
4202 lmod_bytes(po, po->operand[0].lmod));
4203 fprintf(fout, " %sedi = eax;",
4204 lmod_cast_u_ptr(po, po->operand[0].lmod));
4205 strcpy(g_comment, "rep stos");
4208 fprintf(fout, " %sedi = eax; edi %c= %d;",
4209 lmod_cast_u_ptr(po, po->operand[0].lmod),
4210 (po->flags & OPF_DF) ? '-' : '+',
4211 lmod_bytes(po, po->operand[0].lmod));
4212 strcpy(g_comment, "stos");
4217 assert_operand_cnt(3);
4218 j = lmod_bytes(po, po->operand[0].lmod);
4219 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4220 l = (po->flags & OPF_DF) ? '-' : '+';
4221 if (po->flags & OPF_REP) {
4223 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4226 " %sedi = %sesi;", buf1, buf1);
4227 strcpy(g_comment, "rep movs");
4230 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
4231 buf1, buf1, l, j, l, j);
4232 strcpy(g_comment, "movs");
4237 // repe ~ repeat while ZF=1
4238 assert_operand_cnt(3);
4239 j = lmod_bytes(po, po->operand[0].lmod);
4240 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4241 l = (po->flags & OPF_DF) ? '-' : '+';
4242 if (po->flags & OPF_REP) {
4244 " for (; ecx != 0; ecx--) {\n");
4245 if (pfomask & (1 << PFO_C)) {
4248 " cond_c = %sesi < %sedi;\n", buf1, buf1);
4249 pfomask &= ~(1 << PFO_C);
4252 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
4253 buf1, buf1, l, j, l, j);
4255 " if (cond_z %s 0) break;\n",
4256 (po->flags & OPF_REPZ) ? "==" : "!=");
4259 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4260 (po->flags & OPF_REPZ) ? "e" : "ne");
4264 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4265 buf1, buf1, l, j, l, j);
4266 strcpy(g_comment, "cmps");
4268 pfomask &= ~(1 << PFO_Z);
4269 last_arith_dst = NULL;
4270 delayed_flag_op = NULL;
4274 // only does ZF (for now)
4275 // repe ~ repeat while ZF=1
4276 assert_operand_cnt(3);
4277 j = lmod_bytes(po, po->operand[0].lmod);
4278 l = (po->flags & OPF_DF) ? '-' : '+';
4279 if (po->flags & OPF_REP) {
4281 " for (; ecx != 0; ecx--) {\n");
4283 " cond_z = (%seax == %sedi); edi %c= %d;\n",
4284 lmod_cast_u(po, po->operand[0].lmod),
4285 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4287 " if (cond_z %s 0) break;\n",
4288 (po->flags & OPF_REPZ) ? "==" : "!=");
4291 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4292 (po->flags & OPF_REPZ) ? "e" : "ne");
4295 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
4296 lmod_cast_u(po, po->operand[0].lmod),
4297 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4298 strcpy(g_comment, "scas");
4300 pfomask &= ~(1 << PFO_Z);
4301 last_arith_dst = NULL;
4302 delayed_flag_op = NULL;
4305 // arithmetic w/flags
4308 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4311 assert_operand_cnt(2);
4312 fprintf(fout, " %s %s= %s;",
4313 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4315 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4316 output_std_flags(fout, po, &pfomask, buf1);
4317 last_arith_dst = &po->operand[0];
4318 delayed_flag_op = NULL;
4323 assert_operand_cnt(2);
4324 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4325 if (pfomask & (1 << PFO_C)) {
4326 if (po->operand[1].type == OPT_CONST) {
4327 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4328 j = po->operand[1].val;
4331 if (po->op == OP_SHL)
4335 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
4339 ferr(po, "zero shift?\n");
4343 pfomask &= ~(1 << PFO_C);
4345 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
4346 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4347 output_std_flags(fout, po, &pfomask, buf1);
4348 last_arith_dst = &po->operand[0];
4349 delayed_flag_op = NULL;
4353 assert_operand_cnt(2);
4354 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4355 fprintf(fout, " %s = %s%s >> %s;", buf1,
4356 lmod_cast_s(po, po->operand[0].lmod), buf1,
4357 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4358 output_std_flags(fout, po, &pfomask, buf1);
4359 last_arith_dst = &po->operand[0];
4360 delayed_flag_op = NULL;
4364 assert_operand_cnt(3);
4365 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4366 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4367 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4368 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4369 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
4370 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
4371 buf1, buf3, buf1, buf2, l, buf3);
4372 strcpy(g_comment, "shrd");
4373 output_std_flags(fout, po, &pfomask, buf1);
4374 last_arith_dst = &po->operand[0];
4375 delayed_flag_op = NULL;
4380 assert_operand_cnt(2);
4381 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4382 if (po->operand[1].type == OPT_CONST) {
4383 j = po->operand[1].val;
4384 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4385 fprintf(fout, po->op == OP_ROL ?
4386 " %s = (%s << %d) | (%s >> %d);" :
4387 " %s = (%s >> %d) | (%s << %d);",
4388 buf1, buf1, j, buf1,
4389 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4393 output_std_flags(fout, po, &pfomask, buf1);
4394 last_arith_dst = &po->operand[0];
4395 delayed_flag_op = NULL;
4400 assert_operand_cnt(2);
4401 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4402 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4403 if (po->operand[1].type == OPT_CONST) {
4404 j = po->operand[1].val % l;
4406 ferr(po, "zero rotate\n");
4407 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
4408 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4409 if (po->op == OP_RCL) {
4411 " %s = (%s << %d) | (cond_c << %d)",
4412 buf1, buf1, j, j - 1);
4414 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4418 " %s = (%s >> %d) | (cond_c << %d)",
4419 buf1, buf1, j, l - j);
4421 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4423 fprintf(fout, ";\n");
4424 fprintf(fout, " cond_c = tmp;");
4428 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4429 output_std_flags(fout, po, &pfomask, buf1);
4430 last_arith_dst = &po->operand[0];
4431 delayed_flag_op = NULL;
4435 assert_operand_cnt(2);
4436 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4437 if (IS(opr_name(po, 0), opr_name(po, 1))) {
4438 // special case for XOR
4439 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4440 fprintf(fout, " cond_be = 1;\n");
4441 pfomask &= ~(1 << PFO_BE);
4443 fprintf(fout, " %s = 0;",
4444 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4445 last_arith_dst = &po->operand[0];
4446 delayed_flag_op = NULL;
4452 assert_operand_cnt(2);
4453 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4454 if (pfomask & (1 << PFO_C)) {
4455 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4456 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4457 if (po->operand[0].lmod == OPLM_DWORD) {
4458 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
4459 fprintf(fout, " cond_c = tmp64 >> 32;\n");
4460 fprintf(fout, " %s = (u32)tmp64;",
4461 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4462 strcat(g_comment, "add64");
4465 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
4466 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
4467 fprintf(fout, " %s += %s;",
4468 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4471 pfomask &= ~(1 << PFO_C);
4472 output_std_flags(fout, po, &pfomask, buf1);
4473 last_arith_dst = &po->operand[0];
4474 delayed_flag_op = NULL;
4480 assert_operand_cnt(2);
4481 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4482 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
4483 for (j = 0; j <= PFO_LE; j++) {
4484 if (!(pfomask & (1 << j)))
4486 if (j == PFO_Z || j == PFO_S)
4489 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4490 fprintf(fout, " cond_%s = %s;\n",
4491 parsed_flag_op_names[j], buf1);
4492 pfomask &= ~(1 << j);
4499 assert_operand_cnt(2);
4500 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4501 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4502 if (po->op == OP_SBB
4503 && IS(po->operand[0].name, po->operand[1].name))
4505 // avoid use of unitialized var
4506 fprintf(fout, " %s = -cond_c;", buf1);
4507 // carry remains what it was
4508 pfomask &= ~(1 << PFO_C);
4511 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
4512 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4514 output_std_flags(fout, po, &pfomask, buf1);
4515 last_arith_dst = &po->operand[0];
4516 delayed_flag_op = NULL;
4520 assert_operand_cnt(2);
4521 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4522 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4523 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4525 output_std_flags(fout, po, &pfomask, buf1);
4526 last_arith_dst = &po->operand[0];
4527 delayed_flag_op = NULL;
4528 strcat(g_comment, "bsf");
4532 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
4533 for (j = 0; j <= PFO_LE; j++) {
4534 if (!(pfomask & (1 << j)))
4536 if (j == PFO_Z || j == PFO_S || j == PFO_C)
4539 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4540 fprintf(fout, " cond_%s = %s;\n",
4541 parsed_flag_op_names[j], buf1);
4542 pfomask &= ~(1 << j);
4548 if (pfomask & (1 << PFO_C))
4549 // carry is unaffected by inc/dec.. wtf?
4550 ferr(po, "carry propagation needed\n");
4552 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4553 if (po->operand[0].type == OPT_REG) {
4554 strcpy(buf2, po->op == OP_INC ? "++" : "--");
4555 fprintf(fout, " %s%s;", buf1, buf2);
4558 strcpy(buf2, po->op == OP_INC ? "+" : "-");
4559 fprintf(fout, " %s %s= 1;", buf1, buf2);
4561 output_std_flags(fout, po, &pfomask, buf1);
4562 last_arith_dst = &po->operand[0];
4563 delayed_flag_op = NULL;
4567 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4568 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
4569 fprintf(fout, " %s = -%s%s;", buf1,
4570 lmod_cast_s(po, po->operand[0].lmod), buf2);
4571 last_arith_dst = &po->operand[0];
4572 delayed_flag_op = NULL;
4573 if (pfomask & (1 << PFO_C)) {
4574 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
4575 pfomask &= ~(1 << PFO_C);
4580 if (po->operand_cnt == 2) {
4581 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4584 if (po->operand_cnt == 3)
4585 ferr(po, "TODO imul3\n");
4588 assert_operand_cnt(1);
4589 switch (po->operand[0].lmod) {
4591 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
4592 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
4593 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
4594 fprintf(fout, " edx = tmp64 >> 32;\n");
4595 fprintf(fout, " eax = tmp64;");
4598 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
4599 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
4600 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
4604 ferr(po, "TODO: unhandled mul type\n");
4607 last_arith_dst = NULL;
4608 delayed_flag_op = NULL;
4613 assert_operand_cnt(1);
4614 if (po->operand[0].lmod != OPLM_DWORD)
4615 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
4617 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4618 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
4619 po->op == OP_IDIV));
4620 switch (po->operand[0].lmod) {
4622 if (po->flags & OPF_32BIT)
4623 snprintf(buf3, sizeof(buf3), "%seax", buf2);
4625 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
4626 snprintf(buf3, sizeof(buf3), "%stmp64",
4627 (po->op == OP_IDIV) ? "(s64)" : "");
4629 if (po->operand[0].type == OPT_REG
4630 && po->operand[0].reg == xDX)
4632 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
4633 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
4636 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
4637 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
4641 ferr(po, "unhandled division type\n");
4643 last_arith_dst = NULL;
4644 delayed_flag_op = NULL;
4649 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4651 for (j = 0; j < 8; j++) {
4652 if (pfomask & (1 << j)) {
4653 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
4654 fprintf(fout, " cond_%s = %s;",
4655 parsed_flag_op_names[j], buf1);
4662 last_arith_dst = NULL;
4663 delayed_flag_op = po;
4667 // SETcc - should already be handled
4670 // note: we reuse OP_Jcc for SETcc, only flags differ
4672 fprintf(fout, "\n goto %s;", po->operand[0].name);
4676 fprintf(fout, " if (ecx == 0)\n");
4677 fprintf(fout, " goto %s;", po->operand[0].name);
4678 strcat(g_comment, "jecxz");
4682 assert_operand_cnt(1);
4683 last_arith_dst = NULL;
4684 delayed_flag_op = NULL;
4686 if (po->operand[0].type == OPT_REGMEM) {
4687 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
4690 ferr(po, "parse failure for jmp '%s'\n",
4691 po->operand[0].name);
4692 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
4695 else if (po->operand[0].type != OPT_LABEL)
4696 ferr(po, "unhandled jmp type\n");
4698 fprintf(fout, " goto %s;", po->operand[0].name);
4702 assert_operand_cnt(1);
4704 my_assert_not(pp, NULL);
4707 if (po->flags & OPF_CC) {
4708 // we treat conditional branch to another func
4709 // (yes such code exists..) as conditional tailcall
4711 fprintf(fout, " {\n");
4714 if (pp->is_fptr && !pp->is_arg) {
4715 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
4716 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
4718 if (pp->is_unresolved)
4719 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
4720 buf3, asmfn, po->asmln, pp->name);
4723 fprintf(fout, "%s", buf3);
4724 if (strstr(pp->ret_type.name, "int64")) {
4725 if (po->flags & OPF_TAIL)
4726 ferr(po, "int64 and tail?\n");
4727 fprintf(fout, "tmp64 = ");
4729 else if (!IS(pp->ret_type.name, "void")) {
4730 if (po->flags & OPF_TAIL) {
4731 if (!IS(g_func_pp->ret_type.name, "void")) {
4732 fprintf(fout, "return ");
4733 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
4734 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
4737 else if (regmask & (1 << xAX)) {
4738 fprintf(fout, "eax = ");
4739 if (pp->ret_type.is_ptr)
4740 fprintf(fout, "(u32)");
4744 if (pp->name[0] == 0)
4745 ferr(po, "missing pp->name\n");
4746 fprintf(fout, "%s%s(", pp->name,
4747 pp->has_structarg ? "_sa" : "");
4749 if (po->flags & OPF_ATAIL) {
4750 if (pp->argc_stack != g_func_pp->argc_stack
4751 || (pp->argc_stack > 0
4752 && pp->is_stdcall != g_func_pp->is_stdcall))
4753 ferr(po, "incompatible tailcall\n");
4754 if (g_func_pp->has_retreg)
4755 ferr(po, "TODO: retreg+tailcall\n");
4757 for (arg = j = 0; arg < pp->argc; arg++) {
4759 fprintf(fout, ", ");
4762 if (pp->arg[arg].type.is_ptr)
4763 snprintf(cast, sizeof(cast), "(%s)",
4764 pp->arg[arg].type.name);
4766 if (pp->arg[arg].reg != NULL) {
4767 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4771 for (; j < g_func_pp->argc; j++)
4772 if (g_func_pp->arg[j].reg == NULL)
4774 fprintf(fout, "%sa%d", cast, j + 1);
4779 for (arg = 0; arg < pp->argc; arg++) {
4781 fprintf(fout, ", ");
4784 if (pp->arg[arg].type.is_ptr)
4785 snprintf(cast, sizeof(cast), "(%s)",
4786 pp->arg[arg].type.name);
4788 if (pp->arg[arg].reg != NULL) {
4789 if (pp->arg[arg].type.is_retreg)
4790 fprintf(fout, "&%s", pp->arg[arg].reg);
4792 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4797 tmp_op = pp->arg[arg].datap;
4799 ferr(po, "parsed_op missing for arg%d\n", arg);
4801 if (tmp_op->flags & OPF_VAPUSH) {
4802 fprintf(fout, "ap");
4804 else if (tmp_op->p_argpass != 0) {
4805 fprintf(fout, "a%d", tmp_op->p_argpass);
4807 else if (tmp_op->p_argnum != 0) {
4808 fprintf(fout, "%ss_a%d", cast, tmp_op->p_argnum);
4812 out_src_opr(buf1, sizeof(buf1),
4813 tmp_op, &tmp_op->operand[0], cast, 0));
4817 fprintf(fout, ");");
4819 if (strstr(pp->ret_type.name, "int64")) {
4820 fprintf(fout, "\n");
4821 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
4822 fprintf(fout, "%seax = tmp64;", buf3);
4825 if (pp->is_unresolved) {
4826 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
4828 strcat(g_comment, buf2);
4831 if (po->flags & OPF_TAIL) {
4833 if (i == opcnt - 1 || pp->is_noreturn)
4835 else if (IS(pp->ret_type.name, "void"))
4837 else if (IS(g_func_pp->ret_type.name, "void"))
4839 // else already handled as 'return f()'
4842 if (!IS(g_func_pp->ret_type.name, "void")) {
4843 ferr(po, "int func -> void func tailcall?\n");
4846 fprintf(fout, "\n%sreturn;", buf3);
4847 strcat(g_comment, " ^ tailcall");
4851 strcat(g_comment, " tailcall");
4853 if (pp->is_noreturn)
4854 strcat(g_comment, " noreturn");
4855 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
4856 strcat(g_comment, " argframe");
4857 if (po->flags & OPF_CC)
4858 strcat(g_comment, " cond");
4860 if (po->flags & OPF_CC)
4861 fprintf(fout, "\n }");
4863 delayed_flag_op = NULL;
4864 last_arith_dst = NULL;
4868 if (g_func_pp->is_vararg)
4869 fprintf(fout, " va_end(ap);\n");
4870 if (g_func_pp->has_retreg) {
4871 for (arg = 0; arg < g_func_pp->argc; arg++)
4872 if (g_func_pp->arg[arg].type.is_retreg)
4873 fprintf(fout, " *r_%s = %s;\n",
4874 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
4877 if (IS(g_func_pp->ret_type.name, "void")) {
4878 if (i != opcnt - 1 || label_pending)
4879 fprintf(fout, " return;");
4881 else if (g_func_pp->ret_type.is_ptr) {
4882 fprintf(fout, " return (%s)eax;",
4883 g_func_pp->ret_type.name);
4885 else if (IS(g_func_pp->ret_type.name, "__int64"))
4886 fprintf(fout, " return ((u64)edx << 32) | eax;");
4888 fprintf(fout, " return eax;");
4890 last_arith_dst = NULL;
4891 delayed_flag_op = NULL;
4895 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4896 if (po->p_argnum != 0) {
4897 // special case - saved func arg
4898 fprintf(fout, " s_a%d = %s;", po->p_argnum, buf1);
4901 else if (po->flags & OPF_RSAVE) {
4902 fprintf(fout, " s_%s = %s;", buf1, buf1);
4905 else if (g_func_pp->is_userstack) {
4906 fprintf(fout, " *(--esp) = %s;", buf1);
4909 if (!(g_ida_func_attr & IDAFA_NORETURN))
4910 ferr(po, "stray push encountered\n");
4915 if (po->flags & OPF_RSAVE) {
4916 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4917 fprintf(fout, " %s = s_%s;", buf1, buf1);
4920 else if (po->datap != NULL) {
4923 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4924 fprintf(fout, " %s = %s;", buf1,
4925 out_src_opr(buf2, sizeof(buf2),
4926 tmp_op, &tmp_op->operand[0],
4927 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4930 else if (g_func_pp->is_userstack) {
4931 fprintf(fout, " %s = *esp++;",
4932 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4936 ferr(po, "stray pop encountered\n");
4945 strcpy(g_comment, "(emms)");
4950 ferr(po, "unhandled op type %d, flags %x\n",
4955 if (g_comment[0] != 0) {
4956 char *p = g_comment;
4957 while (my_isblank(*p))
4959 fprintf(fout, " // %s", p);
4964 fprintf(fout, "\n");
4966 // some sanity checking
4967 if (po->flags & OPF_REP) {
4968 if (po->op != OP_STOS && po->op != OP_MOVS
4969 && po->op != OP_CMPS && po->op != OP_SCAS)
4970 ferr(po, "unexpected rep\n");
4971 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
4972 && (po->op == OP_CMPS || po->op == OP_SCAS))
4973 ferr(po, "cmps/scas with plain rep\n");
4975 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
4976 && po->op != OP_CMPS && po->op != OP_SCAS)
4977 ferr(po, "unexpected repz/repnz\n");
4980 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4982 // see is delayed flag stuff is still valid
4983 if (delayed_flag_op != NULL && delayed_flag_op != po) {
4984 if (is_any_opr_modified(delayed_flag_op, po, 0))
4985 delayed_flag_op = NULL;
4988 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4989 if (is_opr_modified(last_arith_dst, po))
4990 last_arith_dst = NULL;
4996 if (g_stack_fsz && !g_stack_frame_used)
4997 fprintf(fout, " (void)sf;\n");
4999 fprintf(fout, "}\n\n");
5002 for (i = 0; i < opcnt; i++) {
5003 struct label_ref *lr, *lr_del;
5005 lr = g_label_refs[i].next;
5006 while (lr != NULL) {
5011 g_label_refs[i].i = -1;
5012 g_label_refs[i].next = NULL;
5014 if (ops[i].op == OP_CALL) {
5016 proto_release(ops[i].pp);
5022 static void set_label(int i, const char *name)
5028 p = strchr(name, ':');
5032 if (len > sizeof(g_labels[0]) - 1)
5033 aerr("label '%s' too long: %d\n", name, len);
5034 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
5035 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
5036 memcpy(g_labels[i], name, len);
5037 g_labels[i][len] = 0;
5040 // '=' needs special treatment..
5041 static char *next_word_s(char *w, size_t wsize, char *s)
5047 for (i = 0; i < wsize - 1; i++) {
5048 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
5054 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
5055 printf("warning: '%s' truncated\n", w);
5066 static struct chunk_item *func_chunks;
5067 static int func_chunk_cnt;
5068 static int func_chunk_alloc;
5070 static void add_func_chunk(FILE *fasm, const char *name, int line)
5072 if (func_chunk_cnt >= func_chunk_alloc) {
5073 func_chunk_alloc *= 2;
5074 func_chunks = realloc(func_chunks,
5075 func_chunk_alloc * sizeof(func_chunks[0]));
5076 my_assert_not(func_chunks, NULL);
5078 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
5079 func_chunks[func_chunk_cnt].name = strdup(name);
5080 func_chunks[func_chunk_cnt].asmln = line;
5084 static int cmp_chunks(const void *p1, const void *p2)
5086 const struct chunk_item *c1 = p1, *c2 = p2;
5087 return strcmp(c1->name, c2->name);
5090 static int cmpstringp(const void *p1, const void *p2)
5092 return strcmp(*(char * const *)p1, *(char * const *)p2);
5095 static void scan_ahead(FILE *fasm)
5105 oldpos = ftell(fasm);
5108 while (fgets(line, sizeof(line), fasm))
5119 // get rid of random tabs
5120 for (i = 0; line[i] != 0; i++)
5121 if (line[i] == '\t')
5124 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
5127 next_word(words[0], sizeof(words[0]), p);
5128 if (words[0][0] == 0)
5129 aerr("missing name for func chunk?\n");
5131 add_func_chunk(fasm, words[0], asmln);
5133 else if (IS_START(p, "; sctend"))
5139 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
5140 words[wordc][0] = 0;
5141 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
5142 if (*p == 0 || *p == ';') {
5148 if (wordc == 2 && IS(words[1], "ends"))
5152 fseek(fasm, oldpos, SEEK_SET);
5156 int main(int argc, char *argv[])
5158 FILE *fout, *fasm, *frlist;
5159 struct parsed_data *pd = NULL;
5161 char **rlist = NULL;
5163 int rlist_alloc = 0;
5164 int func_chunks_used = 0;
5165 int func_chunks_sorted = 0;
5166 int func_chunk_i = -1;
5167 long func_chunk_ret = 0;
5168 int func_chunk_ret_ln = 0;
5169 int scanned_ahead = 0;
5171 char words[20][256];
5172 enum opr_lenmod lmod;
5173 char *sctproto = NULL;
5175 int pending_endp = 0;
5177 int skip_warned = 0;
5190 for (arg = 1; arg < argc; arg++) {
5191 if (IS(argv[arg], "-v"))
5193 else if (IS(argv[arg], "-rf"))
5194 g_allow_regfunc = 1;
5195 else if (IS(argv[arg], "-m"))
5201 if (argc < arg + 3) {
5202 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdrf> [rlist]*\n",
5209 asmfn = argv[arg++];
5210 fasm = fopen(asmfn, "r");
5211 my_assert_not(fasm, NULL);
5213 hdrfn = argv[arg++];
5214 g_fhdr = fopen(hdrfn, "r");
5215 my_assert_not(g_fhdr, NULL);
5218 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
5219 my_assert_not(rlist, NULL);
5220 // needs special handling..
5221 rlist[rlist_len++] = "__alloca_probe";
5223 func_chunk_alloc = 32;
5224 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
5225 my_assert_not(func_chunks, NULL);
5227 memset(words, 0, sizeof(words));
5229 for (; arg < argc; arg++) {
5230 frlist = fopen(argv[arg], "r");
5231 my_assert_not(frlist, NULL);
5233 while (fgets(line, sizeof(line), frlist)) {
5235 if (*p == 0 || *p == ';')
5238 if (IS_START(p, "#if 0")
5239 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
5243 else if (IS_START(p, "#endif"))
5250 p = next_word(words[0], sizeof(words[0]), p);
5251 if (words[0][0] == 0)
5254 if (rlist_len >= rlist_alloc) {
5255 rlist_alloc = rlist_alloc * 2 + 64;
5256 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
5257 my_assert_not(rlist, NULL);
5259 rlist[rlist_len++] = strdup(words[0]);
5268 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
5270 fout = fopen(argv[arg_out], "w");
5271 my_assert_not(fout, NULL);
5274 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
5275 my_assert_not(g_eqs, NULL);
5277 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
5278 g_label_refs[i].i = -1;
5279 g_label_refs[i].next = NULL;
5282 while (fgets(line, sizeof(line), fasm))
5291 // get rid of random tabs
5292 for (i = 0; line[i] != 0; i++)
5293 if (line[i] == '\t')
5298 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
5299 goto do_pending_endp; // eww..
5301 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
5303 static const char *attrs[] = {
5312 // parse IDA's attribute-list comment
5313 g_ida_func_attr = 0;
5316 for (; *p != 0; p = sskip(p)) {
5317 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
5318 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
5319 g_ida_func_attr |= 1 << i;
5320 p += strlen(attrs[i]);
5324 if (i == ARRAY_SIZE(attrs)) {
5325 anote("unparsed IDA attr: %s\n", p);
5328 if (IS(attrs[i], "fpd=")) {
5329 p = next_word(words[0], sizeof(words[0]), p);
5334 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
5337 next_word(words[0], sizeof(words[0]), p);
5338 if (words[0][0] == 0)
5339 aerr("missing name for func chunk?\n");
5341 if (!scanned_ahead) {
5342 add_func_chunk(fasm, words[0], asmln);
5343 func_chunks_sorted = 0;
5346 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
5348 if (func_chunk_i >= 0) {
5349 if (func_chunk_i < func_chunk_cnt
5350 && IS(func_chunks[func_chunk_i].name, g_func))
5352 // move on to next chunk
5353 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5355 aerr("seek failed for '%s' chunk #%d\n",
5356 g_func, func_chunk_i);
5357 asmln = func_chunks[func_chunk_i].asmln;
5361 if (func_chunk_ret == 0)
5362 aerr("no return from chunk?\n");
5363 fseek(fasm, func_chunk_ret, SEEK_SET);
5364 asmln = func_chunk_ret_ln;
5370 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
5371 func_chunks_used = 1;
5373 if (IS_START(g_func, "sub_")) {
5374 unsigned long addr = strtoul(p, NULL, 16);
5375 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
5376 if (addr > f_addr && !scanned_ahead) {
5377 anote("scan_ahead caused by '%s', addr %lx\n",
5381 func_chunks_sorted = 0;
5389 for (i = wordc; i < ARRAY_SIZE(words); i++)
5391 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
5392 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
5393 if (*p == 0 || *p == ';') {
5398 if (*p != 0 && *p != ';')
5399 aerr("too many words\n");
5401 // alow asm patches in comments
5403 if (IS_START(p, "; sctpatch:")) {
5405 if (*p == 0 || *p == ';')
5407 goto parse_words; // lame
5409 if (IS_START(p, "; sctproto:")) {
5410 sctproto = strdup(p + 11);
5412 else if (IS_START(p, "; sctend")) {
5421 awarn("wordc == 0?\n");
5425 // don't care about this:
5426 if (words[0][0] == '.'
5427 || IS(words[0], "include")
5428 || IS(words[0], "assume") || IS(words[1], "segment")
5429 || IS(words[0], "align"))
5435 // do delayed endp processing to collect switch jumptables
5437 if (in_func && !skip_func && !end && wordc >= 2
5438 && ((words[0][0] == 'd' && words[0][2] == 0)
5439 || (words[1][0] == 'd' && words[1][2] == 0)))
5442 if (words[1][0] == 'd' && words[1][2] == 0) {
5444 if (g_func_pd_cnt >= pd_alloc) {
5445 pd_alloc = pd_alloc * 2 + 16;
5446 g_func_pd = realloc(g_func_pd,
5447 sizeof(g_func_pd[0]) * pd_alloc);
5448 my_assert_not(g_func_pd, NULL);
5450 pd = &g_func_pd[g_func_pd_cnt];
5452 memset(pd, 0, sizeof(*pd));
5453 strcpy(pd->label, words[0]);
5454 pd->type = OPT_CONST;
5455 pd->lmod = lmod_from_directive(words[1]);
5461 anote("skipping alignment byte?\n");
5464 lmod = lmod_from_directive(words[0]);
5465 if (lmod != pd->lmod)
5466 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
5469 if (pd->count_alloc < pd->count + wordc) {
5470 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
5471 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
5472 my_assert_not(pd->d, NULL);
5474 for (; i < wordc; i++) {
5475 if (IS(words[i], "offset")) {
5476 pd->type = OPT_OFFSET;
5479 p = strchr(words[i], ',');
5482 if (pd->type == OPT_OFFSET)
5483 pd->d[pd->count].u.label = strdup(words[i]);
5485 pd->d[pd->count].u.val = parse_number(words[i]);
5486 pd->d[pd->count].bt_i = -1;
5492 if (in_func && !skip_func)
5493 gen_func(fout, g_fhdr, g_func, pi);
5497 g_ida_func_attr = 0;
5501 func_chunks_used = 0;
5504 memset(&ops, 0, pi * sizeof(ops[0]));
5505 memset(g_labels, 0, pi * sizeof(g_labels[0]));
5509 for (i = 0; i < g_func_pd_cnt; i++) {
5511 if (pd->type == OPT_OFFSET) {
5512 for (j = 0; j < pd->count; j++)
5513 free(pd->d[j].u.label);
5527 if (IS(words[1], "proc")) {
5529 aerr("proc '%s' while in_func '%s'?\n",
5532 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
5534 strcpy(g_func, words[0]);
5535 set_label(0, words[0]);
5540 if (IS(words[1], "endp"))
5543 aerr("endp '%s' while not in_func?\n", words[0]);
5544 if (!IS(g_func, words[0]))
5545 aerr("endp '%s' while in_func '%s'?\n",
5548 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
5549 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
5555 if (!skip_func && func_chunks_used) {
5556 // start processing chunks
5557 struct chunk_item *ci, key = { g_func, 0 };
5559 func_chunk_ret = ftell(fasm);
5560 func_chunk_ret_ln = asmln;
5561 if (!func_chunks_sorted) {
5562 qsort(func_chunks, func_chunk_cnt,
5563 sizeof(func_chunks[0]), cmp_chunks);
5564 func_chunks_sorted = 1;
5566 ci = bsearch(&key, func_chunks, func_chunk_cnt,
5567 sizeof(func_chunks[0]), cmp_chunks);
5569 aerr("'%s' needs chunks, but none found\n", g_func);
5570 func_chunk_i = ci - func_chunks;
5571 for (; func_chunk_i > 0; func_chunk_i--)
5572 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
5575 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5577 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
5578 asmln = func_chunks[func_chunk_i].asmln;
5586 if (wordc == 2 && IS(words[1], "ends")) {
5590 goto do_pending_endp;
5594 // scan for next text segment
5595 while (fgets(line, sizeof(line), fasm)) {
5598 if (*p == 0 || *p == ';')
5601 if (strstr(p, "segment para public 'CODE' use32"))
5608 p = strchr(words[0], ':');
5610 set_label(pi, words[0]);
5614 if (!in_func || skip_func) {
5615 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
5617 anote("skipping from '%s'\n", g_labels[pi]);
5620 g_labels[pi][0] = 0;
5624 if (wordc > 1 && IS(words[1], "="))
5627 aerr("unhandled equ, wc=%d\n", wordc);
5628 if (g_eqcnt >= eq_alloc) {
5630 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
5631 my_assert_not(g_eqs, NULL);
5634 len = strlen(words[0]);
5635 if (len > sizeof(g_eqs[0].name) - 1)
5636 aerr("equ name too long: %d\n", len);
5637 strcpy(g_eqs[g_eqcnt].name, words[0]);
5639 if (!IS(words[3], "ptr"))
5640 aerr("unhandled equ\n");
5641 if (IS(words[2], "dword"))
5642 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
5643 else if (IS(words[2], "word"))
5644 g_eqs[g_eqcnt].lmod = OPLM_WORD;
5645 else if (IS(words[2], "byte"))
5646 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
5647 else if (IS(words[2], "qword"))
5648 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
5650 aerr("bad lmod: '%s'\n", words[2]);
5652 g_eqs[g_eqcnt].offset = parse_number(words[4]);
5657 if (pi >= ARRAY_SIZE(ops))
5658 aerr("too many ops\n");
5660 parse_op(&ops[pi], words, wordc);
5662 if (sctproto != NULL) {
5663 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
5664 ops[pi].datap = sctproto;
5677 // vim:ts=2:shiftwidth=2:expandtab