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 from code generation */
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 */
52 OPF_FARGNR = (1 << 12), /* push collected as func arg (no reuse) */
53 OPF_EBP_S = (1 << 13), /* ebp used as scratch here, not BP */
54 OPF_DF = (1 << 14), /* DF flag set */
55 OPF_ATAIL = (1 << 15), /* tail call with reused arg frame */
56 OPF_32BIT = (1 << 16), /* 32bit division */
57 OPF_LOCK = (1 << 17), /* op has lock prefix */
58 OPF_VAPUSH = (1 << 18), /* vararg ptr push (as call arg) */
59 OPF_DONE = (1 << 19), /* already fully handled by analysis */
129 // must be sorted (larger len must be further in enum)
138 #define MAX_OPERANDS 3
143 enum opr_lenmod lmod;
144 unsigned int is_ptr:1; // pointer in C
145 unsigned int is_array:1; // array in C
146 unsigned int type_from_var:1; // .. in header, sometimes wrong
147 unsigned int size_mismatch:1; // type override differs from C
148 unsigned int size_lt:1; // type override is larger than C
149 unsigned int had_ds:1; // had ds: prefix
150 const struct parsed_proto *pp; // for OPT_LABEL
158 struct parsed_opr operand[MAX_OPERANDS];
161 unsigned char pfo_inv;
162 unsigned char operand_cnt;
163 unsigned char p_argnum; // arg push: altered before call arg #
164 unsigned char p_arggrp; // arg push: arg group # for above
165 unsigned char p_argpass;// arg push: arg of host func
166 short p_argnext;// arg push: same arg pushed elsewhere or -1
167 int regmask_src; // all referensed regs
169 int pfomask; // flagop: parsed_flag_op that can't be delayed
170 int cc_scratch; // scratch storage during analysis
171 int bt_i; // branch target for branches
172 struct parsed_data *btj;// branch targets for jumptables
173 struct parsed_proto *pp;// parsed_proto for OP_CALL
179 // OP_CALL - parser proto hint (str)
180 // (OPF_CC) - points to one of (OPF_FLAGS) that affects cc op
181 // OP_POP - points to OP_PUSH in push/pop pair
185 enum opr_lenmod lmod;
192 enum opr_lenmod lmod;
206 struct label_ref *next;
210 IDAFA_BP_FRAME = (1 << 0),
211 IDAFA_LIB_FUNC = (1 << 1),
212 IDAFA_STATIC = (1 << 2),
213 IDAFA_NORETURN = (1 << 3),
214 IDAFA_THUNK = (1 << 4),
215 IDAFA_FPD = (1 << 5),
218 // note: limited to 32k due to p_argnext
220 #define MAX_ARG_GRP 2
222 static struct parsed_op ops[MAX_OPS];
223 static struct parsed_equ *g_eqs;
225 static char *g_labels[MAX_OPS];
226 static struct label_ref g_label_refs[MAX_OPS];
227 static const struct parsed_proto *g_func_pp;
228 static struct parsed_data *g_func_pd;
229 static int g_func_pd_cnt;
230 static char g_func[256];
231 static char g_comment[256];
232 static int g_bp_frame;
233 static int g_sp_frame;
234 static int g_stack_frame_used;
235 static int g_stack_fsz;
236 static int g_ida_func_attr;
237 static int g_skip_func;
238 static int g_allow_regfunc;
239 static int g_quiet_pp;
240 static int g_header_mode;
242 #define ferr(op_, fmt, ...) do { \
243 printf("%s:%d: error: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
244 dump_op(op_), ##__VA_ARGS__); \
248 #define fnote(op_, fmt, ...) \
249 printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
250 dump_op(op_), ##__VA_ARGS__)
252 #define ferr_assert(op_, cond) do { \
253 if (!(cond)) ferr(op_, "assertion '%s' failed on ln :%d\n", #cond, \
257 const char *regs_r32[] = {
258 "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
259 // not r32, but list here for easy parsing and printing
260 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
262 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
263 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
264 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
266 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
268 // possible basic comparison types (without inversion)
269 enum parsed_flag_op {
273 PFO_BE, // 6 CF=1||ZF=1
277 PFO_LE, // e ZF=1||SF!=OF
280 #define PFOB_O (1 << PFO_O)
281 #define PFOB_C (1 << PFO_C)
282 #define PFOB_Z (1 << PFO_Z)
283 #define PFOB_S (1 << PFO_S)
285 static const char *parsed_flag_op_names[] = {
286 "o", "c", "z", "be", "s", "p", "l", "le"
289 static int char_array_i(const char *array[], size_t len, const char *s)
293 for (i = 0; i < len; i++)
300 static void printf_number(char *buf, size_t buf_size,
301 unsigned long number)
303 // output in C-friendly form
304 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
307 static int check_segment_prefix(const char *s)
309 if (s[0] == 0 || s[1] != 's' || s[2] != ':')
323 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
327 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
329 *reg_lmod = OPLM_QWORD;
333 *reg_lmod = OPLM_DWORD;
336 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
338 *reg_lmod = OPLM_WORD;
341 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
343 *reg_lmod = OPLM_BYTE;
346 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
348 *reg_lmod = OPLM_BYTE;
355 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
357 enum opr_lenmod lmod;
370 while (my_isblank(*s))
372 for (; my_issep(*s); d++, s++)
374 while (my_isblank(*s))
378 // skip '?s:' prefixes
379 if (check_segment_prefix(s))
382 s = next_idt(w, sizeof(w), s);
387 reg = parse_reg(&lmod, w);
389 *regmask |= 1 << reg;
393 if ('0' <= w[0] && w[0] <= '9') {
394 number = parse_number(w);
395 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
399 // probably some label/identifier - pass
402 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
406 strcpy(name, cvtbuf);
411 static int is_reg_in_str(const char *s)
415 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
418 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
419 if (!strncmp(s, regs_r32[i], 3))
425 static const char *parse_stack_el(const char *name, char *extra_reg,
428 const char *p, *p2, *s;
434 if (g_bp_frame || early_try)
437 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
439 if (extra_reg != NULL) {
440 strncpy(extra_reg, name, 3);
445 if (IS_START(p, "ebp+")) {
449 if (p2 != NULL && is_reg_in_str(p)) {
450 if (extra_reg != NULL) {
451 strncpy(extra_reg, p, p2 - p);
452 extra_reg[p2 - p] = 0;
457 if (!('0' <= *p && *p <= '9'))
464 if (!IS_START(name, "esp+"))
470 if (is_reg_in_str(s)) {
471 if (extra_reg != NULL) {
472 strncpy(extra_reg, s, p - s);
473 extra_reg[p - s] = 0;
478 aerr("%s IDA stackvar not set?\n", __func__);
480 if (!('0' <= *s && *s <= '9')) {
481 aerr("%s IDA stackvar offset not set?\n", __func__);
484 if (s[0] == '0' && s[1] == 'x')
487 if (len < sizeof(buf) - 1) {
488 strncpy(buf, s, len);
490 val = strtol(buf, &endp, 16);
491 if (val == 0 || *endp != 0) {
492 aerr("%s num parse fail for '%s'\n", __func__, buf);
501 if ('0' <= *p && *p <= '9')
507 static int guess_lmod_from_name(struct parsed_opr *opr)
509 if (!strncmp(opr->name, "dword_", 6)) {
510 opr->lmod = OPLM_DWORD;
513 if (!strncmp(opr->name, "word_", 5)) {
514 opr->lmod = OPLM_WORD;
517 if (!strncmp(opr->name, "byte_", 5)) {
518 opr->lmod = OPLM_BYTE;
521 if (!strncmp(opr->name, "qword_", 6)) {
522 opr->lmod = OPLM_QWORD;
528 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
529 const struct parsed_type *c_type)
531 static const char *dword_types[] = {
532 "uint32_t", "int", "_DWORD", "UINT_PTR", "DWORD",
533 "WPARAM", "LPARAM", "UINT", "__int32",
534 "LONG", "HIMC", "BOOL", "size_t",
537 static const char *word_types[] = {
538 "uint16_t", "int16_t", "_WORD", "WORD",
539 "unsigned __int16", "__int16",
541 static const char *byte_types[] = {
542 "uint8_t", "int8_t", "char",
543 "unsigned __int8", "__int8", "BYTE", "_BYTE",
545 // structures.. deal the same as with _UNKNOWN for now
551 if (c_type->is_ptr) {
556 n = skip_type_mod(c_type->name);
558 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
559 if (IS(n, dword_types[i])) {
565 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
566 if (IS(n, word_types[i])) {
572 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
573 if (IS(n, byte_types[i])) {
582 static char *default_cast_to(char *buf, size_t buf_size,
583 struct parsed_opr *opr)
589 if (opr->pp == NULL || opr->pp->type.name == NULL
592 snprintf(buf, buf_size, "%s", "(void *)");
596 snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
600 static enum opr_type lmod_from_directive(const char *d)
604 else if (IS(d, "dw"))
606 else if (IS(d, "db"))
609 aerr("unhandled directive: '%s'\n", d);
613 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
619 *regmask |= 1 << reg;
622 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
625 static int parse_operand(struct parsed_opr *opr,
626 int *regmask, int *regmask_indirect,
627 char words[16][256], int wordc, int w, unsigned int op_flags)
629 const struct parsed_proto *pp = NULL;
630 enum opr_lenmod tmplmod;
631 unsigned long number;
639 aerr("parse_operand w %d, wordc %d\n", w, wordc);
643 for (i = w; i < wordc; i++) {
644 len = strlen(words[i]);
645 if (words[i][len - 1] == ',') {
646 words[i][len - 1] = 0;
652 wordc_in = wordc - w;
654 if ((op_flags & OPF_JMP) && wordc_in > 0
655 && !('0' <= words[w][0] && words[w][0] <= '9'))
657 const char *label = NULL;
659 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
660 && IS(words[w + 1], "ptr"))
661 label = words[w + 2];
662 else if (wordc_in == 2 && IS(words[w], "short"))
663 label = words[w + 1];
664 else if (wordc_in == 1
665 && strchr(words[w], '[') == NULL
666 && parse_reg(&tmplmod, words[w]) < 0)
670 opr->type = OPT_LABEL;
671 ret = check_segment_prefix(label);
674 aerr("fs/gs used\n");
678 strcpy(opr->name, label);
684 if (IS(words[w + 1], "ptr")) {
685 if (IS(words[w], "dword"))
686 opr->lmod = OPLM_DWORD;
687 else if (IS(words[w], "word"))
688 opr->lmod = OPLM_WORD;
689 else if (IS(words[w], "byte"))
690 opr->lmod = OPLM_BYTE;
691 else if (IS(words[w], "qword"))
692 opr->lmod = OPLM_QWORD;
694 aerr("type parsing failed\n");
696 wordc_in = wordc - w;
701 if (IS(words[w], "offset")) {
702 opr->type = OPT_OFFSET;
703 opr->lmod = OPLM_DWORD;
704 strcpy(opr->name, words[w + 1]);
705 pp = proto_parse(g_fhdr, opr->name, 1);
708 if (IS(words[w], "(offset")) {
709 p = strchr(words[w + 1], ')');
711 aerr("parse of bracketed offset failed\n");
713 opr->type = OPT_OFFSET;
714 strcpy(opr->name, words[w + 1]);
720 aerr("parse_operand 1 word expected\n");
722 ret = check_segment_prefix(words[w]);
725 aerr("fs/gs used\n");
727 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
729 strcpy(opr->name, words[w]);
731 if (words[w][0] == '[') {
732 opr->type = OPT_REGMEM;
733 ret = sscanf(words[w], "[%[^]]]", opr->name);
735 aerr("[] parse failure\n");
737 parse_indmode(opr->name, regmask_indirect, 1);
738 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
741 struct parsed_equ *eq =
742 equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
744 opr->lmod = eq->lmod;
748 else if (strchr(words[w], '[')) {
750 p = strchr(words[w], '[');
751 opr->type = OPT_REGMEM;
752 parse_indmode(p, regmask_indirect, 0);
753 strncpy(buf, words[w], p - words[w]);
754 buf[p - words[w]] = 0;
755 pp = proto_parse(g_fhdr, buf, 1);
758 else if (('0' <= words[w][0] && words[w][0] <= '9')
759 || words[w][0] == '-')
761 number = parse_number(words[w]);
762 opr->type = OPT_CONST;
764 printf_number(opr->name, sizeof(opr->name), number);
768 ret = parse_reg(&tmplmod, opr->name);
770 setup_reg_opr(opr, ret, tmplmod, regmask);
774 // most likely var in data segment
775 opr->type = OPT_LABEL;
776 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
780 if (pp->is_fptr || pp->is_func) {
781 opr->lmod = OPLM_DWORD;
785 tmplmod = OPLM_UNSPEC;
786 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
787 anote("unhandled C type '%s' for '%s'\n",
788 pp->type.name, opr->name);
790 if (opr->lmod == OPLM_UNSPEC) {
792 opr->type_from_var = 1;
794 else if (opr->lmod != tmplmod) {
795 opr->size_mismatch = 1;
796 if (tmplmod < opr->lmod)
799 opr->is_ptr = pp->type.is_ptr;
801 opr->is_array = pp->type.is_array;
805 if (opr->lmod == OPLM_UNSPEC)
806 guess_lmod_from_name(opr);
810 static const struct {
815 { "repe", OPF_REP|OPF_REPZ },
816 { "repz", OPF_REP|OPF_REPZ },
817 { "repne", OPF_REP|OPF_REPNZ },
818 { "repnz", OPF_REP|OPF_REPNZ },
819 { "lock", OPF_LOCK }, // ignored for now..
822 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
824 static const struct {
827 unsigned short minopr;
828 unsigned short maxopr;
831 unsigned char pfo_inv;
833 { "nop", OP_NOP, 0, 0, 0 },
834 { "push", OP_PUSH, 1, 1, 0 },
835 { "pop", OP_POP, 1, 1, OPF_DATA },
836 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
837 { "mov" , OP_MOV, 2, 2, OPF_DATA },
838 { "lea", OP_LEA, 2, 2, OPF_DATA },
839 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
840 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
841 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
842 { "not", OP_NOT, 1, 1, OPF_DATA },
843 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
844 { "lodsb",OP_LODS, 0, 0, OPF_DATA },
845 { "lodsw",OP_LODS, 0, 0, OPF_DATA },
846 { "lodsd",OP_LODS, 0, 0, OPF_DATA },
847 { "stosb",OP_STOS, 0, 0, OPF_DATA },
848 { "stosw",OP_STOS, 0, 0, OPF_DATA },
849 { "stosd",OP_STOS, 0, 0, OPF_DATA },
850 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
851 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
852 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
853 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
854 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
855 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
856 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
857 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
858 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
859 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
860 { "cld", OP_CLD, 0, 0, OPF_DATA },
861 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
862 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
863 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
864 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
865 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
866 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
867 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
868 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
869 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
870 { "shrd", OP_SHRD, 3, 3, OPF_DATA|OPF_FLAGS },
871 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
872 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
873 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
874 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
875 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
876 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
877 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
878 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
879 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
880 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
881 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
882 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
883 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
884 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
885 { "test", OP_TEST, 2, 2, OPF_FLAGS },
886 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
887 { "retn", OP_RET, 0, 1, OPF_TAIL },
888 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
889 { "jmp", OP_JMP, 1, 1, OPF_JMP },
890 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
891 { "jo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 0 }, // 70 OF=1
892 { "jno", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 1 }, // 71 OF=0
893 { "jc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72 CF=1
894 { "jb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72
895 { "jnc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73 CF=0
896 { "jnb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
897 { "jae", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
898 { "jz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74 ZF=1
899 { "je", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74
900 { "jnz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75 ZF=0
901 { "jne", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75
902 { "jbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
903 { "jna", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
904 { "ja", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
905 { "jnbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
906 { "js", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 0 }, // 78 SF=1
907 { "jns", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 1 }, // 79 SF=0
908 { "jp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a PF=1
909 { "jpe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a
910 { "jnp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b PF=0
911 { "jpo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b
912 { "jl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c SF!=OF
913 { "jnge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c
914 { "jge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d SF=OF
915 { "jnl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d
916 { "jle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
917 { "jng", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
918 { "jg", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
919 { "jnle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
920 { "seto", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 0 },
921 { "setno", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 1 },
922 { "setc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
923 { "setb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
924 { "setnc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
925 { "setae", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
926 { "setnb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
927 { "setz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
928 { "sete", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
929 { "setnz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
930 { "setne", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
931 { "setbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
932 { "setna", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
933 { "seta", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
934 { "setnbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
935 { "sets", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 0 },
936 { "setns", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 1 },
937 { "setp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
938 { "setpe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
939 { "setnp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
940 { "setpo", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
941 { "setl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
942 { "setnge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
943 { "setge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
944 { "setnl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
945 { "setle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
946 { "setng", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
947 { "setg", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
948 { "setnle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
951 { "emms", OP_EMMS, 0, 0, OPF_DATA },
952 { "movq", OP_MOV, 2, 2, OPF_DATA },
957 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
959 enum opr_lenmod lmod = OPLM_UNSPEC;
960 int prefix_flags = 0;
968 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
969 if (IS(words[w], pref_table[i].name)) {
970 prefix_flags = pref_table[i].flags;
977 aerr("lone prefix: '%s'\n", words[0]);
982 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
983 if (IS(words[w], op_table[i].name))
987 if (i == ARRAY_SIZE(op_table)) {
989 aerr("unhandled op: '%s'\n", words[0]);
994 op->op = op_table[i].op;
995 op->flags = op_table[i].flags | prefix_flags;
996 op->pfo = op_table[i].pfo;
997 op->pfo_inv = op_table[i].pfo_inv;
998 op->regmask_src = op->regmask_dst = 0;
1001 if (op->op == OP_UD2)
1004 for (opr = 0; opr < op_table[i].maxopr; opr++) {
1005 if (opr >= op_table[i].minopr && w >= wordc)
1008 regmask = regmask_ind = 0;
1009 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
1010 words, wordc, w, op->flags);
1012 if (opr == 0 && (op->flags & OPF_DATA))
1013 op->regmask_dst = regmask;
1015 op->regmask_src |= regmask;
1016 op->regmask_src |= regmask_ind;
1020 aerr("parse_op %s incomplete: %d/%d\n",
1021 words[0], w, wordc);
1024 op->operand_cnt = opr;
1025 if (!strncmp(op_table[i].name, "set", 3))
1026 op->operand[0].lmod = OPLM_BYTE;
1029 // first operand is not dst
1032 op->regmask_src |= op->regmask_dst;
1033 op->regmask_dst = 0;
1036 // first operand is src too
1048 op->regmask_src |= op->regmask_dst;
1053 op->regmask_src |= op->regmask_dst;
1054 op->regmask_dst |= op->regmask_src;
1060 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1061 && op->operand[0].lmod == op->operand[1].lmod
1062 && op->operand[0].reg == op->operand[1].reg
1063 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1065 op->regmask_src = 0;
1068 op->regmask_src |= op->regmask_dst;
1071 // ops with implicit argumets
1073 op->operand_cnt = 2;
1074 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1075 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1081 if (op->operand_cnt != 0)
1083 if (words[op_w][4] == 'b')
1085 else if (words[op_w][4] == 'w')
1087 else if (words[op_w][4] == 'd')
1089 op->operand_cnt = 3;
1090 setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1091 lmod, &op->regmask_src);
1092 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1093 op->regmask_dst = op->regmask_src;
1094 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1095 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1100 if (op->operand_cnt != 0)
1102 if (words[op_w][4] == 'b')
1104 else if (words[op_w][4] == 'w')
1106 else if (words[op_w][4] == 'd')
1108 op->operand_cnt = 3;
1109 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1110 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1111 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1112 op->regmask_dst = op->regmask_src;
1116 op->operand_cnt = 1;
1117 op->regmask_src = 1 << xCX;
1118 op->operand[0].type = OPT_REG;
1119 op->operand[0].reg = xCX;
1120 op->operand[0].lmod = OPLM_DWORD;
1124 if (op->operand_cnt != 1)
1129 op->regmask_src |= op->regmask_dst;
1130 op->regmask_dst = (1 << xDX) | (1 << xAX);
1131 if (op->operand[0].lmod == OPLM_UNSPEC)
1132 op->operand[0].lmod = OPLM_DWORD;
1137 // we could set up operands for edx:eax, but there is no real need to
1138 // (see is_opr_modified())
1139 op->regmask_src |= op->regmask_dst;
1140 op->regmask_dst = (1 << xDX) | (1 << xAX);
1141 if (op->operand[0].lmod == OPLM_UNSPEC)
1142 op->operand[0].lmod = OPLM_DWORD;
1150 op->regmask_src |= op->regmask_dst;
1151 if (op->operand[1].lmod == OPLM_UNSPEC)
1152 op->operand[1].lmod = OPLM_BYTE;
1156 op->regmask_src |= op->regmask_dst;
1157 if (op->operand[2].lmod == OPLM_UNSPEC)
1158 op->operand[2].lmod = OPLM_BYTE;
1162 op->regmask_src |= op->regmask_dst;
1163 op->regmask_dst = 0;
1164 if (op->operand[0].lmod == OPLM_UNSPEC
1165 && (op->operand[0].type == OPT_CONST
1166 || op->operand[0].type == OPT_OFFSET
1167 || op->operand[0].type == OPT_LABEL))
1168 op->operand[0].lmod = OPLM_DWORD;
1174 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1175 && op->operand[0].lmod == op->operand[1].lmod
1176 && op->operand[0].reg == op->operand[1].reg
1177 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1179 op->flags |= OPF_RMD | OPF_DONE;
1180 op->regmask_src = op->regmask_dst = 0;
1185 if (op->operand[0].type == OPT_REG
1186 && op->operand[1].type == OPT_REGMEM)
1189 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1190 if (IS(buf, op->operand[1].name))
1191 op->flags |= OPF_RMD | OPF_DONE;
1196 // trashed regs must be explicitly detected later
1197 op->regmask_dst = 0;
1201 op->regmask_dst = (1 << xBP) | (1 << xSP);
1202 op->regmask_src = 1 << xBP;
1210 static const char *op_name(struct parsed_op *po)
1212 static char buf[16];
1216 if (po->op == OP_JCC || po->op == OP_SCC) {
1218 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1221 strcpy(p, parsed_flag_op_names[po->pfo]);
1225 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1226 if (op_table[i].op == po->op)
1227 return op_table[i].name;
1233 static const char *dump_op(struct parsed_op *po)
1235 static char out[128];
1242 snprintf(out, sizeof(out), "%s", op_name(po));
1243 for (i = 0; i < po->operand_cnt; i++) {
1247 snprintf(p, sizeof(out) - (p - out),
1248 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1249 po->operand[i].name);
1255 static const char *lmod_type_u(struct parsed_op *po,
1256 enum opr_lenmod lmod)
1268 ferr(po, "invalid lmod: %d\n", lmod);
1269 return "(_invalid_)";
1273 static const char *lmod_cast_u(struct parsed_op *po,
1274 enum opr_lenmod lmod)
1286 ferr(po, "invalid lmod: %d\n", lmod);
1287 return "(_invalid_)";
1291 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1292 enum opr_lenmod lmod)
1304 ferr(po, "invalid lmod: %d\n", lmod);
1305 return "(_invalid_)";
1309 static const char *lmod_cast_s(struct parsed_op *po,
1310 enum opr_lenmod lmod)
1322 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1323 return "(_invalid_)";
1327 static const char *lmod_cast(struct parsed_op *po,
1328 enum opr_lenmod lmod, int is_signed)
1331 lmod_cast_s(po, lmod) :
1332 lmod_cast_u(po, lmod);
1335 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1347 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1352 static const char *opr_name(struct parsed_op *po, int opr_num)
1354 if (opr_num >= po->operand_cnt)
1355 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1356 return po->operand[opr_num].name;
1359 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1361 if (opr_num >= po->operand_cnt)
1362 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1363 if (po->operand[opr_num].type != OPT_CONST)
1364 ferr(po, "opr %d: const expected\n", opr_num);
1365 return po->operand[opr_num].val;
1368 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1370 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1371 ferr(po, "invalid reg: %d\n", popr->reg);
1372 return regs_r32[popr->reg];
1375 // cast1 is the "final" cast
1376 static const char *simplify_cast(const char *cast1, const char *cast2)
1378 static char buf[256];
1384 if (IS(cast1, cast2))
1386 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1388 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1390 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1392 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1394 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1397 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1401 static const char *simplify_cast_num(const char *cast, unsigned int val)
1403 if (IS(cast, "(u8)") && val < 0x100)
1405 if (IS(cast, "(s8)") && val < 0x80)
1407 if (IS(cast, "(u16)") && val < 0x10000)
1409 if (IS(cast, "(s16)") && val < 0x8000)
1411 if (IS(cast, "(s32)") && val < 0x80000000)
1417 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1426 namelen = strlen(name);
1428 p = strchr(name, '+');
1432 ferr(po, "equ parse failed for '%s'\n", name);
1434 if (IS_START(p, "0x"))
1436 *extra_offs = strtol(p, &endp, 16);
1438 ferr(po, "equ parse failed for '%s'\n", name);
1441 for (i = 0; i < g_eqcnt; i++)
1442 if (strncmp(g_eqs[i].name, name, namelen) == 0
1443 && g_eqs[i].name[namelen] == 0)
1447 ferr(po, "unresolved equ name: '%s'\n", name);
1454 static int is_stack_access(struct parsed_op *po,
1455 const struct parsed_opr *popr)
1457 return (parse_stack_el(popr->name, NULL, 0)
1458 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1459 && IS_START(popr->name, "ebp")));
1462 static void parse_stack_access(struct parsed_op *po,
1463 const char *name, char *ofs_reg, int *offset_out,
1464 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1466 const char *bp_arg = "";
1467 const char *p = NULL;
1468 struct parsed_equ *eq;
1475 if (IS_START(name, "ebp-")
1476 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1479 if (IS_START(p, "0x"))
1481 offset = strtoul(p, &endp, 16);
1485 ferr(po, "ebp- parse of '%s' failed\n", name);
1488 bp_arg = parse_stack_el(name, ofs_reg, 0);
1489 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1490 eq = equ_find(po, bp_arg, &offset);
1492 ferr(po, "detected but missing eq\n");
1493 offset += eq->offset;
1496 if (!strncmp(name, "ebp", 3))
1499 // yes it sometimes LEAs ra for compares..
1500 if (!is_lea && ofs_reg[0] == 0
1501 && stack_ra <= offset && offset < stack_ra + 4)
1503 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1506 *offset_out = offset;
1507 *stack_ra_out = stack_ra;
1509 *bp_arg_out = bp_arg;
1512 static int stack_frame_access(struct parsed_op *po,
1513 struct parsed_opr *popr, char *buf, size_t buf_size,
1514 const char *name, const char *cast, int is_src, int is_lea)
1516 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1517 const char *prefix = "";
1518 const char *bp_arg = NULL;
1519 char ofs_reg[16] = { 0, };
1520 int i, arg_i, arg_s;
1528 if (po->flags & OPF_EBP_S)
1529 ferr(po, "stack_frame_access while ebp is scratch\n");
1531 parse_stack_access(po, name, ofs_reg, &offset,
1532 &stack_ra, &bp_arg, is_lea);
1534 if (offset > stack_ra)
1536 arg_i = (offset - stack_ra - 4) / 4;
1537 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1539 if (g_func_pp->is_vararg
1540 && arg_i == g_func_pp->argc_stack && is_lea)
1542 // should be va_list
1545 snprintf(buf, buf_size, "%sap", cast);
1548 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1549 offset, bp_arg, arg_i);
1551 if (ofs_reg[0] != 0)
1552 ferr(po, "offset reg on arg access?\n");
1554 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1555 if (g_func_pp->arg[i].reg != NULL)
1561 if (i == g_func_pp->argc)
1562 ferr(po, "arg %d not in prototype?\n", arg_i);
1564 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1571 ferr(po, "lea/byte to arg?\n");
1572 if (is_src && (offset & 3) == 0)
1573 snprintf(buf, buf_size, "%sa%d",
1574 simplify_cast(cast, "(u8)"), i + 1);
1576 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1577 cast, offset & 3, i + 1);
1582 ferr(po, "lea/word to arg?\n");
1587 ferr(po, "problematic arg store\n");
1588 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1589 simplify_cast(cast, "*(u16 *)"), i + 1);
1592 ferr(po, "unaligned arg word load\n");
1594 else if (is_src && (offset & 2) == 0)
1595 snprintf(buf, buf_size, "%sa%d",
1596 simplify_cast(cast, "(u16)"), i + 1);
1598 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1599 cast, (offset & 2) ? "HI" : "LO", i + 1);
1611 snprintf(buf, buf_size, "(u32)&a%d + %d",
1614 ferr(po, "unaligned arg store\n");
1616 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1617 snprintf(buf, buf_size, "%s(a%d >> %d)",
1618 prefix, i + 1, (offset & 3) * 8);
1622 snprintf(buf, buf_size, "%s%sa%d",
1623 prefix, is_lea ? "&" : "", i + 1);
1628 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1632 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1635 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1636 if (tmp_lmod != OPLM_DWORD
1637 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1638 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1640 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1641 i + 1, offset, g_func_pp->arg[i].type.name);
1643 // can't check this because msvc likes to reuse
1644 // arg space for scratch..
1645 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1646 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1650 if (g_stack_fsz == 0)
1651 ferr(po, "stack var access without stackframe\n");
1652 g_stack_frame_used = 1;
1654 sf_ofs = g_stack_fsz + offset;
1655 lim = (ofs_reg[0] != 0) ? -4 : 0;
1656 if (offset > 0 || sf_ofs < lim)
1657 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1667 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1668 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1672 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1673 // known unaligned or possibly unaligned
1674 strcat(g_comment, " unaligned");
1676 prefix = "*(u16 *)&";
1677 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1678 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1681 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1685 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1686 // known unaligned or possibly unaligned
1687 strcat(g_comment, " unaligned");
1689 prefix = "*(u32 *)&";
1690 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1691 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1694 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1698 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1705 static void check_func_pp(struct parsed_op *po,
1706 const struct parsed_proto *pp, const char *pfx)
1708 enum opr_lenmod tmp_lmod;
1712 if (pp->argc_reg != 0) {
1713 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1714 pp_print(buf, sizeof(buf), pp);
1715 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1717 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1718 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1719 pfx, pp->argc_reg, pp->argc_stack);
1722 // fptrs must use 32bit args, callsite might have no information and
1723 // lack a cast to smaller types, which results in incorrectly masked
1724 // args passed (callee may assume masked args, it does on ARM)
1725 if (!pp->is_osinc) {
1726 for (i = 0; i < pp->argc; i++) {
1727 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1728 if (ret && tmp_lmod != OPLM_DWORD)
1729 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1730 i + 1, pp->arg[i].type.name);
1735 static const char *check_label_read_ref(struct parsed_op *po,
1738 const struct parsed_proto *pp;
1740 pp = proto_parse(g_fhdr, name, 0);
1742 ferr(po, "proto_parse failed for ref '%s'\n", name);
1745 check_func_pp(po, pp, "ref");
1750 static char *out_src_opr(char *buf, size_t buf_size,
1751 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1754 char tmp1[256], tmp2[256];
1763 switch (popr->type) {
1766 ferr(po, "lea from reg?\n");
1768 switch (popr->lmod) {
1770 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1773 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1776 snprintf(buf, buf_size, "%s%s",
1777 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1780 if (popr->name[1] == 'h') // XXX..
1781 snprintf(buf, buf_size, "%s(%s >> 8)",
1782 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1784 snprintf(buf, buf_size, "%s%s",
1785 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1788 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1793 if (is_stack_access(po, popr)) {
1794 stack_frame_access(po, popr, buf, buf_size,
1795 popr->name, cast, 1, is_lea);
1799 strcpy(expr, popr->name);
1800 if (strchr(expr, '[')) {
1801 // special case: '[' can only be left for label[reg] form
1802 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1804 ferr(po, "parse failure for '%s'\n", expr);
1805 if (tmp1[0] == '(') {
1806 // (off_4FFF50+3)[eax]
1807 p = strchr(tmp1 + 1, ')');
1808 if (p == NULL || p[1] != 0)
1809 ferr(po, "parse failure (2) for '%s'\n", expr);
1811 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1813 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1816 // XXX: do we need more parsing?
1818 snprintf(buf, buf_size, "%s", expr);
1822 snprintf(buf, buf_size, "%s(%s)",
1823 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1827 name = check_label_read_ref(po, popr->name);
1828 if (cast[0] == 0 && popr->is_ptr)
1832 snprintf(buf, buf_size, "(u32)&%s", name);
1833 else if (popr->size_lt)
1834 snprintf(buf, buf_size, "%s%s%s%s", cast,
1835 lmod_cast_u_ptr(po, popr->lmod),
1836 popr->is_array ? "" : "&", name);
1838 snprintf(buf, buf_size, "%s%s%s", cast, name,
1839 popr->is_array ? "[0]" : "");
1843 name = check_label_read_ref(po, popr->name);
1847 ferr(po, "lea an offset?\n");
1848 snprintf(buf, buf_size, "%s&%s", cast, name);
1853 ferr(po, "lea from const?\n");
1855 printf_number(tmp1, sizeof(tmp1), popr->val);
1856 if (popr->val == 0 && strchr(cast, '*'))
1857 snprintf(buf, buf_size, "NULL");
1859 snprintf(buf, buf_size, "%s%s",
1860 simplify_cast_num(cast, popr->val), tmp1);
1864 ferr(po, "invalid src type: %d\n", popr->type);
1870 // note: may set is_ptr (we find that out late for ebp frame..)
1871 static char *out_dst_opr(char *buf, size_t buf_size,
1872 struct parsed_op *po, struct parsed_opr *popr)
1874 switch (popr->type) {
1876 switch (popr->lmod) {
1878 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1881 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1885 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1889 if (popr->name[1] == 'h') // XXX..
1890 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1892 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1895 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1900 if (is_stack_access(po, popr)) {
1901 stack_frame_access(po, popr, buf, buf_size,
1902 popr->name, "", 0, 0);
1906 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1909 if (popr->size_mismatch)
1910 snprintf(buf, buf_size, "%s%s%s",
1911 lmod_cast_u_ptr(po, popr->lmod),
1912 popr->is_array ? "" : "&", popr->name);
1914 snprintf(buf, buf_size, "%s%s", popr->name,
1915 popr->is_array ? "[0]" : "");
1919 ferr(po, "invalid dst type: %d\n", popr->type);
1925 static char *out_src_opr_u32(char *buf, size_t buf_size,
1926 struct parsed_op *po, struct parsed_opr *popr)
1928 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1931 static void out_test_for_cc(char *buf, size_t buf_size,
1932 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1933 enum opr_lenmod lmod, const char *expr)
1935 const char *cast, *scast;
1937 cast = lmod_cast_u(po, lmod);
1938 scast = lmod_cast_s(po, lmod);
1942 case PFO_BE: // CF=1||ZF=1; CF=0
1943 snprintf(buf, buf_size, "(%s%s %s 0)",
1944 cast, expr, is_inv ? "!=" : "==");
1948 case PFO_L: // SF!=OF; OF=0
1949 snprintf(buf, buf_size, "(%s%s %s 0)",
1950 scast, expr, is_inv ? ">=" : "<");
1953 case PFO_LE: // ZF=1||SF!=OF; OF=0
1954 snprintf(buf, buf_size, "(%s%s %s 0)",
1955 scast, expr, is_inv ? ">" : "<=");
1959 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1963 static void out_cmp_for_cc(char *buf, size_t buf_size,
1964 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1966 const char *cast, *scast, *cast_use;
1967 char buf1[256], buf2[256];
1968 enum opr_lenmod lmod;
1970 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
1971 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1972 po->operand[0].lmod, po->operand[1].lmod);
1973 lmod = po->operand[0].lmod;
1975 cast = lmod_cast_u(po, lmod);
1976 scast = lmod_cast_s(po, lmod);
1992 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1995 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1996 if (po->op == OP_DEC)
1997 snprintf(buf2, sizeof(buf2), "1");
1999 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
2003 // note: must be unsigned compare
2004 snprintf(buf, buf_size, "(%s %s %s)",
2005 buf1, is_inv ? ">=" : "<", buf2);
2009 snprintf(buf, buf_size, "(%s %s %s)",
2010 buf1, is_inv ? "!=" : "==", buf2);
2014 // note: must be unsigned compare
2015 snprintf(buf, buf_size, "(%s %s %s)",
2016 buf1, is_inv ? ">" : "<=", buf2);
2019 if (is_inv && lmod == OPLM_BYTE
2020 && po->operand[1].type == OPT_CONST
2021 && po->operand[1].val == 0xff)
2023 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2024 snprintf(buf, buf_size, "(0)");
2028 // note: must be signed compare
2030 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
2031 scast, buf1, buf2, is_inv ? ">=" : "<");
2035 snprintf(buf, buf_size, "(%s %s %s)",
2036 buf1, is_inv ? ">=" : "<", buf2);
2040 snprintf(buf, buf_size, "(%s %s %s)",
2041 buf1, is_inv ? ">" : "<=", buf2);
2049 static void out_cmp_test(char *buf, size_t buf_size,
2050 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2052 char buf1[256], buf2[256], buf3[256];
2054 if (po->op == OP_TEST) {
2055 if (IS(opr_name(po, 0), opr_name(po, 1))) {
2056 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
2059 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2060 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
2061 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2063 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
2064 po->operand[0].lmod, buf3);
2066 else if (po->op == OP_CMP) {
2067 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2070 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2073 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2074 struct parsed_opr *popr2)
2076 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2077 ferr(po, "missing lmod for both operands\n");
2079 if (popr1->lmod == OPLM_UNSPEC)
2080 popr1->lmod = popr2->lmod;
2081 else if (popr2->lmod == OPLM_UNSPEC)
2082 popr2->lmod = popr1->lmod;
2083 else if (popr1->lmod != popr2->lmod) {
2084 if (popr1->type_from_var) {
2085 popr1->size_mismatch = 1;
2086 if (popr1->lmod < popr2->lmod)
2088 popr1->lmod = popr2->lmod;
2090 else if (popr2->type_from_var) {
2091 popr2->size_mismatch = 1;
2092 if (popr2->lmod < popr1->lmod)
2094 popr2->lmod = popr1->lmod;
2097 ferr(po, "conflicting lmods: %d vs %d\n",
2098 popr1->lmod, popr2->lmod);
2102 static const char *op_to_c(struct parsed_op *po)
2126 ferr(po, "op_to_c was supplied with %d\n", po->op);
2130 static void op_set_clear_flag(struct parsed_op *po,
2131 enum op_flags flag_set, enum op_flags flag_clear)
2133 po->flags |= flag_set;
2134 po->flags &= ~flag_clear;
2137 // last op in stream - unconditional branch or ret
2138 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2139 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2140 && ops[_i].op != OP_CALL))
2142 static int scan_for_pop(int i, int opcnt, const char *reg,
2143 int magic, int depth, int *maxdepth, int do_flags)
2145 const struct parsed_proto *pp;
2146 struct parsed_op *po;
2150 for (; i < opcnt; i++) {
2152 if (po->cc_scratch == magic)
2153 break; // already checked
2154 po->cc_scratch = magic;
2156 if (po->flags & OPF_TAIL) {
2157 if (po->op == OP_CALL) {
2158 pp = proto_parse(g_fhdr, po->operand[0].name, g_quiet_pp);
2159 if (pp != NULL && pp->is_noreturn)
2160 // no stack cleanup for noreturn
2163 return -1; // deadend
2166 if ((po->flags & (OPF_RMD|OPF_DONE))
2167 || (po->op == OP_PUSH && po->p_argnum != 0)) // arg push
2170 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2171 if (po->btj != NULL) {
2173 for (j = 0; j < po->btj->count; j++) {
2174 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2175 depth, maxdepth, do_flags);
2177 return ret; // dead end
2183 ferr(po, "dead branch\n");
2187 if (po->flags & OPF_CJMP) {
2188 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2189 depth, maxdepth, do_flags);
2191 return ret; // dead end
2199 if ((po->op == OP_POP || po->op == OP_PUSH)
2200 && po->operand[0].type == OPT_REG
2201 && IS(po->operand[0].name, reg))
2203 if (po->op == OP_PUSH && !(po->flags & OPF_FARGNR)) {
2205 if (depth > *maxdepth)
2208 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2210 else if (po->op == OP_POP) {
2213 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2218 if (depth < 0) // should not happen
2219 ferr(po, "fail with depth\n");
2221 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2230 // scan for pop starting from 'ret' op (all paths)
2231 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2237 for (; i < opcnt; i++) {
2238 if (!(ops[i].flags & OPF_TAIL))
2241 for (j = i - 1; j >= 0; j--) {
2242 if (ops[j].flags & (OPF_RMD|OPF_DONE))
2244 if (ops[j].flags & OPF_JMP)
2247 if (ops[j].op == OP_POP && ops[j].datap == NULL
2248 && ops[j].operand[0].type == OPT_REG
2249 && IS(ops[j].operand[0].name, reg))
2252 ops[j].flags |= flag_set;
2256 if (g_labels[j] != NULL)
2261 return found ? 0 : -1;
2264 static void scan_for_pop_const(int i, int opcnt)
2268 for (j = i + 1; j < opcnt; j++) {
2269 if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
2270 || ops[j].op == OP_PUSH || g_labels[i] != NULL)
2275 if (ops[j].op == OP_POP && !(ops[j].flags & (OPF_RMD|OPF_DONE)))
2277 ops[i].flags |= OPF_RMD | OPF_DONE;
2278 ops[j].flags |= OPF_DONE;
2279 ops[j].datap = &ops[i];
2285 static void scan_propagate_df(int i, int opcnt)
2287 struct parsed_op *po = &ops[i];
2290 for (; i < opcnt; i++) {
2292 if (po->flags & OPF_DF)
2293 return; // already resolved
2294 po->flags |= OPF_DF;
2296 if (po->op == OP_CALL)
2297 ferr(po, "call with DF set?\n");
2299 if (po->flags & OPF_JMP) {
2300 if (po->btj != NULL) {
2302 for (j = 0; j < po->btj->count; j++)
2303 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2308 ferr(po, "dead branch\n");
2312 if (po->flags & OPF_CJMP)
2313 scan_propagate_df(po->bt_i, opcnt);
2319 if (po->flags & OPF_TAIL)
2322 if (po->op == OP_CLD) {
2323 po->flags |= OPF_RMD | OPF_DONE;
2328 ferr(po, "missing DF clear?\n");
2331 // is operand 'opr' modified by parsed_op 'po'?
2332 static int is_opr_modified(const struct parsed_opr *opr,
2333 const struct parsed_op *po)
2337 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2340 if (opr->type == OPT_REG) {
2341 if (po->op == OP_CALL) {
2342 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2343 if ((1 << opr->reg) & mask)
2349 if (po->operand[0].type == OPT_REG) {
2350 if (po->regmask_dst & (1 << opr->reg))
2357 return IS(po->operand[0].name, opr->name);
2360 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2361 static int is_any_opr_modified(const struct parsed_op *po_test,
2362 const struct parsed_op *po, int c_mode)
2367 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2370 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2373 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2376 // in reality, it can wreck any register, but in decompiled C
2377 // version it can only overwrite eax or edx:eax
2378 mask = (1 << xAX) | (1 << xDX);
2382 if (po->op == OP_CALL
2383 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2386 for (i = 0; i < po_test->operand_cnt; i++)
2387 if (IS(po_test->operand[i].name, po->operand[0].name))
2393 // scan for any po_test operand modification in range given
2394 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2397 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2400 for (; i < opcnt; i++) {
2401 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2408 // scan for po_test operand[0] modification in range given
2409 static int scan_for_mod_opr0(struct parsed_op *po_test,
2412 for (; i < opcnt; i++) {
2413 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2420 #define check_i(po, i) \
2422 ferr(po, "bad " #i ": %d\n", i)
2424 static int scan_for_flag_set(int i, int magic, int *branched,
2425 int *setters, int *setter_cnt)
2427 struct label_ref *lr;
2431 if (ops[i].cc_scratch == magic) {
2432 ferr(&ops[i], "%s looped\n", __func__);
2435 ops[i].cc_scratch = magic;
2437 if (g_labels[i] != NULL) {
2440 lr = &g_label_refs[i];
2441 for (; lr->next; lr = lr->next) {
2442 check_i(&ops[i], lr->i);
2443 ret = scan_for_flag_set(lr->i, magic,
2444 branched, setters, setter_cnt);
2449 check_i(&ops[i], lr->i);
2450 if (i > 0 && LAST_OP(i - 1)) {
2454 ret = scan_for_flag_set(lr->i, magic,
2455 branched, setters, setter_cnt);
2461 if (ops[i].flags & OPF_FLAGS) {
2462 setters[*setter_cnt] = i;
2467 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2474 // scan back for cdq, if anything modifies edx, fail
2475 static int scan_for_cdq_edx(int i)
2478 if (g_labels[i] != NULL) {
2479 if (g_label_refs[i].next != NULL)
2481 if (i > 0 && LAST_OP(i - 1)) {
2482 i = g_label_refs[i].i;
2489 if (ops[i].op == OP_CDQ)
2492 if (ops[i].regmask_dst & (1 << xDX))
2499 static int scan_for_reg_clear(int i, int reg)
2502 if (g_labels[i] != NULL) {
2503 if (g_label_refs[i].next != NULL)
2505 if (i > 0 && LAST_OP(i - 1)) {
2506 i = g_label_refs[i].i;
2513 if (ops[i].op == OP_XOR
2514 && ops[i].operand[0].lmod == OPLM_DWORD
2515 && ops[i].operand[0].reg == ops[i].operand[1].reg
2516 && ops[i].operand[0].reg == reg)
2519 if (ops[i].regmask_dst & (1 << reg))
2526 static void patch_esp_adjust(struct parsed_op *po, int adj)
2528 ferr_assert(po, po->op == OP_ADD);
2529 ferr_assert(po, IS(opr_name(po, 0), "esp"));
2530 ferr_assert(po, po->operand[1].type == OPT_CONST);
2532 // this is a bit of a hack, but deals with use of
2533 // single adj for multiple calls
2534 po->operand[1].val -= adj;
2535 po->flags |= OPF_RMD;
2536 if (po->operand[1].val == 0)
2537 po->flags |= OPF_DONE;
2538 ferr_assert(po, (int)po->operand[1].val >= 0);
2541 // scan for positive, constant esp adjust
2542 // multipath case is preliminary
2543 static int scan_for_esp_adjust(int i, int opcnt,
2544 int adj_expect, int *adj, int *is_multipath, int do_update)
2546 struct parsed_op *po;
2549 *adj = *is_multipath = 0;
2551 for (; i < opcnt && *adj < adj_expect; i++) {
2552 if (g_labels[i] != NULL)
2556 if (po->flags & OPF_DONE)
2559 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2560 if (po->operand[1].type != OPT_CONST)
2561 ferr(&ops[i], "non-const esp adjust?\n");
2562 *adj += po->operand[1].val;
2564 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2567 patch_esp_adjust(po, adj_expect);
2569 po->flags |= OPF_RMD;
2573 else if (po->op == OP_PUSH) {
2574 //if (first_pop == -1)
2575 // first_pop = -2; // none
2576 *adj -= lmod_bytes(po, po->operand[0].lmod);
2578 else if (po->op == OP_POP) {
2579 if (!(po->flags & OPF_DONE)) {
2580 // seems like msvc only uses 'pop ecx' for stack realignment..
2581 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2583 if (first_pop == -1 && *adj >= 0)
2586 if (do_update && *adj >= 0) {
2587 po->flags |= OPF_RMD;
2589 po->flags |= OPF_DONE;
2592 *adj += lmod_bytes(po, po->operand[0].lmod);
2594 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2595 if (po->op == OP_JMP && po->btj == NULL) {
2601 if (po->op != OP_CALL)
2603 if (po->operand[0].type != OPT_LABEL)
2605 if (po->pp != NULL && po->pp->is_stdcall)
2607 // assume it's another cdecl call
2611 if (first_pop >= 0) {
2612 // probably 'pop ecx' was used..
2619 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2621 struct parsed_op *po;
2625 ferr(ops, "%s: followed bad branch?\n", __func__);
2627 for (; i < opcnt; i++) {
2629 if (po->cc_scratch == magic)
2631 po->cc_scratch = magic;
2634 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2635 if (po->btj != NULL) {
2637 for (j = 0; j < po->btj->count; j++)
2638 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2642 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2643 if (!(po->flags & OPF_CJMP))
2646 if (po->flags & OPF_TAIL)
2651 static const struct parsed_proto *try_recover_pp(
2652 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2654 const struct parsed_proto *pp = NULL;
2658 // maybe an arg of g_func?
2659 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2661 char ofs_reg[16] = { 0, };
2662 int arg, arg_s, arg_i;
2669 parse_stack_access(po, opr->name, ofs_reg,
2670 &offset, &stack_ra, NULL, 0);
2671 if (ofs_reg[0] != 0)
2672 ferr(po, "offset reg on arg access?\n");
2673 if (offset <= stack_ra) {
2674 // search who set the stack var instead
2675 if (search_instead != NULL)
2676 *search_instead = 1;
2680 arg_i = (offset - stack_ra - 4) / 4;
2681 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2682 if (g_func_pp->arg[arg].reg != NULL)
2688 if (arg == g_func_pp->argc)
2689 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2691 pp = g_func_pp->arg[arg].fptr;
2693 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2694 check_func_pp(po, pp, "icall arg");
2696 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2698 p = strchr(opr->name + 1, '[');
2699 memcpy(buf, opr->name, p - opr->name);
2700 buf[p - opr->name] = 0;
2701 pp = proto_parse(g_fhdr, buf, g_quiet_pp);
2703 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2704 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
2707 ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
2710 check_func_pp(po, pp, "reg-fptr ref");
2716 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2717 int magic, const struct parsed_proto **pp_found, int *multi)
2719 const struct parsed_proto *pp = NULL;
2720 struct parsed_op *po;
2721 struct label_ref *lr;
2723 ops[i].cc_scratch = magic;
2726 if (g_labels[i] != NULL) {
2727 lr = &g_label_refs[i];
2728 for (; lr != NULL; lr = lr->next) {
2729 check_i(&ops[i], lr->i);
2730 scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2732 if (i > 0 && LAST_OP(i - 1))
2740 if (ops[i].cc_scratch == magic)
2742 ops[i].cc_scratch = magic;
2744 if (!(ops[i].flags & OPF_DATA))
2746 if (!is_opr_modified(opr, &ops[i]))
2748 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2749 // most probably trashed by some processing
2754 opr = &ops[i].operand[1];
2755 if (opr->type != OPT_REG)
2759 po = (i >= 0) ? &ops[i] : ops;
2762 // reached the top - can only be an arg-reg
2763 if (opr->type != OPT_REG)
2766 for (i = 0; i < g_func_pp->argc; i++) {
2767 if (g_func_pp->arg[i].reg == NULL)
2769 if (IS(opr->name, g_func_pp->arg[i].reg))
2772 if (i == g_func_pp->argc)
2774 pp = g_func_pp->arg[i].fptr;
2776 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2777 i + 1, g_func_pp->arg[i].reg);
2778 check_func_pp(po, pp, "icall reg-arg");
2781 pp = try_recover_pp(po, opr, NULL);
2783 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2784 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2785 || (*pp_found)->is_stdcall != pp->is_stdcall
2786 || (*pp_found)->is_fptr != pp->is_fptr
2787 || (*pp_found)->argc != pp->argc
2788 || (*pp_found)->argc_reg != pp->argc_reg
2789 || (*pp_found)->argc_stack != pp->argc_stack)
2791 ferr(po, "icall: parsed_proto mismatch\n");
2799 // early check for tail call or branch back
2800 static int is_like_tailjmp(int j)
2802 if (!(ops[j].flags & OPF_JMP))
2805 if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2806 // probably local branch back..
2808 if (ops[j].op == OP_CALL)
2809 // probably noreturn call..
2815 static void scan_prologue_epilogue(int opcnt)
2817 int ecx_push = 0, esp_sub = 0;
2821 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2822 && ops[1].op == OP_MOV
2823 && IS(opr_name(&ops[1], 0), "ebp")
2824 && IS(opr_name(&ops[1], 1), "esp"))
2827 ops[0].flags |= OPF_RMD | OPF_DONE;
2828 ops[1].flags |= OPF_RMD | OPF_DONE;
2831 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2832 g_stack_fsz = opr_const(&ops[2], 1);
2833 ops[2].flags |= OPF_RMD | OPF_DONE;
2837 // another way msvc builds stack frame..
2839 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2841 ops[i].flags |= OPF_RMD | OPF_DONE;
2845 // and another way..
2846 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2847 && ops[i].operand[1].type == OPT_CONST
2848 && ops[i + 1].op == OP_CALL
2849 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2851 g_stack_fsz += ops[i].operand[1].val;
2852 ops[i].flags |= OPF_RMD | OPF_DONE;
2854 ops[i].flags |= OPF_RMD | OPF_DONE;
2861 for (; i < opcnt; i++)
2862 if (ops[i].op == OP_RET)
2865 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2866 if (found && is_like_tailjmp(j))
2871 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
2872 || ops[j].op == OP_LEAVE)
2874 ops[j].flags |= OPF_RMD | OPF_DONE;
2876 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2877 ferr(&ops[j], "'pop ebp' expected\n");
2879 if (g_stack_fsz != 0) {
2880 if (ops[j - 1].op == OP_MOV
2881 && IS(opr_name(&ops[j - 1], 0), "esp")
2882 && IS(opr_name(&ops[j - 1], 1), "ebp"))
2884 ops[j - 1].flags |= OPF_RMD | OPF_DONE;
2886 else if (ops[j].op != OP_LEAVE
2887 && !(g_ida_func_attr & IDAFA_NORETURN))
2889 ferr(&ops[j - 1], "esp restore expected\n");
2892 if (ecx_push && ops[j - 2].op == OP_POP
2893 && IS(opr_name(&ops[j - 2], 0), "ecx"))
2895 ferr(&ops[j - 2], "unexpected ecx pop\n");
2901 } while (i < opcnt);
2908 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2909 ops[i].flags |= OPF_RMD | OPF_DONE;
2915 for (; i < opcnt; i++) {
2916 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2918 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2919 && ops[i].operand[1].type == OPT_CONST)
2921 g_stack_fsz = ops[i].operand[1].val;
2922 ops[i].flags |= OPF_RMD | OPF_DONE;
2928 if (ecx_push && !esp_sub) {
2929 // could actually be args for a call..
2930 for (; i < opcnt; i++)
2931 if (ops[i].op != OP_PUSH)
2934 if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
2935 const struct parsed_proto *pp;
2936 pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
2937 j = pp ? pp->argc_stack : 0;
2938 while (i > 0 && j > 0) {
2940 if (ops[i].op == OP_PUSH) {
2941 ops[i].flags &= ~(OPF_RMD | OPF_DONE);
2946 ferr(&ops[i], "unhandled prologue\n");
2949 i = g_stack_fsz = ecx_push = 0;
2950 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2951 if (!(ops[i].flags & OPF_RMD))
2961 if (ecx_push || esp_sub)
2967 for (; i < opcnt; i++)
2968 if (ops[i].op == OP_RET)
2971 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2972 if (found && is_like_tailjmp(j))
2978 for (l = 0; l < ecx_push; l++) {
2979 if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
2981 else if (ops[j].op == OP_ADD
2982 && IS(opr_name(&ops[j], 0), "esp")
2983 && ops[j].operand[1].type == OPT_CONST)
2986 l += ops[j].operand[1].val / 4 - 1;
2989 ferr(&ops[j], "'pop ecx' expected\n");
2991 ops[j].flags |= OPF_RMD | OPF_DONE;
2995 ferr(&ops[j], "epilogue scan failed\n");
3001 if (ops[j].op != OP_ADD
3002 || !IS(opr_name(&ops[j], 0), "esp")
3003 || ops[j].operand[1].type != OPT_CONST
3004 || ops[j].operand[1].val != g_stack_fsz)
3005 ferr(&ops[j], "'add esp' expected\n");
3007 ops[j].flags |= OPF_RMD | OPF_DONE;
3008 ops[j].operand[1].val = 0; // hack for stack arg scanner
3013 } while (i < opcnt);
3017 static const struct parsed_proto *resolve_icall(int i, int opcnt,
3020 const struct parsed_proto *pp = NULL;
3021 int search_advice = 0;
3025 switch (ops[i].operand[0].type) {
3029 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3034 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3042 // find an instruction that changed opr before i op
3043 // *op_i must be set to -1 by caller
3044 // *entry is set to 1 if one source is determined to be the caller
3045 // returns 1 if found, *op_i is then set to origin
3046 static int resolve_origin(int i, const struct parsed_opr *opr,
3047 int magic, int *op_i, int *is_caller)
3049 struct label_ref *lr;
3052 if (ops[i].cc_scratch == magic)
3054 ops[i].cc_scratch = magic;
3057 if (g_labels[i] != NULL) {
3058 lr = &g_label_refs[i];
3059 for (; lr != NULL; lr = lr->next) {
3060 check_i(&ops[i], lr->i);
3061 ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3063 if (i > 0 && LAST_OP(i - 1))
3069 if (is_caller != NULL)
3074 if (ops[i].cc_scratch == magic)
3076 ops[i].cc_scratch = magic;
3078 if (!(ops[i].flags & OPF_DATA))
3080 if (!is_opr_modified(opr, &ops[i]))
3086 // XXX: could check if the other op does the same
3095 static int try_resolve_const(int i, const struct parsed_opr *opr,
3096 int magic, unsigned int *val)
3101 ret = resolve_origin(i, opr, magic, &s_i, NULL);
3104 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3107 *val = ops[i].operand[1].val;
3114 static struct parsed_proto *process_call_early(int i, int opcnt,
3117 struct parsed_op *po = &ops[i];
3118 struct parsed_proto *pp;
3124 if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3128 // look for and make use of esp adjust
3130 if (!pp->is_stdcall && pp->argc_stack > 0)
3131 ret = scan_for_esp_adjust(i + 1, opcnt,
3132 pp->argc_stack * 4, &adj, &multipath, 0);
3134 if (pp->argc_stack > adj / 4)
3138 if (ops[ret].op == OP_POP && adj != 4)
3146 static struct parsed_proto *process_call(int i, int opcnt)
3148 struct parsed_op *po = &ops[i];
3149 const struct parsed_proto *pp_c;
3150 struct parsed_proto *pp;
3151 const char *tmpname;
3152 int adj = 0, multipath = 0;
3155 tmpname = opr_name(po, 0);
3160 pp_c = resolve_icall(i, opcnt, &multipath);
3162 if (!pp_c->is_func && !pp_c->is_fptr)
3163 ferr(po, "call to non-func: %s\n", pp_c->name);
3164 pp = proto_clone(pp_c);
3165 my_assert_not(pp, NULL);
3167 // not resolved just to single func
3170 switch (po->operand[0].type) {
3172 // we resolved this call and no longer need the register
3173 po->regmask_src &= ~(1 << po->operand[0].reg);
3183 pp = calloc(1, sizeof(*pp));
3184 my_assert_not(pp, NULL);
3187 ret = scan_for_esp_adjust(i + 1, opcnt,
3188 32*4, &adj, &multipath, 0);
3189 if (ret < 0 || adj < 0) {
3190 if (!g_allow_regfunc)
3191 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3192 pp->is_unresolved = 1;
3196 if (adj > ARRAY_SIZE(pp->arg))
3197 ferr(po, "esp adjust too large: %d\n", adj);
3198 pp->ret_type.name = strdup("int");
3199 pp->argc = pp->argc_stack = adj;
3200 for (arg = 0; arg < pp->argc; arg++)
3201 pp->arg[arg].type.name = strdup("int");
3206 // look for and make use of esp adjust
3209 if (!pp->is_stdcall && pp->argc_stack > 0)
3210 ret = scan_for_esp_adjust(i + 1, opcnt,
3211 pp->argc_stack * 4, &adj, &multipath, 0);
3213 if (pp->is_vararg) {
3214 if (adj / 4 < pp->argc_stack) {
3215 fnote(po, "(this call)\n");
3216 ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3217 adj, pp->argc_stack * 4);
3219 // modify pp to make it have varargs as normal args
3221 pp->argc += adj / 4 - pp->argc_stack;
3222 for (; arg < pp->argc; arg++) {
3223 pp->arg[arg].type.name = strdup("int");
3226 if (pp->argc > ARRAY_SIZE(pp->arg))
3227 ferr(po, "too many args for '%s'\n", tmpname);
3229 if (pp->argc_stack > adj / 4) {
3230 fnote(po, "(this call)\n");
3231 ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3232 tmpname, pp->argc_stack * 4, adj);
3235 scan_for_esp_adjust(i + 1, opcnt,
3236 pp->argc_stack * 4, &adj, &multipath, 1);
3238 else if (pp->is_vararg)
3239 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3245 static int collect_call_args_early(struct parsed_op *po, int i,
3246 struct parsed_proto *pp, int *regmask)
3251 for (arg = 0; arg < pp->argc; arg++)
3252 if (pp->arg[arg].reg == NULL)
3255 // first see if it can be easily done
3256 for (j = i; j > 0 && arg < pp->argc; )
3258 if (g_labels[j] != NULL)
3262 if (ops[j].op == OP_CALL)
3264 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3266 else if (ops[j].op == OP_POP)
3268 else if (ops[j].flags & OPF_CJMP)
3270 else if (ops[j].op == OP_PUSH) {
3271 if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3273 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3277 if (pp->arg[arg].type.is_va_list)
3281 for (arg++; arg < pp->argc; arg++)
3282 if (pp->arg[arg].reg == NULL)
3291 for (arg = 0; arg < pp->argc; arg++)
3292 if (pp->arg[arg].reg == NULL)
3295 for (j = i; j > 0 && arg < pp->argc; )
3299 if (ops[j].op == OP_PUSH)
3301 ops[j].p_argnext = -1;
3302 ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3303 pp->arg[arg].datap = &ops[j];
3305 if (ops[j].operand[0].type == OPT_REG)
3306 *regmask |= 1 << ops[j].operand[0].reg;
3308 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
3309 ops[j].flags &= ~OPF_RSAVE;
3312 for (arg++; arg < pp->argc; arg++)
3313 if (pp->arg[arg].reg == NULL)
3321 static int collect_call_args_r(struct parsed_op *po, int i,
3322 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3323 int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
3325 struct parsed_proto *pp_tmp;
3326 struct parsed_op *po_tmp;
3327 struct label_ref *lr;
3328 int need_to_save_current;
3329 int arg_grp_current = 0;
3330 int save_args_seen = 0;
3338 ferr(po, "dead label encountered\n");
3342 for (; arg < pp->argc; arg++)
3343 if (pp->arg[arg].reg == NULL)
3345 magic = (magic & 0xffffff) | (arg << 24);
3347 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
3349 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
3350 if (ops[j].cc_scratch != magic) {
3351 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
3355 // ok: have already been here
3358 ops[j].cc_scratch = magic;
3360 if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
3361 lr = &g_label_refs[j];
3362 if (lr->next != NULL)
3364 for (; lr->next; lr = lr->next) {
3365 check_i(&ops[j], lr->i);
3366 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3368 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3369 arg_grp, arg, magic, need_op_saving, may_reuse);
3374 check_i(&ops[j], lr->i);
3375 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3377 if (j > 0 && LAST_OP(j - 1)) {
3378 // follow last branch in reverse
3383 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3384 arg_grp, arg, magic, need_op_saving, may_reuse);
3390 if (ops[j].op == OP_CALL)
3392 if (pp->is_unresolved)
3397 ferr(po, "arg collect hit unparsed call '%s'\n",
3398 ops[j].operand[0].name);
3399 if (may_reuse && pp_tmp->argc_stack > 0)
3400 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
3401 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
3403 // esp adjust of 0 means we collected it before
3404 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
3405 && (ops[j].operand[1].type != OPT_CONST
3406 || ops[j].operand[1].val != 0))
3408 if (pp->is_unresolved)
3411 ferr(po, "arg collect %d/%d hit esp adjust of %d\n",
3412 arg, pp->argc, ops[j].operand[1].val);
3414 else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
3416 if (pp->is_unresolved)
3419 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
3421 else if (ops[j].flags & OPF_CJMP)
3423 if (pp->is_unresolved)
3428 else if (ops[j].op == OP_PUSH
3429 && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
3431 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
3434 ops[j].p_argnext = -1;
3435 po_tmp = pp->arg[arg].datap;
3437 ops[j].p_argnext = po_tmp - ops;
3438 pp->arg[arg].datap = &ops[j];
3440 need_to_save_current = 0;
3443 if (ops[j].operand[0].type == OPT_REG)
3444 reg = ops[j].operand[0].reg;
3446 if (!need_op_saving) {
3447 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3448 need_to_save_current = (ret >= 0);
3450 if (need_op_saving || need_to_save_current) {
3451 // mark this push as one that needs operand saving
3452 ops[j].flags &= ~OPF_RMD;
3453 if (ops[j].p_argnum == 0) {
3454 ops[j].p_argnum = arg + 1;
3455 save_args |= 1 << arg;
3457 else if (ops[j].p_argnum < arg + 1) {
3458 // XXX: might kill valid var..
3459 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
3460 ops[j].p_argnum = arg + 1;
3461 save_args |= 1 << arg;
3464 if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
3467 if (arg_grp_current >= MAX_ARG_GRP)
3468 ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
3469 ops[j].p_argnum, pp->name);
3472 else if (ops[j].p_argnum == 0)
3473 ops[j].flags |= OPF_RMD;
3475 // some PUSHes are reused by different calls on other branches,
3476 // but that can't happen if we didn't branch, so they
3477 // can be removed from future searches (handles nested calls)
3479 ops[j].flags |= OPF_FARGNR;
3481 ops[j].flags |= OPF_FARG;
3482 ops[j].flags &= ~OPF_RSAVE;
3484 // check for __VALIST
3485 if (!pp->is_unresolved && pp->arg[arg].type.is_va_list) {
3487 ret = resolve_origin(j, &ops[j].operand[0],
3488 magic + 1, &k, NULL);
3489 if (ret == 1 && k >= 0)
3491 if (ops[k].op == OP_LEA) {
3492 snprintf(buf, sizeof(buf), "arg_%X",
3493 g_func_pp->argc_stack * 4);
3494 if (!g_func_pp->is_vararg
3495 || strstr(ops[k].operand[1].name, buf))
3497 ops[k].flags |= OPF_RMD | OPF_DONE;
3498 ops[j].flags |= OPF_RMD | OPF_VAPUSH;
3499 save_args &= ~(1 << arg);
3503 ferr(&ops[j], "lea va_list used, but no vararg?\n");
3505 // check for va_list from g_func_pp arg too
3506 else if (ops[k].op == OP_MOV
3507 && is_stack_access(&ops[k], &ops[k].operand[1]))
3509 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
3510 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
3512 ops[k].flags |= OPF_RMD | OPF_DONE;
3513 ops[j].flags |= OPF_RMD;
3514 ops[j].p_argpass = ret + 1;
3515 save_args &= ~(1 << arg);
3522 *save_arg_vars |= save_args;
3524 // tracking reg usage
3526 *regmask |= 1 << reg;
3529 if (!pp->is_unresolved) {
3531 for (; arg < pp->argc; arg++)
3532 if (pp->arg[arg].reg == NULL)
3535 magic = (magic & 0xffffff) | (arg << 24);
3538 if (ops[j].p_arggrp > arg_grp_current) {
3540 arg_grp_current = ops[j].p_arggrp;
3542 if (ops[j].p_argnum > 0)
3543 save_args_seen |= 1 << (ops[j].p_argnum - 1);
3546 if (arg < pp->argc) {
3547 ferr(po, "arg collect failed for '%s': %d/%d\n",
3548 pp->name, arg, pp->argc);
3552 if (arg_grp_current > *arg_grp)
3553 *arg_grp = arg_grp_current;
3558 static int collect_call_args(struct parsed_op *po, int i,
3559 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3562 // arg group is for cases when pushes for
3563 // multiple funcs are going on
3564 struct parsed_op *po_tmp;
3565 int save_arg_vars_current = 0;
3570 ret = collect_call_args_r(po, i, pp, regmask,
3571 &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
3576 // propagate arg_grp
3577 for (a = 0; a < pp->argc; a++) {
3578 if (pp->arg[a].reg != NULL)
3581 po_tmp = pp->arg[a].datap;
3582 while (po_tmp != NULL) {
3583 po_tmp->p_arggrp = arg_grp;
3584 if (po_tmp->p_argnext > 0)
3585 po_tmp = &ops[po_tmp->p_argnext];
3591 save_arg_vars[arg_grp] |= save_arg_vars_current;
3593 if (pp->is_unresolved) {
3595 pp->argc_stack += ret;
3596 for (a = 0; a < pp->argc; a++)
3597 if (pp->arg[a].type.name == NULL)
3598 pp->arg[a].type.name = strdup("int");
3604 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
3608 for (i = 0; i < pp->argc; i++)
3609 if (pp->arg[i].reg == NULL)
3613 memmove(&pp->arg[i + 1], &pp->arg[i],
3614 sizeof(pp->arg[0]) * pp->argc_stack);
3615 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
3616 pp->arg[i].reg = strdup(reg);
3617 pp->arg[i].type.name = strdup("int");
3622 static void add_label_ref(struct label_ref *lr, int op_i)
3624 struct label_ref *lr_new;
3631 lr_new = calloc(1, sizeof(*lr_new));
3633 lr_new->next = lr->next;
3637 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
3639 struct parsed_op *po = &ops[i];
3640 struct parsed_data *pd;
3641 char label[NAMELEN], *p;
3644 p = strchr(po->operand[0].name, '[');
3648 len = p - po->operand[0].name;
3649 strncpy(label, po->operand[0].name, len);
3652 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3653 if (IS(g_func_pd[j].label, label)) {
3659 //ferr(po, "label '%s' not parsed?\n", label);
3662 if (pd->type != OPT_OFFSET)
3663 ferr(po, "label '%s' with non-offset data?\n", label);
3665 // find all labels, link
3666 for (j = 0; j < pd->count; j++) {
3667 for (l = 0; l < opcnt; l++) {
3668 if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
3669 add_label_ref(&g_label_refs[l], i);
3679 static void clear_labels(int count)
3683 for (i = 0; i < count; i++) {
3684 if (g_labels[i] != NULL) {
3691 static void output_std_flags(FILE *fout, struct parsed_op *po,
3692 int *pfomask, const char *dst_opr_text)
3694 if (*pfomask & (1 << PFO_Z)) {
3695 fprintf(fout, "\n cond_z = (%s%s == 0);",
3696 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
3697 *pfomask &= ~(1 << PFO_Z);
3699 if (*pfomask & (1 << PFO_S)) {
3700 fprintf(fout, "\n cond_s = (%s%s < 0);",
3701 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
3702 *pfomask &= ~(1 << PFO_S);
3707 OPP_FORCE_NORETURN = (1 << 0),
3708 OPP_SIMPLE_ARGS = (1 << 1),
3709 OPP_ALIGN = (1 << 2),
3712 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
3715 const char *cconv = "";
3717 if (pp->is_fastcall)
3718 cconv = "__fastcall ";
3719 else if (pp->is_stdcall && pp->argc_reg == 0)
3720 cconv = "__stdcall ";
3722 fprintf(fout, (flags & OPP_ALIGN) ? "%-16s" : "%s", cconv);
3724 if (pp->is_noreturn || (flags & OPP_FORCE_NORETURN))
3725 fprintf(fout, "noreturn ");
3728 static void output_pp(FILE *fout, const struct parsed_proto *pp,
3733 fprintf(fout, (flags & OPP_ALIGN) ? "%-5s" : "%s ",
3737 output_pp_attrs(fout, pp, flags);
3740 fprintf(fout, "%s", pp->name);
3745 for (i = 0; i < pp->argc; i++) {
3747 fprintf(fout, ", ");
3748 if (pp->arg[i].fptr != NULL && !(flags & OPP_SIMPLE_ARGS)) {
3750 output_pp(fout, pp->arg[i].fptr, 0);
3752 else if (pp->arg[i].type.is_retreg) {
3753 fprintf(fout, "u32 *r_%s", pp->arg[i].reg);
3756 fprintf(fout, "%s", pp->arg[i].type.name);
3758 fprintf(fout, " a%d", i + 1);
3761 if (pp->is_vararg) {
3763 fprintf(fout, ", ");
3764 fprintf(fout, "...");
3769 static int get_pp_arg_regmask(const struct parsed_proto *pp)
3774 for (i = 0; i < pp->argc; i++) {
3775 if (pp->arg[i].reg != NULL) {
3776 reg = char_array_i(regs_r32,
3777 ARRAY_SIZE(regs_r32), pp->arg[i].reg);
3779 ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
3780 pp->arg[i].reg, pp->name);
3781 regmask |= 1 << reg;
3788 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
3794 snprintf(buf1, sizeof(buf1), "%d", grp);
3795 snprintf(buf, buf_size, "s%s_a%d", buf1, num);
3800 static void gen_x_cleanup(int opcnt);
3802 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
3804 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
3805 struct parsed_opr *last_arith_dst = NULL;
3806 char buf1[256], buf2[256], buf3[256], cast[64];
3807 const struct parsed_proto *pp_c;
3808 struct parsed_proto *pp, *pp_tmp;
3809 struct parsed_data *pd;
3810 const char *tmpname;
3812 int save_arg_vars[MAX_ARG_GRP] = { 0, };
3814 int need_tmp_var = 0;
3817 int label_pending = 0;
3818 int regmask_save = 0;
3819 int regmask_arg = 0;
3820 int regmask_now = 0;
3821 int regmask_init = 0;
3832 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
3833 g_stack_frame_used = 0;
3835 g_func_pp = proto_parse(fhdr, funcn, 0);
3836 if (g_func_pp == NULL)
3837 ferr(ops, "proto_parse failed for '%s'\n", funcn);
3839 regmask_arg = get_pp_arg_regmask(g_func_pp);
3842 // - handle ebp/esp frame, remove ops related to it
3843 scan_prologue_epilogue(opcnt);
3846 // - parse calls with labels
3847 // - resolve all branches
3848 for (i = 0; i < opcnt; i++)
3854 if (po->flags & (OPF_RMD|OPF_DONE))
3857 if (po->op == OP_CALL) {
3860 if (po->operand[0].type == OPT_LABEL) {
3861 tmpname = opr_name(po, 0);
3862 if (IS_START(tmpname, "loc_"))
3863 ferr(po, "call to loc_*\n");
3864 pp_c = proto_parse(fhdr, tmpname, 0);
3866 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3868 pp = proto_clone(pp_c);
3869 my_assert_not(pp, NULL);
3871 else if (po->datap != NULL) {
3872 pp = calloc(1, sizeof(*pp));
3873 my_assert_not(pp, NULL);
3875 ret = parse_protostr(po->datap, pp);
3877 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3884 check_func_pp(po, pp, "fptr var call");
3885 if (pp->is_noreturn)
3886 po->flags |= OPF_TAIL;
3892 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3895 if (po->operand[0].type == OPT_REGMEM) {
3896 pd = try_resolve_jumptab(i, opcnt);
3904 for (l = 0; l < opcnt; l++) {
3905 if (g_labels[l] != NULL
3906 && IS(po->operand[0].name, g_labels[l]))
3908 if (l == i + 1 && po->op == OP_JMP) {
3909 // yet another alignment type..
3910 po->flags |= OPF_RMD|OPF_DONE;
3913 add_label_ref(&g_label_refs[l], i);
3919 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3922 if (po->operand[0].type == OPT_LABEL)
3926 ferr(po, "unhandled branch\n");
3930 po->flags |= OPF_TAIL;
3931 if (i > 0 && ops[i - 1].op == OP_POP)
3932 po->flags |= OPF_ATAIL;
3937 // - remove dead labels
3938 // - process trivial calls
3939 for (i = 0; i < opcnt; i++)
3941 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
3947 if (po->flags & (OPF_RMD|OPF_DONE))
3950 if (po->op == OP_CALL)
3952 pp = process_call_early(i, opcnt, &j);
3954 if (!(po->flags & OPF_ATAIL))
3955 // since we know the args, try to collect them
3956 if (collect_call_args_early(po, i, pp, ®mask) != 0)
3962 // commit esp adjust
3963 ops[j].flags |= OPF_RMD;
3964 if (ops[j].op != OP_POP)
3965 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
3967 ops[j].flags |= OPF_DONE;
3970 if (strstr(pp->ret_type.name, "int64"))
3973 po->flags |= OPF_DONE;
3980 // - handle push <const>/pop pairs
3981 for (i = 0; i < opcnt; i++)
3984 if (po->flags & (OPF_RMD|OPF_DONE))
3987 if (po->op == OP_CALL && !(po->flags & OPF_DONE))
3989 pp = process_call(i, opcnt);
3991 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3992 // since we know the args, collect them
3993 collect_call_args(po, i, pp, ®mask, save_arg_vars,
3997 if (strstr(pp->ret_type.name, "int64"))
4000 else if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4001 && !(po->flags & OPF_RSAVE) && po->operand[0].type == OPT_CONST)
4002 scan_for_pop_const(i, opcnt);
4006 // - find POPs for PUSHes, rm both
4007 // - scan for STD/CLD, propagate DF
4008 // - scan for all used registers
4009 // - find flag set ops for their users
4010 // - do unreselved calls
4011 // - declare indirect functions
4012 for (i = 0; i < opcnt; i++)
4015 if (po->flags & (OPF_RMD|OPF_DONE))
4018 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
4019 reg = po->operand[0].reg;
4020 if (!(regmask & (1 << reg)))
4021 // not a reg save after all, rerun scan_for_pop
4022 po->flags &= ~OPF_RSAVE;
4024 regmask_save |= 1 << reg;
4027 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4028 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
4030 if (po->operand[0].type == OPT_REG)
4032 reg = po->operand[0].reg;
4034 ferr(po, "reg not set for push?\n");
4037 ret = scan_for_pop(i + 1, opcnt,
4038 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
4041 ferr(po, "too much depth: %d\n", depth);
4043 po->flags |= OPF_RMD;
4044 scan_for_pop(i + 1, opcnt, po->operand[0].name,
4045 i + opcnt * 4, 0, &depth, 1);
4048 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
4051 if (regmask & (1 << reg)) {
4052 if (regmask_save & (1 << reg))
4053 ferr(po, "%s already saved?\n", po->operand[0].name);
4057 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
4063 if (po->op == OP_STD) {
4064 po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
4065 scan_propagate_df(i + 1, opcnt);
4068 regmask_now = po->regmask_src | po->regmask_dst;
4069 if (regmask_now & (1 << xBP)) {
4070 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4071 if (po->regmask_dst & (1 << xBP))
4072 // compiler decided to drop bp frame and use ebp as scratch
4073 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
4075 regmask_now &= ~(1 << xBP);
4079 regmask |= regmask_now;
4081 if (po->flags & OPF_CC)
4083 int setters[16], cnt = 0, branched = 0;
4085 ret = scan_for_flag_set(i, i + opcnt * 6,
4086 &branched, setters, &cnt);
4087 if (ret < 0 || cnt <= 0)
4088 ferr(po, "unable to trace flag setter(s)\n");
4089 if (cnt > ARRAY_SIZE(setters))
4090 ferr(po, "too many flag setters\n");
4092 for (j = 0; j < cnt; j++)
4094 tmp_op = &ops[setters[j]]; // flag setter
4097 // to get nicer code, we try to delay test and cmp;
4098 // if we can't because of operand modification, or if we
4099 // have arith op, or branch, make it calculate flags explicitly
4100 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4102 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4103 pfomask = 1 << po->pfo;
4105 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4106 pfomask = 1 << po->pfo;
4109 // see if we'll be able to handle based on op result
4110 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4111 && po->pfo != PFO_Z && po->pfo != PFO_S
4112 && po->pfo != PFO_P)
4114 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4116 pfomask = 1 << po->pfo;
4119 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4120 propagate_lmod(tmp_op, &tmp_op->operand[0],
4121 &tmp_op->operand[1]);
4122 if (tmp_op->operand[0].lmod == OPLM_DWORD)
4127 tmp_op->pfomask |= pfomask;
4128 cond_vars |= pfomask;
4130 // note: may overwrite, currently not a problem
4134 if (po->op == OP_RCL || po->op == OP_RCR
4135 || po->op == OP_ADC || po->op == OP_SBB)
4136 cond_vars |= 1 << PFO_C;
4139 if (po->op == OP_CMPS || po->op == OP_SCAS) {
4140 cond_vars |= 1 << PFO_Z;
4142 else if (po->op == OP_MUL
4143 || (po->op == OP_IMUL && po->operand_cnt == 1))
4145 if (po->operand[0].lmod == OPLM_DWORD)
4148 else if (po->op == OP_CALL) {
4149 // note: resolved non-reg calls are OPF_DONE already
4152 ferr(po, "NULL pp\n");
4154 if (pp->is_unresolved) {
4155 int regmask_stack = 0;
4156 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4159 // this is pretty rough guess:
4160 // see ecx and edx were pushed (and not their saved versions)
4161 for (arg = 0; arg < pp->argc; arg++) {
4162 if (pp->arg[arg].reg != NULL)
4165 tmp_op = pp->arg[arg].datap;
4167 ferr(po, "parsed_op missing for arg%d\n", arg);
4168 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4169 regmask_stack |= 1 << tmp_op->operand[0].reg;
4172 if (!((regmask_stack & (1 << xCX))
4173 && (regmask_stack & (1 << xDX))))
4175 if (pp->argc_stack != 0
4176 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4178 pp_insert_reg_arg(pp, "ecx");
4179 pp->is_fastcall = 1;
4180 regmask_init |= 1 << xCX;
4181 regmask |= 1 << xCX;
4183 if (pp->argc_stack != 0
4184 || ((regmask | regmask_arg) & (1 << xDX)))
4186 pp_insert_reg_arg(pp, "edx");
4187 regmask_init |= 1 << xDX;
4188 regmask |= 1 << xDX;
4192 // note: __cdecl doesn't fall into is_unresolved category
4193 if (pp->argc_stack > 0)
4197 for (arg = 0; arg < pp->argc; arg++) {
4198 if (pp->arg[arg].reg != NULL) {
4199 reg = char_array_i(regs_r32,
4200 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
4202 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
4203 if (!(regmask & (1 << reg))) {
4204 regmask_init |= 1 << reg;
4205 regmask |= 1 << reg;
4210 else if (po->op == OP_MOV && po->operand[0].pp != NULL
4211 && po->operand[1].pp != NULL)
4213 // <var> = offset <something>
4214 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4215 && !IS_START(po->operand[1].name, "off_"))
4217 if (!po->operand[0].pp->is_fptr)
4218 ferr(po, "%s not declared as fptr when it should be\n",
4219 po->operand[0].name);
4220 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4221 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4222 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4223 fnote(po, "var: %s\n", buf1);
4224 fnote(po, "func: %s\n", buf2);
4225 ferr(po, "^ mismatch\n");
4229 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
4230 regmask |= 1 << xAX;
4231 else if (po->op == OP_DIV || po->op == OP_IDIV) {
4232 // 32bit division is common, look for it
4233 if (po->op == OP_DIV)
4234 ret = scan_for_reg_clear(i, xDX);
4236 ret = scan_for_cdq_edx(i);
4238 po->flags |= OPF_32BIT;
4242 else if (po->op == OP_CLD)
4243 po->flags |= OPF_RMD | OPF_DONE;
4245 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4251 // - confirm regmask_save, it might have been reduced
4252 if (regmask_save != 0)
4255 for (i = 0; i < opcnt; i++) {
4257 if (po->flags & OPF_RMD)
4260 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
4261 regmask_save |= 1 << po->operand[0].reg;
4265 // output starts here
4267 // define userstack size
4268 if (g_func_pp->is_userstack) {
4269 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4270 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4271 fprintf(fout, "#endif\n");
4274 // the function itself
4275 ferr_assert(ops, !g_func_pp->is_fptr);
4276 output_pp(fout, g_func_pp,
4277 (g_ida_func_attr & IDAFA_NORETURN) ? OPP_FORCE_NORETURN : 0);
4278 fprintf(fout, "\n{\n");
4280 // declare indirect functions
4281 for (i = 0; i < opcnt; i++) {
4283 if (po->flags & OPF_RMD)
4286 if (po->op == OP_CALL) {
4289 ferr(po, "NULL pp\n");
4291 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4292 if (pp->name[0] != 0) {
4293 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4294 memcpy(pp->name, "i_", 2);
4296 // might be declared already
4298 for (j = 0; j < i; j++) {
4299 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4300 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4310 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4313 output_pp(fout, pp, OPP_SIMPLE_ARGS);
4314 fprintf(fout, ";\n");
4319 // output LUTs/jumptables
4320 for (i = 0; i < g_func_pd_cnt; i++) {
4322 fprintf(fout, " static const ");
4323 if (pd->type == OPT_OFFSET) {
4324 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
4326 for (j = 0; j < pd->count; j++) {
4328 fprintf(fout, ", ");
4329 fprintf(fout, "&&%s", pd->d[j].u.label);
4333 fprintf(fout, "%s %s[] =\n { ",
4334 lmod_type_u(ops, pd->lmod), pd->label);
4336 for (j = 0; j < pd->count; j++) {
4338 fprintf(fout, ", ");
4339 fprintf(fout, "%u", pd->d[j].u.val);
4342 fprintf(fout, " };\n");
4346 // declare stack frame, va_arg
4348 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
4349 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
4353 if (g_func_pp->is_userstack) {
4354 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4355 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
4359 if (g_func_pp->is_vararg) {
4360 fprintf(fout, " va_list ap;\n");
4364 // declare arg-registers
4365 for (i = 0; i < g_func_pp->argc; i++) {
4366 if (g_func_pp->arg[i].reg != NULL) {
4367 reg = char_array_i(regs_r32,
4368 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
4369 if (regmask & (1 << reg)) {
4370 if (g_func_pp->arg[i].type.is_retreg)
4371 fprintf(fout, " u32 %s = *r_%s;\n",
4372 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4374 fprintf(fout, " u32 %s = (u32)a%d;\n",
4375 g_func_pp->arg[i].reg, i + 1);
4378 if (g_func_pp->arg[i].type.is_retreg)
4379 ferr(ops, "retreg '%s' is unused?\n",
4380 g_func_pp->arg[i].reg);
4381 fprintf(fout, " // %s = a%d; // unused\n",
4382 g_func_pp->arg[i].reg, i + 1);
4388 regmask_now = regmask & ~regmask_arg;
4389 regmask_now &= ~(1 << xSP);
4390 if (regmask_now & 0x00ff) {
4391 for (reg = 0; reg < 8; reg++) {
4392 if (regmask_now & (1 << reg)) {
4393 fprintf(fout, " u32 %s", regs_r32[reg]);
4394 if (regmask_init & (1 << reg))
4395 fprintf(fout, " = 0");
4396 fprintf(fout, ";\n");
4401 if (regmask_now & 0xff00) {
4402 for (reg = 8; reg < 16; reg++) {
4403 if (regmask_now & (1 << reg)) {
4404 fprintf(fout, " mmxr %s", regs_r32[reg]);
4405 if (regmask_init & (1 << reg))
4406 fprintf(fout, " = { 0, }");
4407 fprintf(fout, ";\n");
4414 for (reg = 0; reg < 8; reg++) {
4415 if (regmask_save & (1 << reg)) {
4416 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
4422 for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
4423 if (save_arg_vars[i] == 0)
4425 for (reg = 0; reg < 32; reg++) {
4426 if (save_arg_vars[i] & (1 << reg)) {
4427 fprintf(fout, " u32 %s;\n",
4428 saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
4435 for (i = 0; i < 8; i++) {
4436 if (cond_vars & (1 << i)) {
4437 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
4444 fprintf(fout, " u32 tmp;\n");
4449 fprintf(fout, " u64 tmp64;\n");
4454 fprintf(fout, "\n");
4456 if (g_func_pp->is_vararg) {
4457 if (g_func_pp->argc_stack == 0)
4458 ferr(ops, "vararg func without stack args?\n");
4459 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
4463 for (i = 0; i < opcnt; i++)
4465 if (g_labels[i] != NULL) {
4466 fprintf(fout, "\n%s:\n", g_labels[i]);
4469 delayed_flag_op = NULL;
4470 last_arith_dst = NULL;
4474 if (po->flags & OPF_RMD)
4479 #define assert_operand_cnt(n_) \
4480 if (po->operand_cnt != n_) \
4481 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4483 // conditional/flag using op?
4484 if (po->flags & OPF_CC)
4490 // we go through all this trouble to avoid using parsed_flag_op,
4491 // which makes generated code much nicer
4492 if (delayed_flag_op != NULL)
4494 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
4495 po->pfo, po->pfo_inv);
4498 else if (last_arith_dst != NULL
4499 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
4500 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
4503 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4504 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
4505 last_arith_dst->lmod, buf3);
4508 else if (tmp_op != NULL) {
4509 // use preprocessed flag calc results
4510 if (!(tmp_op->pfomask & (1 << po->pfo)))
4511 ferr(po, "not prepared for pfo %d\n", po->pfo);
4513 // note: pfo_inv was not yet applied
4514 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
4515 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
4518 ferr(po, "all methods of finding comparison failed\n");
4521 if (po->flags & OPF_JMP) {
4522 fprintf(fout, " if %s", buf1);
4524 else if (po->op == OP_RCL || po->op == OP_RCR
4525 || po->op == OP_ADC || po->op == OP_SBB)
4528 fprintf(fout, " cond_%s = %s;\n",
4529 parsed_flag_op_names[po->pfo], buf1);
4531 else if (po->flags & OPF_DATA) { // SETcc
4532 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
4533 fprintf(fout, " %s = %s;", buf2, buf1);
4536 ferr(po, "unhandled conditional op\n");
4540 pfomask = po->pfomask;
4542 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
4543 struct parsed_opr opr = {0,};
4546 opr.lmod = OPLM_DWORD;
4547 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
4549 if (ret != 1 || uval == 0) {
4550 // we need initial flags for ecx=0 case..
4551 if (i > 0 && ops[i - 1].op == OP_XOR
4552 && IS(ops[i - 1].operand[0].name,
4553 ops[i - 1].operand[1].name))
4555 fprintf(fout, " cond_z = ");
4556 if (pfomask & (1 << PFO_C))
4557 fprintf(fout, "cond_c = ");
4558 fprintf(fout, "0;\n");
4560 else if (last_arith_dst != NULL) {
4561 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4562 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
4563 last_arith_dst->lmod, buf3);
4564 fprintf(fout, " cond_z = %s;\n", buf1);
4567 ferr(po, "missing initial ZF\n");
4574 assert_operand_cnt(2);
4575 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4576 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4577 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
4578 fprintf(fout, " %s = %s;", buf1,
4579 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4584 assert_operand_cnt(2);
4585 po->operand[1].lmod = OPLM_DWORD; // always
4586 fprintf(fout, " %s = %s;",
4587 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4588 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4593 assert_operand_cnt(2);
4594 fprintf(fout, " %s = %s;",
4595 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4596 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4600 assert_operand_cnt(2);
4601 switch (po->operand[1].lmod) {
4603 strcpy(buf3, "(s8)");
4606 strcpy(buf3, "(s16)");
4609 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4611 fprintf(fout, " %s = %s;",
4612 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4613 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4618 assert_operand_cnt(2);
4619 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4620 fprintf(fout, " tmp = %s;",
4621 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4622 fprintf(fout, " %s = %s;",
4623 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4624 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4625 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4626 fprintf(fout, " %s = %stmp;",
4627 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4628 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
4629 snprintf(g_comment, sizeof(g_comment), "xchg");
4633 assert_operand_cnt(1);
4634 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4635 fprintf(fout, " %s = ~%s;", buf1, buf1);
4639 assert_operand_cnt(2);
4640 fprintf(fout, " %s = (s32)%s >> 31;",
4641 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4642 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4643 strcpy(g_comment, "cdq");
4647 assert_operand_cnt(3);
4648 if (po->flags & OPF_REP) {
4653 fprintf(fout, " eax = %sesi; esi %c= %d;",
4654 lmod_cast_u_ptr(po, po->operand[0].lmod),
4655 (po->flags & OPF_DF) ? '-' : '+',
4656 lmod_bytes(po, po->operand[0].lmod));
4657 strcpy(g_comment, "lods");
4662 assert_operand_cnt(3);
4663 if (po->flags & OPF_REP) {
4664 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
4665 (po->flags & OPF_DF) ? '-' : '+',
4666 lmod_bytes(po, po->operand[0].lmod));
4667 fprintf(fout, " %sedi = eax;",
4668 lmod_cast_u_ptr(po, po->operand[0].lmod));
4669 strcpy(g_comment, "rep stos");
4672 fprintf(fout, " %sedi = eax; edi %c= %d;",
4673 lmod_cast_u_ptr(po, po->operand[0].lmod),
4674 (po->flags & OPF_DF) ? '-' : '+',
4675 lmod_bytes(po, po->operand[0].lmod));
4676 strcpy(g_comment, "stos");
4681 assert_operand_cnt(3);
4682 j = lmod_bytes(po, po->operand[0].lmod);
4683 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4684 l = (po->flags & OPF_DF) ? '-' : '+';
4685 if (po->flags & OPF_REP) {
4687 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4690 " %sedi = %sesi;", buf1, buf1);
4691 strcpy(g_comment, "rep movs");
4694 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
4695 buf1, buf1, l, j, l, j);
4696 strcpy(g_comment, "movs");
4701 // repe ~ repeat while ZF=1
4702 assert_operand_cnt(3);
4703 j = lmod_bytes(po, po->operand[0].lmod);
4704 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4705 l = (po->flags & OPF_DF) ? '-' : '+';
4706 if (po->flags & OPF_REP) {
4708 " for (; ecx != 0; ecx--) {\n");
4709 if (pfomask & (1 << PFO_C)) {
4712 " cond_c = %sesi < %sedi;\n", buf1, buf1);
4713 pfomask &= ~(1 << PFO_C);
4716 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
4717 buf1, buf1, l, j, l, j);
4719 " if (cond_z %s 0) break;\n",
4720 (po->flags & OPF_REPZ) ? "==" : "!=");
4723 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4724 (po->flags & OPF_REPZ) ? "e" : "ne");
4728 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4729 buf1, buf1, l, j, l, j);
4730 strcpy(g_comment, "cmps");
4732 pfomask &= ~(1 << PFO_Z);
4733 last_arith_dst = NULL;
4734 delayed_flag_op = NULL;
4738 // only does ZF (for now)
4739 // repe ~ repeat while ZF=1
4740 assert_operand_cnt(3);
4741 j = lmod_bytes(po, po->operand[0].lmod);
4742 l = (po->flags & OPF_DF) ? '-' : '+';
4743 if (po->flags & OPF_REP) {
4745 " for (; ecx != 0; ecx--) {\n");
4747 " cond_z = (%seax == %sedi); edi %c= %d;\n",
4748 lmod_cast_u(po, po->operand[0].lmod),
4749 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4751 " if (cond_z %s 0) break;\n",
4752 (po->flags & OPF_REPZ) ? "==" : "!=");
4755 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4756 (po->flags & OPF_REPZ) ? "e" : "ne");
4759 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
4760 lmod_cast_u(po, po->operand[0].lmod),
4761 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4762 strcpy(g_comment, "scas");
4764 pfomask &= ~(1 << PFO_Z);
4765 last_arith_dst = NULL;
4766 delayed_flag_op = NULL;
4769 // arithmetic w/flags
4772 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4775 assert_operand_cnt(2);
4776 fprintf(fout, " %s %s= %s;",
4777 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4779 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4780 output_std_flags(fout, po, &pfomask, buf1);
4781 last_arith_dst = &po->operand[0];
4782 delayed_flag_op = NULL;
4787 assert_operand_cnt(2);
4788 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4789 if (pfomask & (1 << PFO_C)) {
4790 if (po->operand[1].type == OPT_CONST) {
4791 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4792 j = po->operand[1].val;
4795 if (po->op == OP_SHL)
4799 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
4803 ferr(po, "zero shift?\n");
4807 pfomask &= ~(1 << PFO_C);
4809 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
4810 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4811 output_std_flags(fout, po, &pfomask, buf1);
4812 last_arith_dst = &po->operand[0];
4813 delayed_flag_op = NULL;
4817 assert_operand_cnt(2);
4818 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4819 fprintf(fout, " %s = %s%s >> %s;", buf1,
4820 lmod_cast_s(po, po->operand[0].lmod), buf1,
4821 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4822 output_std_flags(fout, po, &pfomask, buf1);
4823 last_arith_dst = &po->operand[0];
4824 delayed_flag_op = NULL;
4828 assert_operand_cnt(3);
4829 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4830 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4831 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4832 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4833 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
4834 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
4835 buf1, buf3, buf1, buf2, l, buf3);
4836 strcpy(g_comment, "shrd");
4837 output_std_flags(fout, po, &pfomask, buf1);
4838 last_arith_dst = &po->operand[0];
4839 delayed_flag_op = NULL;
4844 assert_operand_cnt(2);
4845 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4846 if (po->operand[1].type == OPT_CONST) {
4847 j = po->operand[1].val;
4848 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4849 fprintf(fout, po->op == OP_ROL ?
4850 " %s = (%s << %d) | (%s >> %d);" :
4851 " %s = (%s >> %d) | (%s << %d);",
4852 buf1, buf1, j, buf1,
4853 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4857 output_std_flags(fout, po, &pfomask, buf1);
4858 last_arith_dst = &po->operand[0];
4859 delayed_flag_op = NULL;
4864 assert_operand_cnt(2);
4865 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4866 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4867 if (po->operand[1].type == OPT_CONST) {
4868 j = po->operand[1].val % l;
4870 ferr(po, "zero rotate\n");
4871 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
4872 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4873 if (po->op == OP_RCL) {
4875 " %s = (%s << %d) | (cond_c << %d)",
4876 buf1, buf1, j, j - 1);
4878 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4882 " %s = (%s >> %d) | (cond_c << %d)",
4883 buf1, buf1, j, l - j);
4885 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4887 fprintf(fout, ";\n");
4888 fprintf(fout, " cond_c = tmp;");
4892 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4893 output_std_flags(fout, po, &pfomask, buf1);
4894 last_arith_dst = &po->operand[0];
4895 delayed_flag_op = NULL;
4899 assert_operand_cnt(2);
4900 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4901 if (IS(opr_name(po, 0), opr_name(po, 1))) {
4902 // special case for XOR
4903 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4904 fprintf(fout, " cond_be = 1;\n");
4905 pfomask &= ~(1 << PFO_BE);
4907 fprintf(fout, " %s = 0;",
4908 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4909 last_arith_dst = &po->operand[0];
4910 delayed_flag_op = NULL;
4916 assert_operand_cnt(2);
4917 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4918 if (pfomask & (1 << PFO_C)) {
4919 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4920 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4921 if (po->operand[0].lmod == OPLM_DWORD) {
4922 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
4923 fprintf(fout, " cond_c = tmp64 >> 32;\n");
4924 fprintf(fout, " %s = (u32)tmp64;",
4925 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4926 strcat(g_comment, "add64");
4929 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
4930 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
4931 fprintf(fout, " %s += %s;",
4932 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4935 pfomask &= ~(1 << PFO_C);
4936 output_std_flags(fout, po, &pfomask, buf1);
4937 last_arith_dst = &po->operand[0];
4938 delayed_flag_op = NULL;
4944 assert_operand_cnt(2);
4945 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4946 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
4947 for (j = 0; j <= PFO_LE; j++) {
4948 if (!(pfomask & (1 << j)))
4950 if (j == PFO_Z || j == PFO_S)
4953 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4954 fprintf(fout, " cond_%s = %s;\n",
4955 parsed_flag_op_names[j], buf1);
4956 pfomask &= ~(1 << j);
4963 assert_operand_cnt(2);
4964 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4965 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4966 if (po->op == OP_SBB
4967 && IS(po->operand[0].name, po->operand[1].name))
4969 // avoid use of unitialized var
4970 fprintf(fout, " %s = -cond_c;", buf1);
4971 // carry remains what it was
4972 pfomask &= ~(1 << PFO_C);
4975 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
4976 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4978 output_std_flags(fout, po, &pfomask, buf1);
4979 last_arith_dst = &po->operand[0];
4980 delayed_flag_op = NULL;
4984 assert_operand_cnt(2);
4985 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4986 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4987 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4989 output_std_flags(fout, po, &pfomask, buf1);
4990 last_arith_dst = &po->operand[0];
4991 delayed_flag_op = NULL;
4992 strcat(g_comment, "bsf");
4996 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
4997 for (j = 0; j <= PFO_LE; j++) {
4998 if (!(pfomask & (1 << j)))
5000 if (j == PFO_Z || j == PFO_S || j == PFO_C)
5003 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5004 fprintf(fout, " cond_%s = %s;\n",
5005 parsed_flag_op_names[j], buf1);
5006 pfomask &= ~(1 << j);
5012 if (pfomask & (1 << PFO_C))
5013 // carry is unaffected by inc/dec.. wtf?
5014 ferr(po, "carry propagation needed\n");
5016 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5017 if (po->operand[0].type == OPT_REG) {
5018 strcpy(buf2, po->op == OP_INC ? "++" : "--");
5019 fprintf(fout, " %s%s;", buf1, buf2);
5022 strcpy(buf2, po->op == OP_INC ? "+" : "-");
5023 fprintf(fout, " %s %s= 1;", buf1, buf2);
5025 output_std_flags(fout, po, &pfomask, buf1);
5026 last_arith_dst = &po->operand[0];
5027 delayed_flag_op = NULL;
5031 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5032 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5033 fprintf(fout, " %s = -%s%s;", buf1,
5034 lmod_cast_s(po, po->operand[0].lmod), buf2);
5035 last_arith_dst = &po->operand[0];
5036 delayed_flag_op = NULL;
5037 if (pfomask & (1 << PFO_C)) {
5038 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
5039 pfomask &= ~(1 << PFO_C);
5044 if (po->operand_cnt == 2) {
5045 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5048 if (po->operand_cnt == 3)
5049 ferr(po, "TODO imul3\n");
5052 assert_operand_cnt(1);
5053 switch (po->operand[0].lmod) {
5055 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5056 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
5057 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5058 fprintf(fout, " edx = tmp64 >> 32;\n");
5059 fprintf(fout, " eax = tmp64;");
5062 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5063 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
5064 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5068 ferr(po, "TODO: unhandled mul type\n");
5071 last_arith_dst = NULL;
5072 delayed_flag_op = NULL;
5077 assert_operand_cnt(1);
5078 if (po->operand[0].lmod != OPLM_DWORD)
5079 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5081 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5082 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5083 po->op == OP_IDIV));
5084 switch (po->operand[0].lmod) {
5086 if (po->flags & OPF_32BIT)
5087 snprintf(buf3, sizeof(buf3), "%seax", buf2);
5089 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
5090 snprintf(buf3, sizeof(buf3), "%stmp64",
5091 (po->op == OP_IDIV) ? "(s64)" : "");
5093 if (po->operand[0].type == OPT_REG
5094 && po->operand[0].reg == xDX)
5096 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5097 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5100 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5101 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5105 ferr(po, "unhandled division type\n");
5107 last_arith_dst = NULL;
5108 delayed_flag_op = NULL;
5113 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5115 for (j = 0; j < 8; j++) {
5116 if (pfomask & (1 << j)) {
5117 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5118 fprintf(fout, " cond_%s = %s;",
5119 parsed_flag_op_names[j], buf1);
5126 last_arith_dst = NULL;
5127 delayed_flag_op = po;
5131 // SETcc - should already be handled
5134 // note: we reuse OP_Jcc for SETcc, only flags differ
5136 fprintf(fout, "\n goto %s;", po->operand[0].name);
5140 fprintf(fout, " if (ecx == 0)\n");
5141 fprintf(fout, " goto %s;", po->operand[0].name);
5142 strcat(g_comment, "jecxz");
5146 assert_operand_cnt(1);
5147 last_arith_dst = NULL;
5148 delayed_flag_op = NULL;
5150 if (po->operand[0].type == OPT_REGMEM) {
5151 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5154 ferr(po, "parse failure for jmp '%s'\n",
5155 po->operand[0].name);
5156 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
5159 else if (po->operand[0].type != OPT_LABEL)
5160 ferr(po, "unhandled jmp type\n");
5162 fprintf(fout, " goto %s;", po->operand[0].name);
5166 assert_operand_cnt(1);
5168 my_assert_not(pp, NULL);
5171 if (po->flags & OPF_CC) {
5172 // we treat conditional branch to another func
5173 // (yes such code exists..) as conditional tailcall
5175 fprintf(fout, " {\n");
5178 if (pp->is_fptr && !pp->is_arg) {
5179 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5180 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5182 if (pp->is_unresolved)
5183 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5184 buf3, asmfn, po->asmln, pp->name);
5187 fprintf(fout, "%s", buf3);
5188 if (strstr(pp->ret_type.name, "int64")) {
5189 if (po->flags & OPF_TAIL)
5190 ferr(po, "int64 and tail?\n");
5191 fprintf(fout, "tmp64 = ");
5193 else if (!IS(pp->ret_type.name, "void")) {
5194 if (po->flags & OPF_TAIL) {
5195 if (!IS(g_func_pp->ret_type.name, "void")) {
5196 fprintf(fout, "return ");
5197 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5198 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5201 else if (regmask & (1 << xAX)) {
5202 fprintf(fout, "eax = ");
5203 if (pp->ret_type.is_ptr)
5204 fprintf(fout, "(u32)");
5208 if (pp->name[0] == 0)
5209 ferr(po, "missing pp->name\n");
5210 fprintf(fout, "%s%s(", pp->name,
5211 pp->has_structarg ? "_sa" : "");
5213 if (po->flags & OPF_ATAIL) {
5214 if (pp->argc_stack != g_func_pp->argc_stack
5215 || (pp->argc_stack > 0
5216 && pp->is_stdcall != g_func_pp->is_stdcall))
5217 ferr(po, "incompatible tailcall\n");
5218 if (g_func_pp->has_retreg)
5219 ferr(po, "TODO: retreg+tailcall\n");
5221 for (arg = j = 0; arg < pp->argc; arg++) {
5223 fprintf(fout, ", ");
5226 if (pp->arg[arg].type.is_ptr)
5227 snprintf(cast, sizeof(cast), "(%s)",
5228 pp->arg[arg].type.name);
5230 if (pp->arg[arg].reg != NULL) {
5231 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5235 for (; j < g_func_pp->argc; j++)
5236 if (g_func_pp->arg[j].reg == NULL)
5238 fprintf(fout, "%sa%d", cast, j + 1);
5243 for (arg = 0; arg < pp->argc; arg++) {
5245 fprintf(fout, ", ");
5248 if (pp->arg[arg].type.is_ptr)
5249 snprintf(cast, sizeof(cast), "(%s)",
5250 pp->arg[arg].type.name);
5252 if (pp->arg[arg].reg != NULL) {
5253 if (pp->arg[arg].type.is_retreg)
5254 fprintf(fout, "&%s", pp->arg[arg].reg);
5256 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5261 tmp_op = pp->arg[arg].datap;
5263 ferr(po, "parsed_op missing for arg%d\n", arg);
5265 if (tmp_op->flags & OPF_VAPUSH) {
5266 fprintf(fout, "ap");
5268 else if (tmp_op->p_argpass != 0) {
5269 fprintf(fout, "a%d", tmp_op->p_argpass);
5271 else if (tmp_op->p_argnum != 0) {
5272 fprintf(fout, "%s%s", cast,
5273 saved_arg_name(buf1, sizeof(buf1),
5274 tmp_op->p_arggrp, tmp_op->p_argnum));
5278 out_src_opr(buf1, sizeof(buf1),
5279 tmp_op, &tmp_op->operand[0], cast, 0));
5283 fprintf(fout, ");");
5285 if (strstr(pp->ret_type.name, "int64")) {
5286 fprintf(fout, "\n");
5287 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5288 fprintf(fout, "%seax = tmp64;", buf3);
5291 if (pp->is_unresolved) {
5292 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
5294 strcat(g_comment, buf2);
5297 if (po->flags & OPF_TAIL) {
5299 if (i == opcnt - 1 || pp->is_noreturn)
5301 else if (IS(pp->ret_type.name, "void"))
5303 else if (IS(g_func_pp->ret_type.name, "void"))
5305 // else already handled as 'return f()'
5308 if (!IS(g_func_pp->ret_type.name, "void")) {
5309 ferr(po, "int func -> void func tailcall?\n");
5312 fprintf(fout, "\n%sreturn;", buf3);
5313 strcat(g_comment, " ^ tailcall");
5317 strcat(g_comment, " tailcall");
5319 if (pp->is_noreturn)
5320 strcat(g_comment, " noreturn");
5321 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5322 strcat(g_comment, " argframe");
5323 if (po->flags & OPF_CC)
5324 strcat(g_comment, " cond");
5326 if (po->flags & OPF_CC)
5327 fprintf(fout, "\n }");
5329 delayed_flag_op = NULL;
5330 last_arith_dst = NULL;
5334 if (g_func_pp->is_vararg)
5335 fprintf(fout, " va_end(ap);\n");
5336 if (g_func_pp->has_retreg) {
5337 for (arg = 0; arg < g_func_pp->argc; arg++)
5338 if (g_func_pp->arg[arg].type.is_retreg)
5339 fprintf(fout, " *r_%s = %s;\n",
5340 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
5343 if (IS(g_func_pp->ret_type.name, "void")) {
5344 if (i != opcnt - 1 || label_pending)
5345 fprintf(fout, " return;");
5347 else if (g_func_pp->ret_type.is_ptr) {
5348 fprintf(fout, " return (%s)eax;",
5349 g_func_pp->ret_type.name);
5351 else if (IS(g_func_pp->ret_type.name, "__int64"))
5352 fprintf(fout, " return ((u64)edx << 32) | eax;");
5354 fprintf(fout, " return eax;");
5356 last_arith_dst = NULL;
5357 delayed_flag_op = NULL;
5361 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5362 if (po->p_argnum != 0) {
5363 // special case - saved func arg
5364 fprintf(fout, " %s = %s;",
5365 saved_arg_name(buf2, sizeof(buf2),
5366 po->p_arggrp, po->p_argnum), buf1);
5369 else if (po->flags & OPF_RSAVE) {
5370 fprintf(fout, " s_%s = %s;", buf1, buf1);
5373 else if (g_func_pp->is_userstack) {
5374 fprintf(fout, " *(--esp) = %s;", buf1);
5377 if (!(g_ida_func_attr & IDAFA_NORETURN))
5378 ferr(po, "stray push encountered\n");
5383 if (po->flags & OPF_RSAVE) {
5384 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5385 fprintf(fout, " %s = s_%s;", buf1, buf1);
5388 else if (po->datap != NULL) {
5391 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5392 fprintf(fout, " %s = %s;", buf1,
5393 out_src_opr(buf2, sizeof(buf2),
5394 tmp_op, &tmp_op->operand[0],
5395 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5398 else if (g_func_pp->is_userstack) {
5399 fprintf(fout, " %s = *esp++;",
5400 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5404 ferr(po, "stray pop encountered\n");
5413 strcpy(g_comment, "(emms)");
5418 ferr(po, "unhandled op type %d, flags %x\n",
5423 if (g_comment[0] != 0) {
5424 char *p = g_comment;
5425 while (my_isblank(*p))
5427 fprintf(fout, " // %s", p);
5432 fprintf(fout, "\n");
5434 // some sanity checking
5435 if (po->flags & OPF_REP) {
5436 if (po->op != OP_STOS && po->op != OP_MOVS
5437 && po->op != OP_CMPS && po->op != OP_SCAS)
5438 ferr(po, "unexpected rep\n");
5439 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
5440 && (po->op == OP_CMPS || po->op == OP_SCAS))
5441 ferr(po, "cmps/scas with plain rep\n");
5443 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
5444 && po->op != OP_CMPS && po->op != OP_SCAS)
5445 ferr(po, "unexpected repz/repnz\n");
5448 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
5450 // see is delayed flag stuff is still valid
5451 if (delayed_flag_op != NULL && delayed_flag_op != po) {
5452 if (is_any_opr_modified(delayed_flag_op, po, 0))
5453 delayed_flag_op = NULL;
5456 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
5457 if (is_opr_modified(last_arith_dst, po))
5458 last_arith_dst = NULL;
5464 if (g_stack_fsz && !g_stack_frame_used)
5465 fprintf(fout, " (void)sf;\n");
5467 fprintf(fout, "}\n\n");
5469 gen_x_cleanup(opcnt);
5472 static void gen_x_cleanup(int opcnt)
5476 for (i = 0; i < opcnt; i++) {
5477 struct label_ref *lr, *lr_del;
5479 lr = g_label_refs[i].next;
5480 while (lr != NULL) {
5485 g_label_refs[i].i = -1;
5486 g_label_refs[i].next = NULL;
5488 if (ops[i].op == OP_CALL) {
5490 proto_release(ops[i].pp);
5496 struct func_proto_dep;
5498 struct func_prototype {
5503 int has_ret:3; // -1, 0, 1: unresolved, no, yes
5504 unsigned int dep_resolved:1;
5505 unsigned int is_stdcall:1;
5506 struct func_proto_dep *dep_func;
5508 const struct parsed_proto *pp; // seed pp, if any
5511 struct func_proto_dep {
5513 struct func_prototype *proto;
5514 int regmask_live; // .. at the time of call
5515 unsigned int ret_dep:1; // return from this is caller's return
5518 static struct func_prototype *hg_fp;
5519 static int hg_fp_cnt;
5521 static struct scanned_var {
5523 enum opr_lenmod lmod;
5524 unsigned int is_seeded:1;
5525 unsigned int is_c_str:1;
5526 const struct parsed_proto *pp; // seed pp, if any
5528 static int hg_var_cnt;
5530 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5533 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
5538 for (i = 0; i < fp->dep_func_cnt; i++)
5539 if (IS(fp->dep_func[i].name, name))
5540 return &fp->dep_func[i];
5545 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
5548 if (hg_fp_find_dep(fp, name))
5551 if ((fp->dep_func_cnt & 0xff) == 0) {
5552 fp->dep_func = realloc(fp->dep_func,
5553 sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
5554 my_assert_not(fp->dep_func, NULL);
5555 memset(&fp->dep_func[fp->dep_func_cnt], 0,
5556 sizeof(fp->dep_func[0]) * 0x100);
5558 fp->dep_func[fp->dep_func_cnt].name = strdup(name);
5562 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
5564 const struct func_prototype *p1 = p1_, *p2 = p2_;
5565 return strcmp(p1->name, p2->name);
5569 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
5571 const struct func_prototype *p1 = p1_, *p2 = p2_;
5572 return p1->id - p2->id;
5576 // recursive register dep pass
5577 // - track saved regs (part 2)
5578 // - try to figure out arg-regs
5579 // - calculate reg deps
5580 static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
5581 struct func_prototype *fp, int regmask_save, int regmask_dst,
5582 int *regmask_dep, int *has_ret)
5584 struct func_proto_dep *dep;
5585 struct parsed_op *po;
5586 int from_caller = 0;
5592 for (; i < opcnt; i++)
5594 if (cbits[i >> 3] & (1 << (i & 7)))
5596 cbits[i >> 3] |= (1 << (i & 7));
5600 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
5601 if (po->btj != NULL) {
5603 for (j = 0; j < po->btj->count; j++) {
5604 gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
5605 regmask_save, regmask_dst, regmask_dep, has_ret);
5611 ferr(po, "dead branch\n");
5615 if (po->flags & OPF_CJMP) {
5616 gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
5617 regmask_save, regmask_dst, regmask_dep, has_ret);
5625 if (po->flags & OPF_FARG)
5626 /* (just calculate register deps) */;
5627 else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5629 reg = po->operand[0].reg;
5631 ferr(po, "reg not set for push?\n");
5633 if (po->flags & OPF_RSAVE) {
5634 regmask_save |= 1 << reg;
5637 if (po->flags & OPF_DONE)
5641 ret = scan_for_pop(i + 1, opcnt,
5642 po->operand[0].name, i + opcnt * 2, 0, &depth, 0);
5644 regmask_save |= 1 << reg;
5645 po->flags |= OPF_RMD;
5646 scan_for_pop(i + 1, opcnt,
5647 po->operand[0].name, i + opcnt * 3, 0, &depth, 1);
5651 else if (po->flags & OPF_RMD)
5653 else if (po->op == OP_CALL) {
5654 po->regmask_dst |= 1 << xAX;
5656 dep = hg_fp_find_dep(fp, po->operand[0].name);
5658 dep->regmask_live = regmask_save | regmask_dst;
5660 else if (po->op == OP_RET) {
5661 if (po->operand_cnt > 0) {
5663 if (fp->argc_stack >= 0
5664 && fp->argc_stack != po->operand[0].val / 4)
5665 ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
5666 fp->argc_stack = po->operand[0].val / 4;
5670 if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
5671 if (po->op == OP_CALL) {
5676 struct parsed_opr opr = { 0, };
5681 ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
5684 if (ret == -1 && from_caller) {
5685 // unresolved eax - probably void func
5689 if (ops[j].op == OP_CALL) {
5690 dep = hg_fp_find_dep(fp, po->operand[0].name);
5701 l = regmask_save | regmask_dst;
5702 if (g_bp_frame && !(po->flags & OPF_EBP_S))
5705 l = po->regmask_src & ~l;
5708 fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
5709 l, regmask_dst, regmask_save, po->flags);
5712 regmask_dst |= po->regmask_dst;
5714 if (po->flags & OPF_TAIL)
5719 static void gen_hdr(const char *funcn, int opcnt)
5721 int save_arg_vars[MAX_ARG_GRP] = { 0, };
5722 unsigned char cbits[MAX_OPS / 8];
5723 const struct parsed_proto *pp_c;
5724 struct parsed_proto *pp;
5725 struct func_prototype *fp;
5726 struct parsed_data *pd;
5727 struct parsed_op *po;
5728 const char *tmpname;
5729 int regmask_dummy = 0;
5731 int max_bp_offset = 0;
5735 if ((hg_fp_cnt & 0xff) == 0) {
5736 hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
5737 my_assert_not(hg_fp, NULL);
5738 memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
5741 fp = &hg_fp[hg_fp_cnt];
5742 snprintf(fp->name, sizeof(fp->name), "%s", funcn);
5744 fp->argc_stack = -1;
5747 // perhaps already in seed header?
5748 fp->pp = proto_parse(g_fhdr, funcn, 1);
5749 if (fp->pp != NULL) {
5750 fp->argc_stack = fp->pp->argc_stack;
5751 fp->is_stdcall = fp->pp->is_stdcall;
5752 fp->regmask_dep = get_pp_arg_regmask(fp->pp);
5753 fp->has_ret = !IS(fp->pp->ret_type.name, "void");
5757 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
5758 g_stack_frame_used = 0;
5761 // - handle ebp/esp frame, remove ops related to it
5762 scan_prologue_epilogue(opcnt);
5766 // - resolve all branches
5767 for (i = 0; i < opcnt; i++)
5773 if (po->flags & (OPF_RMD|OPF_DONE))
5776 if (po->op == OP_CALL) {
5777 tmpname = opr_name(po, 0);
5779 if (po->operand[0].type == OPT_LABEL) {
5780 hg_fp_add_dep(fp, tmpname);
5782 // perhaps a call to already known func?
5783 pp_c = proto_parse(g_fhdr, tmpname, 1);
5785 pp = proto_clone(pp_c);
5787 else if (po->datap != NULL) {
5788 pp = calloc(1, sizeof(*pp));
5789 my_assert_not(pp, NULL);
5791 ret = parse_protostr(po->datap, pp);
5793 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
5797 if (pp != NULL && pp->is_noreturn)
5798 po->flags |= OPF_TAIL;
5804 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
5807 if (po->operand[0].type == OPT_REGMEM) {
5808 pd = try_resolve_jumptab(i, opcnt);
5816 for (l = 0; l < opcnt; l++) {
5817 if (g_labels[l] != NULL
5818 && IS(po->operand[0].name, g_labels[l]))
5820 add_label_ref(&g_label_refs[l], i);
5826 if (po->bt_i != -1 || (po->flags & OPF_RMD))
5829 if (po->operand[0].type == OPT_LABEL)
5833 ferr(po, "unhandled branch\n");
5837 po->flags |= OPF_TAIL;
5838 if (i > 0 && ops[i - 1].op == OP_POP)
5839 po->flags |= OPF_ATAIL;
5844 // - remove dead labels
5845 // - handle push <const>/pop pairs
5846 for (i = 0; i < opcnt; i++)
5848 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
5854 if (po->flags & (OPF_RMD|OPF_DONE))
5857 if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
5858 scan_for_pop_const(i, opcnt);
5862 // - process trivial calls
5863 for (i = 0; i < opcnt; i++)
5866 if (po->flags & (OPF_RMD|OPF_DONE))
5869 if (po->op == OP_CALL)
5871 pp = process_call_early(i, opcnt, &j);
5873 if (!(po->flags & OPF_ATAIL))
5874 // since we know the args, try to collect them
5875 if (collect_call_args_early(po, i, pp, ®mask_dummy) != 0)
5881 // commit esp adjust
5882 ops[j].flags |= OPF_RMD;
5883 if (ops[j].op != OP_POP)
5884 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
5886 ops[j].flags |= OPF_DONE;
5889 po->flags |= OPF_DONE;
5895 // - track saved regs (simple)
5897 for (i = 0; i < opcnt; i++)
5900 if (po->flags & (OPF_RMD|OPF_DONE))
5903 if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5905 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
5907 // regmask_save |= 1 << po->operand[0].reg; // do it later
5908 po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
5909 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, OPF_RMD);
5912 else if (po->op == OP_CALL && !(po->flags & OPF_DONE))
5914 pp = process_call(i, opcnt);
5916 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
5917 // since we know the args, collect them
5918 ret = collect_call_args(po, i, pp, ®mask_dummy, save_arg_vars,
5925 memset(cbits, 0, sizeof(cbits));
5929 gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, ®mask_dep, &has_ret);
5931 // find unreachable code - must be fixed in IDA
5932 for (i = 0; i < opcnt; i++)
5934 if (cbits[i >> 3] & (1 << (i & 7)))
5937 if (ops[i].op != OP_NOP)
5938 ferr(&ops[i], "unreachable code\n");
5941 if (has_ret == -1 && (regmask_dep & (1 << xAX)))
5944 for (i = 0; i < g_eqcnt; i++) {
5945 if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
5946 max_bp_offset = g_eqs[i].offset;
5949 if (fp->argc_stack < 0) {
5950 max_bp_offset = (max_bp_offset + 3) & ~3;
5951 fp->argc_stack = max_bp_offset / 4;
5952 if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
5956 fp->regmask_dep = regmask_dep & ~(1 << xSP);
5957 fp->has_ret = has_ret;
5959 printf("// has_ret %d, regmask_dep %x\n",
5960 fp->has_ret, fp->regmask_dep);
5961 output_hdr_fp(stdout, fp, 1);
5962 if (IS(funcn, "sub_100073FD")) exit(1);
5965 gen_x_cleanup(opcnt);
5968 static void hg_fp_resolve_deps(struct func_prototype *fp)
5970 struct func_prototype fp_s;
5974 // this thing is recursive, so mark first..
5975 fp->dep_resolved = 1;
5977 for (i = 0; i < fp->dep_func_cnt; i++) {
5978 strcpy(fp_s.name, fp->dep_func[i].name);
5979 fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
5980 sizeof(hg_fp[0]), hg_fp_cmp_name);
5981 if (fp->dep_func[i].proto != NULL) {
5982 if (!fp->dep_func[i].proto->dep_resolved)
5983 hg_fp_resolve_deps(fp->dep_func[i].proto);
5985 dep = ~fp->dep_func[i].regmask_live
5986 & fp->dep_func[i].proto->regmask_dep;
5987 fp->regmask_dep |= dep;
5988 // printf("dep %s %s |= %x\n", fp->name,
5989 // fp->dep_func[i].name, dep);
5991 if (fp->has_ret == -1)
5992 fp->has_ret = fp->dep_func[i].proto->has_ret;
5997 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6000 const struct parsed_proto *pp;
6001 char *p, namebuf[NAMELEN];
6007 for (; count > 0; count--, fp++) {
6008 if (fp->has_ret == -1)
6009 fprintf(fout, "// ret unresolved\n");
6011 fprintf(fout, "// dep:");
6012 for (j = 0; j < fp->dep_func_cnt; j++) {
6013 fprintf(fout, " %s/", fp->dep_func[j].name);
6014 if (fp->dep_func[j].proto != NULL)
6015 fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6016 fp->dep_func[j].proto->has_ret);
6018 fprintf(fout, "\n");
6021 p = strchr(fp->name, '@');
6023 memcpy(namebuf, fp->name, p - fp->name);
6024 namebuf[p - fp->name] = 0;
6032 pp = proto_parse(g_fhdr, name, 1);
6033 if (pp != NULL && pp->is_include)
6036 if (fp->pp != NULL) {
6037 // prefer fp for common style,
6038 // only use output_pp if args are complex
6039 for (j = 0; j < fp->pp->argc; j++) {
6040 if (fp->pp->arg[j].fptr != NULL)
6043 if (j != fp->pp->argc) {
6044 output_pp(fout, fp->pp, OPP_ALIGN);
6045 fprintf(fout, ";\n");
6050 regmask_dep = fp->regmask_dep;
6051 argc_stack = fp->argc_stack;
6053 fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6054 (fp->has_ret ? "int" : "void"));
6055 if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6056 && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6058 fprintf(fout, " __fastcall ");
6059 if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6065 else if (regmask_dep && !fp->is_stdcall) {
6066 fprintf(fout, "/*__usercall*/ ");
6068 else if (regmask_dep) {
6069 fprintf(fout, "/*__userpurge*/ ");
6071 else if (fp->is_stdcall)
6072 fprintf(fout, " __stdcall ");
6074 fprintf(fout, " __cdecl ");
6076 fprintf(fout, "%s(", name);
6079 for (j = 0; j < xSP; j++) {
6080 if (regmask_dep & (1 << j)) {
6083 fprintf(fout, ", ");
6085 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6087 fprintf(fout, "int");
6088 fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
6092 for (j = 0; j < argc_stack; j++) {
6095 fprintf(fout, ", ");
6096 if (fp->pp != NULL) {
6097 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6098 if (!fp->pp->arg[arg - 1].type.is_ptr)
6102 fprintf(fout, "int ");
6103 fprintf(fout, "a%d", arg);
6106 fprintf(fout, ");\n");
6110 static void output_hdr(FILE *fout)
6112 static const char *lmod_c_names[] = {
6113 [OPLM_UNSPEC] = "???",
6114 [OPLM_BYTE] = "uint8_t",
6115 [OPLM_WORD] = "uint16_t",
6116 [OPLM_DWORD] = "uint32_t",
6117 [OPLM_QWORD] = "uint64_t",
6119 const struct scanned_var *var;
6120 char line[256] = { 0, };
6124 qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6125 for (i = 0; i < hg_fp_cnt; i++)
6126 hg_fp_resolve_deps(&hg_fp[i]);
6128 // note: messes up .proto ptr, don't use
6129 //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6132 for (i = 0; i < hg_var_cnt; i++) {
6135 if (var->pp != NULL && var->pp->is_fptr) {
6136 fprintf(fout, "extern ");
6137 output_pp(fout, var->pp, 0);
6140 else if (var->is_c_str)
6141 fprintf(fout, "extern %-8s %s[];", "char", var->name);
6143 fprintf(fout, "extern %-8s %s;",
6144 lmod_c_names[var->lmod], var->name);
6147 fprintf(fout, " // seeded");
6148 fprintf(fout, "\n");
6151 fprintf(fout, "\n");
6153 // output function prototypes
6154 output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6156 // include passthrough
6157 fprintf(fout, "\n// for translate\n");
6160 while (fgets(line, sizeof(line), g_fhdr)) {
6161 if (IS_START(line, "//#"))
6162 fwrite(line, 1, strlen(line), fout);
6166 // read a line, truncating it if it doesn't fit
6167 static char *my_fgets(char *s, size_t size, FILE *stream)
6177 ret = fgets(s, size, stream);
6178 if (ret != NULL && p >= 0 && s[p] != 0 && s[p] != '\n') {
6179 p = sizeof(buf) - 2;
6182 ret2 = fgets(buf, sizeof(buf), stream);
6184 while (ret2 != NULL && buf[p] != 0 && buf[p] != '\n');
6190 // '=' needs special treatment
6192 static char *next_word_s(char *w, size_t wsize, char *s)
6201 for (i = 1; i < wsize - 1; i++) {
6203 printf("warning: missing closing quote: \"%s\"\n", s);
6212 for (; i < wsize - 1; i++) {
6213 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6219 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6220 printf("warning: '%s' truncated\n", w);
6225 static void scan_variables(FILE *fasm)
6227 struct scanned_var *var;
6228 char line[256] = { 0, };
6236 // skip to next data section
6237 while (my_fgets(line, sizeof(line), fasm))
6242 if (*p == 0 || *p == ';')
6245 p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6246 if (*p == 0 || *p == ';')
6249 if (*p != 's' || !IS_START(p, "segment para public"))
6255 if (p == NULL || !IS_START(p, "segment para public"))
6259 if (!IS_START(p, "'DATA'"))
6263 while (my_fgets(line, sizeof(line), fasm))
6272 if (*p == 0 || *p == ';')
6275 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6276 words[wordc][0] = 0;
6277 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6278 if (*p == 0 || *p == ';') {
6284 if (wordc == 2 && IS(words[1], "ends"))
6289 if ((hg_var_cnt & 0xff) == 0) {
6290 hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6291 * (hg_var_cnt + 0x100));
6292 my_assert_not(hg_vars, NULL);
6293 memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6296 var = &hg_vars[hg_var_cnt++];
6297 snprintf(var->name, sizeof(var->name), "%s", words[0]);
6299 // maybe already in seed header?
6300 var->pp = proto_parse(g_fhdr, var->name, 1);
6301 if (var->pp != NULL) {
6302 if (var->pp->is_fptr) {
6303 var->lmod = OPLM_DWORD;
6306 else if (var->pp->is_func)
6308 else if (!guess_lmod_from_c_type(&var->lmod, &var->pp->type))
6309 aerr("unhandled C type '%s' for '%s'\n",
6310 var->pp->type.name, var->name);
6316 if (IS(words[1], "dd"))
6317 var->lmod = OPLM_DWORD;
6318 else if (IS(words[1], "dw"))
6319 var->lmod = OPLM_WORD;
6320 else if (IS(words[1], "db")) {
6321 var->lmod = OPLM_BYTE;
6322 if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6323 if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6327 else if (IS(words[1], "dq"))
6328 var->lmod = OPLM_QWORD;
6329 //else if (IS(words[1], "dt"))
6331 aerr("type '%s' not known\n", words[1]);
6339 static void set_label(int i, const char *name)
6345 p = strchr(name, ':');
6349 if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6350 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6351 g_labels[i] = realloc(g_labels[i], len + 1);
6352 my_assert_not(g_labels[i], NULL);
6353 memcpy(g_labels[i], name, len);
6354 g_labels[i][len] = 0;
6363 static struct chunk_item *func_chunks;
6364 static int func_chunk_cnt;
6365 static int func_chunk_alloc;
6367 static void add_func_chunk(FILE *fasm, const char *name, int line)
6369 if (func_chunk_cnt >= func_chunk_alloc) {
6370 func_chunk_alloc *= 2;
6371 func_chunks = realloc(func_chunks,
6372 func_chunk_alloc * sizeof(func_chunks[0]));
6373 my_assert_not(func_chunks, NULL);
6375 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6376 func_chunks[func_chunk_cnt].name = strdup(name);
6377 func_chunks[func_chunk_cnt].asmln = line;
6381 static int cmp_chunks(const void *p1, const void *p2)
6383 const struct chunk_item *c1 = p1, *c2 = p2;
6384 return strcmp(c1->name, c2->name);
6387 static int cmpstringp(const void *p1, const void *p2)
6389 return strcmp(*(char * const *)p1, *(char * const *)p2);
6392 static void scan_ahead(FILE *fasm)
6402 oldpos = ftell(fasm);
6405 while (my_fgets(line, sizeof(line), fasm))
6416 // get rid of random tabs
6417 for (i = 0; line[i] != 0; i++)
6418 if (line[i] == '\t')
6421 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6424 next_word(words[0], sizeof(words[0]), p);
6425 if (words[0][0] == 0)
6426 aerr("missing name for func chunk?\n");
6428 add_func_chunk(fasm, words[0], asmln);
6430 else if (IS_START(p, "; sctend"))
6436 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6437 words[wordc][0] = 0;
6438 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6439 if (*p == 0 || *p == ';') {
6445 if (wordc == 2 && IS(words[1], "ends"))
6449 fseek(fasm, oldpos, SEEK_SET);
6453 int main(int argc, char *argv[])
6455 FILE *fout, *fasm, *frlist;
6456 struct parsed_data *pd = NULL;
6458 char **rlist = NULL;
6460 int rlist_alloc = 0;
6461 int func_chunks_used = 0;
6462 int func_chunks_sorted = 0;
6463 int func_chunk_i = -1;
6464 long func_chunk_ret = 0;
6465 int func_chunk_ret_ln = 0;
6466 int scanned_ahead = 0;
6468 char words[20][256];
6469 enum opr_lenmod lmod;
6470 char *sctproto = NULL;
6472 int pending_endp = 0;
6474 int skip_warned = 0;
6487 for (arg = 1; arg < argc; arg++) {
6488 if (IS(argv[arg], "-v"))
6490 else if (IS(argv[arg], "-rf"))
6491 g_allow_regfunc = 1;
6492 else if (IS(argv[arg], "-m"))
6494 else if (IS(argv[arg], "-hdr"))
6495 g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
6500 if (argc < arg + 3) {
6501 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdr.h> [rlist]*\n"
6502 "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n"
6504 " -hdr - header generation mode\n"
6505 " -rf - allow unannotated indirect calls\n"
6506 " -m - allow multiple .text sections\n"
6507 "[rlist] is a file with function names to skip,"
6515 asmfn = argv[arg++];
6516 fasm = fopen(asmfn, "r");
6517 my_assert_not(fasm, NULL);
6519 hdrfn = argv[arg++];
6520 g_fhdr = fopen(hdrfn, "r");
6521 my_assert_not(g_fhdr, NULL);
6524 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
6525 my_assert_not(rlist, NULL);
6526 // needs special handling..
6527 rlist[rlist_len++] = "__alloca_probe";
6529 func_chunk_alloc = 32;
6530 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
6531 my_assert_not(func_chunks, NULL);
6533 memset(words, 0, sizeof(words));
6535 for (; arg < argc; arg++) {
6536 frlist = fopen(argv[arg], "r");
6537 my_assert_not(frlist, NULL);
6539 while (my_fgets(line, sizeof(line), frlist)) {
6541 if (*p == 0 || *p == ';')
6544 if (IS_START(p, "#if 0")
6545 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
6549 else if (IS_START(p, "#endif"))
6556 p = next_word(words[0], sizeof(words[0]), p);
6557 if (words[0][0] == 0)
6560 if (rlist_len >= rlist_alloc) {
6561 rlist_alloc = rlist_alloc * 2 + 64;
6562 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
6563 my_assert_not(rlist, NULL);
6565 rlist[rlist_len++] = strdup(words[0]);
6574 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
6576 fout = fopen(argv[arg_out], "w");
6577 my_assert_not(fout, NULL);
6580 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
6581 my_assert_not(g_eqs, NULL);
6583 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
6584 g_label_refs[i].i = -1;
6585 g_label_refs[i].next = NULL;
6589 scan_variables(fasm);
6591 while (my_fgets(line, sizeof(line), fasm))
6600 // get rid of random tabs
6601 for (i = 0; line[i] != 0; i++)
6602 if (line[i] == '\t')
6607 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
6608 goto do_pending_endp; // eww..
6610 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
6612 static const char *attrs[] = {
6621 // parse IDA's attribute-list comment
6622 g_ida_func_attr = 0;
6625 for (; *p != 0; p = sskip(p)) {
6626 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
6627 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
6628 g_ida_func_attr |= 1 << i;
6629 p += strlen(attrs[i]);
6633 if (i == ARRAY_SIZE(attrs)) {
6634 anote("unparsed IDA attr: %s\n", p);
6637 if (IS(attrs[i], "fpd=")) {
6638 p = next_word(words[0], sizeof(words[0]), p);
6643 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6646 next_word(words[0], sizeof(words[0]), p);
6647 if (words[0][0] == 0)
6648 aerr("missing name for func chunk?\n");
6650 if (!scanned_ahead) {
6651 add_func_chunk(fasm, words[0], asmln);
6652 func_chunks_sorted = 0;
6655 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
6657 if (func_chunk_i >= 0) {
6658 if (func_chunk_i < func_chunk_cnt
6659 && IS(func_chunks[func_chunk_i].name, g_func))
6661 // move on to next chunk
6662 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6664 aerr("seek failed for '%s' chunk #%d\n",
6665 g_func, func_chunk_i);
6666 asmln = func_chunks[func_chunk_i].asmln;
6670 if (func_chunk_ret == 0)
6671 aerr("no return from chunk?\n");
6672 fseek(fasm, func_chunk_ret, SEEK_SET);
6673 asmln = func_chunk_ret_ln;
6679 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
6680 func_chunks_used = 1;
6682 if (IS_START(g_func, "sub_")) {
6683 unsigned long addr = strtoul(p, NULL, 16);
6684 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
6685 if (addr > f_addr && !scanned_ahead) {
6686 anote("scan_ahead caused by '%s', addr %lx\n",
6690 func_chunks_sorted = 0;
6698 for (i = wordc; i < ARRAY_SIZE(words); i++)
6700 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6701 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6702 if (*p == 0 || *p == ';') {
6707 if (*p != 0 && *p != ';')
6708 aerr("too many words\n");
6710 // alow asm patches in comments
6712 if (IS_START(p, "; sctpatch:")) {
6714 if (*p == 0 || *p == ';')
6716 goto parse_words; // lame
6718 if (IS_START(p, "; sctproto:")) {
6719 sctproto = strdup(p + 11);
6721 else if (IS_START(p, "; sctend")) {
6730 awarn("wordc == 0?\n");
6734 // don't care about this:
6735 if (words[0][0] == '.'
6736 || IS(words[0], "include")
6737 || IS(words[0], "assume") || IS(words[1], "segment")
6738 || IS(words[0], "align"))
6744 // do delayed endp processing to collect switch jumptables
6746 if (in_func && !g_skip_func && !end && wordc >= 2
6747 && ((words[0][0] == 'd' && words[0][2] == 0)
6748 || (words[1][0] == 'd' && words[1][2] == 0)))
6751 if (words[1][0] == 'd' && words[1][2] == 0) {
6753 if (g_func_pd_cnt >= pd_alloc) {
6754 pd_alloc = pd_alloc * 2 + 16;
6755 g_func_pd = realloc(g_func_pd,
6756 sizeof(g_func_pd[0]) * pd_alloc);
6757 my_assert_not(g_func_pd, NULL);
6759 pd = &g_func_pd[g_func_pd_cnt];
6761 memset(pd, 0, sizeof(*pd));
6762 strcpy(pd->label, words[0]);
6763 pd->type = OPT_CONST;
6764 pd->lmod = lmod_from_directive(words[1]);
6770 anote("skipping alignment byte?\n");
6773 lmod = lmod_from_directive(words[0]);
6774 if (lmod != pd->lmod)
6775 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
6778 if (pd->count_alloc < pd->count + wordc) {
6779 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
6780 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
6781 my_assert_not(pd->d, NULL);
6783 for (; i < wordc; i++) {
6784 if (IS(words[i], "offset")) {
6785 pd->type = OPT_OFFSET;
6788 p = strchr(words[i], ',');
6791 if (pd->type == OPT_OFFSET)
6792 pd->d[pd->count].u.label = strdup(words[i]);
6794 pd->d[pd->count].u.val = parse_number(words[i]);
6795 pd->d[pd->count].bt_i = -1;
6801 if (in_func && !g_skip_func) {
6803 gen_hdr(g_func, pi);
6805 gen_func(fout, g_fhdr, g_func, pi);
6810 g_ida_func_attr = 0;
6814 func_chunks_used = 0;
6817 memset(&ops, 0, pi * sizeof(ops[0]));
6822 for (i = 0; i < g_func_pd_cnt; i++) {
6824 if (pd->type == OPT_OFFSET) {
6825 for (j = 0; j < pd->count; j++)
6826 free(pd->d[j].u.label);
6840 if (IS(words[1], "proc")) {
6842 aerr("proc '%s' while in_func '%s'?\n",
6845 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
6847 strcpy(g_func, words[0]);
6848 set_label(0, words[0]);
6853 if (IS(words[1], "endp"))
6856 aerr("endp '%s' while not in_func?\n", words[0]);
6857 if (!IS(g_func, words[0]))
6858 aerr("endp '%s' while in_func '%s'?\n",
6861 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
6862 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
6868 if (!g_skip_func && func_chunks_used) {
6869 // start processing chunks
6870 struct chunk_item *ci, key = { g_func, 0 };
6872 func_chunk_ret = ftell(fasm);
6873 func_chunk_ret_ln = asmln;
6874 if (!func_chunks_sorted) {
6875 qsort(func_chunks, func_chunk_cnt,
6876 sizeof(func_chunks[0]), cmp_chunks);
6877 func_chunks_sorted = 1;
6879 ci = bsearch(&key, func_chunks, func_chunk_cnt,
6880 sizeof(func_chunks[0]), cmp_chunks);
6882 aerr("'%s' needs chunks, but none found\n", g_func);
6883 func_chunk_i = ci - func_chunks;
6884 for (; func_chunk_i > 0; func_chunk_i--)
6885 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
6888 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6890 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
6891 asmln = func_chunks[func_chunk_i].asmln;
6899 if (wordc == 2 && IS(words[1], "ends")) {
6903 goto do_pending_endp;
6907 // scan for next text segment
6908 while (my_fgets(line, sizeof(line), fasm)) {
6911 if (*p == 0 || *p == ';')
6914 if (strstr(p, "segment para public 'CODE' use32"))
6921 p = strchr(words[0], ':');
6923 set_label(pi, words[0]);
6927 if (!in_func || g_skip_func) {
6928 if (!skip_warned && !g_skip_func && g_labels[pi] != NULL) {
6930 anote("skipping from '%s'\n", g_labels[pi]);
6934 g_labels[pi] = NULL;
6938 if (wordc > 1 && IS(words[1], "="))
6941 aerr("unhandled equ, wc=%d\n", wordc);
6942 if (g_eqcnt >= eq_alloc) {
6944 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
6945 my_assert_not(g_eqs, NULL);
6948 len = strlen(words[0]);
6949 if (len > sizeof(g_eqs[0].name) - 1)
6950 aerr("equ name too long: %d\n", len);
6951 strcpy(g_eqs[g_eqcnt].name, words[0]);
6953 if (!IS(words[3], "ptr"))
6954 aerr("unhandled equ\n");
6955 if (IS(words[2], "dword"))
6956 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
6957 else if (IS(words[2], "word"))
6958 g_eqs[g_eqcnt].lmod = OPLM_WORD;
6959 else if (IS(words[2], "byte"))
6960 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
6961 else if (IS(words[2], "qword"))
6962 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
6964 aerr("bad lmod: '%s'\n", words[2]);
6966 g_eqs[g_eqcnt].offset = parse_number(words[4]);
6971 if (pi >= ARRAY_SIZE(ops))
6972 aerr("too many ops\n");
6974 parse_op(&ops[pi], words, wordc);
6976 if (sctproto != NULL) {
6977 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
6978 ops[pi].datap = sctproto;
6994 // vim:ts=2:shiftwidth=2:expandtab