5 * This work is licensed under the terms of 3-clause BSD license.
6 * See COPYING file in the top-level directory.
14 #include "my_assert.h"
17 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
18 #define IS(w, y) !strcmp(w, y)
19 #define IS_START(w, y) !strncmp(w, y, strlen(y))
21 #include "protoparse.h"
23 static const char *asmfn;
27 #define anote(fmt, ...) \
28 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
29 #define awarn(fmt, ...) \
30 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
31 #define aerr(fmt, ...) do { \
32 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
37 #include "masm_tools.h"
40 OPF_RMD = (1 << 0), /* removed or optimized out */
41 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
42 OPF_FLAGS = (1 << 2), /* sets flags */
43 OPF_JMP = (1 << 3), /* branch, call */
44 OPF_CJMP = (1 << 4), /* cond. branch (cc or jecxz) */
45 OPF_CC = (1 << 5), /* uses flags */
46 OPF_TAIL = (1 << 6), /* ret or tail call */
47 OPF_RSAVE = (1 << 7), /* push/pop is local reg save/load */
48 OPF_REP = (1 << 8), /* prefixed by rep */
49 OPF_REPZ = (1 << 9), /* rep is repe/repz */
50 OPF_REPNZ = (1 << 10), /* rep is repne/repnz */
51 OPF_FARG = (1 << 11), /* push collected as func arg */
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_allow_regfunc;
238 static int g_quiet_pp;
239 static int g_header_mode;
241 #define ferr(op_, fmt, ...) do { \
242 printf("%s:%d: error: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
243 dump_op(op_), ##__VA_ARGS__); \
247 #define fnote(op_, fmt, ...) \
248 printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
249 dump_op(op_), ##__VA_ARGS__)
251 #define ferr_assert(op_, cond) do { \
252 if (!(cond)) ferr(op_, "assertion '%s' failed on ln :%d\n", #cond, \
256 const char *regs_r32[] = {
257 "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
258 // not r32, but list here for easy parsing and printing
259 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
261 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
262 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
263 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
265 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
267 // possible basic comparison types (without inversion)
268 enum parsed_flag_op {
272 PFO_BE, // 6 CF=1||ZF=1
276 PFO_LE, // e ZF=1||SF!=OF
279 #define PFOB_O (1 << PFO_O)
280 #define PFOB_C (1 << PFO_C)
281 #define PFOB_Z (1 << PFO_Z)
282 #define PFOB_S (1 << PFO_S)
284 static const char *parsed_flag_op_names[] = {
285 "o", "c", "z", "be", "s", "p", "l", "le"
288 static int char_array_i(const char *array[], size_t len, const char *s)
292 for (i = 0; i < len; i++)
299 static void printf_number(char *buf, size_t buf_size,
300 unsigned long number)
302 // output in C-friendly form
303 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
306 static int check_segment_prefix(const char *s)
308 if (s[0] == 0 || s[1] != 's' || s[2] != ':')
322 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
326 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
328 *reg_lmod = OPLM_QWORD;
332 *reg_lmod = OPLM_DWORD;
335 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
337 *reg_lmod = OPLM_WORD;
340 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
342 *reg_lmod = OPLM_BYTE;
345 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
347 *reg_lmod = OPLM_BYTE;
354 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
356 enum opr_lenmod lmod;
369 while (my_isblank(*s))
371 for (; my_issep(*s); d++, s++)
373 while (my_isblank(*s))
377 // skip '?s:' prefixes
378 if (check_segment_prefix(s))
381 s = next_idt(w, sizeof(w), s);
386 reg = parse_reg(&lmod, w);
388 *regmask |= 1 << reg;
392 if ('0' <= w[0] && w[0] <= '9') {
393 number = parse_number(w);
394 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
398 // probably some label/identifier - pass
401 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
405 strcpy(name, cvtbuf);
410 static int is_reg_in_str(const char *s)
414 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
417 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
418 if (!strncmp(s, regs_r32[i], 3))
424 static const char *parse_stack_el(const char *name, char *extra_reg,
427 const char *p, *p2, *s;
433 if (g_bp_frame || early_try)
436 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
438 if (extra_reg != NULL) {
439 strncpy(extra_reg, name, 3);
444 if (IS_START(p, "ebp+")) {
448 if (p2 != NULL && is_reg_in_str(p)) {
449 if (extra_reg != NULL) {
450 strncpy(extra_reg, p, p2 - p);
451 extra_reg[p2 - p] = 0;
456 if (!('0' <= *p && *p <= '9'))
463 if (!IS_START(name, "esp+"))
469 if (is_reg_in_str(s)) {
470 if (extra_reg != NULL) {
471 strncpy(extra_reg, s, p - s);
472 extra_reg[p - s] = 0;
477 aerr("%s IDA stackvar not set?\n", __func__);
479 if (!('0' <= *s && *s <= '9')) {
480 aerr("%s IDA stackvar offset not set?\n", __func__);
483 if (s[0] == '0' && s[1] == 'x')
486 if (len < sizeof(buf) - 1) {
487 strncpy(buf, s, len);
489 val = strtol(buf, &endp, 16);
490 if (val == 0 || *endp != 0) {
491 aerr("%s num parse fail for '%s'\n", __func__, buf);
500 if ('0' <= *p && *p <= '9')
506 static int guess_lmod_from_name(struct parsed_opr *opr)
508 if (!strncmp(opr->name, "dword_", 6)) {
509 opr->lmod = OPLM_DWORD;
512 if (!strncmp(opr->name, "word_", 5)) {
513 opr->lmod = OPLM_WORD;
516 if (!strncmp(opr->name, "byte_", 5)) {
517 opr->lmod = OPLM_BYTE;
520 if (!strncmp(opr->name, "qword_", 6)) {
521 opr->lmod = OPLM_QWORD;
527 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
528 const struct parsed_type *c_type)
530 static const char *dword_types[] = {
531 "int", "_DWORD", "UINT_PTR", "DWORD",
532 "WPARAM", "LPARAM", "UINT", "__int32",
533 "LONG", "HIMC", "BOOL", "size_t",
536 static const char *word_types[] = {
537 "uint16_t", "int16_t", "_WORD", "WORD",
538 "unsigned __int16", "__int16",
540 static const char *byte_types[] = {
541 "uint8_t", "int8_t", "char",
542 "unsigned __int8", "__int8", "BYTE", "_BYTE",
544 // structures.. deal the same as with _UNKNOWN for now
550 if (c_type->is_ptr) {
555 n = skip_type_mod(c_type->name);
557 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
558 if (IS(n, dword_types[i])) {
564 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
565 if (IS(n, word_types[i])) {
571 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
572 if (IS(n, byte_types[i])) {
581 static char *default_cast_to(char *buf, size_t buf_size,
582 struct parsed_opr *opr)
588 if (opr->pp == NULL || opr->pp->type.name == NULL
591 snprintf(buf, buf_size, "%s", "(void *)");
595 snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
599 static enum opr_type lmod_from_directive(const char *d)
603 else if (IS(d, "dw"))
605 else if (IS(d, "db"))
608 aerr("unhandled directive: '%s'\n", d);
612 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
618 *regmask |= 1 << reg;
621 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
624 static int parse_operand(struct parsed_opr *opr,
625 int *regmask, int *regmask_indirect,
626 char words[16][256], int wordc, int w, unsigned int op_flags)
628 const struct parsed_proto *pp = NULL;
629 enum opr_lenmod tmplmod;
630 unsigned long number;
638 aerr("parse_operand w %d, wordc %d\n", w, wordc);
642 for (i = w; i < wordc; i++) {
643 len = strlen(words[i]);
644 if (words[i][len - 1] == ',') {
645 words[i][len - 1] = 0;
651 wordc_in = wordc - w;
653 if ((op_flags & OPF_JMP) && wordc_in > 0
654 && !('0' <= words[w][0] && words[w][0] <= '9'))
656 const char *label = NULL;
658 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
659 && IS(words[w + 1], "ptr"))
660 label = words[w + 2];
661 else if (wordc_in == 2 && IS(words[w], "short"))
662 label = words[w + 1];
663 else if (wordc_in == 1
664 && strchr(words[w], '[') == NULL
665 && parse_reg(&tmplmod, words[w]) < 0)
669 opr->type = OPT_LABEL;
670 ret = check_segment_prefix(label);
673 aerr("fs/gs used\n");
677 strcpy(opr->name, label);
683 if (IS(words[w + 1], "ptr")) {
684 if (IS(words[w], "dword"))
685 opr->lmod = OPLM_DWORD;
686 else if (IS(words[w], "word"))
687 opr->lmod = OPLM_WORD;
688 else if (IS(words[w], "byte"))
689 opr->lmod = OPLM_BYTE;
690 else if (IS(words[w], "qword"))
691 opr->lmod = OPLM_QWORD;
693 aerr("type parsing failed\n");
695 wordc_in = wordc - w;
700 if (IS(words[w], "offset")) {
701 opr->type = OPT_OFFSET;
702 opr->lmod = OPLM_DWORD;
703 strcpy(opr->name, words[w + 1]);
704 pp = proto_parse(g_fhdr, opr->name, 1);
707 if (IS(words[w], "(offset")) {
708 p = strchr(words[w + 1], ')');
710 aerr("parse of bracketed offset failed\n");
712 opr->type = OPT_OFFSET;
713 strcpy(opr->name, words[w + 1]);
719 aerr("parse_operand 1 word expected\n");
721 ret = check_segment_prefix(words[w]);
724 aerr("fs/gs used\n");
726 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
728 strcpy(opr->name, words[w]);
730 if (words[w][0] == '[') {
731 opr->type = OPT_REGMEM;
732 ret = sscanf(words[w], "[%[^]]]", opr->name);
734 aerr("[] parse failure\n");
736 parse_indmode(opr->name, regmask_indirect, 1);
737 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
740 struct parsed_equ *eq =
741 equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
743 opr->lmod = eq->lmod;
747 else if (strchr(words[w], '[')) {
749 p = strchr(words[w], '[');
750 opr->type = OPT_REGMEM;
751 parse_indmode(p, regmask_indirect, 0);
752 strncpy(buf, words[w], p - words[w]);
753 buf[p - words[w]] = 0;
754 pp = proto_parse(g_fhdr, buf, 1);
757 else if (('0' <= words[w][0] && words[w][0] <= '9')
758 || words[w][0] == '-')
760 number = parse_number(words[w]);
761 opr->type = OPT_CONST;
763 printf_number(opr->name, sizeof(opr->name), number);
767 ret = parse_reg(&tmplmod, opr->name);
769 setup_reg_opr(opr, ret, tmplmod, regmask);
773 // most likely var in data segment
774 opr->type = OPT_LABEL;
775 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
779 if (pp->is_fptr || pp->is_func) {
780 opr->lmod = OPLM_DWORD;
784 tmplmod = OPLM_UNSPEC;
785 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
786 anote("unhandled C type '%s' for '%s'\n",
787 pp->type.name, opr->name);
789 if (opr->lmod == OPLM_UNSPEC) {
791 opr->type_from_var = 1;
793 else if (opr->lmod != tmplmod) {
794 opr->size_mismatch = 1;
795 if (tmplmod < opr->lmod)
798 opr->is_ptr = pp->type.is_ptr;
800 opr->is_array = pp->type.is_array;
804 if (opr->lmod == OPLM_UNSPEC)
805 guess_lmod_from_name(opr);
809 static const struct {
814 { "repe", OPF_REP|OPF_REPZ },
815 { "repz", OPF_REP|OPF_REPZ },
816 { "repne", OPF_REP|OPF_REPNZ },
817 { "repnz", OPF_REP|OPF_REPNZ },
818 { "lock", OPF_LOCK }, // ignored for now..
821 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
823 static const struct {
826 unsigned short minopr;
827 unsigned short maxopr;
830 unsigned char pfo_inv;
832 { "nop", OP_NOP, 0, 0, 0 },
833 { "push", OP_PUSH, 1, 1, 0 },
834 { "pop", OP_POP, 1, 1, OPF_DATA },
835 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
836 { "mov" , OP_MOV, 2, 2, OPF_DATA },
837 { "lea", OP_LEA, 2, 2, OPF_DATA },
838 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
839 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
840 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
841 { "not", OP_NOT, 1, 1, OPF_DATA },
842 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
843 { "lodsb",OP_LODS, 0, 0, OPF_DATA },
844 { "lodsw",OP_LODS, 0, 0, OPF_DATA },
845 { "lodsd",OP_LODS, 0, 0, OPF_DATA },
846 { "stosb",OP_STOS, 0, 0, OPF_DATA },
847 { "stosw",OP_STOS, 0, 0, OPF_DATA },
848 { "stosd",OP_STOS, 0, 0, OPF_DATA },
849 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
850 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
851 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
852 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
853 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
854 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
855 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
856 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
857 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
858 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
859 { "cld", OP_CLD, 0, 0, OPF_DATA },
860 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
861 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
862 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
863 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
864 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
865 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
866 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
867 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
868 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
869 { "shrd", OP_SHRD, 3, 3, OPF_DATA|OPF_FLAGS },
870 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
871 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
872 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
873 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
874 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
875 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
876 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
877 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
878 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
879 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
880 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
881 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
882 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
883 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
884 { "test", OP_TEST, 2, 2, OPF_FLAGS },
885 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
886 { "retn", OP_RET, 0, 1, OPF_TAIL },
887 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
888 { "jmp", OP_JMP, 1, 1, OPF_JMP },
889 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
890 { "jo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 0 }, // 70 OF=1
891 { "jno", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 1 }, // 71 OF=0
892 { "jc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72 CF=1
893 { "jb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72
894 { "jnc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73 CF=0
895 { "jnb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
896 { "jae", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
897 { "jz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74 ZF=1
898 { "je", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74
899 { "jnz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75 ZF=0
900 { "jne", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75
901 { "jbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
902 { "jna", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
903 { "ja", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
904 { "jnbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
905 { "js", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 0 }, // 78 SF=1
906 { "jns", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 1 }, // 79 SF=0
907 { "jp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a PF=1
908 { "jpe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a
909 { "jnp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b PF=0
910 { "jpo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b
911 { "jl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c SF!=OF
912 { "jnge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c
913 { "jge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d SF=OF
914 { "jnl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d
915 { "jle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
916 { "jng", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
917 { "jg", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
918 { "jnle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
919 { "seto", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 0 },
920 { "setno", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 1 },
921 { "setc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
922 { "setb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
923 { "setnc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
924 { "setae", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
925 { "setnb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
926 { "setz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
927 { "sete", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
928 { "setnz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
929 { "setne", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
930 { "setbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
931 { "setna", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
932 { "seta", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
933 { "setnbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
934 { "sets", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 0 },
935 { "setns", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 1 },
936 { "setp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
937 { "setpe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
938 { "setnp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
939 { "setpo", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
940 { "setl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
941 { "setnge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
942 { "setge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
943 { "setnl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
944 { "setle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
945 { "setng", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
946 { "setg", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
947 { "setnle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
950 { "emms", OP_EMMS, 0, 0, OPF_DATA },
951 { "movq", OP_MOV, 2, 2, OPF_DATA },
956 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
958 enum opr_lenmod lmod = OPLM_UNSPEC;
959 int prefix_flags = 0;
967 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
968 if (IS(words[w], pref_table[i].name)) {
969 prefix_flags = pref_table[i].flags;
976 aerr("lone prefix: '%s'\n", words[0]);
981 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
982 if (IS(words[w], op_table[i].name))
986 if (i == ARRAY_SIZE(op_table)) {
987 anote("unhandled op: '%s'\n", words[0]);
992 op->op = op_table[i].op;
993 op->flags = op_table[i].flags | prefix_flags;
994 op->pfo = op_table[i].pfo;
995 op->pfo_inv = op_table[i].pfo_inv;
996 op->regmask_src = op->regmask_dst = 0;
999 if (op->op == OP_UD2)
1002 for (opr = 0; opr < op_table[i].maxopr; opr++) {
1003 if (opr >= op_table[i].minopr && w >= wordc)
1006 regmask = regmask_ind = 0;
1007 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
1008 words, wordc, w, op->flags);
1010 if (opr == 0 && (op->flags & OPF_DATA))
1011 op->regmask_dst = regmask;
1013 op->regmask_src |= regmask;
1014 op->regmask_src |= regmask_ind;
1018 aerr("parse_op %s incomplete: %d/%d\n",
1019 words[0], w, wordc);
1022 op->operand_cnt = opr;
1023 if (!strncmp(op_table[i].name, "set", 3))
1024 op->operand[0].lmod = OPLM_BYTE;
1027 // first operand is not dst
1030 op->regmask_src |= op->regmask_dst;
1031 op->regmask_dst = 0;
1034 // first operand is src too
1046 op->regmask_src |= op->regmask_dst;
1051 op->regmask_src |= op->regmask_dst;
1052 op->regmask_dst |= op->regmask_src;
1058 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1059 && op->operand[0].lmod == op->operand[1].lmod
1060 && op->operand[0].reg == op->operand[1].reg
1061 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1063 op->regmask_src = 0;
1066 op->regmask_src |= op->regmask_dst;
1069 // ops with implicit argumets
1071 op->operand_cnt = 2;
1072 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1073 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1079 if (op->operand_cnt != 0)
1081 if (words[op_w][4] == 'b')
1083 else if (words[op_w][4] == 'w')
1085 else if (words[op_w][4] == 'd')
1087 op->operand_cnt = 3;
1088 setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1089 lmod, &op->regmask_src);
1090 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1091 op->regmask_dst = op->regmask_src;
1092 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1093 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1098 if (op->operand_cnt != 0)
1100 if (words[op_w][4] == 'b')
1102 else if (words[op_w][4] == 'w')
1104 else if (words[op_w][4] == 'd')
1106 op->operand_cnt = 3;
1107 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1108 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1109 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1110 op->regmask_dst = op->regmask_src;
1114 op->operand_cnt = 1;
1115 op->regmask_src = 1 << xCX;
1116 op->operand[0].type = OPT_REG;
1117 op->operand[0].reg = xCX;
1118 op->operand[0].lmod = OPLM_DWORD;
1122 if (op->operand_cnt != 1)
1127 op->regmask_src |= op->regmask_dst;
1128 op->regmask_dst = (1 << xDX) | (1 << xAX);
1129 if (op->operand[0].lmod == OPLM_UNSPEC)
1130 op->operand[0].lmod = OPLM_DWORD;
1135 // we could set up operands for edx:eax, but there is no real need to
1136 // (see is_opr_modified())
1137 op->regmask_src |= op->regmask_dst;
1138 op->regmask_dst = (1 << xDX) | (1 << xAX);
1139 if (op->operand[0].lmod == OPLM_UNSPEC)
1140 op->operand[0].lmod = OPLM_DWORD;
1148 op->regmask_src |= op->regmask_dst;
1149 if (op->operand[1].lmod == OPLM_UNSPEC)
1150 op->operand[1].lmod = OPLM_BYTE;
1154 op->regmask_src |= op->regmask_dst;
1155 if (op->operand[2].lmod == OPLM_UNSPEC)
1156 op->operand[2].lmod = OPLM_BYTE;
1160 op->regmask_src |= op->regmask_dst;
1161 op->regmask_dst = 0;
1162 if (op->operand[0].lmod == OPLM_UNSPEC
1163 && (op->operand[0].type == OPT_CONST
1164 || op->operand[0].type == OPT_OFFSET
1165 || op->operand[0].type == OPT_LABEL))
1166 op->operand[0].lmod = OPLM_DWORD;
1172 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1173 && op->operand[0].lmod == op->operand[1].lmod
1174 && op->operand[0].reg == op->operand[1].reg
1175 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1177 op->flags |= OPF_RMD;
1178 op->regmask_src = op->regmask_dst = 0;
1183 if (op->operand[0].type == OPT_REG
1184 && op->operand[1].type == OPT_REGMEM)
1187 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1188 if (IS(buf, op->operand[1].name))
1189 op->flags |= OPF_RMD;
1194 // trashed regs must be explicitly detected later
1195 op->regmask_dst = 0;
1199 op->regmask_dst = (1 << xBP) | (1 << xSP);
1200 op->regmask_src = 1 << xBP;
1208 static const char *op_name(struct parsed_op *po)
1210 static char buf[16];
1214 if (po->op == OP_JCC || po->op == OP_SCC) {
1216 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1219 strcpy(p, parsed_flag_op_names[po->pfo]);
1223 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1224 if (op_table[i].op == po->op)
1225 return op_table[i].name;
1231 static const char *dump_op(struct parsed_op *po)
1233 static char out[128];
1240 snprintf(out, sizeof(out), "%s", op_name(po));
1241 for (i = 0; i < po->operand_cnt; i++) {
1245 snprintf(p, sizeof(out) - (p - out),
1246 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1247 po->operand[i].name);
1253 static const char *lmod_type_u(struct parsed_op *po,
1254 enum opr_lenmod lmod)
1266 ferr(po, "invalid lmod: %d\n", lmod);
1267 return "(_invalid_)";
1271 static const char *lmod_cast_u(struct parsed_op *po,
1272 enum opr_lenmod lmod)
1284 ferr(po, "invalid lmod: %d\n", lmod);
1285 return "(_invalid_)";
1289 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1290 enum opr_lenmod lmod)
1302 ferr(po, "invalid lmod: %d\n", lmod);
1303 return "(_invalid_)";
1307 static const char *lmod_cast_s(struct parsed_op *po,
1308 enum opr_lenmod lmod)
1320 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1321 return "(_invalid_)";
1325 static const char *lmod_cast(struct parsed_op *po,
1326 enum opr_lenmod lmod, int is_signed)
1329 lmod_cast_s(po, lmod) :
1330 lmod_cast_u(po, lmod);
1333 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1345 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1350 static const char *opr_name(struct parsed_op *po, int opr_num)
1352 if (opr_num >= po->operand_cnt)
1353 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1354 return po->operand[opr_num].name;
1357 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1359 if (opr_num >= po->operand_cnt)
1360 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1361 if (po->operand[opr_num].type != OPT_CONST)
1362 ferr(po, "opr %d: const expected\n", opr_num);
1363 return po->operand[opr_num].val;
1366 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1368 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1369 ferr(po, "invalid reg: %d\n", popr->reg);
1370 return regs_r32[popr->reg];
1373 // cast1 is the "final" cast
1374 static const char *simplify_cast(const char *cast1, const char *cast2)
1376 static char buf[256];
1382 if (IS(cast1, cast2))
1384 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1386 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1388 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1390 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1392 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1395 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1399 static const char *simplify_cast_num(const char *cast, unsigned int val)
1401 if (IS(cast, "(u8)") && val < 0x100)
1403 if (IS(cast, "(s8)") && val < 0x80)
1405 if (IS(cast, "(u16)") && val < 0x10000)
1407 if (IS(cast, "(s16)") && val < 0x8000)
1409 if (IS(cast, "(s32)") && val < 0x80000000)
1415 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1424 namelen = strlen(name);
1426 p = strchr(name, '+');
1430 ferr(po, "equ parse failed for '%s'\n", name);
1432 if (IS_START(p, "0x"))
1434 *extra_offs = strtol(p, &endp, 16);
1436 ferr(po, "equ parse failed for '%s'\n", name);
1439 for (i = 0; i < g_eqcnt; i++)
1440 if (strncmp(g_eqs[i].name, name, namelen) == 0
1441 && g_eqs[i].name[namelen] == 0)
1445 ferr(po, "unresolved equ name: '%s'\n", name);
1452 static int is_stack_access(struct parsed_op *po,
1453 const struct parsed_opr *popr)
1455 return (parse_stack_el(popr->name, NULL, 0)
1456 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1457 && IS_START(popr->name, "ebp")));
1460 static void parse_stack_access(struct parsed_op *po,
1461 const char *name, char *ofs_reg, int *offset_out,
1462 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1464 const char *bp_arg = "";
1465 const char *p = NULL;
1466 struct parsed_equ *eq;
1473 if (IS_START(name, "ebp-")
1474 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1477 if (IS_START(p, "0x"))
1479 offset = strtoul(p, &endp, 16);
1483 ferr(po, "ebp- parse of '%s' failed\n", name);
1486 bp_arg = parse_stack_el(name, ofs_reg, 0);
1487 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1488 eq = equ_find(po, bp_arg, &offset);
1490 ferr(po, "detected but missing eq\n");
1491 offset += eq->offset;
1494 if (!strncmp(name, "ebp", 3))
1497 // yes it sometimes LEAs ra for compares..
1498 if (!is_lea && ofs_reg[0] == 0
1499 && stack_ra <= offset && offset < stack_ra + 4)
1501 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1504 *offset_out = offset;
1505 *stack_ra_out = stack_ra;
1507 *bp_arg_out = bp_arg;
1510 static int stack_frame_access(struct parsed_op *po,
1511 struct parsed_opr *popr, char *buf, size_t buf_size,
1512 const char *name, const char *cast, int is_src, int is_lea)
1514 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1515 const char *prefix = "";
1516 const char *bp_arg = NULL;
1517 char ofs_reg[16] = { 0, };
1518 int i, arg_i, arg_s;
1526 if (po->flags & OPF_EBP_S)
1527 ferr(po, "stack_frame_access while ebp is scratch\n");
1529 parse_stack_access(po, name, ofs_reg, &offset,
1530 &stack_ra, &bp_arg, is_lea);
1532 if (offset > stack_ra)
1534 arg_i = (offset - stack_ra - 4) / 4;
1535 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1537 if (g_func_pp->is_vararg
1538 && arg_i == g_func_pp->argc_stack && is_lea)
1540 // should be va_list
1543 snprintf(buf, buf_size, "%sap", cast);
1546 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1547 offset, bp_arg, arg_i);
1549 if (ofs_reg[0] != 0)
1550 ferr(po, "offset reg on arg access?\n");
1552 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1553 if (g_func_pp->arg[i].reg != NULL)
1559 if (i == g_func_pp->argc)
1560 ferr(po, "arg %d not in prototype?\n", arg_i);
1562 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1569 ferr(po, "lea/byte to arg?\n");
1570 if (is_src && (offset & 3) == 0)
1571 snprintf(buf, buf_size, "%sa%d",
1572 simplify_cast(cast, "(u8)"), i + 1);
1574 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1575 cast, offset & 3, i + 1);
1580 ferr(po, "lea/word to arg?\n");
1585 ferr(po, "problematic arg store\n");
1586 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1587 simplify_cast(cast, "*(u16 *)"), i + 1);
1590 ferr(po, "unaligned arg word load\n");
1592 else if (is_src && (offset & 2) == 0)
1593 snprintf(buf, buf_size, "%sa%d",
1594 simplify_cast(cast, "(u16)"), i + 1);
1596 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1597 cast, (offset & 2) ? "HI" : "LO", i + 1);
1609 snprintf(buf, buf_size, "(u32)&a%d + %d",
1612 ferr(po, "unaligned arg store\n");
1614 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1615 snprintf(buf, buf_size, "%s(a%d >> %d)",
1616 prefix, i + 1, (offset & 3) * 8);
1620 snprintf(buf, buf_size, "%s%sa%d",
1621 prefix, is_lea ? "&" : "", i + 1);
1626 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1630 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1633 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1634 if (tmp_lmod != OPLM_DWORD
1635 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1636 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1638 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1639 i + 1, offset, g_func_pp->arg[i].type.name);
1641 // can't check this because msvc likes to reuse
1642 // arg space for scratch..
1643 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1644 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1648 if (g_stack_fsz == 0)
1649 ferr(po, "stack var access without stackframe\n");
1650 g_stack_frame_used = 1;
1652 sf_ofs = g_stack_fsz + offset;
1653 lim = (ofs_reg[0] != 0) ? -4 : 0;
1654 if (offset > 0 || sf_ofs < lim)
1655 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1665 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1666 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1670 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1671 // known unaligned or possibly unaligned
1672 strcat(g_comment, " unaligned");
1674 prefix = "*(u16 *)&";
1675 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1676 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1679 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1683 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1684 // known unaligned or possibly unaligned
1685 strcat(g_comment, " unaligned");
1687 prefix = "*(u32 *)&";
1688 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1689 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1692 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1696 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1703 static void check_func_pp(struct parsed_op *po,
1704 const struct parsed_proto *pp, const char *pfx)
1706 enum opr_lenmod tmp_lmod;
1710 if (pp->argc_reg != 0) {
1711 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1712 pp_print(buf, sizeof(buf), pp);
1713 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1715 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1716 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1717 pfx, pp->argc_reg, pp->argc_stack);
1720 // fptrs must use 32bit args, callsite might have no information and
1721 // lack a cast to smaller types, which results in incorrectly masked
1722 // args passed (callee may assume masked args, it does on ARM)
1723 if (!pp->is_osinc) {
1724 for (i = 0; i < pp->argc; i++) {
1725 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1726 if (ret && tmp_lmod != OPLM_DWORD)
1727 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1728 i + 1, pp->arg[i].type.name);
1733 static const char *check_label_read_ref(struct parsed_op *po,
1736 const struct parsed_proto *pp;
1738 pp = proto_parse(g_fhdr, name, 0);
1740 ferr(po, "proto_parse failed for ref '%s'\n", name);
1743 check_func_pp(po, pp, "ref");
1748 static char *out_src_opr(char *buf, size_t buf_size,
1749 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1752 char tmp1[256], tmp2[256];
1761 switch (popr->type) {
1764 ferr(po, "lea from reg?\n");
1766 switch (popr->lmod) {
1768 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1771 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1774 snprintf(buf, buf_size, "%s%s",
1775 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1778 if (popr->name[1] == 'h') // XXX..
1779 snprintf(buf, buf_size, "%s(%s >> 8)",
1780 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1782 snprintf(buf, buf_size, "%s%s",
1783 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1786 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1791 if (is_stack_access(po, popr)) {
1792 stack_frame_access(po, popr, buf, buf_size,
1793 popr->name, cast, 1, is_lea);
1797 strcpy(expr, popr->name);
1798 if (strchr(expr, '[')) {
1799 // special case: '[' can only be left for label[reg] form
1800 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1802 ferr(po, "parse failure for '%s'\n", expr);
1803 if (tmp1[0] == '(') {
1804 // (off_4FFF50+3)[eax]
1805 p = strchr(tmp1 + 1, ')');
1806 if (p == NULL || p[1] != 0)
1807 ferr(po, "parse failure (2) for '%s'\n", expr);
1809 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1811 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1814 // XXX: do we need more parsing?
1816 snprintf(buf, buf_size, "%s", expr);
1820 snprintf(buf, buf_size, "%s(%s)",
1821 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1825 name = check_label_read_ref(po, popr->name);
1826 if (cast[0] == 0 && popr->is_ptr)
1830 snprintf(buf, buf_size, "(u32)&%s", name);
1831 else if (popr->size_lt)
1832 snprintf(buf, buf_size, "%s%s%s%s", cast,
1833 lmod_cast_u_ptr(po, popr->lmod),
1834 popr->is_array ? "" : "&", name);
1836 snprintf(buf, buf_size, "%s%s%s", cast, name,
1837 popr->is_array ? "[0]" : "");
1841 name = check_label_read_ref(po, popr->name);
1845 ferr(po, "lea an offset?\n");
1846 snprintf(buf, buf_size, "%s&%s", cast, name);
1851 ferr(po, "lea from const?\n");
1853 printf_number(tmp1, sizeof(tmp1), popr->val);
1854 if (popr->val == 0 && strchr(cast, '*'))
1855 snprintf(buf, buf_size, "NULL");
1857 snprintf(buf, buf_size, "%s%s",
1858 simplify_cast_num(cast, popr->val), tmp1);
1862 ferr(po, "invalid src type: %d\n", popr->type);
1868 // note: may set is_ptr (we find that out late for ebp frame..)
1869 static char *out_dst_opr(char *buf, size_t buf_size,
1870 struct parsed_op *po, struct parsed_opr *popr)
1872 switch (popr->type) {
1874 switch (popr->lmod) {
1876 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1879 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1883 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1887 if (popr->name[1] == 'h') // XXX..
1888 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1890 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1893 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1898 if (is_stack_access(po, popr)) {
1899 stack_frame_access(po, popr, buf, buf_size,
1900 popr->name, "", 0, 0);
1904 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1907 if (popr->size_mismatch)
1908 snprintf(buf, buf_size, "%s%s%s",
1909 lmod_cast_u_ptr(po, popr->lmod),
1910 popr->is_array ? "" : "&", popr->name);
1912 snprintf(buf, buf_size, "%s%s", popr->name,
1913 popr->is_array ? "[0]" : "");
1917 ferr(po, "invalid dst type: %d\n", popr->type);
1923 static char *out_src_opr_u32(char *buf, size_t buf_size,
1924 struct parsed_op *po, struct parsed_opr *popr)
1926 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1929 static void out_test_for_cc(char *buf, size_t buf_size,
1930 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1931 enum opr_lenmod lmod, const char *expr)
1933 const char *cast, *scast;
1935 cast = lmod_cast_u(po, lmod);
1936 scast = lmod_cast_s(po, lmod);
1940 case PFO_BE: // CF=1||ZF=1; CF=0
1941 snprintf(buf, buf_size, "(%s%s %s 0)",
1942 cast, expr, is_inv ? "!=" : "==");
1946 case PFO_L: // SF!=OF; OF=0
1947 snprintf(buf, buf_size, "(%s%s %s 0)",
1948 scast, expr, is_inv ? ">=" : "<");
1951 case PFO_LE: // ZF=1||SF!=OF; OF=0
1952 snprintf(buf, buf_size, "(%s%s %s 0)",
1953 scast, expr, is_inv ? ">" : "<=");
1957 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1961 static void out_cmp_for_cc(char *buf, size_t buf_size,
1962 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1964 const char *cast, *scast, *cast_use;
1965 char buf1[256], buf2[256];
1966 enum opr_lenmod lmod;
1968 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
1969 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1970 po->operand[0].lmod, po->operand[1].lmod);
1971 lmod = po->operand[0].lmod;
1973 cast = lmod_cast_u(po, lmod);
1974 scast = lmod_cast_s(po, lmod);
1990 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1993 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1994 if (po->op == OP_DEC)
1995 snprintf(buf2, sizeof(buf2), "1");
1997 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
2001 // note: must be unsigned compare
2002 snprintf(buf, buf_size, "(%s %s %s)",
2003 buf1, is_inv ? ">=" : "<", buf2);
2007 snprintf(buf, buf_size, "(%s %s %s)",
2008 buf1, is_inv ? "!=" : "==", buf2);
2012 // note: must be unsigned compare
2013 snprintf(buf, buf_size, "(%s %s %s)",
2014 buf1, is_inv ? ">" : "<=", buf2);
2017 if (is_inv && lmod == OPLM_BYTE
2018 && po->operand[1].type == OPT_CONST
2019 && po->operand[1].val == 0xff)
2021 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2022 snprintf(buf, buf_size, "(0)");
2026 // note: must be signed compare
2028 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
2029 scast, buf1, buf2, is_inv ? ">=" : "<");
2033 snprintf(buf, buf_size, "(%s %s %s)",
2034 buf1, is_inv ? ">=" : "<", buf2);
2038 snprintf(buf, buf_size, "(%s %s %s)",
2039 buf1, is_inv ? ">" : "<=", buf2);
2047 static void out_cmp_test(char *buf, size_t buf_size,
2048 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2050 char buf1[256], buf2[256], buf3[256];
2052 if (po->op == OP_TEST) {
2053 if (IS(opr_name(po, 0), opr_name(po, 1))) {
2054 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
2057 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2058 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
2059 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2061 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
2062 po->operand[0].lmod, buf3);
2064 else if (po->op == OP_CMP) {
2065 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2068 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2071 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2072 struct parsed_opr *popr2)
2074 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2075 ferr(po, "missing lmod for both operands\n");
2077 if (popr1->lmod == OPLM_UNSPEC)
2078 popr1->lmod = popr2->lmod;
2079 else if (popr2->lmod == OPLM_UNSPEC)
2080 popr2->lmod = popr1->lmod;
2081 else if (popr1->lmod != popr2->lmod) {
2082 if (popr1->type_from_var) {
2083 popr1->size_mismatch = 1;
2084 if (popr1->lmod < popr2->lmod)
2086 popr1->lmod = popr2->lmod;
2088 else if (popr2->type_from_var) {
2089 popr2->size_mismatch = 1;
2090 if (popr2->lmod < popr1->lmod)
2092 popr2->lmod = popr1->lmod;
2095 ferr(po, "conflicting lmods: %d vs %d\n",
2096 popr1->lmod, popr2->lmod);
2100 static const char *op_to_c(struct parsed_op *po)
2124 ferr(po, "op_to_c was supplied with %d\n", po->op);
2128 static void op_set_clear_flag(struct parsed_op *po,
2129 enum op_flags flag_set, enum op_flags flag_clear)
2131 po->flags |= flag_set;
2132 po->flags &= ~flag_clear;
2135 // last op in stream - unconditional branch or ret
2136 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2137 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2138 && ops[_i].op != OP_CALL))
2140 static int scan_for_pop(int i, int opcnt, const char *reg,
2141 int magic, int depth, int *maxdepth, int do_flags)
2143 const struct parsed_proto *pp;
2144 struct parsed_op *po;
2148 for (; i < opcnt; i++) {
2150 if (po->cc_scratch == magic)
2151 break; // already checked
2152 po->cc_scratch = magic;
2154 if (po->flags & OPF_TAIL) {
2155 if (po->op == OP_CALL) {
2156 pp = proto_parse(g_fhdr, po->operand[0].name, g_quiet_pp);
2157 if (pp != NULL && pp->is_noreturn)
2158 // no stack cleanup for noreturn
2161 return -1; // deadend
2164 if ((po->flags & OPF_RMD)
2165 || (po->op == OP_PUSH && po->p_argnum != 0)) // arg push
2168 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2169 if (po->btj != NULL) {
2171 for (j = 0; j < po->btj->count; j++) {
2172 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2173 depth, maxdepth, do_flags);
2175 return ret; // dead end
2181 ferr(po, "dead branch\n");
2185 if (po->flags & OPF_CJMP) {
2186 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2187 depth, maxdepth, do_flags);
2189 return ret; // dead end
2197 if ((po->op == OP_POP || po->op == OP_PUSH)
2198 && po->operand[0].type == OPT_REG
2199 && IS(po->operand[0].name, reg))
2201 if (po->op == OP_PUSH && !(po->flags & OPF_FARGNR)) {
2203 if (depth > *maxdepth)
2206 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2208 else if (po->op == OP_POP) {
2211 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2216 if (depth < 0) // should not happen
2217 ferr(po, "fail with depth\n");
2219 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2228 // scan for pop starting from 'ret' op (all paths)
2229 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2235 for (; i < opcnt; i++) {
2236 if (!(ops[i].flags & OPF_TAIL))
2239 for (j = i - 1; j >= 0; j--) {
2240 if (ops[j].flags & OPF_RMD)
2242 if (ops[j].flags & OPF_JMP)
2245 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2246 && IS(ops[j].operand[0].name, reg))
2249 ops[j].flags |= flag_set;
2253 if (g_labels[j] != NULL)
2258 return found ? 0 : -1;
2261 // XXX: merge with scan_for_pop?
2262 static void scan_for_pop_const(int i, int opcnt)
2266 for (j = i + 1; j < opcnt; j++) {
2267 if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
2268 || ops[j].op == OP_PUSH || g_labels[i] != NULL)
2273 if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
2275 ops[i].flags |= OPF_RMD;
2276 ops[j].datap = &ops[i];
2282 static void scan_propagate_df(int i, int opcnt)
2284 struct parsed_op *po = &ops[i];
2287 for (; i < opcnt; i++) {
2289 if (po->flags & OPF_DF)
2290 return; // already resolved
2291 po->flags |= OPF_DF;
2293 if (po->op == OP_CALL)
2294 ferr(po, "call with DF set?\n");
2296 if (po->flags & OPF_JMP) {
2297 if (po->btj != NULL) {
2299 for (j = 0; j < po->btj->count; j++)
2300 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2305 ferr(po, "dead branch\n");
2309 if (po->flags & OPF_CJMP)
2310 scan_propagate_df(po->bt_i, opcnt);
2316 if (po->flags & OPF_TAIL)
2319 if (po->op == OP_CLD) {
2320 po->flags |= OPF_RMD;
2325 ferr(po, "missing DF clear?\n");
2328 // is operand 'opr' modified by parsed_op 'po'?
2329 static int is_opr_modified(const struct parsed_opr *opr,
2330 const struct parsed_op *po)
2334 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2337 if (opr->type == OPT_REG) {
2338 if (po->op == OP_CALL) {
2339 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2340 if ((1 << opr->reg) & mask)
2346 if (po->operand[0].type == OPT_REG) {
2347 if (po->regmask_dst & (1 << opr->reg))
2354 return IS(po->operand[0].name, opr->name);
2357 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2358 static int is_any_opr_modified(const struct parsed_op *po_test,
2359 const struct parsed_op *po, int c_mode)
2364 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2367 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2370 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2373 // in reality, it can wreck any register, but in decompiled C
2374 // version it can only overwrite eax or edx:eax
2375 mask = (1 << xAX) | (1 << xDX);
2379 if (po->op == OP_CALL
2380 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2383 for (i = 0; i < po_test->operand_cnt; i++)
2384 if (IS(po_test->operand[i].name, po->operand[0].name))
2390 // scan for any po_test operand modification in range given
2391 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2394 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2397 for (; i < opcnt; i++) {
2398 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2405 // scan for po_test operand[0] modification in range given
2406 static int scan_for_mod_opr0(struct parsed_op *po_test,
2409 for (; i < opcnt; i++) {
2410 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2417 #define check_i(po, i) \
2419 ferr(po, "bad " #i ": %d\n", i)
2421 static int scan_for_flag_set(int i, int magic, int *branched,
2422 int *setters, int *setter_cnt)
2424 struct label_ref *lr;
2428 if (ops[i].cc_scratch == magic) {
2429 ferr(&ops[i], "%s looped\n", __func__);
2432 ops[i].cc_scratch = magic;
2434 if (g_labels[i] != NULL) {
2437 lr = &g_label_refs[i];
2438 for (; lr->next; lr = lr->next) {
2439 check_i(&ops[i], lr->i);
2440 ret = scan_for_flag_set(lr->i, magic,
2441 branched, setters, setter_cnt);
2446 check_i(&ops[i], lr->i);
2447 if (i > 0 && LAST_OP(i - 1)) {
2451 ret = scan_for_flag_set(lr->i, magic,
2452 branched, setters, setter_cnt);
2458 if (ops[i].flags & OPF_FLAGS) {
2459 setters[*setter_cnt] = i;
2464 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2471 // scan back for cdq, if anything modifies edx, fail
2472 static int scan_for_cdq_edx(int i)
2475 if (g_labels[i] != NULL) {
2476 if (g_label_refs[i].next != NULL)
2478 if (i > 0 && LAST_OP(i - 1)) {
2479 i = g_label_refs[i].i;
2486 if (ops[i].op == OP_CDQ)
2489 if (ops[i].regmask_dst & (1 << xDX))
2496 static int scan_for_reg_clear(int i, int reg)
2499 if (g_labels[i] != NULL) {
2500 if (g_label_refs[i].next != NULL)
2502 if (i > 0 && LAST_OP(i - 1)) {
2503 i = g_label_refs[i].i;
2510 if (ops[i].op == OP_XOR
2511 && ops[i].operand[0].lmod == OPLM_DWORD
2512 && ops[i].operand[0].reg == ops[i].operand[1].reg
2513 && ops[i].operand[0].reg == reg)
2516 if (ops[i].regmask_dst & (1 << reg))
2523 // scan for positive, constant esp adjust
2524 static int scan_for_esp_adjust(int i, int opcnt,
2525 unsigned int adj_expect, int *adj, int *multipath)
2527 struct parsed_op *po;
2530 *adj = *multipath = 0;
2532 for (; i < opcnt && *adj < adj_expect; i++) {
2535 if (g_labels[i] != NULL)
2538 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2539 if (po->operand[1].type != OPT_CONST)
2540 ferr(&ops[i], "non-const esp adjust?\n");
2541 *adj += po->operand[1].val;
2543 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2546 else if (po->op == OP_PUSH && !(po->flags & OPF_RMD)) {
2547 //if (first_pop == -1)
2548 // first_pop = -2; // none
2549 *adj -= lmod_bytes(po, po->operand[0].lmod);
2551 else if (po->op == OP_POP && !(po->flags & OPF_RMD)) {
2552 if (po->datap != NULL) // in push/pop pair?
2554 // seems like msvc only uses 'pop ecx' for stack realignment..
2555 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2557 if (first_pop == -1 && *adj >= 0)
2559 *adj += lmod_bytes(po, po->operand[0].lmod);
2561 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2562 if (po->op == OP_JMP && po->btj == NULL) {
2566 if (po->op != OP_CALL)
2568 if (po->operand[0].type != OPT_LABEL)
2570 if (po->pp != NULL && po->pp->is_stdcall)
2575 if (first_pop >= 0) {
2576 // probably 'pop ecx' was used..
2583 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2585 struct parsed_op *po;
2589 ferr(ops, "%s: followed bad branch?\n", __func__);
2591 for (; i < opcnt; i++) {
2593 if (po->cc_scratch == magic)
2595 po->cc_scratch = magic;
2598 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2599 if (po->btj != NULL) {
2601 for (j = 0; j < po->btj->count; j++)
2602 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2606 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2607 if (!(po->flags & OPF_CJMP))
2610 if (po->flags & OPF_TAIL)
2615 static const struct parsed_proto *try_recover_pp(
2616 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2618 const struct parsed_proto *pp = NULL;
2622 // maybe an arg of g_func?
2623 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2625 char ofs_reg[16] = { 0, };
2626 int arg, arg_s, arg_i;
2633 parse_stack_access(po, opr->name, ofs_reg,
2634 &offset, &stack_ra, NULL, 0);
2635 if (ofs_reg[0] != 0)
2636 ferr(po, "offset reg on arg access?\n");
2637 if (offset <= stack_ra) {
2638 // search who set the stack var instead
2639 if (search_instead != NULL)
2640 *search_instead = 1;
2644 arg_i = (offset - stack_ra - 4) / 4;
2645 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2646 if (g_func_pp->arg[arg].reg != NULL)
2652 if (arg == g_func_pp->argc)
2653 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2655 pp = g_func_pp->arg[arg].fptr;
2657 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2658 check_func_pp(po, pp, "icall arg");
2660 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2662 p = strchr(opr->name + 1, '[');
2663 memcpy(buf, opr->name, p - opr->name);
2664 buf[p - opr->name] = 0;
2665 pp = proto_parse(g_fhdr, buf, g_quiet_pp);
2667 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2668 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
2671 ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
2674 check_func_pp(po, pp, "reg-fptr ref");
2680 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2681 int magic, const struct parsed_proto **pp_found, int *multi)
2683 const struct parsed_proto *pp = NULL;
2684 struct parsed_op *po;
2685 struct label_ref *lr;
2687 ops[i].cc_scratch = magic;
2690 if (g_labels[i] != NULL) {
2691 lr = &g_label_refs[i];
2692 for (; lr != NULL; lr = lr->next) {
2693 check_i(&ops[i], lr->i);
2694 scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2696 if (i > 0 && LAST_OP(i - 1))
2704 if (ops[i].cc_scratch == magic)
2706 ops[i].cc_scratch = magic;
2708 if (!(ops[i].flags & OPF_DATA))
2710 if (!is_opr_modified(opr, &ops[i]))
2712 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2713 // most probably trashed by some processing
2718 opr = &ops[i].operand[1];
2719 if (opr->type != OPT_REG)
2723 po = (i >= 0) ? &ops[i] : ops;
2726 // reached the top - can only be an arg-reg
2727 if (opr->type != OPT_REG)
2730 for (i = 0; i < g_func_pp->argc; i++) {
2731 if (g_func_pp->arg[i].reg == NULL)
2733 if (IS(opr->name, g_func_pp->arg[i].reg))
2736 if (i == g_func_pp->argc)
2738 pp = g_func_pp->arg[i].fptr;
2740 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2741 i + 1, g_func_pp->arg[i].reg);
2742 check_func_pp(po, pp, "icall reg-arg");
2745 pp = try_recover_pp(po, opr, NULL);
2747 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2748 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2749 || (*pp_found)->is_stdcall != pp->is_stdcall
2750 || (*pp_found)->is_fptr != pp->is_fptr
2751 || (*pp_found)->argc != pp->argc
2752 || (*pp_found)->argc_reg != pp->argc_reg
2753 || (*pp_found)->argc_stack != pp->argc_stack)
2755 ferr(po, "icall: parsed_proto mismatch\n");
2763 // early check for tail call or branch back
2764 static int is_like_tailjmp(int j)
2766 if (!(ops[j].flags & OPF_JMP))
2769 if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2770 // probably local branch back..
2772 if (ops[j].op == OP_CALL)
2773 // probably noreturn call..
2779 static void scan_prologue_epilogue(int opcnt)
2781 int ecx_push = 0, esp_sub = 0;
2785 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2786 && ops[1].op == OP_MOV
2787 && IS(opr_name(&ops[1], 0), "ebp")
2788 && IS(opr_name(&ops[1], 1), "esp"))
2791 ops[0].flags |= OPF_RMD;
2792 ops[1].flags |= OPF_RMD;
2795 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2796 g_stack_fsz = opr_const(&ops[2], 1);
2797 ops[2].flags |= OPF_RMD;
2801 // another way msvc builds stack frame..
2803 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2805 ops[i].flags |= OPF_RMD;
2809 // and another way..
2810 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2811 && ops[i].operand[1].type == OPT_CONST
2812 && ops[i + 1].op == OP_CALL
2813 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2815 g_stack_fsz += ops[i].operand[1].val;
2816 ops[i].flags |= OPF_RMD;
2818 ops[i].flags |= OPF_RMD;
2825 for (; i < opcnt; i++)
2826 if (ops[i].op == OP_RET)
2829 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2830 if (found && is_like_tailjmp(j))
2835 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
2836 || ops[j].op == OP_LEAVE)
2838 ops[j].flags |= OPF_RMD;
2840 else if (!(g_ida_func_attr & IDAFA_NORETURN))
2841 ferr(&ops[j], "'pop ebp' expected\n");
2843 if (g_stack_fsz != 0) {
2844 if (ops[j - 1].op == OP_MOV
2845 && IS(opr_name(&ops[j - 1], 0), "esp")
2846 && IS(opr_name(&ops[j - 1], 1), "ebp"))
2848 ops[j - 1].flags |= OPF_RMD;
2850 else if (ops[j].op != OP_LEAVE
2851 && !(g_ida_func_attr & IDAFA_NORETURN))
2853 ferr(&ops[j - 1], "esp restore expected\n");
2856 if (ecx_push && ops[j - 2].op == OP_POP
2857 && IS(opr_name(&ops[j - 2], 0), "ecx"))
2859 ferr(&ops[j - 2], "unexpected ecx pop\n");
2865 } while (i < opcnt);
2872 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2873 ops[i].flags |= OPF_RMD;
2879 for (; i < opcnt; i++) {
2880 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2882 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2883 && ops[i].operand[1].type == OPT_CONST)
2885 g_stack_fsz = ops[i].operand[1].val;
2886 ops[i].flags |= OPF_RMD;
2892 if (ecx_push && !esp_sub) {
2893 // could actually be args for a call..
2894 for (; i < opcnt; i++)
2895 if (ops[i].op != OP_PUSH)
2898 if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
2899 const struct parsed_proto *pp;
2900 pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
2901 j = pp ? pp->argc_stack : 0;
2902 while (i > 0 && j > 0) {
2904 if (ops[i].op == OP_PUSH) {
2905 ops[i].flags &= ~OPF_RMD;
2910 ferr(&ops[i], "unhandled prologue\n");
2913 i = g_stack_fsz = ecx_push = 0;
2914 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2915 if (!(ops[i].flags & OPF_RMD))
2925 if (ecx_push || esp_sub)
2931 for (; i < opcnt; i++)
2932 if (ops[i].op == OP_RET)
2935 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2936 if (found && is_like_tailjmp(j))
2942 for (l = 0; l < ecx_push; l++) {
2943 if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
2945 else if (ops[j].op == OP_ADD
2946 && IS(opr_name(&ops[j], 0), "esp")
2947 && ops[j].operand[1].type == OPT_CONST)
2950 ecx_push -= ops[j].operand[1].val / 4 - 1;
2953 ferr(&ops[j], "'pop ecx' expected\n");
2955 ops[j].flags |= OPF_RMD;
2959 ferr(&ops[j], "epilogue scan failed\n");
2965 if (ops[j].op != OP_ADD
2966 || !IS(opr_name(&ops[j], 0), "esp")
2967 || ops[j].operand[1].type != OPT_CONST
2968 || ops[j].operand[1].val != g_stack_fsz)
2969 ferr(&ops[j], "'add esp' expected\n");
2971 ops[j].flags |= OPF_RMD;
2972 ops[j].operand[1].val = 0; // hack for stack arg scanner
2977 } while (i < opcnt);
2981 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2984 const struct parsed_proto *pp = NULL;
2985 int search_advice = 0;
2989 switch (ops[i].operand[0].type) {
2993 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2998 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3006 // find an instruction that changed opr before i op
3007 // *op_i must be set to -1 by caller
3008 // *entry is set to 1 if one source is determined to be the caller
3009 // returns 1 if found, *op_i is then set to origin
3010 static int resolve_origin(int i, const struct parsed_opr *opr,
3011 int magic, int *op_i, int *is_caller)
3013 struct label_ref *lr;
3016 if (ops[i].cc_scratch == magic)
3018 ops[i].cc_scratch = magic;
3021 if (g_labels[i] != NULL) {
3022 lr = &g_label_refs[i];
3023 for (; lr != NULL; lr = lr->next) {
3024 check_i(&ops[i], lr->i);
3025 ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3027 if (i > 0 && LAST_OP(i - 1))
3033 if (is_caller != NULL)
3038 if (ops[i].cc_scratch == magic)
3040 ops[i].cc_scratch = magic;
3042 if (!(ops[i].flags & OPF_DATA))
3044 if (!is_opr_modified(opr, &ops[i]))
3050 // XXX: could check if the other op does the same
3059 static int try_resolve_const(int i, const struct parsed_opr *opr,
3060 int magic, unsigned int *val)
3065 ret = resolve_origin(i, opr, magic, &s_i, NULL);
3068 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3071 *val = ops[i].operand[1].val;
3078 static struct parsed_proto *process_call_early(int i, int opcnt,
3081 struct parsed_op *po = &ops[i];
3082 struct parsed_proto *pp;
3088 if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3092 // look for and make use of esp adjust
3094 if (!pp->is_stdcall && pp->argc_stack > 0)
3095 ret = scan_for_esp_adjust(i + 1, opcnt,
3096 pp->argc_stack * 4, &adj, &multipath);
3098 if (pp->argc_stack > adj / 4)
3102 if (ops[ret].op == OP_POP && adj != 4)
3110 static struct parsed_proto *process_call(int i, int opcnt)
3112 struct parsed_op *po = &ops[i];
3113 const struct parsed_proto *pp_c;
3114 struct parsed_proto *pp;
3115 const char *tmpname;
3116 int adj = 0, multipath = 0;
3119 tmpname = opr_name(po, 0);
3124 pp_c = resolve_icall(i, opcnt, &multipath);
3126 if (!pp_c->is_func && !pp_c->is_fptr)
3127 ferr(po, "call to non-func: %s\n", pp_c->name);
3128 pp = proto_clone(pp_c);
3129 my_assert_not(pp, NULL);
3131 // not resolved just to single func
3134 switch (po->operand[0].type) {
3136 // we resolved this call and no longer need the register
3137 po->regmask_src &= ~(1 << po->operand[0].reg);
3147 pp = calloc(1, sizeof(*pp));
3148 my_assert_not(pp, NULL);
3151 ret = scan_for_esp_adjust(i + 1, opcnt, ~0, &adj, &multipath);
3152 if (ret < 0 || adj < 0) {
3153 if (!g_allow_regfunc)
3154 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3155 pp->is_unresolved = 1;
3159 if (adj > ARRAY_SIZE(pp->arg))
3160 ferr(po, "esp adjust too large: %d\n", adj);
3161 pp->ret_type.name = strdup("int");
3162 pp->argc = pp->argc_stack = adj;
3163 for (arg = 0; arg < pp->argc; arg++)
3164 pp->arg[arg].type.name = strdup("int");
3169 // look for and make use of esp adjust
3171 if (!pp->is_stdcall && pp->argc_stack > 0)
3172 ret = scan_for_esp_adjust(i + 1, opcnt,
3173 pp->argc_stack * 4, &adj, &multipath);
3175 if (pp->is_vararg) {
3176 if (adj / 4 < pp->argc_stack) {
3177 fnote(po, "(this call)\n");
3178 ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3179 adj, pp->argc_stack * 4);
3181 // modify pp to make it have varargs as normal args
3183 pp->argc += adj / 4 - pp->argc_stack;
3184 for (; arg < pp->argc; arg++) {
3185 pp->arg[arg].type.name = strdup("int");
3188 if (pp->argc > ARRAY_SIZE(pp->arg))
3189 ferr(po, "too many args for '%s'\n", tmpname);
3191 if (pp->argc_stack > adj / 4) {
3192 fnote(po, "(this call)\n");
3193 ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3194 tmpname, pp->argc_stack * 4, adj);
3197 ops[ret].flags |= OPF_RMD;
3198 if (ops[ret].op == OP_POP) {
3200 // deal with multi-pop stack adjust
3201 adj = pp->argc_stack;
3202 while (ops[ret].op == OP_POP && adj > 0 && ret < opcnt) {
3203 ops[ret].flags |= OPF_RMD;
3209 else if (!multipath) {
3210 // a bit of a hack, but deals with use of
3211 // single adj for multiple calls
3212 ops[ret].operand[1].val -= pp->argc_stack * 4;
3215 else if (pp->is_vararg)
3216 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3222 static int collect_call_args_early(struct parsed_op *po, int i,
3223 struct parsed_proto *pp, int *regmask)
3228 for (arg = 0; arg < pp->argc; arg++)
3229 if (pp->arg[arg].reg == NULL)
3232 // first see if it can be easily done
3233 for (j = i; j > 0 && arg < pp->argc; )
3235 if (g_labels[j] != NULL)
3239 if (ops[j].op == OP_CALL)
3241 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3243 else if (ops[j].op == OP_POP)
3245 else if (ops[j].flags & OPF_CJMP)
3247 else if (ops[j].op == OP_PUSH) {
3248 if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3250 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3254 if (pp->arg[arg].type.is_va_list)
3258 for (arg++; arg < pp->argc; arg++)
3259 if (pp->arg[arg].reg == NULL)
3268 for (arg = 0; arg < pp->argc; arg++)
3269 if (pp->arg[arg].reg == NULL)
3272 for (j = i; j > 0 && arg < pp->argc; )
3276 if (ops[j].op == OP_PUSH)
3278 ops[j].p_argnext = -1;
3279 ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3280 pp->arg[arg].datap = &ops[j];
3282 if (ops[j].operand[0].type == OPT_REG)
3283 *regmask |= 1 << ops[j].operand[0].reg;
3285 ops[j].flags |= OPF_RMD | OPF_FARGNR | OPF_FARG;
3286 ops[j].flags &= ~OPF_RSAVE;
3289 for (arg++; arg < pp->argc; arg++)
3290 if (pp->arg[arg].reg == NULL)
3298 static int collect_call_args_r(struct parsed_op *po, int i,
3299 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3300 int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
3302 struct parsed_proto *pp_tmp;
3303 struct parsed_op *po_tmp;
3304 struct label_ref *lr;
3305 int need_to_save_current;
3306 int arg_grp_current = 0;
3307 int save_args_seen = 0;
3315 ferr(po, "dead label encountered\n");
3319 for (; arg < pp->argc; arg++)
3320 if (pp->arg[arg].reg == NULL)
3322 magic = (magic & 0xffffff) | (arg << 24);
3324 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
3326 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
3327 if (ops[j].cc_scratch != magic) {
3328 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
3332 // ok: have already been here
3335 ops[j].cc_scratch = magic;
3337 if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
3338 lr = &g_label_refs[j];
3339 if (lr->next != NULL)
3341 for (; lr->next; lr = lr->next) {
3342 check_i(&ops[j], lr->i);
3343 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3345 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3346 arg_grp, arg, magic, need_op_saving, may_reuse);
3351 check_i(&ops[j], lr->i);
3352 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3354 if (j > 0 && LAST_OP(j - 1)) {
3355 // follow last branch in reverse
3360 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3361 arg_grp, arg, magic, need_op_saving, may_reuse);
3367 if (ops[j].op == OP_CALL)
3369 if (pp->is_unresolved)
3374 ferr(po, "arg collect hit unparsed call '%s'\n",
3375 ops[j].operand[0].name);
3376 if (may_reuse && pp_tmp->argc_stack > 0)
3377 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
3378 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
3380 // esp adjust of 0 means we collected it before
3381 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
3382 && (ops[j].operand[1].type != OPT_CONST
3383 || ops[j].operand[1].val != 0))
3385 if (pp->is_unresolved)
3388 ferr(po, "arg collect %d/%d hit esp adjust of %d\n",
3389 arg, pp->argc, ops[j].operand[1].val);
3391 else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_RMD)
3392 && ops[j].datap == NULL)
3394 if (pp->is_unresolved)
3397 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
3399 else if (ops[j].flags & OPF_CJMP)
3401 if (pp->is_unresolved)
3406 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARGNR))
3408 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
3411 ops[j].p_argnext = -1;
3412 po_tmp = pp->arg[arg].datap;
3414 ops[j].p_argnext = po_tmp - ops;
3415 pp->arg[arg].datap = &ops[j];
3417 need_to_save_current = 0;
3420 if (ops[j].operand[0].type == OPT_REG)
3421 reg = ops[j].operand[0].reg;
3423 if (!need_op_saving) {
3424 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3425 need_to_save_current = (ret >= 0);
3427 if (need_op_saving || need_to_save_current) {
3428 // mark this push as one that needs operand saving
3429 ops[j].flags &= ~OPF_RMD;
3430 if (ops[j].p_argnum == 0) {
3431 ops[j].p_argnum = arg + 1;
3432 save_args |= 1 << arg;
3434 else if (ops[j].p_argnum < arg + 1) {
3435 // XXX: might kill valid var..
3436 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
3437 ops[j].p_argnum = arg + 1;
3438 save_args |= 1 << arg;
3441 if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
3444 if (arg_grp_current >= MAX_ARG_GRP)
3445 ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
3446 ops[j].p_argnum, pp->name);
3449 else if (ops[j].p_argnum == 0)
3450 ops[j].flags |= OPF_RMD;
3452 // some PUSHes are reused by different calls on other branches,
3453 // but that can't happen if we didn't branch, so they
3454 // can be removed from future searches (handles nested calls)
3456 ops[j].flags |= OPF_FARGNR;
3458 ops[j].flags |= OPF_FARG;
3459 ops[j].flags &= ~OPF_RSAVE;
3461 // check for __VALIST
3462 if (!pp->is_unresolved && pp->arg[arg].type.is_va_list) {
3464 ret = resolve_origin(j, &ops[j].operand[0],
3465 magic + 1, &k, NULL);
3466 if (ret == 1 && k >= 0)
3468 if (ops[k].op == OP_LEA) {
3469 snprintf(buf, sizeof(buf), "arg_%X",
3470 g_func_pp->argc_stack * 4);
3471 if (!g_func_pp->is_vararg
3472 || strstr(ops[k].operand[1].name, buf))
3474 ops[k].flags |= OPF_RMD;
3475 ops[j].flags |= OPF_RMD | OPF_VAPUSH;
3476 save_args &= ~(1 << arg);
3480 ferr(&ops[j], "lea va_list used, but no vararg?\n");
3482 // check for va_list from g_func_pp arg too
3483 else if (ops[k].op == OP_MOV
3484 && is_stack_access(&ops[k], &ops[k].operand[1]))
3486 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
3487 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
3489 ops[k].flags |= OPF_RMD;
3490 ops[j].flags |= OPF_RMD;
3491 ops[j].p_argpass = ret + 1;
3492 save_args &= ~(1 << arg);
3499 *save_arg_vars |= save_args;
3501 // tracking reg usage
3503 *regmask |= 1 << reg;
3506 if (!pp->is_unresolved) {
3508 for (; arg < pp->argc; arg++)
3509 if (pp->arg[arg].reg == NULL)
3512 magic = (magic & 0xffffff) | (arg << 24);
3515 if (ops[j].p_arggrp > arg_grp_current) {
3517 arg_grp_current = ops[j].p_arggrp;
3519 if (ops[j].p_argnum > 0)
3520 save_args_seen |= 1 << (ops[j].p_argnum - 1);
3523 if (arg < pp->argc) {
3524 ferr(po, "arg collect failed for '%s': %d/%d\n",
3525 pp->name, arg, pp->argc);
3529 if (arg_grp_current > *arg_grp)
3530 *arg_grp = arg_grp_current;
3535 static int collect_call_args(struct parsed_op *po, int i,
3536 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3539 // arg group is for cases when pushes for
3540 // multiple funcs are going on
3541 struct parsed_op *po_tmp;
3542 int save_arg_vars_current = 0;
3547 ret = collect_call_args_r(po, i, pp, regmask,
3548 &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
3553 // propagate arg_grp
3554 for (a = 0; a < pp->argc; a++) {
3555 if (pp->arg[a].reg != NULL)
3558 po_tmp = pp->arg[a].datap;
3559 while (po_tmp != NULL) {
3560 po_tmp->p_arggrp = arg_grp;
3561 if (po_tmp->p_argnext > 0)
3562 po_tmp = &ops[po_tmp->p_argnext];
3568 save_arg_vars[arg_grp] |= save_arg_vars_current;
3570 if (pp->is_unresolved) {
3572 pp->argc_stack += ret;
3573 for (a = 0; a < pp->argc; a++)
3574 if (pp->arg[a].type.name == NULL)
3575 pp->arg[a].type.name = strdup("int");
3581 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
3585 for (i = 0; i < pp->argc; i++)
3586 if (pp->arg[i].reg == NULL)
3590 memmove(&pp->arg[i + 1], &pp->arg[i],
3591 sizeof(pp->arg[0]) * pp->argc_stack);
3592 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
3593 pp->arg[i].reg = strdup(reg);
3594 pp->arg[i].type.name = strdup("int");
3599 static void add_label_ref(struct label_ref *lr, int op_i)
3601 struct label_ref *lr_new;
3608 lr_new = calloc(1, sizeof(*lr_new));
3610 lr_new->next = lr->next;
3614 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
3616 struct parsed_op *po = &ops[i];
3617 struct parsed_data *pd;
3618 char label[NAMELEN], *p;
3621 p = strchr(po->operand[0].name, '[');
3625 len = p - po->operand[0].name;
3626 strncpy(label, po->operand[0].name, len);
3629 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3630 if (IS(g_func_pd[j].label, label)) {
3636 //ferr(po, "label '%s' not parsed?\n", label);
3639 if (pd->type != OPT_OFFSET)
3640 ferr(po, "label '%s' with non-offset data?\n", label);
3642 // find all labels, link
3643 for (j = 0; j < pd->count; j++) {
3644 for (l = 0; l < opcnt; l++) {
3645 if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
3646 add_label_ref(&g_label_refs[l], i);
3656 static void clear_labels(int count)
3660 for (i = 0; i < count; i++) {
3661 if (g_labels[i] != NULL) {
3668 static void output_std_flags(FILE *fout, struct parsed_op *po,
3669 int *pfomask, const char *dst_opr_text)
3671 if (*pfomask & (1 << PFO_Z)) {
3672 fprintf(fout, "\n cond_z = (%s%s == 0);",
3673 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
3674 *pfomask &= ~(1 << PFO_Z);
3676 if (*pfomask & (1 << PFO_S)) {
3677 fprintf(fout, "\n cond_s = (%s%s < 0);",
3678 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
3679 *pfomask &= ~(1 << PFO_S);
3683 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
3686 if (pp->is_fastcall)
3687 fprintf(fout, "__fastcall ");
3688 else if (pp->is_stdcall && pp->argc_reg == 0)
3689 fprintf(fout, "__stdcall ");
3690 if (pp->is_noreturn || is_noreturn)
3691 fprintf(fout, "noreturn ");
3694 static int get_pp_arg_regmask(const struct parsed_proto *pp)
3699 for (i = 0; i < pp->argc; i++) {
3700 if (pp->arg[i].reg != NULL) {
3701 reg = char_array_i(regs_r32,
3702 ARRAY_SIZE(regs_r32), pp->arg[i].reg);
3704 ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
3705 pp->arg[i].reg, pp->name);
3706 regmask |= 1 << reg;
3713 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
3719 snprintf(buf1, sizeof(buf1), "%d", grp);
3720 snprintf(buf, buf_size, "s%s_a%d", buf1, num);
3725 static void gen_x_cleanup(int opcnt);
3727 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
3729 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
3730 struct parsed_opr *last_arith_dst = NULL;
3731 char buf1[256], buf2[256], buf3[256], cast[64];
3732 const struct parsed_proto *pp_c;
3733 struct parsed_proto *pp, *pp_tmp;
3734 struct parsed_data *pd;
3735 const char *tmpname;
3737 int save_arg_vars[MAX_ARG_GRP] = { 0, };
3739 int need_tmp_var = 0;
3742 int label_pending = 0;
3743 int regmask_save = 0;
3744 int regmask_arg = 0;
3745 int regmask_now = 0;
3746 int regmask_init = 0;
3757 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
3758 g_stack_frame_used = 0;
3760 g_func_pp = proto_parse(fhdr, funcn, 0);
3761 if (g_func_pp == NULL)
3762 ferr(ops, "proto_parse failed for '%s'\n", funcn);
3764 regmask_arg = get_pp_arg_regmask(g_func_pp);
3767 // - handle ebp/esp frame, remove ops related to it
3768 scan_prologue_epilogue(opcnt);
3771 // - parse calls with labels
3772 // - resolve all branches
3773 for (i = 0; i < opcnt; i++)
3779 if (po->flags & OPF_RMD)
3782 if (po->op == OP_CALL) {
3785 if (po->operand[0].type == OPT_LABEL) {
3786 tmpname = opr_name(po, 0);
3787 if (IS_START(tmpname, "loc_"))
3788 ferr(po, "call to loc_*\n");
3789 pp_c = proto_parse(fhdr, tmpname, 0);
3791 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3793 pp = proto_clone(pp_c);
3794 my_assert_not(pp, NULL);
3796 else if (po->datap != NULL) {
3797 pp = calloc(1, sizeof(*pp));
3798 my_assert_not(pp, NULL);
3800 ret = parse_protostr(po->datap, pp);
3802 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3809 check_func_pp(po, pp, "fptr var call");
3810 if (pp->is_noreturn)
3811 po->flags |= OPF_TAIL;
3817 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3820 if (po->operand[0].type == OPT_REGMEM) {
3821 pd = try_resolve_jumptab(i, opcnt);
3829 for (l = 0; l < opcnt; l++) {
3830 if (g_labels[l] != NULL
3831 && IS(po->operand[0].name, g_labels[l]))
3833 if (l == i + 1 && po->op == OP_JMP) {
3834 // yet another alignment type..
3835 po->flags |= OPF_RMD;
3838 add_label_ref(&g_label_refs[l], i);
3844 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3847 if (po->operand[0].type == OPT_LABEL)
3851 ferr(po, "unhandled branch\n");
3855 po->flags |= OPF_TAIL;
3856 if (i > 0 && ops[i - 1].op == OP_POP)
3857 po->flags |= OPF_ATAIL;
3862 // - remove dead labels
3863 // - process trivial calls
3864 for (i = 0; i < opcnt; i++)
3866 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
3872 if (po->flags & OPF_RMD)
3875 if (po->op == OP_CALL)
3877 pp = process_call_early(i, opcnt, &j);
3879 if (!(po->flags & OPF_ATAIL))
3880 // since we know the args, try to collect them
3881 if (collect_call_args_early(po, i, pp, ®mask) != 0)
3887 // commit esp adjust
3888 ops[j].flags |= OPF_RMD;
3889 if (ops[j].op != OP_POP) {
3890 ferr_assert(&ops[j], ops[j].op == OP_ADD);
3891 ops[j].operand[1].val -= pp->argc_stack * 4;
3895 if (strstr(pp->ret_type.name, "int64"))
3898 po->flags |= OPF_DONE;
3905 for (i = 0; i < opcnt; i++)
3908 if (po->flags & OPF_RMD)
3911 if (po->op == OP_CALL && !(po->flags & OPF_DONE))
3913 pp = process_call(i, opcnt);
3915 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3916 // since we know the args, collect them
3917 collect_call_args(po, i, pp, ®mask, save_arg_vars,
3921 if (strstr(pp->ret_type.name, "int64"))
3927 // - find POPs for PUSHes, rm both
3928 // - scan for STD/CLD, propagate DF
3929 // - scan for all used registers
3930 // - find flag set ops for their users
3931 // - do unreselved calls
3932 // - declare indirect functions
3933 for (i = 0; i < opcnt; i++)
3936 if (po->flags & OPF_RMD)
3939 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3940 reg = po->operand[0].reg;
3941 if (!(regmask & (1 << reg)))
3942 // not a reg save after all, rerun scan_for_pop
3943 po->flags &= ~OPF_RSAVE;
3945 regmask_save |= 1 << reg;
3948 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
3949 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
3951 if (po->operand[0].type == OPT_REG)
3953 reg = po->operand[0].reg;
3955 ferr(po, "reg not set for push?\n");
3958 ret = scan_for_pop(i + 1, opcnt,
3959 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3962 ferr(po, "too much depth: %d\n", depth);
3964 po->flags |= OPF_RMD;
3965 scan_for_pop(i + 1, opcnt, po->operand[0].name,
3966 i + opcnt * 4, 0, &depth, 1);
3969 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3972 if (regmask & (1 << reg)) {
3973 if (regmask_save & (1 << reg))
3974 ferr(po, "%s already saved?\n", po->operand[0].name);
3978 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3982 else if (po->operand[0].type == OPT_CONST) {
3983 scan_for_pop_const(i, opcnt);
3987 if (po->op == OP_STD) {
3988 po->flags |= OPF_DF | OPF_RMD;
3989 scan_propagate_df(i + 1, opcnt);
3992 regmask_now = po->regmask_src | po->regmask_dst;
3993 if (regmask_now & (1 << xBP)) {
3994 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3995 if (po->regmask_dst & (1 << xBP))
3996 // compiler decided to drop bp frame and use ebp as scratch
3997 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
3999 regmask_now &= ~(1 << xBP);
4003 regmask |= regmask_now;
4005 if (po->flags & OPF_CC)
4007 int setters[16], cnt = 0, branched = 0;
4009 ret = scan_for_flag_set(i, i + opcnt * 6,
4010 &branched, setters, &cnt);
4011 if (ret < 0 || cnt <= 0)
4012 ferr(po, "unable to trace flag setter(s)\n");
4013 if (cnt > ARRAY_SIZE(setters))
4014 ferr(po, "too many flag setters\n");
4016 for (j = 0; j < cnt; j++)
4018 tmp_op = &ops[setters[j]]; // flag setter
4021 // to get nicer code, we try to delay test and cmp;
4022 // if we can't because of operand modification, or if we
4023 // have arith op, or branch, make it calculate flags explicitly
4024 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4026 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4027 pfomask = 1 << po->pfo;
4029 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4030 pfomask = 1 << po->pfo;
4033 // see if we'll be able to handle based on op result
4034 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4035 && po->pfo != PFO_Z && po->pfo != PFO_S
4036 && po->pfo != PFO_P)
4038 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4040 pfomask = 1 << po->pfo;
4043 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4044 propagate_lmod(tmp_op, &tmp_op->operand[0],
4045 &tmp_op->operand[1]);
4046 if (tmp_op->operand[0].lmod == OPLM_DWORD)
4051 tmp_op->pfomask |= pfomask;
4052 cond_vars |= pfomask;
4054 // note: may overwrite, currently not a problem
4058 if (po->op == OP_RCL || po->op == OP_RCR
4059 || po->op == OP_ADC || po->op == OP_SBB)
4060 cond_vars |= 1 << PFO_C;
4063 if (po->op == OP_CMPS || po->op == OP_SCAS) {
4064 cond_vars |= 1 << PFO_Z;
4066 else if (po->op == OP_MUL
4067 || (po->op == OP_IMUL && po->operand_cnt == 1))
4069 if (po->operand[0].lmod == OPLM_DWORD)
4072 else if (po->op == OP_CALL) {
4073 // note: resolved non-reg calls are OPF_DONE already
4076 ferr(po, "NULL pp\n");
4078 if (pp->is_unresolved) {
4079 int regmask_stack = 0;
4080 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4083 // this is pretty rough guess:
4084 // see ecx and edx were pushed (and not their saved versions)
4085 for (arg = 0; arg < pp->argc; arg++) {
4086 if (pp->arg[arg].reg != NULL)
4089 tmp_op = pp->arg[arg].datap;
4091 ferr(po, "parsed_op missing for arg%d\n", arg);
4092 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4093 regmask_stack |= 1 << tmp_op->operand[0].reg;
4096 if (!((regmask_stack & (1 << xCX))
4097 && (regmask_stack & (1 << xDX))))
4099 if (pp->argc_stack != 0
4100 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4102 pp_insert_reg_arg(pp, "ecx");
4103 pp->is_fastcall = 1;
4104 regmask_init |= 1 << xCX;
4105 regmask |= 1 << xCX;
4107 if (pp->argc_stack != 0
4108 || ((regmask | regmask_arg) & (1 << xDX)))
4110 pp_insert_reg_arg(pp, "edx");
4111 regmask_init |= 1 << xDX;
4112 regmask |= 1 << xDX;
4116 // note: __cdecl doesn't fall into is_unresolved category
4117 if (pp->argc_stack > 0)
4121 for (arg = 0; arg < pp->argc; arg++) {
4122 if (pp->arg[arg].reg != NULL) {
4123 reg = char_array_i(regs_r32,
4124 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
4126 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
4127 if (!(regmask & (1 << reg))) {
4128 regmask_init |= 1 << reg;
4129 regmask |= 1 << reg;
4134 else if (po->op == OP_MOV && po->operand[0].pp != NULL
4135 && po->operand[1].pp != NULL)
4137 // <var> = offset <something>
4138 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4139 && !IS_START(po->operand[1].name, "off_"))
4141 if (!po->operand[0].pp->is_fptr)
4142 ferr(po, "%s not declared as fptr when it should be\n",
4143 po->operand[0].name);
4144 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4145 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4146 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4147 fnote(po, "var: %s\n", buf1);
4148 fnote(po, "func: %s\n", buf2);
4149 ferr(po, "^ mismatch\n");
4153 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
4154 regmask |= 1 << xAX;
4155 else if (po->op == OP_DIV || po->op == OP_IDIV) {
4156 // 32bit division is common, look for it
4157 if (po->op == OP_DIV)
4158 ret = scan_for_reg_clear(i, xDX);
4160 ret = scan_for_cdq_edx(i);
4162 po->flags |= OPF_32BIT;
4166 else if (po->op == OP_CLD)
4167 po->flags |= OPF_RMD;
4169 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4175 // - confirm regmask_save, it might have been reduced
4176 if (regmask_save != 0)
4179 for (i = 0; i < opcnt; i++) {
4181 if (po->flags & OPF_RMD)
4184 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
4185 regmask_save |= 1 << po->operand[0].reg;
4189 // output starts here
4191 // define userstack size
4192 if (g_func_pp->is_userstack) {
4193 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4194 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4195 fprintf(fout, "#endif\n");
4198 // the function itself
4199 fprintf(fout, "%s ", g_func_pp->ret_type.name);
4200 output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
4201 fprintf(fout, "%s(", g_func_pp->name);
4203 for (i = 0; i < g_func_pp->argc; i++) {
4205 fprintf(fout, ", ");
4206 if (g_func_pp->arg[i].fptr != NULL) {
4208 pp = g_func_pp->arg[i].fptr;
4209 fprintf(fout, "%s (", pp->ret_type.name);
4210 output_pp_attrs(fout, pp, 0);
4211 fprintf(fout, "*a%d)(", i + 1);
4212 for (j = 0; j < pp->argc; j++) {
4214 fprintf(fout, ", ");
4215 if (pp->arg[j].fptr)
4216 ferr(ops, "nested fptr\n");
4217 fprintf(fout, "%s", pp->arg[j].type.name);
4219 if (pp->is_vararg) {
4221 fprintf(fout, ", ");
4222 fprintf(fout, "...");
4226 else if (g_func_pp->arg[i].type.is_retreg) {
4227 fprintf(fout, "u32 *r_%s", g_func_pp->arg[i].reg);
4230 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
4233 if (g_func_pp->is_vararg) {
4235 fprintf(fout, ", ");
4236 fprintf(fout, "...");
4239 fprintf(fout, ")\n{\n");
4241 // declare indirect functions
4242 for (i = 0; i < opcnt; i++) {
4244 if (po->flags & OPF_RMD)
4247 if (po->op == OP_CALL) {
4250 ferr(po, "NULL pp\n");
4252 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4253 if (pp->name[0] != 0) {
4254 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4255 memcpy(pp->name, "i_", 2);
4257 // might be declared already
4259 for (j = 0; j < i; j++) {
4260 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4261 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4271 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4273 fprintf(fout, " %s (", pp->ret_type.name);
4274 output_pp_attrs(fout, pp, 0);
4275 fprintf(fout, "*%s)(", pp->name);
4276 for (j = 0; j < pp->argc; j++) {
4278 fprintf(fout, ", ");
4279 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
4281 fprintf(fout, ");\n");
4286 // output LUTs/jumptables
4287 for (i = 0; i < g_func_pd_cnt; i++) {
4289 fprintf(fout, " static const ");
4290 if (pd->type == OPT_OFFSET) {
4291 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
4293 for (j = 0; j < pd->count; j++) {
4295 fprintf(fout, ", ");
4296 fprintf(fout, "&&%s", pd->d[j].u.label);
4300 fprintf(fout, "%s %s[] =\n { ",
4301 lmod_type_u(ops, pd->lmod), pd->label);
4303 for (j = 0; j < pd->count; j++) {
4305 fprintf(fout, ", ");
4306 fprintf(fout, "%u", pd->d[j].u.val);
4309 fprintf(fout, " };\n");
4313 // declare stack frame, va_arg
4315 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
4316 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
4320 if (g_func_pp->is_userstack) {
4321 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4322 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
4326 if (g_func_pp->is_vararg) {
4327 fprintf(fout, " va_list ap;\n");
4331 // declare arg-registers
4332 for (i = 0; i < g_func_pp->argc; i++) {
4333 if (g_func_pp->arg[i].reg != NULL) {
4334 reg = char_array_i(regs_r32,
4335 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
4336 if (regmask & (1 << reg)) {
4337 if (g_func_pp->arg[i].type.is_retreg)
4338 fprintf(fout, " u32 %s = *r_%s;\n",
4339 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4341 fprintf(fout, " u32 %s = (u32)a%d;\n",
4342 g_func_pp->arg[i].reg, i + 1);
4345 if (g_func_pp->arg[i].type.is_retreg)
4346 ferr(ops, "retreg '%s' is unused?\n",
4347 g_func_pp->arg[i].reg);
4348 fprintf(fout, " // %s = a%d; // unused\n",
4349 g_func_pp->arg[i].reg, i + 1);
4355 regmask_now = regmask & ~regmask_arg;
4356 regmask_now &= ~(1 << xSP);
4357 if (regmask_now & 0x00ff) {
4358 for (reg = 0; reg < 8; reg++) {
4359 if (regmask_now & (1 << reg)) {
4360 fprintf(fout, " u32 %s", regs_r32[reg]);
4361 if (regmask_init & (1 << reg))
4362 fprintf(fout, " = 0");
4363 fprintf(fout, ";\n");
4368 if (regmask_now & 0xff00) {
4369 for (reg = 8; reg < 16; reg++) {
4370 if (regmask_now & (1 << reg)) {
4371 fprintf(fout, " mmxr %s", regs_r32[reg]);
4372 if (regmask_init & (1 << reg))
4373 fprintf(fout, " = { 0, }");
4374 fprintf(fout, ";\n");
4381 for (reg = 0; reg < 8; reg++) {
4382 if (regmask_save & (1 << reg)) {
4383 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
4389 for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
4390 if (save_arg_vars[i] == 0)
4392 for (reg = 0; reg < 32; reg++) {
4393 if (save_arg_vars[i] & (1 << reg)) {
4394 fprintf(fout, " u32 %s;\n",
4395 saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
4402 for (i = 0; i < 8; i++) {
4403 if (cond_vars & (1 << i)) {
4404 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
4411 fprintf(fout, " u32 tmp;\n");
4416 fprintf(fout, " u64 tmp64;\n");
4421 fprintf(fout, "\n");
4423 if (g_func_pp->is_vararg) {
4424 if (g_func_pp->argc_stack == 0)
4425 ferr(ops, "vararg func without stack args?\n");
4426 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
4430 for (i = 0; i < opcnt; i++)
4432 if (g_labels[i] != NULL) {
4433 fprintf(fout, "\n%s:\n", g_labels[i]);
4436 delayed_flag_op = NULL;
4437 last_arith_dst = NULL;
4441 if (po->flags & OPF_RMD)
4446 #define assert_operand_cnt(n_) \
4447 if (po->operand_cnt != n_) \
4448 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4450 // conditional/flag using op?
4451 if (po->flags & OPF_CC)
4457 // we go through all this trouble to avoid using parsed_flag_op,
4458 // which makes generated code much nicer
4459 if (delayed_flag_op != NULL)
4461 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
4462 po->pfo, po->pfo_inv);
4465 else if (last_arith_dst != NULL
4466 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
4467 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
4470 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4471 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
4472 last_arith_dst->lmod, buf3);
4475 else if (tmp_op != NULL) {
4476 // use preprocessed flag calc results
4477 if (!(tmp_op->pfomask & (1 << po->pfo)))
4478 ferr(po, "not prepared for pfo %d\n", po->pfo);
4480 // note: pfo_inv was not yet applied
4481 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
4482 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
4485 ferr(po, "all methods of finding comparison failed\n");
4488 if (po->flags & OPF_JMP) {
4489 fprintf(fout, " if %s", buf1);
4491 else if (po->op == OP_RCL || po->op == OP_RCR
4492 || po->op == OP_ADC || po->op == OP_SBB)
4495 fprintf(fout, " cond_%s = %s;\n",
4496 parsed_flag_op_names[po->pfo], buf1);
4498 else if (po->flags & OPF_DATA) { // SETcc
4499 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
4500 fprintf(fout, " %s = %s;", buf2, buf1);
4503 ferr(po, "unhandled conditional op\n");
4507 pfomask = po->pfomask;
4509 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
4510 struct parsed_opr opr = {0,};
4513 opr.lmod = OPLM_DWORD;
4514 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
4516 if (ret != 1 || uval == 0) {
4517 // we need initial flags for ecx=0 case..
4518 if (i > 0 && ops[i - 1].op == OP_XOR
4519 && IS(ops[i - 1].operand[0].name,
4520 ops[i - 1].operand[1].name))
4522 fprintf(fout, " cond_z = ");
4523 if (pfomask & (1 << PFO_C))
4524 fprintf(fout, "cond_c = ");
4525 fprintf(fout, "0;\n");
4527 else if (last_arith_dst != NULL) {
4528 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4529 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
4530 last_arith_dst->lmod, buf3);
4531 fprintf(fout, " cond_z = %s;\n", buf1);
4534 ferr(po, "missing initial ZF\n");
4541 assert_operand_cnt(2);
4542 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4543 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4544 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
4545 fprintf(fout, " %s = %s;", buf1,
4546 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4551 assert_operand_cnt(2);
4552 po->operand[1].lmod = OPLM_DWORD; // always
4553 fprintf(fout, " %s = %s;",
4554 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4555 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4560 assert_operand_cnt(2);
4561 fprintf(fout, " %s = %s;",
4562 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4563 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4567 assert_operand_cnt(2);
4568 switch (po->operand[1].lmod) {
4570 strcpy(buf3, "(s8)");
4573 strcpy(buf3, "(s16)");
4576 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4578 fprintf(fout, " %s = %s;",
4579 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4580 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4585 assert_operand_cnt(2);
4586 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4587 fprintf(fout, " tmp = %s;",
4588 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4589 fprintf(fout, " %s = %s;",
4590 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4591 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4592 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4593 fprintf(fout, " %s = %stmp;",
4594 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4595 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
4596 snprintf(g_comment, sizeof(g_comment), "xchg");
4600 assert_operand_cnt(1);
4601 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4602 fprintf(fout, " %s = ~%s;", buf1, buf1);
4606 assert_operand_cnt(2);
4607 fprintf(fout, " %s = (s32)%s >> 31;",
4608 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4609 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4610 strcpy(g_comment, "cdq");
4614 assert_operand_cnt(3);
4615 if (po->flags & OPF_REP) {
4620 fprintf(fout, " eax = %sesi; esi %c= %d;",
4621 lmod_cast_u_ptr(po, po->operand[0].lmod),
4622 (po->flags & OPF_DF) ? '-' : '+',
4623 lmod_bytes(po, po->operand[0].lmod));
4624 strcpy(g_comment, "lods");
4629 assert_operand_cnt(3);
4630 if (po->flags & OPF_REP) {
4631 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
4632 (po->flags & OPF_DF) ? '-' : '+',
4633 lmod_bytes(po, po->operand[0].lmod));
4634 fprintf(fout, " %sedi = eax;",
4635 lmod_cast_u_ptr(po, po->operand[0].lmod));
4636 strcpy(g_comment, "rep stos");
4639 fprintf(fout, " %sedi = eax; edi %c= %d;",
4640 lmod_cast_u_ptr(po, po->operand[0].lmod),
4641 (po->flags & OPF_DF) ? '-' : '+',
4642 lmod_bytes(po, po->operand[0].lmod));
4643 strcpy(g_comment, "stos");
4648 assert_operand_cnt(3);
4649 j = lmod_bytes(po, po->operand[0].lmod);
4650 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4651 l = (po->flags & OPF_DF) ? '-' : '+';
4652 if (po->flags & OPF_REP) {
4654 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4657 " %sedi = %sesi;", buf1, buf1);
4658 strcpy(g_comment, "rep movs");
4661 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
4662 buf1, buf1, l, j, l, j);
4663 strcpy(g_comment, "movs");
4668 // repe ~ repeat while ZF=1
4669 assert_operand_cnt(3);
4670 j = lmod_bytes(po, po->operand[0].lmod);
4671 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4672 l = (po->flags & OPF_DF) ? '-' : '+';
4673 if (po->flags & OPF_REP) {
4675 " for (; ecx != 0; ecx--) {\n");
4676 if (pfomask & (1 << PFO_C)) {
4679 " cond_c = %sesi < %sedi;\n", buf1, buf1);
4680 pfomask &= ~(1 << PFO_C);
4683 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
4684 buf1, buf1, l, j, l, j);
4686 " if (cond_z %s 0) break;\n",
4687 (po->flags & OPF_REPZ) ? "==" : "!=");
4690 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4691 (po->flags & OPF_REPZ) ? "e" : "ne");
4695 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4696 buf1, buf1, l, j, l, j);
4697 strcpy(g_comment, "cmps");
4699 pfomask &= ~(1 << PFO_Z);
4700 last_arith_dst = NULL;
4701 delayed_flag_op = NULL;
4705 // only does ZF (for now)
4706 // repe ~ repeat while ZF=1
4707 assert_operand_cnt(3);
4708 j = lmod_bytes(po, po->operand[0].lmod);
4709 l = (po->flags & OPF_DF) ? '-' : '+';
4710 if (po->flags & OPF_REP) {
4712 " for (; ecx != 0; ecx--) {\n");
4714 " cond_z = (%seax == %sedi); edi %c= %d;\n",
4715 lmod_cast_u(po, po->operand[0].lmod),
4716 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4718 " if (cond_z %s 0) break;\n",
4719 (po->flags & OPF_REPZ) ? "==" : "!=");
4722 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4723 (po->flags & OPF_REPZ) ? "e" : "ne");
4726 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
4727 lmod_cast_u(po, po->operand[0].lmod),
4728 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4729 strcpy(g_comment, "scas");
4731 pfomask &= ~(1 << PFO_Z);
4732 last_arith_dst = NULL;
4733 delayed_flag_op = NULL;
4736 // arithmetic w/flags
4739 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4742 assert_operand_cnt(2);
4743 fprintf(fout, " %s %s= %s;",
4744 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4746 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4747 output_std_flags(fout, po, &pfomask, buf1);
4748 last_arith_dst = &po->operand[0];
4749 delayed_flag_op = NULL;
4754 assert_operand_cnt(2);
4755 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4756 if (pfomask & (1 << PFO_C)) {
4757 if (po->operand[1].type == OPT_CONST) {
4758 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4759 j = po->operand[1].val;
4762 if (po->op == OP_SHL)
4766 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
4770 ferr(po, "zero shift?\n");
4774 pfomask &= ~(1 << PFO_C);
4776 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
4777 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4778 output_std_flags(fout, po, &pfomask, buf1);
4779 last_arith_dst = &po->operand[0];
4780 delayed_flag_op = NULL;
4784 assert_operand_cnt(2);
4785 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4786 fprintf(fout, " %s = %s%s >> %s;", buf1,
4787 lmod_cast_s(po, po->operand[0].lmod), buf1,
4788 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4789 output_std_flags(fout, po, &pfomask, buf1);
4790 last_arith_dst = &po->operand[0];
4791 delayed_flag_op = NULL;
4795 assert_operand_cnt(3);
4796 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4797 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4798 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4799 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4800 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
4801 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
4802 buf1, buf3, buf1, buf2, l, buf3);
4803 strcpy(g_comment, "shrd");
4804 output_std_flags(fout, po, &pfomask, buf1);
4805 last_arith_dst = &po->operand[0];
4806 delayed_flag_op = NULL;
4811 assert_operand_cnt(2);
4812 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4813 if (po->operand[1].type == OPT_CONST) {
4814 j = po->operand[1].val;
4815 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4816 fprintf(fout, po->op == OP_ROL ?
4817 " %s = (%s << %d) | (%s >> %d);" :
4818 " %s = (%s >> %d) | (%s << %d);",
4819 buf1, buf1, j, buf1,
4820 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4824 output_std_flags(fout, po, &pfomask, buf1);
4825 last_arith_dst = &po->operand[0];
4826 delayed_flag_op = NULL;
4831 assert_operand_cnt(2);
4832 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4833 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4834 if (po->operand[1].type == OPT_CONST) {
4835 j = po->operand[1].val % l;
4837 ferr(po, "zero rotate\n");
4838 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
4839 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4840 if (po->op == OP_RCL) {
4842 " %s = (%s << %d) | (cond_c << %d)",
4843 buf1, buf1, j, j - 1);
4845 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4849 " %s = (%s >> %d) | (cond_c << %d)",
4850 buf1, buf1, j, l - j);
4852 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4854 fprintf(fout, ";\n");
4855 fprintf(fout, " cond_c = tmp;");
4859 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4860 output_std_flags(fout, po, &pfomask, buf1);
4861 last_arith_dst = &po->operand[0];
4862 delayed_flag_op = NULL;
4866 assert_operand_cnt(2);
4867 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4868 if (IS(opr_name(po, 0), opr_name(po, 1))) {
4869 // special case for XOR
4870 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4871 fprintf(fout, " cond_be = 1;\n");
4872 pfomask &= ~(1 << PFO_BE);
4874 fprintf(fout, " %s = 0;",
4875 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4876 last_arith_dst = &po->operand[0];
4877 delayed_flag_op = NULL;
4883 assert_operand_cnt(2);
4884 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4885 if (pfomask & (1 << PFO_C)) {
4886 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4887 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4888 if (po->operand[0].lmod == OPLM_DWORD) {
4889 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
4890 fprintf(fout, " cond_c = tmp64 >> 32;\n");
4891 fprintf(fout, " %s = (u32)tmp64;",
4892 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4893 strcat(g_comment, "add64");
4896 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
4897 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
4898 fprintf(fout, " %s += %s;",
4899 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4902 pfomask &= ~(1 << PFO_C);
4903 output_std_flags(fout, po, &pfomask, buf1);
4904 last_arith_dst = &po->operand[0];
4905 delayed_flag_op = NULL;
4911 assert_operand_cnt(2);
4912 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4913 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
4914 for (j = 0; j <= PFO_LE; j++) {
4915 if (!(pfomask & (1 << j)))
4917 if (j == PFO_Z || j == PFO_S)
4920 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4921 fprintf(fout, " cond_%s = %s;\n",
4922 parsed_flag_op_names[j], buf1);
4923 pfomask &= ~(1 << j);
4930 assert_operand_cnt(2);
4931 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4932 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4933 if (po->op == OP_SBB
4934 && IS(po->operand[0].name, po->operand[1].name))
4936 // avoid use of unitialized var
4937 fprintf(fout, " %s = -cond_c;", buf1);
4938 // carry remains what it was
4939 pfomask &= ~(1 << PFO_C);
4942 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
4943 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4945 output_std_flags(fout, po, &pfomask, buf1);
4946 last_arith_dst = &po->operand[0];
4947 delayed_flag_op = NULL;
4951 assert_operand_cnt(2);
4952 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4953 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4954 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4956 output_std_flags(fout, po, &pfomask, buf1);
4957 last_arith_dst = &po->operand[0];
4958 delayed_flag_op = NULL;
4959 strcat(g_comment, "bsf");
4963 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
4964 for (j = 0; j <= PFO_LE; j++) {
4965 if (!(pfomask & (1 << j)))
4967 if (j == PFO_Z || j == PFO_S || j == PFO_C)
4970 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4971 fprintf(fout, " cond_%s = %s;\n",
4972 parsed_flag_op_names[j], buf1);
4973 pfomask &= ~(1 << j);
4979 if (pfomask & (1 << PFO_C))
4980 // carry is unaffected by inc/dec.. wtf?
4981 ferr(po, "carry propagation needed\n");
4983 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4984 if (po->operand[0].type == OPT_REG) {
4985 strcpy(buf2, po->op == OP_INC ? "++" : "--");
4986 fprintf(fout, " %s%s;", buf1, buf2);
4989 strcpy(buf2, po->op == OP_INC ? "+" : "-");
4990 fprintf(fout, " %s %s= 1;", buf1, buf2);
4992 output_std_flags(fout, po, &pfomask, buf1);
4993 last_arith_dst = &po->operand[0];
4994 delayed_flag_op = NULL;
4998 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4999 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5000 fprintf(fout, " %s = -%s%s;", buf1,
5001 lmod_cast_s(po, po->operand[0].lmod), buf2);
5002 last_arith_dst = &po->operand[0];
5003 delayed_flag_op = NULL;
5004 if (pfomask & (1 << PFO_C)) {
5005 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
5006 pfomask &= ~(1 << PFO_C);
5011 if (po->operand_cnt == 2) {
5012 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5015 if (po->operand_cnt == 3)
5016 ferr(po, "TODO imul3\n");
5019 assert_operand_cnt(1);
5020 switch (po->operand[0].lmod) {
5022 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5023 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
5024 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5025 fprintf(fout, " edx = tmp64 >> 32;\n");
5026 fprintf(fout, " eax = tmp64;");
5029 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5030 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
5031 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5035 ferr(po, "TODO: unhandled mul type\n");
5038 last_arith_dst = NULL;
5039 delayed_flag_op = NULL;
5044 assert_operand_cnt(1);
5045 if (po->operand[0].lmod != OPLM_DWORD)
5046 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5048 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5049 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5050 po->op == OP_IDIV));
5051 switch (po->operand[0].lmod) {
5053 if (po->flags & OPF_32BIT)
5054 snprintf(buf3, sizeof(buf3), "%seax", buf2);
5056 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
5057 snprintf(buf3, sizeof(buf3), "%stmp64",
5058 (po->op == OP_IDIV) ? "(s64)" : "");
5060 if (po->operand[0].type == OPT_REG
5061 && po->operand[0].reg == xDX)
5063 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5064 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5067 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5068 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5072 ferr(po, "unhandled division type\n");
5074 last_arith_dst = NULL;
5075 delayed_flag_op = NULL;
5080 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5082 for (j = 0; j < 8; j++) {
5083 if (pfomask & (1 << j)) {
5084 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5085 fprintf(fout, " cond_%s = %s;",
5086 parsed_flag_op_names[j], buf1);
5093 last_arith_dst = NULL;
5094 delayed_flag_op = po;
5098 // SETcc - should already be handled
5101 // note: we reuse OP_Jcc for SETcc, only flags differ
5103 fprintf(fout, "\n goto %s;", po->operand[0].name);
5107 fprintf(fout, " if (ecx == 0)\n");
5108 fprintf(fout, " goto %s;", po->operand[0].name);
5109 strcat(g_comment, "jecxz");
5113 assert_operand_cnt(1);
5114 last_arith_dst = NULL;
5115 delayed_flag_op = NULL;
5117 if (po->operand[0].type == OPT_REGMEM) {
5118 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5121 ferr(po, "parse failure for jmp '%s'\n",
5122 po->operand[0].name);
5123 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
5126 else if (po->operand[0].type != OPT_LABEL)
5127 ferr(po, "unhandled jmp type\n");
5129 fprintf(fout, " goto %s;", po->operand[0].name);
5133 assert_operand_cnt(1);
5135 my_assert_not(pp, NULL);
5138 if (po->flags & OPF_CC) {
5139 // we treat conditional branch to another func
5140 // (yes such code exists..) as conditional tailcall
5142 fprintf(fout, " {\n");
5145 if (pp->is_fptr && !pp->is_arg) {
5146 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5147 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5149 if (pp->is_unresolved)
5150 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5151 buf3, asmfn, po->asmln, pp->name);
5154 fprintf(fout, "%s", buf3);
5155 if (strstr(pp->ret_type.name, "int64")) {
5156 if (po->flags & OPF_TAIL)
5157 ferr(po, "int64 and tail?\n");
5158 fprintf(fout, "tmp64 = ");
5160 else if (!IS(pp->ret_type.name, "void")) {
5161 if (po->flags & OPF_TAIL) {
5162 if (!IS(g_func_pp->ret_type.name, "void")) {
5163 fprintf(fout, "return ");
5164 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5165 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5168 else if (regmask & (1 << xAX)) {
5169 fprintf(fout, "eax = ");
5170 if (pp->ret_type.is_ptr)
5171 fprintf(fout, "(u32)");
5175 if (pp->name[0] == 0)
5176 ferr(po, "missing pp->name\n");
5177 fprintf(fout, "%s%s(", pp->name,
5178 pp->has_structarg ? "_sa" : "");
5180 if (po->flags & OPF_ATAIL) {
5181 if (pp->argc_stack != g_func_pp->argc_stack
5182 || (pp->argc_stack > 0
5183 && pp->is_stdcall != g_func_pp->is_stdcall))
5184 ferr(po, "incompatible tailcall\n");
5185 if (g_func_pp->has_retreg)
5186 ferr(po, "TODO: retreg+tailcall\n");
5188 for (arg = j = 0; arg < pp->argc; arg++) {
5190 fprintf(fout, ", ");
5193 if (pp->arg[arg].type.is_ptr)
5194 snprintf(cast, sizeof(cast), "(%s)",
5195 pp->arg[arg].type.name);
5197 if (pp->arg[arg].reg != NULL) {
5198 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5202 for (; j < g_func_pp->argc; j++)
5203 if (g_func_pp->arg[j].reg == NULL)
5205 fprintf(fout, "%sa%d", cast, j + 1);
5210 for (arg = 0; arg < pp->argc; arg++) {
5212 fprintf(fout, ", ");
5215 if (pp->arg[arg].type.is_ptr)
5216 snprintf(cast, sizeof(cast), "(%s)",
5217 pp->arg[arg].type.name);
5219 if (pp->arg[arg].reg != NULL) {
5220 if (pp->arg[arg].type.is_retreg)
5221 fprintf(fout, "&%s", pp->arg[arg].reg);
5223 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5228 tmp_op = pp->arg[arg].datap;
5230 ferr(po, "parsed_op missing for arg%d\n", arg);
5232 if (tmp_op->flags & OPF_VAPUSH) {
5233 fprintf(fout, "ap");
5235 else if (tmp_op->p_argpass != 0) {
5236 fprintf(fout, "a%d", tmp_op->p_argpass);
5238 else if (tmp_op->p_argnum != 0) {
5239 fprintf(fout, "%s%s", cast,
5240 saved_arg_name(buf1, sizeof(buf1),
5241 tmp_op->p_arggrp, tmp_op->p_argnum));
5245 out_src_opr(buf1, sizeof(buf1),
5246 tmp_op, &tmp_op->operand[0], cast, 0));
5250 fprintf(fout, ");");
5252 if (strstr(pp->ret_type.name, "int64")) {
5253 fprintf(fout, "\n");
5254 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5255 fprintf(fout, "%seax = tmp64;", buf3);
5258 if (pp->is_unresolved) {
5259 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
5261 strcat(g_comment, buf2);
5264 if (po->flags & OPF_TAIL) {
5266 if (i == opcnt - 1 || pp->is_noreturn)
5268 else if (IS(pp->ret_type.name, "void"))
5270 else if (IS(g_func_pp->ret_type.name, "void"))
5272 // else already handled as 'return f()'
5275 if (!IS(g_func_pp->ret_type.name, "void")) {
5276 ferr(po, "int func -> void func tailcall?\n");
5279 fprintf(fout, "\n%sreturn;", buf3);
5280 strcat(g_comment, " ^ tailcall");
5284 strcat(g_comment, " tailcall");
5286 if (pp->is_noreturn)
5287 strcat(g_comment, " noreturn");
5288 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5289 strcat(g_comment, " argframe");
5290 if (po->flags & OPF_CC)
5291 strcat(g_comment, " cond");
5293 if (po->flags & OPF_CC)
5294 fprintf(fout, "\n }");
5296 delayed_flag_op = NULL;
5297 last_arith_dst = NULL;
5301 if (g_func_pp->is_vararg)
5302 fprintf(fout, " va_end(ap);\n");
5303 if (g_func_pp->has_retreg) {
5304 for (arg = 0; arg < g_func_pp->argc; arg++)
5305 if (g_func_pp->arg[arg].type.is_retreg)
5306 fprintf(fout, " *r_%s = %s;\n",
5307 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
5310 if (IS(g_func_pp->ret_type.name, "void")) {
5311 if (i != opcnt - 1 || label_pending)
5312 fprintf(fout, " return;");
5314 else if (g_func_pp->ret_type.is_ptr) {
5315 fprintf(fout, " return (%s)eax;",
5316 g_func_pp->ret_type.name);
5318 else if (IS(g_func_pp->ret_type.name, "__int64"))
5319 fprintf(fout, " return ((u64)edx << 32) | eax;");
5321 fprintf(fout, " return eax;");
5323 last_arith_dst = NULL;
5324 delayed_flag_op = NULL;
5328 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5329 if (po->p_argnum != 0) {
5330 // special case - saved func arg
5331 fprintf(fout, " %s = %s;",
5332 saved_arg_name(buf2, sizeof(buf2),
5333 po->p_arggrp, po->p_argnum), buf1);
5336 else if (po->flags & OPF_RSAVE) {
5337 fprintf(fout, " s_%s = %s;", buf1, buf1);
5340 else if (g_func_pp->is_userstack) {
5341 fprintf(fout, " *(--esp) = %s;", buf1);
5344 if (!(g_ida_func_attr & IDAFA_NORETURN))
5345 ferr(po, "stray push encountered\n");
5350 if (po->flags & OPF_RSAVE) {
5351 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5352 fprintf(fout, " %s = s_%s;", buf1, buf1);
5355 else if (po->datap != NULL) {
5358 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5359 fprintf(fout, " %s = %s;", buf1,
5360 out_src_opr(buf2, sizeof(buf2),
5361 tmp_op, &tmp_op->operand[0],
5362 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5365 else if (g_func_pp->is_userstack) {
5366 fprintf(fout, " %s = *esp++;",
5367 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5371 ferr(po, "stray pop encountered\n");
5380 strcpy(g_comment, "(emms)");
5385 ferr(po, "unhandled op type %d, flags %x\n",
5390 if (g_comment[0] != 0) {
5391 char *p = g_comment;
5392 while (my_isblank(*p))
5394 fprintf(fout, " // %s", p);
5399 fprintf(fout, "\n");
5401 // some sanity checking
5402 if (po->flags & OPF_REP) {
5403 if (po->op != OP_STOS && po->op != OP_MOVS
5404 && po->op != OP_CMPS && po->op != OP_SCAS)
5405 ferr(po, "unexpected rep\n");
5406 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
5407 && (po->op == OP_CMPS || po->op == OP_SCAS))
5408 ferr(po, "cmps/scas with plain rep\n");
5410 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
5411 && po->op != OP_CMPS && po->op != OP_SCAS)
5412 ferr(po, "unexpected repz/repnz\n");
5415 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
5417 // see is delayed flag stuff is still valid
5418 if (delayed_flag_op != NULL && delayed_flag_op != po) {
5419 if (is_any_opr_modified(delayed_flag_op, po, 0))
5420 delayed_flag_op = NULL;
5423 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
5424 if (is_opr_modified(last_arith_dst, po))
5425 last_arith_dst = NULL;
5431 if (g_stack_fsz && !g_stack_frame_used)
5432 fprintf(fout, " (void)sf;\n");
5434 fprintf(fout, "}\n\n");
5436 gen_x_cleanup(opcnt);
5439 static void gen_x_cleanup(int opcnt)
5443 for (i = 0; i < opcnt; i++) {
5444 struct label_ref *lr, *lr_del;
5446 lr = g_label_refs[i].next;
5447 while (lr != NULL) {
5452 g_label_refs[i].i = -1;
5453 g_label_refs[i].next = NULL;
5455 if (ops[i].op == OP_CALL) {
5457 proto_release(ops[i].pp);
5463 struct func_proto_dep;
5465 struct func_prototype {
5470 int has_ret:3; // -1, 0, 1: unresolved, no, yes
5471 unsigned int dep_resolved:1;
5472 unsigned int is_stdcall:1;
5473 struct func_proto_dep *dep_func;
5477 struct func_proto_dep {
5479 struct func_prototype *proto;
5480 int regmask_live; // .. at the time of call
5481 unsigned int ret_dep:1; // return from this is caller's return
5484 static struct func_prototype *hg_fp;
5485 static int hg_fp_cnt;
5487 static struct scanned_var {
5489 enum opr_lenmod lmod;
5490 unsigned int is_seeded:1;
5491 unsigned int is_c_str:1;
5493 static int hg_var_cnt;
5495 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5498 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
5503 for (i = 0; i < fp->dep_func_cnt; i++)
5504 if (IS(fp->dep_func[i].name, name))
5505 return &fp->dep_func[i];
5510 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
5513 if (hg_fp_find_dep(fp, name))
5516 if ((fp->dep_func_cnt & 0xff) == 0) {
5517 fp->dep_func = realloc(fp->dep_func,
5518 sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
5519 my_assert_not(fp->dep_func, NULL);
5520 memset(&fp->dep_func[fp->dep_func_cnt], 0,
5521 sizeof(fp->dep_func[0]) * 0x100);
5523 fp->dep_func[fp->dep_func_cnt].name = strdup(name);
5527 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
5529 const struct func_prototype *p1 = p1_, *p2 = p2_;
5530 return strcmp(p1->name, p2->name);
5534 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
5536 const struct func_prototype *p1 = p1_, *p2 = p2_;
5537 return p1->id - p2->id;
5541 static void gen_hdr(const char *funcn, int opcnt)
5543 int save_arg_vars[MAX_ARG_GRP] = { 0, };
5544 const struct parsed_proto *pp_c;
5545 struct parsed_proto *pp;
5546 struct func_prototype *fp;
5547 struct func_proto_dep *dep;
5548 struct parsed_data *pd;
5549 struct parsed_op *po;
5550 const char *tmpname;
5551 int regmask_dummy = 0;
5552 int regmask_save = 0;
5553 int regmask_dst = 0;
5554 int regmask_dep = 0;
5555 int max_bp_offset = 0;
5557 int from_caller = 0;
5561 if ((hg_fp_cnt & 0xff) == 0) {
5562 hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
5563 my_assert_not(hg_fp, NULL);
5564 memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
5567 fp = &hg_fp[hg_fp_cnt];
5568 snprintf(fp->name, sizeof(fp->name), "%s", funcn);
5570 fp->argc_stack = -1;
5573 // perhaps already in seed header?
5574 pp_c = proto_parse(g_fhdr, funcn, 1);
5576 fp->argc_stack = pp_c->argc_stack;
5577 fp->regmask_dep = get_pp_arg_regmask(pp_c);
5578 fp->has_ret = !IS(pp_c->ret_type.name, "void");
5582 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
5583 g_stack_frame_used = 0;
5586 // - handle ebp/esp frame, remove ops related to it
5587 scan_prologue_epilogue(opcnt);
5591 // - resolve all branches
5592 for (i = 0; i < opcnt; i++)
5598 if (po->flags & OPF_RMD)
5601 if (po->op == OP_CALL) {
5602 tmpname = opr_name(po, 0);
5604 if (po->operand[0].type == OPT_LABEL) {
5605 hg_fp_add_dep(fp, tmpname);
5607 // perhaps a call to already known func?
5608 pp_c = proto_parse(g_fhdr, tmpname, 1);
5610 pp = proto_clone(pp_c);
5612 else if (po->datap != NULL) {
5613 pp = calloc(1, sizeof(*pp));
5614 my_assert_not(pp, NULL);
5616 ret = parse_protostr(po->datap, pp);
5618 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
5622 if (pp != NULL && pp->is_noreturn)
5623 po->flags |= OPF_TAIL;
5629 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
5632 if (po->operand[0].type == OPT_REGMEM) {
5633 pd = try_resolve_jumptab(i, opcnt);
5641 for (l = 0; l < opcnt; l++) {
5642 if (g_labels[l] != NULL
5643 && IS(po->operand[0].name, g_labels[l]))
5645 add_label_ref(&g_label_refs[l], i);
5651 if (po->bt_i != -1 || (po->flags & OPF_RMD))
5654 if (po->operand[0].type == OPT_LABEL)
5658 ferr(po, "unhandled branch\n");
5662 po->flags |= OPF_TAIL;
5663 if (i > 0 && ops[i - 1].op == OP_POP)
5664 po->flags |= OPF_ATAIL;
5669 // - remove dead labels
5670 // - process trivial calls
5671 // - handle push <const>/pop pairs
5672 for (i = 0; i < opcnt; i++)
5674 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
5680 if (po->flags & OPF_RMD)
5683 if (po->op == OP_CALL)
5685 pp = process_call_early(i, opcnt, &j);
5687 if (!(po->flags & OPF_ATAIL))
5688 // since we know the args, try to collect them
5689 if (collect_call_args_early(po, i, pp, ®mask_dummy) != 0)
5695 // commit esp adjust
5696 ops[j].flags |= OPF_RMD;
5697 if (ops[j].op != OP_POP) {
5698 ferr_assert(&ops[j], ops[j].op == OP_ADD);
5699 ops[j].operand[1].val -= pp->argc_stack * 4;
5703 po->flags |= OPF_DONE;
5706 else if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST) {
5707 scan_for_pop_const(i, opcnt);
5713 for (i = 0; i < opcnt; i++)
5716 if (po->flags & OPF_RMD)
5719 if (po->op == OP_CALL && !(po->flags & OPF_DONE))
5721 pp = process_call(i, opcnt);
5723 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
5724 // since we know the args, collect them
5725 collect_call_args(po, i, pp, ®mask_dummy, save_arg_vars,
5732 // - track saved regs
5733 // - try to figure out arg-regs
5734 for (i = 0; i < opcnt; i++)
5738 if (po->flags & OPF_FARG)
5739 /* (just calculate register deps) */;
5740 else if (po->flags & OPF_RMD)
5742 else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5744 reg = po->operand[0].reg;
5746 ferr(po, "reg not set for push?\n");
5749 ret = scan_for_pop(i + 1, opcnt,
5750 po->operand[0].name, i + opcnt * 1, 0, &depth, 0);
5752 regmask_save |= 1 << reg;
5753 po->flags |= OPF_RMD;
5754 scan_for_pop(i + 1, opcnt,
5755 po->operand[0].name, i + opcnt * 2, 0, &depth, 1);
5758 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
5760 regmask_save |= 1 << reg;
5761 po->flags |= OPF_RMD;
5762 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, OPF_RMD);
5766 else if (po->op == OP_CALL) {
5767 po->regmask_dst |= 1 << xAX;
5769 dep = hg_fp_find_dep(fp, po->operand[0].name);
5771 dep->regmask_live = regmask_save | regmask_dst;
5773 else if (po->op == OP_RET) {
5774 if (po->operand_cnt > 0) {
5776 if (fp->argc_stack >= 0
5777 && fp->argc_stack != po->operand[0].val / 4)
5778 ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
5779 fp->argc_stack = po->operand[0].val / 4;
5783 if (has_ret != 0 && (po->flags & OPF_TAIL)) {
5784 if (po->op == OP_CALL) {
5789 struct parsed_opr opr = { 0, };
5794 ret = resolve_origin(i, &opr, i + opcnt * 3, &j, &from_caller);
5797 if (ret == -1 && from_caller) {
5798 // unresolved eax - probably void func
5802 if (ops[j].op == OP_CALL) {
5803 dep = hg_fp_find_dep(fp, po->operand[0].name);
5814 l = regmask_save | regmask_dst;
5815 if (g_bp_frame && !(po->flags & OPF_EBP_S))
5818 l = po->regmask_src & ~l;
5821 fnote(po, "dep |= %04x, dst %04x, save %04x\n", l,
5822 regmask_dst, regmask_save);
5825 regmask_dst |= po->regmask_dst;
5828 if (has_ret == -1 && (regmask_dep & (1 << xAX)))
5831 for (i = 0; i < g_eqcnt; i++) {
5832 if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
5833 max_bp_offset = g_eqs[i].offset;
5836 if (fp->argc_stack < 0) {
5837 max_bp_offset = (max_bp_offset + 3) & ~3;
5838 fp->argc_stack = max_bp_offset / 4;
5839 if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
5843 fp->regmask_dep = regmask_dep & ~(1 << xSP);
5844 fp->has_ret = has_ret;
5845 // output_hdr_fp(stdout, fp, 1);
5847 gen_x_cleanup(opcnt);
5850 static void hg_fp_resolve_deps(struct func_prototype *fp)
5852 struct func_prototype fp_s;
5855 // this thing is recursive, so mark first..
5856 fp->dep_resolved = 1;
5858 for (i = 0; i < fp->dep_func_cnt; i++) {
5859 strcpy(fp_s.name, fp->dep_func[i].name);
5860 fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
5861 sizeof(hg_fp[0]), hg_fp_cmp_name);
5862 if (fp->dep_func[i].proto != NULL) {
5863 if (!fp->dep_func[i].proto->dep_resolved)
5864 hg_fp_resolve_deps(fp->dep_func[i].proto);
5866 fp->regmask_dep |= ~fp->dep_func[i].regmask_live
5867 & fp->dep_func[i].proto->regmask_dep;
5869 if (fp->has_ret == -1)
5870 fp->has_ret = fp->dep_func[i].proto->has_ret;
5875 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5878 const struct parsed_proto *pp;
5879 char *p, namebuf[NAMELEN];
5885 for (; count > 0; count--, fp++) {
5886 if (fp->has_ret == -1)
5887 fprintf(fout, "// ret unresolved\n");
5889 fprintf(fout, "// dep:");
5890 for (j = 0; j < fp->dep_func_cnt; j++) {
5891 fprintf(fout, " %s/", fp->dep_func[j].name);
5892 if (fp->dep_func[j].proto != NULL)
5893 fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
5894 fp->dep_func[j].proto->has_ret);
5896 fprintf(fout, "\n");
5899 p = strchr(fp->name, '@');
5901 memcpy(namebuf, fp->name, p - fp->name);
5902 namebuf[p - fp->name] = 0;
5910 pp = proto_parse(g_fhdr, name, 1);
5911 if (pp != NULL && pp->is_include)
5914 regmask_dep = fp->regmask_dep;
5915 argc_stack = fp->argc_stack;
5917 fprintf(fout, fp->has_ret ? "int " : "void ");
5918 if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
5919 && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
5921 fprintf(fout, " __fastcall ");
5922 if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
5928 else if (regmask_dep && !fp->is_stdcall) {
5929 fprintf(fout, "/*__usercall*/ ");
5931 else if (regmask_dep) {
5932 fprintf(fout, "/*__userpurge*/ ");
5934 else if (fp->is_stdcall)
5935 fprintf(fout, " __stdcall ");
5937 fprintf(fout, " __cdecl ");
5939 fprintf(fout, "%s(", name);
5942 for (j = 0; j < xSP; j++) {
5943 if (regmask_dep & (1 << j)) {
5946 fprintf(fout, ", ");
5947 fprintf(fout, "int a%d/*<%s>*/", arg, regs_r32[j]);
5951 for (j = 0; j < argc_stack; j++) {
5954 fprintf(fout, ", ");
5955 fprintf(fout, "int a%d", arg);
5958 fprintf(fout, ");\n");
5962 static void output_hdr(FILE *fout)
5964 static const char *lmod_c_names[] = {
5965 [OPLM_UNSPEC] = "???",
5966 [OPLM_BYTE] = "uint8_t",
5967 [OPLM_WORD] = "uint16_t",
5968 [OPLM_DWORD] = "uint32_t",
5969 [OPLM_QWORD] = "uint64_t",
5971 const struct scanned_var *var;
5975 qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
5976 for (i = 0; i < hg_fp_cnt; i++)
5977 hg_fp_resolve_deps(&hg_fp[i]);
5979 // note: messes up .proto ptr, don't use
5980 //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
5983 for (i = 0; i < hg_var_cnt; i++) {
5987 fprintf(fout, "extern %-8s %s[];", "char", var->name);
5989 fprintf(fout, "extern %-8s %s;",
5990 lmod_c_names[var->lmod], var->name);
5993 fprintf(fout, " // seeded");
5994 fprintf(fout, "\n");
5997 fprintf(fout, "\n");
5999 // output function prototypes
6000 output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6003 // read a line, truncating it if it doesn't fit
6004 static char *my_fgets(char *s, size_t size, FILE *stream)
6014 ret = fgets(s, size, stream);
6015 if (ret != NULL && p >= 0 && s[p] != 0 && s[p] != '\n') {
6016 p = sizeof(buf) - 2;
6019 ret2 = fgets(buf, sizeof(buf), stream);
6021 while (ret2 != NULL && buf[p] != 0 && buf[p] != '\n');
6027 // '=' needs special treatment
6029 static char *next_word_s(char *w, size_t wsize, char *s)
6038 for (i = 1; i < wsize - 1; i++) {
6040 printf("warning: missing closing quote: \"%s\"\n", s);
6049 for (; i < wsize - 1; i++) {
6050 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6056 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6057 printf("warning: '%s' truncated\n", w);
6062 static void scan_variables(FILE *fasm)
6064 const struct parsed_proto *pp_c;
6065 struct scanned_var *var;
6066 char line[256] = { 0, };
6074 // skip to next data section
6075 while (my_fgets(line, sizeof(line), fasm))
6080 if (*p == 0 || *p == ';')
6083 p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6084 if (*p == 0 || *p == ';')
6087 if (*p != 's' || !IS_START(p, "segment para public"))
6093 if (p == NULL || !IS_START(p, "segment para public"))
6097 if (!IS_START(p, "'DATA'"))
6101 while (my_fgets(line, sizeof(line), fasm))
6110 if (*p == 0 || *p == ';')
6113 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6114 words[wordc][0] = 0;
6115 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6116 if (*p == 0 || *p == ';') {
6122 if (wordc == 2 && IS(words[1], "ends"))
6127 if ((hg_var_cnt & 0xff) == 0) {
6128 hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6129 * (hg_var_cnt + 0x100));
6130 my_assert_not(hg_vars, NULL);
6131 memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6134 var = &hg_vars[hg_var_cnt++];
6135 snprintf(var->name, sizeof(var->name), "%s", words[0]);
6137 // maybe already in seed header?
6138 pp_c = proto_parse(g_fhdr, var->name, 1);
6142 else if (pp_c->is_fptr) {
6143 var->lmod = OPLM_DWORD;
6146 else if (!guess_lmod_from_c_type(&var->lmod, &pp_c->type))
6147 aerr("unhandled C type '%s' for '%s'\n",
6148 pp_c->type.name, var->name);
6154 if (IS(words[1], "dd"))
6155 var->lmod = OPLM_DWORD;
6156 else if (IS(words[1], "dw"))
6157 var->lmod = OPLM_WORD;
6158 else if (IS(words[1], "db")) {
6159 var->lmod = OPLM_BYTE;
6160 if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6161 if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6165 else if (IS(words[1], "dq"))
6166 var->lmod = OPLM_QWORD;
6167 //else if (IS(words[1], "dt"))
6169 aerr("type '%s' not known\n", words[1]);
6177 static void set_label(int i, const char *name)
6183 p = strchr(name, ':');
6187 if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6188 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6189 g_labels[i] = realloc(g_labels[i], len + 1);
6190 my_assert_not(g_labels[i], NULL);
6191 memcpy(g_labels[i], name, len);
6192 g_labels[i][len] = 0;
6201 static struct chunk_item *func_chunks;
6202 static int func_chunk_cnt;
6203 static int func_chunk_alloc;
6205 static void add_func_chunk(FILE *fasm, const char *name, int line)
6207 if (func_chunk_cnt >= func_chunk_alloc) {
6208 func_chunk_alloc *= 2;
6209 func_chunks = realloc(func_chunks,
6210 func_chunk_alloc * sizeof(func_chunks[0]));
6211 my_assert_not(func_chunks, NULL);
6213 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6214 func_chunks[func_chunk_cnt].name = strdup(name);
6215 func_chunks[func_chunk_cnt].asmln = line;
6219 static int cmp_chunks(const void *p1, const void *p2)
6221 const struct chunk_item *c1 = p1, *c2 = p2;
6222 return strcmp(c1->name, c2->name);
6225 static int cmpstringp(const void *p1, const void *p2)
6227 return strcmp(*(char * const *)p1, *(char * const *)p2);
6230 static void scan_ahead(FILE *fasm)
6240 oldpos = ftell(fasm);
6243 while (my_fgets(line, sizeof(line), fasm))
6254 // get rid of random tabs
6255 for (i = 0; line[i] != 0; i++)
6256 if (line[i] == '\t')
6259 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6262 next_word(words[0], sizeof(words[0]), p);
6263 if (words[0][0] == 0)
6264 aerr("missing name for func chunk?\n");
6266 add_func_chunk(fasm, words[0], asmln);
6268 else if (IS_START(p, "; sctend"))
6274 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6275 words[wordc][0] = 0;
6276 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6277 if (*p == 0 || *p == ';') {
6283 if (wordc == 2 && IS(words[1], "ends"))
6287 fseek(fasm, oldpos, SEEK_SET);
6291 int main(int argc, char *argv[])
6293 FILE *fout, *fasm, *frlist;
6294 struct parsed_data *pd = NULL;
6296 char **rlist = NULL;
6298 int rlist_alloc = 0;
6299 int func_chunks_used = 0;
6300 int func_chunks_sorted = 0;
6301 int func_chunk_i = -1;
6302 long func_chunk_ret = 0;
6303 int func_chunk_ret_ln = 0;
6304 int scanned_ahead = 0;
6306 char words[20][256];
6307 enum opr_lenmod lmod;
6308 char *sctproto = NULL;
6310 int pending_endp = 0;
6312 int skip_warned = 0;
6325 for (arg = 1; arg < argc; arg++) {
6326 if (IS(argv[arg], "-v"))
6328 else if (IS(argv[arg], "-rf"))
6329 g_allow_regfunc = 1;
6330 else if (IS(argv[arg], "-m"))
6332 else if (IS(argv[arg], "-hdr"))
6333 g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
6338 if (argc < arg + 3) {
6339 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdrf> [rlist]*\n"
6340 "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n",
6347 asmfn = argv[arg++];
6348 fasm = fopen(asmfn, "r");
6349 my_assert_not(fasm, NULL);
6351 hdrfn = argv[arg++];
6352 g_fhdr = fopen(hdrfn, "r");
6353 my_assert_not(g_fhdr, NULL);
6356 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
6357 my_assert_not(rlist, NULL);
6358 // needs special handling..
6359 rlist[rlist_len++] = "__alloca_probe";
6361 func_chunk_alloc = 32;
6362 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
6363 my_assert_not(func_chunks, NULL);
6365 memset(words, 0, sizeof(words));
6367 for (; arg < argc; arg++) {
6368 frlist = fopen(argv[arg], "r");
6369 my_assert_not(frlist, NULL);
6371 while (my_fgets(line, sizeof(line), frlist)) {
6373 if (*p == 0 || *p == ';')
6376 if (IS_START(p, "#if 0")
6377 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
6381 else if (IS_START(p, "#endif"))
6388 p = next_word(words[0], sizeof(words[0]), p);
6389 if (words[0][0] == 0)
6392 if (rlist_len >= rlist_alloc) {
6393 rlist_alloc = rlist_alloc * 2 + 64;
6394 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
6395 my_assert_not(rlist, NULL);
6397 rlist[rlist_len++] = strdup(words[0]);
6406 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
6408 fout = fopen(argv[arg_out], "w");
6409 my_assert_not(fout, NULL);
6412 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
6413 my_assert_not(g_eqs, NULL);
6415 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
6416 g_label_refs[i].i = -1;
6417 g_label_refs[i].next = NULL;
6421 scan_variables(fasm);
6423 while (my_fgets(line, sizeof(line), fasm))
6432 // get rid of random tabs
6433 for (i = 0; line[i] != 0; i++)
6434 if (line[i] == '\t')
6439 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
6440 goto do_pending_endp; // eww..
6442 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
6444 static const char *attrs[] = {
6453 // parse IDA's attribute-list comment
6454 g_ida_func_attr = 0;
6457 for (; *p != 0; p = sskip(p)) {
6458 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
6459 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
6460 g_ida_func_attr |= 1 << i;
6461 p += strlen(attrs[i]);
6465 if (i == ARRAY_SIZE(attrs)) {
6466 anote("unparsed IDA attr: %s\n", p);
6469 if (IS(attrs[i], "fpd=")) {
6470 p = next_word(words[0], sizeof(words[0]), p);
6475 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6478 next_word(words[0], sizeof(words[0]), p);
6479 if (words[0][0] == 0)
6480 aerr("missing name for func chunk?\n");
6482 if (!scanned_ahead) {
6483 add_func_chunk(fasm, words[0], asmln);
6484 func_chunks_sorted = 0;
6487 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
6489 if (func_chunk_i >= 0) {
6490 if (func_chunk_i < func_chunk_cnt
6491 && IS(func_chunks[func_chunk_i].name, g_func))
6493 // move on to next chunk
6494 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6496 aerr("seek failed for '%s' chunk #%d\n",
6497 g_func, func_chunk_i);
6498 asmln = func_chunks[func_chunk_i].asmln;
6502 if (func_chunk_ret == 0)
6503 aerr("no return from chunk?\n");
6504 fseek(fasm, func_chunk_ret, SEEK_SET);
6505 asmln = func_chunk_ret_ln;
6511 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
6512 func_chunks_used = 1;
6514 if (IS_START(g_func, "sub_")) {
6515 unsigned long addr = strtoul(p, NULL, 16);
6516 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
6517 if (addr > f_addr && !scanned_ahead) {
6518 anote("scan_ahead caused by '%s', addr %lx\n",
6522 func_chunks_sorted = 0;
6530 for (i = wordc; i < ARRAY_SIZE(words); i++)
6532 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6533 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6534 if (*p == 0 || *p == ';') {
6539 if (*p != 0 && *p != ';')
6540 aerr("too many words\n");
6542 // alow asm patches in comments
6544 if (IS_START(p, "; sctpatch:")) {
6546 if (*p == 0 || *p == ';')
6548 goto parse_words; // lame
6550 if (IS_START(p, "; sctproto:")) {
6551 sctproto = strdup(p + 11);
6553 else if (IS_START(p, "; sctend")) {
6562 awarn("wordc == 0?\n");
6566 // don't care about this:
6567 if (words[0][0] == '.'
6568 || IS(words[0], "include")
6569 || IS(words[0], "assume") || IS(words[1], "segment")
6570 || IS(words[0], "align"))
6576 // do delayed endp processing to collect switch jumptables
6578 if (in_func && !skip_func && !end && wordc >= 2
6579 && ((words[0][0] == 'd' && words[0][2] == 0)
6580 || (words[1][0] == 'd' && words[1][2] == 0)))
6583 if (words[1][0] == 'd' && words[1][2] == 0) {
6585 if (g_func_pd_cnt >= pd_alloc) {
6586 pd_alloc = pd_alloc * 2 + 16;
6587 g_func_pd = realloc(g_func_pd,
6588 sizeof(g_func_pd[0]) * pd_alloc);
6589 my_assert_not(g_func_pd, NULL);
6591 pd = &g_func_pd[g_func_pd_cnt];
6593 memset(pd, 0, sizeof(*pd));
6594 strcpy(pd->label, words[0]);
6595 pd->type = OPT_CONST;
6596 pd->lmod = lmod_from_directive(words[1]);
6602 anote("skipping alignment byte?\n");
6605 lmod = lmod_from_directive(words[0]);
6606 if (lmod != pd->lmod)
6607 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
6610 if (pd->count_alloc < pd->count + wordc) {
6611 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
6612 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
6613 my_assert_not(pd->d, NULL);
6615 for (; i < wordc; i++) {
6616 if (IS(words[i], "offset")) {
6617 pd->type = OPT_OFFSET;
6620 p = strchr(words[i], ',');
6623 if (pd->type == OPT_OFFSET)
6624 pd->d[pd->count].u.label = strdup(words[i]);
6626 pd->d[pd->count].u.val = parse_number(words[i]);
6627 pd->d[pd->count].bt_i = -1;
6633 if (in_func && !skip_func) {
6635 gen_hdr(g_func, pi);
6637 gen_func(fout, g_fhdr, g_func, pi);
6642 g_ida_func_attr = 0;
6646 func_chunks_used = 0;
6649 memset(&ops, 0, pi * sizeof(ops[0]));
6654 for (i = 0; i < g_func_pd_cnt; i++) {
6656 if (pd->type == OPT_OFFSET) {
6657 for (j = 0; j < pd->count; j++)
6658 free(pd->d[j].u.label);
6672 if (IS(words[1], "proc")) {
6674 aerr("proc '%s' while in_func '%s'?\n",
6677 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
6679 strcpy(g_func, words[0]);
6680 set_label(0, words[0]);
6685 if (IS(words[1], "endp"))
6688 aerr("endp '%s' while not in_func?\n", words[0]);
6689 if (!IS(g_func, words[0]))
6690 aerr("endp '%s' while in_func '%s'?\n",
6693 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
6694 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
6700 if (!skip_func && func_chunks_used) {
6701 // start processing chunks
6702 struct chunk_item *ci, key = { g_func, 0 };
6704 func_chunk_ret = ftell(fasm);
6705 func_chunk_ret_ln = asmln;
6706 if (!func_chunks_sorted) {
6707 qsort(func_chunks, func_chunk_cnt,
6708 sizeof(func_chunks[0]), cmp_chunks);
6709 func_chunks_sorted = 1;
6711 ci = bsearch(&key, func_chunks, func_chunk_cnt,
6712 sizeof(func_chunks[0]), cmp_chunks);
6714 aerr("'%s' needs chunks, but none found\n", g_func);
6715 func_chunk_i = ci - func_chunks;
6716 for (; func_chunk_i > 0; func_chunk_i--)
6717 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
6720 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6722 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
6723 asmln = func_chunks[func_chunk_i].asmln;
6731 if (wordc == 2 && IS(words[1], "ends")) {
6735 goto do_pending_endp;
6739 // scan for next text segment
6740 while (my_fgets(line, sizeof(line), fasm)) {
6743 if (*p == 0 || *p == ';')
6746 if (strstr(p, "segment para public 'CODE' use32"))
6753 p = strchr(words[0], ':');
6755 set_label(pi, words[0]);
6759 if (!in_func || skip_func) {
6760 if (!skip_warned && !skip_func && g_labels[pi] != NULL) {
6762 anote("skipping from '%s'\n", g_labels[pi]);
6766 g_labels[pi] = NULL;
6770 if (wordc > 1 && IS(words[1], "="))
6773 aerr("unhandled equ, wc=%d\n", wordc);
6774 if (g_eqcnt >= eq_alloc) {
6776 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
6777 my_assert_not(g_eqs, NULL);
6780 len = strlen(words[0]);
6781 if (len > sizeof(g_eqs[0].name) - 1)
6782 aerr("equ name too long: %d\n", len);
6783 strcpy(g_eqs[g_eqcnt].name, words[0]);
6785 if (!IS(words[3], "ptr"))
6786 aerr("unhandled equ\n");
6787 if (IS(words[2], "dword"))
6788 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
6789 else if (IS(words[2], "word"))
6790 g_eqs[g_eqcnt].lmod = OPLM_WORD;
6791 else if (IS(words[2], "byte"))
6792 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
6793 else if (IS(words[2], "qword"))
6794 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
6796 aerr("bad lmod: '%s'\n", words[2]);
6798 g_eqs[g_eqcnt].offset = parse_number(words[4]);
6803 if (pi >= ARRAY_SIZE(ops))
6804 aerr("too many ops\n");
6806 parse_op(&ops[pi], words, wordc);
6808 if (sctproto != NULL) {
6809 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
6810 ops[pi].datap = sctproto;
6826 // vim:ts=2:shiftwidth=2:expandtab