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"
18 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
19 #define IS(w, y) !strcmp(w, y)
20 #define IS_START(w, y) !strncmp(w, y, strlen(y))
22 #include "protoparse.h"
24 static const char *asmfn;
28 #define anote(fmt, ...) \
29 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
30 #define awarn(fmt, ...) \
31 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
32 #define aerr(fmt, ...) do { \
33 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
38 #include "masm_tools.h"
41 OPF_RMD = (1 << 0), /* removed from code generation */
42 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
43 OPF_FLAGS = (1 << 2), /* sets flags */
44 OPF_JMP = (1 << 3), /* branch, call */
45 OPF_CJMP = (1 << 4), /* cond. branch (cc or jecxz/loop) */
46 OPF_CC = (1 << 5), /* uses flags */
47 OPF_TAIL = (1 << 6), /* ret or tail call */
48 OPF_RSAVE = (1 << 7), /* push/pop is local reg save/load */
49 OPF_REP = (1 << 8), /* prefixed by rep */
50 OPF_REPZ = (1 << 9), /* rep is repe/repz */
51 OPF_REPNZ = (1 << 10), /* rep is repne/repnz */
52 OPF_FARG = (1 << 11), /* push collected as func arg */
53 OPF_FARGNR = (1 << 12), /* push collected as func arg (no reuse) */
54 OPF_EBP_S = (1 << 13), /* ebp used as scratch here, not BP */
55 OPF_DF = (1 << 14), /* DF flag set */
56 OPF_ATAIL = (1 << 15), /* tail call with reused arg frame */
57 OPF_32BIT = (1 << 16), /* 32bit division */
58 OPF_LOCK = (1 << 17), /* op has lock prefix */
59 OPF_VAPUSH = (1 << 18), /* vararg ptr push (as call arg) */
60 OPF_DONE = (1 << 19), /* already fully handled by analysis */
61 OPF_PPUSH = (1 << 20), /* part of complex push-pop graph */
62 OPF_NOREGS = (1 << 21), /* don't track regs of this op */
135 // must be sorted (larger len must be further in enum)
144 #define MAX_EXITS 128
146 #define MAX_OPERANDS 3
149 #define OPR_INIT(type_, lmod_, reg_) \
150 { type_, lmod_, reg_, }
154 enum opr_lenmod lmod;
156 unsigned int is_ptr:1; // pointer in C
157 unsigned int is_array:1; // array in C
158 unsigned int type_from_var:1; // .. in header, sometimes wrong
159 unsigned int size_mismatch:1; // type override differs from C
160 unsigned int size_lt:1; // type override is larger than C
161 unsigned int had_ds:1; // had ds: prefix
162 const struct parsed_proto *pp; // for OPT_LABEL
169 struct parsed_opr operand[MAX_OPERANDS];
172 unsigned char pfo_inv;
173 unsigned char operand_cnt;
174 unsigned char p_argnum; // arg push: altered before call arg #
175 unsigned char p_arggrp; // arg push: arg group # for above
176 unsigned char p_argpass;// arg push: arg of host func
177 short p_argnext;// arg push: same arg pushed elsewhere or -1
178 int regmask_src; // all referensed regs
180 int pfomask; // flagop: parsed_flag_op that can't be delayed
181 int cc_scratch; // scratch storage during analysis
182 int bt_i; // branch target for branches
183 struct parsed_data *btj;// branch targets for jumptables
184 struct parsed_proto *pp;// parsed_proto for OP_CALL
190 // OP_CALL - parser proto hint (str)
191 // (OPF_CC) - points to one of (OPF_FLAGS) that affects cc op
192 // OP_PUSH - points to OP_POP in complex push/pop graph
193 // OP_POP - points to OP_PUSH in simple push/pop pair
197 enum opr_lenmod lmod;
204 enum opr_lenmod lmod;
218 struct label_ref *next;
222 IDAFA_BP_FRAME = (1 << 0),
223 IDAFA_LIB_FUNC = (1 << 1),
224 IDAFA_STATIC = (1 << 2),
225 IDAFA_NORETURN = (1 << 3),
226 IDAFA_THUNK = (1 << 4),
227 IDAFA_FPD = (1 << 5),
230 // note: limited to 32k due to p_argnext
232 #define MAX_ARG_GRP 2
234 static struct parsed_op ops[MAX_OPS];
235 static struct parsed_equ *g_eqs;
237 static char *g_labels[MAX_OPS];
238 static struct label_ref g_label_refs[MAX_OPS];
239 static const struct parsed_proto *g_func_pp;
240 static struct parsed_data *g_func_pd;
241 static int g_func_pd_cnt;
242 static char g_func[256];
243 static char g_comment[256];
244 static int g_bp_frame;
245 static int g_sp_frame;
246 static int g_stack_frame_used;
247 static int g_stack_fsz;
248 static int g_ida_func_attr;
249 static int g_skip_func;
250 static int g_allow_regfunc;
251 static int g_quiet_pp;
252 static int g_header_mode;
254 #define ferr(op_, fmt, ...) do { \
255 printf("%s:%d: error %u: [%s] '%s': " fmt, asmfn, (op_)->asmln, \
256 __LINE__, g_func, dump_op(op_), ##__VA_ARGS__); \
260 #define fnote(op_, fmt, ...) \
261 printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
262 dump_op(op_), ##__VA_ARGS__)
264 #define ferr_assert(op_, cond) do { \
265 if (!(cond)) ferr(op_, "assertion '%s' failed\n", #cond); \
268 const char *regs_r32[] = {
269 "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
270 // not r32, but list here for easy parsing and printing
271 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
273 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
274 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
275 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
277 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
279 // possible basic comparison types (without inversion)
280 enum parsed_flag_op {
284 PFO_BE, // 6 CF=1||ZF=1
288 PFO_LE, // e ZF=1||SF!=OF
291 #define PFOB_O (1 << PFO_O)
292 #define PFOB_C (1 << PFO_C)
293 #define PFOB_Z (1 << PFO_Z)
294 #define PFOB_S (1 << PFO_S)
296 static const char *parsed_flag_op_names[] = {
297 "o", "c", "z", "be", "s", "p", "l", "le"
300 static int char_array_i(const char *array[], size_t len, const char *s)
304 for (i = 0; i < len; i++)
311 static void printf_number(char *buf, size_t buf_size,
312 unsigned long number)
314 // output in C-friendly form
315 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
318 static int check_segment_prefix(const char *s)
320 if (s[0] == 0 || s[1] != 's' || s[2] != ':')
334 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
338 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
340 *reg_lmod = OPLM_QWORD;
344 *reg_lmod = OPLM_DWORD;
347 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
349 *reg_lmod = OPLM_WORD;
352 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
354 *reg_lmod = OPLM_BYTE;
357 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
359 *reg_lmod = OPLM_BYTE;
366 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
368 enum opr_lenmod lmod;
381 while (my_isblank(*s))
383 for (; my_issep(*s); d++, s++)
385 while (my_isblank(*s))
389 // skip '?s:' prefixes
390 if (check_segment_prefix(s))
393 s = next_idt(w, sizeof(w), s);
398 reg = parse_reg(&lmod, w);
400 *regmask |= 1 << reg;
404 if ('0' <= w[0] && w[0] <= '9') {
405 number = parse_number(w);
406 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
410 // probably some label/identifier - pass
413 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
417 strcpy(name, cvtbuf);
422 static int is_reg_in_str(const char *s)
426 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
429 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
430 if (!strncmp(s, regs_r32[i], 3))
436 static const char *parse_stack_el(const char *name, char *extra_reg,
439 const char *p, *p2, *s;
445 if (g_bp_frame || early_try)
448 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
450 if (extra_reg != NULL) {
451 strncpy(extra_reg, name, 3);
456 if (IS_START(p, "ebp+")) {
460 if (p2 != NULL && is_reg_in_str(p)) {
461 if (extra_reg != NULL) {
462 strncpy(extra_reg, p, p2 - p);
463 extra_reg[p2 - p] = 0;
468 if (!('0' <= *p && *p <= '9'))
475 if (!IS_START(name, "esp+"))
481 if (is_reg_in_str(s)) {
482 if (extra_reg != NULL) {
483 strncpy(extra_reg, s, p - s);
484 extra_reg[p - s] = 0;
489 aerr("%s IDA stackvar not set?\n", __func__);
491 if (!('0' <= *s && *s <= '9')) {
492 aerr("%s IDA stackvar offset not set?\n", __func__);
495 if (s[0] == '0' && s[1] == 'x')
498 if (len < sizeof(buf) - 1) {
499 strncpy(buf, s, len);
501 val = strtol(buf, &endp, 16);
502 if (val == 0 || *endp != 0) {
503 aerr("%s num parse fail for '%s'\n", __func__, buf);
512 if ('0' <= *p && *p <= '9')
518 static int guess_lmod_from_name(struct parsed_opr *opr)
520 if (IS_START(opr->name, "dword_") || IS_START(opr->name, "off_")) {
521 opr->lmod = OPLM_DWORD;
524 if (IS_START(opr->name, "word_")) {
525 opr->lmod = OPLM_WORD;
528 if (IS_START(opr->name, "byte_")) {
529 opr->lmod = OPLM_BYTE;
532 if (IS_START(opr->name, "qword_")) {
533 opr->lmod = OPLM_QWORD;
539 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
540 const struct parsed_type *c_type)
542 static const char *dword_types[] = {
543 "uint32_t", "int", "_DWORD", "UINT_PTR", "DWORD",
544 "WPARAM", "LPARAM", "UINT", "__int32",
545 "LONG", "HIMC", "BOOL", "size_t",
548 static const char *word_types[] = {
549 "uint16_t", "int16_t", "_WORD", "WORD",
550 "unsigned __int16", "__int16",
552 static const char *byte_types[] = {
553 "uint8_t", "int8_t", "char",
554 "unsigned __int8", "__int8", "BYTE", "_BYTE",
556 // structures.. deal the same as with _UNKNOWN for now
562 if (c_type->is_ptr) {
567 n = skip_type_mod(c_type->name);
569 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
570 if (IS(n, dword_types[i])) {
576 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
577 if (IS(n, word_types[i])) {
583 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
584 if (IS(n, byte_types[i])) {
593 static char *default_cast_to(char *buf, size_t buf_size,
594 struct parsed_opr *opr)
600 if (opr->pp == NULL || opr->pp->type.name == NULL
603 snprintf(buf, buf_size, "%s", "(void *)");
607 snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
611 static enum opr_type lmod_from_directive(const char *d)
615 else if (IS(d, "dw"))
617 else if (IS(d, "db"))
620 aerr("unhandled directive: '%s'\n", d);
624 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
630 *regmask |= 1 << reg;
633 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
636 static int parse_operand(struct parsed_opr *opr,
637 int *regmask, int *regmask_indirect,
638 char words[16][256], int wordc, int w, unsigned int op_flags)
640 const struct parsed_proto *pp = NULL;
641 enum opr_lenmod tmplmod;
642 unsigned long number;
650 aerr("parse_operand w %d, wordc %d\n", w, wordc);
654 for (i = w; i < wordc; i++) {
655 len = strlen(words[i]);
656 if (words[i][len - 1] == ',') {
657 words[i][len - 1] = 0;
663 wordc_in = wordc - w;
665 if ((op_flags & OPF_JMP) && wordc_in > 0
666 && !('0' <= words[w][0] && words[w][0] <= '9'))
668 const char *label = NULL;
670 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
671 && IS(words[w + 1], "ptr"))
672 label = words[w + 2];
673 else if (wordc_in == 2 && IS(words[w], "short"))
674 label = words[w + 1];
675 else if (wordc_in == 1
676 && strchr(words[w], '[') == NULL
677 && parse_reg(&tmplmod, words[w]) < 0)
681 opr->type = OPT_LABEL;
682 ret = check_segment_prefix(label);
685 aerr("fs/gs used\n");
689 strcpy(opr->name, label);
695 if (IS(words[w + 1], "ptr")) {
696 if (IS(words[w], "dword"))
697 opr->lmod = OPLM_DWORD;
698 else if (IS(words[w], "word"))
699 opr->lmod = OPLM_WORD;
700 else if (IS(words[w], "byte"))
701 opr->lmod = OPLM_BYTE;
702 else if (IS(words[w], "qword"))
703 opr->lmod = OPLM_QWORD;
705 aerr("type parsing failed\n");
707 wordc_in = wordc - w;
712 if (IS(words[w], "offset")) {
713 opr->type = OPT_OFFSET;
714 opr->lmod = OPLM_DWORD;
715 strcpy(opr->name, words[w + 1]);
716 pp = proto_parse(g_fhdr, opr->name, 1);
719 if (IS(words[w], "(offset")) {
720 p = strchr(words[w + 1], ')');
722 aerr("parse of bracketed offset failed\n");
724 opr->type = OPT_OFFSET;
725 strcpy(opr->name, words[w + 1]);
731 aerr("parse_operand 1 word expected\n");
733 ret = check_segment_prefix(words[w]);
736 aerr("fs/gs used\n");
738 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
740 strcpy(opr->name, words[w]);
742 if (words[w][0] == '[') {
743 opr->type = OPT_REGMEM;
744 ret = sscanf(words[w], "[%[^]]]", opr->name);
746 aerr("[] parse failure\n");
748 parse_indmode(opr->name, regmask_indirect, 1);
749 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
752 struct parsed_equ *eq =
753 equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
755 opr->lmod = eq->lmod;
759 else if (strchr(words[w], '[')) {
761 p = strchr(words[w], '[');
762 opr->type = OPT_REGMEM;
763 parse_indmode(p, regmask_indirect, 0);
764 strncpy(buf, words[w], p - words[w]);
765 buf[p - words[w]] = 0;
766 pp = proto_parse(g_fhdr, buf, 1);
769 else if (('0' <= words[w][0] && words[w][0] <= '9')
770 || words[w][0] == '-')
772 number = parse_number(words[w]);
773 opr->type = OPT_CONST;
775 printf_number(opr->name, sizeof(opr->name), number);
779 ret = parse_reg(&tmplmod, opr->name);
781 setup_reg_opr(opr, ret, tmplmod, regmask);
785 // most likely var in data segment
786 opr->type = OPT_LABEL;
787 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
791 if (pp->is_fptr || pp->is_func) {
792 opr->lmod = OPLM_DWORD;
796 tmplmod = OPLM_UNSPEC;
797 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
798 anote("unhandled C type '%s' for '%s'\n",
799 pp->type.name, opr->name);
801 if (opr->lmod == OPLM_UNSPEC) {
803 opr->type_from_var = 1;
805 else if (opr->lmod != tmplmod) {
806 opr->size_mismatch = 1;
807 if (tmplmod < opr->lmod)
810 opr->is_ptr = pp->type.is_ptr;
812 opr->is_array = pp->type.is_array;
816 if (opr->lmod == OPLM_UNSPEC)
817 guess_lmod_from_name(opr);
821 static const struct {
826 { "repe", OPF_REP|OPF_REPZ },
827 { "repz", OPF_REP|OPF_REPZ },
828 { "repne", OPF_REP|OPF_REPNZ },
829 { "repnz", OPF_REP|OPF_REPNZ },
830 { "lock", OPF_LOCK }, // ignored for now..
833 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
835 static const struct {
838 unsigned short minopr;
839 unsigned short maxopr;
842 unsigned char pfo_inv;
844 { "nop", OP_NOP, 0, 0, 0 },
845 { "push", OP_PUSH, 1, 1, 0 },
846 { "pop", OP_POP, 1, 1, OPF_DATA },
847 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
848 { "mov" , OP_MOV, 2, 2, OPF_DATA },
849 { "lea", OP_LEA, 2, 2, OPF_DATA },
850 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
851 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
852 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
853 { "not", OP_NOT, 1, 1, OPF_DATA },
854 { "xlat", OP_XLAT, 0, 0, OPF_DATA },
855 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
856 { "lodsb",OP_LODS, 0, 0, OPF_DATA },
857 { "lodsw",OP_LODS, 0, 0, OPF_DATA },
858 { "lodsd",OP_LODS, 0, 0, OPF_DATA },
859 { "stosb",OP_STOS, 0, 0, OPF_DATA },
860 { "stosw",OP_STOS, 0, 0, OPF_DATA },
861 { "stosd",OP_STOS, 0, 0, OPF_DATA },
862 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
863 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
864 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
865 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
866 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
867 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
868 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
869 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
870 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
871 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
872 { "cld", OP_CLD, 0, 0, OPF_DATA },
873 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
874 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
875 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
876 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
877 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
878 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
879 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
880 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
881 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
882 { "shld", OP_SHLD, 3, 3, OPF_DATA|OPF_FLAGS },
883 { "shrd", OP_SHRD, 3, 3, OPF_DATA|OPF_FLAGS },
884 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
885 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
886 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
887 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
888 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
889 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
890 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
891 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
892 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
893 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
894 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
895 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
896 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
897 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
898 { "test", OP_TEST, 2, 2, OPF_FLAGS },
899 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
900 { "retn", OP_RET, 0, 1, OPF_TAIL },
901 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
902 { "jmp", OP_JMP, 1, 1, OPF_JMP },
903 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
904 { "loop", OP_LOOP, 1, 1, OPF_JMP|OPF_CJMP|OPF_DATA },
905 { "jo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 0 }, // 70 OF=1
906 { "jno", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 1 }, // 71 OF=0
907 { "jc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72 CF=1
908 { "jb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72
909 { "jnc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73 CF=0
910 { "jnb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
911 { "jae", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
912 { "jz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74 ZF=1
913 { "je", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74
914 { "jnz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75 ZF=0
915 { "jne", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75
916 { "jbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
917 { "jna", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
918 { "ja", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
919 { "jnbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
920 { "js", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 0 }, // 78 SF=1
921 { "jns", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 1 }, // 79 SF=0
922 { "jp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a PF=1
923 { "jpe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a
924 { "jnp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b PF=0
925 { "jpo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b
926 { "jl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c SF!=OF
927 { "jnge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c
928 { "jge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d SF=OF
929 { "jnl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d
930 { "jle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
931 { "jng", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
932 { "jg", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
933 { "jnle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
934 { "seto", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 0 },
935 { "setno", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 1 },
936 { "setc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
937 { "setb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
938 { "setnc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
939 { "setae", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
940 { "setnb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
941 { "setz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
942 { "sete", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
943 { "setnz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
944 { "setne", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
945 { "setbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
946 { "setna", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
947 { "seta", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
948 { "setnbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
949 { "sets", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 0 },
950 { "setns", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 1 },
951 { "setp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
952 { "setpe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
953 { "setnp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
954 { "setpo", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
955 { "setl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
956 { "setnge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
957 { "setge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
958 { "setnl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
959 { "setle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
960 { "setng", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
961 { "setg", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
962 { "setnle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
965 { "emms", OP_EMMS, 0, 0, OPF_DATA },
966 { "movq", OP_MOV, 2, 2, OPF_DATA },
971 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
973 enum opr_lenmod lmod = OPLM_UNSPEC;
974 int prefix_flags = 0;
982 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
983 if (IS(words[w], pref_table[i].name)) {
984 prefix_flags = pref_table[i].flags;
991 aerr("lone prefix: '%s'\n", words[0]);
996 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
997 if (IS(words[w], op_table[i].name))
1001 if (i == ARRAY_SIZE(op_table)) {
1003 aerr("unhandled op: '%s'\n", words[0]);
1008 op->op = op_table[i].op;
1009 op->flags = op_table[i].flags | prefix_flags;
1010 op->pfo = op_table[i].pfo;
1011 op->pfo_inv = op_table[i].pfo_inv;
1012 op->regmask_src = op->regmask_dst = 0;
1015 if (op->op == OP_UD2)
1018 for (opr = 0; opr < op_table[i].maxopr; opr++) {
1019 if (opr >= op_table[i].minopr && w >= wordc)
1022 regmask = regmask_ind = 0;
1023 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
1024 words, wordc, w, op->flags);
1026 if (opr == 0 && (op->flags & OPF_DATA))
1027 op->regmask_dst = regmask;
1029 op->regmask_src |= regmask;
1030 op->regmask_src |= regmask_ind;
1034 aerr("parse_op %s incomplete: %d/%d\n",
1035 words[0], w, wordc);
1038 op->operand_cnt = opr;
1039 if (!strncmp(op_table[i].name, "set", 3))
1040 op->operand[0].lmod = OPLM_BYTE;
1043 // first operand is not dst
1046 op->regmask_src |= op->regmask_dst;
1047 op->regmask_dst = 0;
1050 // first operand is src too
1062 op->regmask_src |= op->regmask_dst;
1067 op->regmask_src |= op->regmask_dst;
1068 op->regmask_dst |= op->regmask_src;
1074 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1075 && op->operand[0].lmod == op->operand[1].lmod
1076 && op->operand[0].reg == op->operand[1].reg
1077 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1079 op->regmask_src = 0;
1082 op->regmask_src |= op->regmask_dst;
1085 // ops with implicit argumets
1087 op->operand_cnt = 2;
1088 setup_reg_opr(&op->operand[0], xAX, OPLM_BYTE, &op->regmask_src);
1089 op->regmask_dst = op->regmask_src;
1090 setup_reg_opr(&op->operand[1], xDX, OPLM_DWORD, &op->regmask_src);
1094 op->operand_cnt = 2;
1095 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1096 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1102 if (op->operand_cnt != 0)
1104 if (words[op_w][4] == 'b')
1106 else if (words[op_w][4] == 'w')
1108 else if (words[op_w][4] == 'd')
1110 op->operand_cnt = 3;
1111 setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1112 lmod, &op->regmask_src);
1113 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1114 op->regmask_dst = op->regmask_src;
1115 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1116 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1121 if (op->operand_cnt != 0)
1123 if (words[op_w][4] == 'b')
1125 else if (words[op_w][4] == 'w')
1127 else if (words[op_w][4] == 'd')
1129 op->operand_cnt = 3;
1130 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1131 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1132 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1133 op->regmask_dst = op->regmask_src;
1137 op->regmask_dst = 1 << xCX;
1140 op->operand_cnt = 2;
1141 op->regmask_src = 1 << xCX;
1142 op->operand[1].type = OPT_REG;
1143 op->operand[1].reg = xCX;
1144 op->operand[1].lmod = OPLM_DWORD;
1148 if (op->operand_cnt == 2) {
1149 if (op->operand[0].type != OPT_REG)
1150 aerr("reg expected\n");
1151 op->regmask_src |= 1 << op->operand[0].reg;
1153 if (op->operand_cnt != 1)
1158 op->regmask_src |= op->regmask_dst;
1159 op->regmask_dst = (1 << xDX) | (1 << xAX);
1160 if (op->operand[0].lmod == OPLM_UNSPEC)
1161 op->operand[0].lmod = OPLM_DWORD;
1166 // we could set up operands for edx:eax, but there is no real need to
1167 // (see is_opr_modified())
1168 op->regmask_src |= op->regmask_dst;
1169 op->regmask_dst = (1 << xDX) | (1 << xAX);
1170 if (op->operand[0].lmod == OPLM_UNSPEC)
1171 op->operand[0].lmod = OPLM_DWORD;
1179 op->regmask_src |= op->regmask_dst;
1180 if (op->operand[1].lmod == OPLM_UNSPEC)
1181 op->operand[1].lmod = OPLM_BYTE;
1185 op->regmask_src |= op->regmask_dst;
1186 if (op->operand[2].lmod == OPLM_UNSPEC)
1187 op->operand[2].lmod = OPLM_BYTE;
1191 op->regmask_src |= op->regmask_dst;
1192 op->regmask_dst = 0;
1193 if (op->operand[0].lmod == OPLM_UNSPEC
1194 && (op->operand[0].type == OPT_CONST
1195 || op->operand[0].type == OPT_OFFSET
1196 || op->operand[0].type == OPT_LABEL))
1197 op->operand[0].lmod = OPLM_DWORD;
1203 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1204 && op->operand[0].lmod == op->operand[1].lmod
1205 && op->operand[0].reg == op->operand[1].reg
1206 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1208 op->flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
1209 op->regmask_src = op->regmask_dst = 0;
1214 if (op->operand[0].type == OPT_REG
1215 && op->operand[1].type == OPT_REGMEM)
1218 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1219 if (IS(buf, op->operand[1].name))
1220 op->flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
1225 // trashed regs must be explicitly detected later
1226 op->regmask_dst = 0;
1230 op->regmask_dst = (1 << xBP) | (1 << xSP);
1231 op->regmask_src = 1 << xBP;
1238 if (op->operand[0].type == OPT_REG
1239 && op->operand[0].lmod == OPLM_DWORD
1240 && op->operand[1].type == OPT_CONST)
1242 if ((op->op == OP_AND && op->operand[1].val == 0)
1243 || (op->op == OP_OR && op->operand[1].val == ~0))
1245 op->regmask_src = 0;
1250 static const char *op_name(struct parsed_op *po)
1252 static char buf[16];
1256 if (po->op == OP_JCC || po->op == OP_SCC) {
1258 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1261 strcpy(p, parsed_flag_op_names[po->pfo]);
1265 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1266 if (op_table[i].op == po->op)
1267 return op_table[i].name;
1273 static const char *dump_op(struct parsed_op *po)
1275 static char out[128];
1282 snprintf(out, sizeof(out), "%s", op_name(po));
1283 for (i = 0; i < po->operand_cnt; i++) {
1287 snprintf(p, sizeof(out) - (p - out),
1288 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1289 po->operand[i].name);
1295 static const char *lmod_type_u(struct parsed_op *po,
1296 enum opr_lenmod lmod)
1308 ferr(po, "invalid lmod: %d\n", lmod);
1309 return "(_invalid_)";
1313 static const char *lmod_cast_u(struct parsed_op *po,
1314 enum opr_lenmod lmod)
1326 ferr(po, "invalid lmod: %d\n", lmod);
1327 return "(_invalid_)";
1331 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1332 enum opr_lenmod lmod)
1344 ferr(po, "invalid lmod: %d\n", lmod);
1345 return "(_invalid_)";
1349 static const char *lmod_cast_s(struct parsed_op *po,
1350 enum opr_lenmod lmod)
1362 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1363 return "(_invalid_)";
1367 static const char *lmod_cast(struct parsed_op *po,
1368 enum opr_lenmod lmod, int is_signed)
1371 lmod_cast_s(po, lmod) :
1372 lmod_cast_u(po, lmod);
1375 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1387 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1392 static const char *opr_name(struct parsed_op *po, int opr_num)
1394 if (opr_num >= po->operand_cnt)
1395 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1396 return po->operand[opr_num].name;
1399 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1401 if (opr_num >= po->operand_cnt)
1402 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1403 if (po->operand[opr_num].type != OPT_CONST)
1404 ferr(po, "opr %d: const expected\n", opr_num);
1405 return po->operand[opr_num].val;
1408 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1410 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1411 ferr(po, "invalid reg: %d\n", popr->reg);
1412 return regs_r32[popr->reg];
1415 // cast1 is the "final" cast
1416 static const char *simplify_cast(const char *cast1, const char *cast2)
1418 static char buf[256];
1424 if (IS(cast1, cast2))
1426 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1428 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1430 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1432 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1434 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1437 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1441 static const char *simplify_cast_num(const char *cast, unsigned int val)
1443 if (IS(cast, "(u8)") && val < 0x100)
1445 if (IS(cast, "(s8)") && val < 0x80)
1447 if (IS(cast, "(u16)") && val < 0x10000)
1449 if (IS(cast, "(s16)") && val < 0x8000)
1451 if (IS(cast, "(s32)") && val < 0x80000000)
1457 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1466 namelen = strlen(name);
1468 p = strchr(name, '+');
1472 ferr(po, "equ parse failed for '%s'\n", name);
1474 if (IS_START(p, "0x"))
1476 *extra_offs = strtol(p, &endp, 16);
1478 ferr(po, "equ parse failed for '%s'\n", name);
1481 for (i = 0; i < g_eqcnt; i++)
1482 if (strncmp(g_eqs[i].name, name, namelen) == 0
1483 && g_eqs[i].name[namelen] == 0)
1487 ferr(po, "unresolved equ name: '%s'\n", name);
1494 static int is_stack_access(struct parsed_op *po,
1495 const struct parsed_opr *popr)
1497 return (parse_stack_el(popr->name, NULL, 0)
1498 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1499 && IS_START(popr->name, "ebp")));
1502 static void parse_stack_access(struct parsed_op *po,
1503 const char *name, char *ofs_reg, int *offset_out,
1504 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1506 const char *bp_arg = "";
1507 const char *p = NULL;
1508 struct parsed_equ *eq;
1515 if (IS_START(name, "ebp-")
1516 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1519 if (IS_START(p, "0x"))
1521 offset = strtoul(p, &endp, 16);
1525 ferr(po, "ebp- parse of '%s' failed\n", name);
1528 bp_arg = parse_stack_el(name, ofs_reg, 0);
1529 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1530 eq = equ_find(po, bp_arg, &offset);
1532 ferr(po, "detected but missing eq\n");
1533 offset += eq->offset;
1536 if (!strncmp(name, "ebp", 3))
1539 // yes it sometimes LEAs ra for compares..
1540 if (!is_lea && ofs_reg[0] == 0
1541 && stack_ra <= offset && offset < stack_ra + 4)
1543 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1546 *offset_out = offset;
1547 *stack_ra_out = stack_ra;
1549 *bp_arg_out = bp_arg;
1552 static int stack_frame_access(struct parsed_op *po,
1553 struct parsed_opr *popr, char *buf, size_t buf_size,
1554 const char *name, const char *cast, int is_src, int is_lea)
1556 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1557 const char *prefix = "";
1558 const char *bp_arg = NULL;
1559 char ofs_reg[16] = { 0, };
1560 int i, arg_i, arg_s;
1568 if (po->flags & OPF_EBP_S)
1569 ferr(po, "stack_frame_access while ebp is scratch\n");
1571 parse_stack_access(po, name, ofs_reg, &offset,
1572 &stack_ra, &bp_arg, is_lea);
1574 if (offset > stack_ra)
1576 arg_i = (offset - stack_ra - 4) / 4;
1577 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1579 if (g_func_pp->is_vararg
1580 && arg_i == g_func_pp->argc_stack && is_lea)
1582 // should be va_list
1585 snprintf(buf, buf_size, "%sap", cast);
1588 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1589 offset, bp_arg, arg_i);
1591 if (ofs_reg[0] != 0)
1592 ferr(po, "offset reg on arg access?\n");
1594 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1595 if (g_func_pp->arg[i].reg != NULL)
1601 if (i == g_func_pp->argc)
1602 ferr(po, "arg %d not in prototype?\n", arg_i);
1604 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1611 ferr(po, "lea/byte to arg?\n");
1612 if (is_src && (offset & 3) == 0)
1613 snprintf(buf, buf_size, "%sa%d",
1614 simplify_cast(cast, "(u8)"), i + 1);
1616 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1617 cast, offset & 3, i + 1);
1622 ferr(po, "lea/word to arg?\n");
1627 ferr(po, "problematic arg store\n");
1628 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1629 simplify_cast(cast, "*(u16 *)"), i + 1);
1632 ferr(po, "unaligned arg word load\n");
1634 else if (is_src && (offset & 2) == 0)
1635 snprintf(buf, buf_size, "%sa%d",
1636 simplify_cast(cast, "(u16)"), i + 1);
1638 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1639 cast, (offset & 2) ? "HI" : "LO", i + 1);
1651 snprintf(buf, buf_size, "(u32)&a%d + %d",
1654 ferr(po, "unaligned arg store\n");
1656 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1657 snprintf(buf, buf_size, "%s(a%d >> %d)",
1658 prefix, i + 1, (offset & 3) * 8);
1662 snprintf(buf, buf_size, "%s%sa%d",
1663 prefix, is_lea ? "&" : "", i + 1);
1668 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1672 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1675 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1676 if (tmp_lmod != OPLM_DWORD
1677 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1678 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1680 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1681 i + 1, offset, g_func_pp->arg[i].type.name);
1683 // can't check this because msvc likes to reuse
1684 // arg space for scratch..
1685 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1686 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1690 if (g_stack_fsz == 0)
1691 ferr(po, "stack var access without stackframe\n");
1692 g_stack_frame_used = 1;
1694 sf_ofs = g_stack_fsz + offset;
1695 lim = (ofs_reg[0] != 0) ? -4 : 0;
1696 if (offset > 0 || sf_ofs < lim)
1697 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1707 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1708 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1712 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1713 // known unaligned or possibly unaligned
1714 strcat(g_comment, " unaligned");
1716 prefix = "*(u16 *)&";
1717 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1718 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1721 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1725 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1726 // known unaligned or possibly unaligned
1727 strcat(g_comment, " unaligned");
1729 prefix = "*(u32 *)&";
1730 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1731 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1734 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1738 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1745 static void check_func_pp(struct parsed_op *po,
1746 const struct parsed_proto *pp, const char *pfx)
1748 enum opr_lenmod tmp_lmod;
1752 if (pp->argc_reg != 0) {
1753 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1754 pp_print(buf, sizeof(buf), pp);
1755 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1757 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1758 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1759 pfx, pp->argc_reg, pp->argc_stack);
1762 // fptrs must use 32bit args, callsite might have no information and
1763 // lack a cast to smaller types, which results in incorrectly masked
1764 // args passed (callee may assume masked args, it does on ARM)
1765 if (!pp->is_osinc) {
1766 for (i = 0; i < pp->argc; i++) {
1767 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1768 if (ret && tmp_lmod != OPLM_DWORD)
1769 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1770 i + 1, pp->arg[i].type.name);
1775 static const char *check_label_read_ref(struct parsed_op *po,
1778 const struct parsed_proto *pp;
1780 pp = proto_parse(g_fhdr, name, 0);
1782 ferr(po, "proto_parse failed for ref '%s'\n", name);
1785 check_func_pp(po, pp, "ref");
1790 static char *out_src_opr(char *buf, size_t buf_size,
1791 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1794 char tmp1[256], tmp2[256];
1803 switch (popr->type) {
1806 ferr(po, "lea from reg?\n");
1808 switch (popr->lmod) {
1810 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1813 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1816 snprintf(buf, buf_size, "%s%s",
1817 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1820 if (popr->name[1] == 'h') // XXX..
1821 snprintf(buf, buf_size, "%s(%s >> 8)",
1822 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1824 snprintf(buf, buf_size, "%s%s",
1825 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1828 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1833 if (is_stack_access(po, popr)) {
1834 stack_frame_access(po, popr, buf, buf_size,
1835 popr->name, cast, 1, is_lea);
1839 strcpy(expr, popr->name);
1840 if (strchr(expr, '[')) {
1841 // special case: '[' can only be left for label[reg] form
1842 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1844 ferr(po, "parse failure for '%s'\n", expr);
1845 if (tmp1[0] == '(') {
1846 // (off_4FFF50+3)[eax]
1847 p = strchr(tmp1 + 1, ')');
1848 if (p == NULL || p[1] != 0)
1849 ferr(po, "parse failure (2) for '%s'\n", expr);
1851 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1853 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1856 // XXX: do we need more parsing?
1858 snprintf(buf, buf_size, "%s", expr);
1862 snprintf(buf, buf_size, "%s(%s)",
1863 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1867 name = check_label_read_ref(po, popr->name);
1868 if (cast[0] == 0 && popr->is_ptr)
1872 snprintf(buf, buf_size, "(u32)&%s", name);
1873 else if (popr->size_lt)
1874 snprintf(buf, buf_size, "%s%s%s%s", cast,
1875 lmod_cast_u_ptr(po, popr->lmod),
1876 popr->is_array ? "" : "&", name);
1878 snprintf(buf, buf_size, "%s%s%s", cast, name,
1879 popr->is_array ? "[0]" : "");
1883 name = check_label_read_ref(po, popr->name);
1887 ferr(po, "lea an offset?\n");
1888 snprintf(buf, buf_size, "%s&%s", cast, name);
1893 ferr(po, "lea from const?\n");
1895 printf_number(tmp1, sizeof(tmp1), popr->val);
1896 if (popr->val == 0 && strchr(cast, '*'))
1897 snprintf(buf, buf_size, "NULL");
1899 snprintf(buf, buf_size, "%s%s",
1900 simplify_cast_num(cast, popr->val), tmp1);
1904 ferr(po, "invalid src type: %d\n", popr->type);
1910 // note: may set is_ptr (we find that out late for ebp frame..)
1911 static char *out_dst_opr(char *buf, size_t buf_size,
1912 struct parsed_op *po, struct parsed_opr *popr)
1914 switch (popr->type) {
1916 switch (popr->lmod) {
1918 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1921 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1925 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1929 if (popr->name[1] == 'h') // XXX..
1930 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1932 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1935 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1940 if (is_stack_access(po, popr)) {
1941 stack_frame_access(po, popr, buf, buf_size,
1942 popr->name, "", 0, 0);
1946 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1949 if (popr->size_mismatch)
1950 snprintf(buf, buf_size, "%s%s%s",
1951 lmod_cast_u_ptr(po, popr->lmod),
1952 popr->is_array ? "" : "&", popr->name);
1954 snprintf(buf, buf_size, "%s%s", popr->name,
1955 popr->is_array ? "[0]" : "");
1959 ferr(po, "invalid dst type: %d\n", popr->type);
1965 static char *out_src_opr_u32(char *buf, size_t buf_size,
1966 struct parsed_op *po, struct parsed_opr *popr)
1968 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1971 static void out_test_for_cc(char *buf, size_t buf_size,
1972 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1973 enum opr_lenmod lmod, const char *expr)
1975 const char *cast, *scast;
1977 cast = lmod_cast_u(po, lmod);
1978 scast = lmod_cast_s(po, lmod);
1982 case PFO_BE: // CF=1||ZF=1; CF=0
1983 snprintf(buf, buf_size, "(%s%s %s 0)",
1984 cast, expr, is_inv ? "!=" : "==");
1988 case PFO_L: // SF!=OF; OF=0
1989 snprintf(buf, buf_size, "(%s%s %s 0)",
1990 scast, expr, is_inv ? ">=" : "<");
1993 case PFO_LE: // ZF=1||SF!=OF; OF=0
1994 snprintf(buf, buf_size, "(%s%s %s 0)",
1995 scast, expr, is_inv ? ">" : "<=");
1999 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
2003 static void out_cmp_for_cc(char *buf, size_t buf_size,
2004 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2006 const char *cast, *scast, *cast_use;
2007 char buf1[256], buf2[256];
2008 enum opr_lenmod lmod;
2010 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
2011 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
2012 po->operand[0].lmod, po->operand[1].lmod);
2013 lmod = po->operand[0].lmod;
2015 cast = lmod_cast_u(po, lmod);
2016 scast = lmod_cast_s(po, lmod);
2032 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
2035 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
2036 if (po->op == OP_DEC)
2037 snprintf(buf2, sizeof(buf2), "1");
2039 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
2043 // note: must be unsigned compare
2044 snprintf(buf, buf_size, "(%s %s %s)",
2045 buf1, is_inv ? ">=" : "<", buf2);
2049 snprintf(buf, buf_size, "(%s %s %s)",
2050 buf1, is_inv ? "!=" : "==", buf2);
2054 // note: must be unsigned compare
2055 snprintf(buf, buf_size, "(%s %s %s)",
2056 buf1, is_inv ? ">" : "<=", buf2);
2059 if (is_inv && lmod == OPLM_BYTE
2060 && po->operand[1].type == OPT_CONST
2061 && po->operand[1].val == 0xff)
2063 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2064 snprintf(buf, buf_size, "(0)");
2068 // note: must be signed compare
2070 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
2071 scast, buf1, buf2, is_inv ? ">=" : "<");
2075 snprintf(buf, buf_size, "(%s %s %s)",
2076 buf1, is_inv ? ">=" : "<", buf2);
2080 snprintf(buf, buf_size, "(%s %s %s)",
2081 buf1, is_inv ? ">" : "<=", buf2);
2089 static void out_cmp_test(char *buf, size_t buf_size,
2090 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2092 char buf1[256], buf2[256], buf3[256];
2094 if (po->op == OP_TEST) {
2095 if (IS(opr_name(po, 0), opr_name(po, 1))) {
2096 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
2099 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2100 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
2101 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2103 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
2104 po->operand[0].lmod, buf3);
2106 else if (po->op == OP_CMP) {
2107 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2110 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2113 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2114 struct parsed_opr *popr2)
2116 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2117 ferr(po, "missing lmod for both operands\n");
2119 if (popr1->lmod == OPLM_UNSPEC)
2120 popr1->lmod = popr2->lmod;
2121 else if (popr2->lmod == OPLM_UNSPEC)
2122 popr2->lmod = popr1->lmod;
2123 else if (popr1->lmod != popr2->lmod) {
2124 if (popr1->type_from_var) {
2125 popr1->size_mismatch = 1;
2126 if (popr1->lmod < popr2->lmod)
2128 popr1->lmod = popr2->lmod;
2130 else if (popr2->type_from_var) {
2131 popr2->size_mismatch = 1;
2132 if (popr2->lmod < popr1->lmod)
2134 popr2->lmod = popr1->lmod;
2137 ferr(po, "conflicting lmods: %d vs %d\n",
2138 popr1->lmod, popr2->lmod);
2142 static const char *op_to_c(struct parsed_op *po)
2166 ferr(po, "op_to_c was supplied with %d\n", po->op);
2170 // last op in stream - unconditional branch or ret
2171 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2172 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2173 && ops[_i].op != OP_CALL))
2175 #define check_i(po, i) \
2177 ferr(po, "bad " #i ": %d\n", i)
2179 // note: this skips over calls and rm'd stuff assuming they're handled
2180 // so it's intended to use at one of final passes
2181 static int scan_for_pop(int i, int opcnt, int magic, int reg,
2182 int depth, int flags_set)
2184 struct parsed_op *po;
2189 for (; i < opcnt; i++) {
2191 if (po->cc_scratch == magic)
2192 return ret; // already checked
2193 po->cc_scratch = magic;
2195 if (po->flags & OPF_TAIL) {
2196 if (po->op == OP_CALL) {
2197 if (po->pp != NULL && po->pp->is_noreturn)
2198 // assume no stack cleanup for noreturn
2201 return -1; // deadend
2204 if (po->flags & (OPF_RMD|OPF_DONE|OPF_FARG))
2207 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2208 if (po->btj != NULL) {
2210 for (j = 0; j < po->btj->count; j++) {
2211 check_i(po, po->btj->d[j].bt_i);
2212 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, magic, reg,
2215 return ret; // dead end
2220 check_i(po, po->bt_i);
2221 if (po->flags & OPF_CJMP) {
2222 ret |= scan_for_pop(po->bt_i, opcnt, magic, reg,
2225 return ret; // dead end
2234 if ((po->op == OP_POP || po->op == OP_PUSH)
2235 && po->operand[0].type == OPT_REG && po->operand[0].reg == reg)
2240 if (po->op == OP_PUSH) {
2243 else if (po->op == OP_POP) {
2244 if (relevant && depth == 0) {
2245 po->flags |= flags_set;
2255 // scan for 'reg' pop backwards starting from i
2256 // intended to use for register restore search, so other reg
2257 // references are considered an error
2258 static int scan_for_rsave_pop_reg(int i, int magic, int reg, int set_flags)
2260 struct parsed_op *po;
2261 struct label_ref *lr;
2264 ops[i].cc_scratch = magic;
2268 if (g_labels[i] != NULL) {
2269 lr = &g_label_refs[i];
2270 for (; lr != NULL; lr = lr->next) {
2271 check_i(&ops[i], lr->i);
2272 ret |= scan_for_rsave_pop_reg(lr->i, magic, reg, set_flags);
2276 if (i > 0 && LAST_OP(i - 1))
2284 if (ops[i].cc_scratch == magic)
2286 ops[i].cc_scratch = magic;
2289 if (po->op == OP_POP && po->operand[0].reg == reg) {
2290 if (po->flags & (OPF_RMD|OPF_DONE))
2293 po->flags |= set_flags;
2297 // this also covers the case where we reach corresponding push
2298 if ((po->regmask_dst | po->regmask_src) & (1 << reg))
2302 // nothing interesting on this path
2306 static void find_reachable_exits(int i, int opcnt, int magic,
2307 int *exits, int *exit_count)
2309 struct parsed_op *po;
2312 for (; i < opcnt; i++)
2315 if (po->cc_scratch == magic)
2317 po->cc_scratch = magic;
2319 if (po->flags & OPF_TAIL) {
2320 ferr_assert(po, *exit_count < MAX_EXITS);
2321 exits[*exit_count] = i;
2326 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2327 if (po->flags & OPF_RMD)
2330 if (po->btj != NULL) {
2331 for (j = 0; j < po->btj->count; j++) {
2332 check_i(po, po->btj->d[j].bt_i);
2333 find_reachable_exits(po->btj->d[j].bt_i, opcnt, magic,
2339 check_i(po, po->bt_i);
2340 if (po->flags & OPF_CJMP)
2341 find_reachable_exits(po->bt_i, opcnt, magic, exits, exit_count);
2349 // scan for 'reg' pop backwards starting from exits (all paths)
2350 static int scan_for_pop_ret(int i, int opcnt, int reg, int set_flags)
2352 static int exits[MAX_EXITS];
2353 static int exit_count;
2358 find_reachable_exits(i, opcnt, i + opcnt * 15, exits,
2360 ferr_assert(&ops[i], exit_count > 0);
2363 for (j = 0; j < exit_count; j++) {
2364 ret = scan_for_rsave_pop_reg(exits[j], i + opcnt * 16 + set_flags,
2373 // scan for one or more pop of push <const>
2374 static int scan_for_pop_const_r(int i, int opcnt, int magic,
2375 int push_i, int is_probe)
2377 struct parsed_op *po;
2378 struct label_ref *lr;
2382 for (; i < opcnt; i++)
2385 if (po->cc_scratch == magic)
2386 return ret; // already checked
2387 po->cc_scratch = magic;
2389 if (po->flags & OPF_JMP) {
2390 if (po->flags & OPF_RMD)
2392 if (po->op == OP_CALL)
2395 if (po->btj != NULL) {
2396 for (j = 0; j < po->btj->count; j++) {
2397 check_i(po, po->btj->d[j].bt_i);
2398 ret |= scan_for_pop_const_r(po->btj->d[j].bt_i, opcnt, magic,
2406 check_i(po, po->bt_i);
2407 if (po->flags & OPF_CJMP) {
2408 ret |= scan_for_pop_const_r(po->bt_i, opcnt, magic, push_i,
2419 if ((po->flags & (OPF_TAIL|OPF_RSAVE)) || po->op == OP_PUSH)
2422 if (g_labels[i] != NULL) {
2423 // all refs must be visited
2424 lr = &g_label_refs[i];
2425 for (; lr != NULL; lr = lr->next) {
2427 if (ops[lr->i].cc_scratch != magic)
2430 if (i > 0 && !LAST_OP(i - 1) && ops[i - 1].cc_scratch != magic)
2434 if (po->op == OP_POP)
2436 if (po->flags & (OPF_RMD|OPF_DONE))
2440 po->flags |= OPF_DONE;
2441 po->datap = &ops[push_i];
2450 static void scan_for_pop_const(int i, int opcnt, int magic)
2454 ret = scan_for_pop_const_r(i + 1, opcnt, magic, i, 1);
2456 ops[i].flags |= OPF_RMD | OPF_DONE;
2457 scan_for_pop_const_r(i + 1, opcnt, magic + 1, i, 0);
2461 // check if all branch targets within a marked path are also marked
2462 // note: the path checked must not be empty or end with a branch
2463 static int check_path_branches(int opcnt, int magic)
2465 struct parsed_op *po;
2468 for (i = 0; i < opcnt; i++) {
2470 if (po->cc_scratch != magic)
2473 if (po->flags & OPF_JMP) {
2474 if ((po->flags & OPF_RMD) || po->op == OP_CALL)
2477 if (po->btj != NULL) {
2478 for (j = 0; j < po->btj->count; j++) {
2479 check_i(po, po->btj->d[j].bt_i);
2480 if (ops[po->btj->d[j].bt_i].cc_scratch != magic)
2485 check_i(po, po->bt_i);
2486 if (ops[po->bt_i].cc_scratch != magic)
2488 if ((po->flags & OPF_CJMP) && ops[i + 1].cc_scratch != magic)
2496 // scan for multiple pushes for given pop
2497 static int scan_pushes_for_pop_r(int i, int magic, int pop_i,
2500 int reg = ops[pop_i].operand[0].reg;
2501 struct parsed_op *po;
2502 struct label_ref *lr;
2505 ops[i].cc_scratch = magic;
2509 if (g_labels[i] != NULL) {
2510 lr = &g_label_refs[i];
2511 for (; lr != NULL; lr = lr->next) {
2512 check_i(&ops[i], lr->i);
2513 ret |= scan_pushes_for_pop_r(lr->i, magic, pop_i, is_probe);
2517 if (i > 0 && LAST_OP(i - 1))
2525 if (ops[i].cc_scratch == magic)
2527 ops[i].cc_scratch = magic;
2530 if (po->op == OP_CALL)
2532 if ((po->flags & (OPF_TAIL|OPF_RSAVE)) || po->op == OP_POP)
2535 if (po->op == OP_PUSH)
2537 if (po->datap != NULL)
2539 if (po->operand[0].type == OPT_REG && po->operand[0].reg == reg)
2540 // leave this case for reg save/restore handlers
2544 po->flags |= OPF_PPUSH | OPF_DONE;
2545 po->datap = &ops[pop_i];
2554 static void scan_pushes_for_pop(int i, int opcnt, int *regmask_pp)
2556 int magic = i + opcnt * 14;
2559 ret = scan_pushes_for_pop_r(i, magic, i, 1);
2561 ret = check_path_branches(opcnt, magic);
2563 ops[i].flags |= OPF_PPUSH | OPF_DONE;
2564 *regmask_pp |= 1 << ops[i].operand[0].reg;
2565 scan_pushes_for_pop_r(i, magic + 1, i, 0);
2570 static void scan_propagate_df(int i, int opcnt)
2572 struct parsed_op *po = &ops[i];
2575 for (; i < opcnt; i++) {
2577 if (po->flags & OPF_DF)
2578 return; // already resolved
2579 po->flags |= OPF_DF;
2581 if (po->op == OP_CALL)
2582 ferr(po, "call with DF set?\n");
2584 if (po->flags & OPF_JMP) {
2585 if (po->btj != NULL) {
2587 for (j = 0; j < po->btj->count; j++) {
2588 check_i(po, po->btj->d[j].bt_i);
2589 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2594 if (po->flags & OPF_RMD)
2596 check_i(po, po->bt_i);
2597 if (po->flags & OPF_CJMP)
2598 scan_propagate_df(po->bt_i, opcnt);
2604 if (po->flags & OPF_TAIL)
2607 if (po->op == OP_CLD) {
2608 po->flags |= OPF_RMD | OPF_DONE;
2613 ferr(po, "missing DF clear?\n");
2616 // is operand 'opr' referenced by parsed_op 'po'?
2617 static int is_opr_referenced(const struct parsed_opr *opr,
2618 const struct parsed_op *po)
2622 if (opr->type == OPT_REG) {
2623 mask = po->regmask_dst | po->regmask_src;
2624 if (po->op == OP_CALL)
2625 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2626 if ((1 << opr->reg) & mask)
2632 for (i = 0; i < po->operand_cnt; i++)
2633 if (IS(po->operand[0].name, opr->name))
2639 // is operand 'opr' read by parsed_op 'po'?
2640 static int is_opr_read(const struct parsed_opr *opr,
2641 const struct parsed_op *po)
2643 if (opr->type == OPT_REG) {
2644 if (po->regmask_src & (1 << opr->reg))
2654 // is operand 'opr' modified by parsed_op 'po'?
2655 static int is_opr_modified(const struct parsed_opr *opr,
2656 const struct parsed_op *po)
2660 if (opr->type == OPT_REG) {
2661 if (po->op == OP_CALL) {
2662 mask = po->regmask_dst;
2663 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX); // ?
2664 if (mask & (1 << opr->reg))
2670 if (po->regmask_dst & (1 << opr->reg))
2676 return IS(po->operand[0].name, opr->name);
2679 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2680 static int is_any_opr_modified(const struct parsed_op *po_test,
2681 const struct parsed_op *po, int c_mode)
2686 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2689 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2692 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2695 // in reality, it can wreck any register, but in decompiled C
2696 // version it can only overwrite eax or edx:eax
2697 mask = (1 << xAX) | (1 << xDX);
2701 if (po->op == OP_CALL
2702 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2705 for (i = 0; i < po_test->operand_cnt; i++)
2706 if (IS(po_test->operand[i].name, po->operand[0].name))
2712 // scan for any po_test operand modification in range given
2713 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2716 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2719 for (; i < opcnt; i++) {
2720 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2727 // scan for po_test operand[0] modification in range given
2728 static int scan_for_mod_opr0(struct parsed_op *po_test,
2731 for (; i < opcnt; i++) {
2732 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2739 static int scan_for_flag_set(int i, int magic, int *branched,
2740 int *setters, int *setter_cnt)
2742 struct label_ref *lr;
2746 if (ops[i].cc_scratch == magic) {
2747 // is this a problem?
2748 //ferr(&ops[i], "%s looped\n", __func__);
2751 ops[i].cc_scratch = magic;
2753 if (g_labels[i] != NULL) {
2756 lr = &g_label_refs[i];
2757 for (; lr->next; lr = lr->next) {
2758 check_i(&ops[i], lr->i);
2759 ret = scan_for_flag_set(lr->i, magic,
2760 branched, setters, setter_cnt);
2765 check_i(&ops[i], lr->i);
2766 if (i > 0 && LAST_OP(i - 1)) {
2770 ret = scan_for_flag_set(lr->i, magic,
2771 branched, setters, setter_cnt);
2777 if (ops[i].flags & OPF_FLAGS) {
2778 setters[*setter_cnt] = i;
2783 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2790 // scan back for cdq, if anything modifies edx, fail
2791 static int scan_for_cdq_edx(int i)
2794 if (g_labels[i] != NULL) {
2795 if (g_label_refs[i].next != NULL)
2797 if (i > 0 && LAST_OP(i - 1)) {
2798 i = g_label_refs[i].i;
2805 if (ops[i].op == OP_CDQ)
2808 if (ops[i].regmask_dst & (1 << xDX))
2815 static int scan_for_reg_clear(int i, int reg)
2818 if (g_labels[i] != NULL) {
2819 if (g_label_refs[i].next != NULL)
2821 if (i > 0 && LAST_OP(i - 1)) {
2822 i = g_label_refs[i].i;
2829 if (ops[i].op == OP_XOR
2830 && ops[i].operand[0].lmod == OPLM_DWORD
2831 && ops[i].operand[0].reg == ops[i].operand[1].reg
2832 && ops[i].operand[0].reg == reg)
2835 if (ops[i].regmask_dst & (1 << reg))
2842 static void patch_esp_adjust(struct parsed_op *po, int adj)
2844 ferr_assert(po, po->op == OP_ADD);
2845 ferr_assert(po, IS(opr_name(po, 0), "esp"));
2846 ferr_assert(po, po->operand[1].type == OPT_CONST);
2848 // this is a bit of a hack, but deals with use of
2849 // single adj for multiple calls
2850 po->operand[1].val -= adj;
2851 po->flags |= OPF_RMD;
2852 if (po->operand[1].val == 0)
2853 po->flags |= OPF_DONE;
2854 ferr_assert(po, (int)po->operand[1].val >= 0);
2857 // scan for positive, constant esp adjust
2858 // multipath case is preliminary
2859 static int scan_for_esp_adjust(int i, int opcnt,
2860 int adj_expect, int *adj, int *is_multipath, int do_update)
2862 int adj_expect_unknown = 0;
2863 struct parsed_op *po;
2867 *adj = *is_multipath = 0;
2868 if (adj_expect < 0) {
2869 adj_expect_unknown = 1;
2870 adj_expect = 32 * 4; // enough?
2873 for (; i < opcnt && *adj < adj_expect; i++) {
2874 if (g_labels[i] != NULL)
2878 if (po->flags & OPF_DONE)
2881 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2882 if (po->operand[1].type != OPT_CONST)
2883 ferr(&ops[i], "non-const esp adjust?\n");
2884 *adj += po->operand[1].val;
2886 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2889 patch_esp_adjust(po, adj_expect);
2891 po->flags |= OPF_RMD;
2895 else if (po->op == OP_PUSH) {
2896 //if (first_pop == -1)
2897 // first_pop = -2; // none
2898 *adj -= lmod_bytes(po, po->operand[0].lmod);
2900 else if (po->op == OP_POP) {
2901 if (!(po->flags & OPF_DONE)) {
2902 // seems like msvc only uses 'pop ecx' for stack realignment..
2903 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2905 if (first_pop == -1 && *adj >= 0)
2908 if (do_update && *adj >= 0) {
2909 po->flags |= OPF_RMD;
2911 po->flags |= OPF_DONE | OPF_NOREGS;
2914 *adj += lmod_bytes(po, po->operand[0].lmod);
2915 if (*adj > adj_best)
2918 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2919 if (po->op == OP_JMP && po->btj == NULL) {
2925 if (po->op != OP_CALL)
2927 if (po->operand[0].type != OPT_LABEL)
2929 if (po->pp != NULL && po->pp->is_stdcall)
2931 if (adj_expect_unknown && first_pop >= 0)
2933 // assume it's another cdecl call
2937 if (first_pop >= 0) {
2938 // probably only 'pop ecx' was used
2946 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2948 struct parsed_op *po;
2952 ferr(ops, "%s: followed bad branch?\n", __func__);
2954 for (; i < opcnt; i++) {
2956 if (po->cc_scratch == magic)
2958 po->cc_scratch = magic;
2961 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2962 if (po->btj != NULL) {
2964 for (j = 0; j < po->btj->count; j++)
2965 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2969 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2970 if (!(po->flags & OPF_CJMP))
2973 if (po->flags & OPF_TAIL)
2978 static const struct parsed_proto *try_recover_pp(
2979 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2981 const struct parsed_proto *pp = NULL;
2985 // maybe an arg of g_func?
2986 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2988 char ofs_reg[16] = { 0, };
2989 int arg, arg_s, arg_i;
2996 parse_stack_access(po, opr->name, ofs_reg,
2997 &offset, &stack_ra, NULL, 0);
2998 if (ofs_reg[0] != 0)
2999 ferr(po, "offset reg on arg access?\n");
3000 if (offset <= stack_ra) {
3001 // search who set the stack var instead
3002 if (search_instead != NULL)
3003 *search_instead = 1;
3007 arg_i = (offset - stack_ra - 4) / 4;
3008 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
3009 if (g_func_pp->arg[arg].reg != NULL)
3015 if (arg == g_func_pp->argc)
3016 ferr(po, "stack arg %d not in prototype?\n", arg_i);
3018 pp = g_func_pp->arg[arg].fptr;
3020 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
3021 check_func_pp(po, pp, "icall arg");
3023 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
3025 p = strchr(opr->name + 1, '[');
3026 memcpy(buf, opr->name, p - opr->name);
3027 buf[p - opr->name] = 0;
3028 pp = proto_parse(g_fhdr, buf, g_quiet_pp);
3030 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
3031 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
3034 ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
3037 check_func_pp(po, pp, "reg-fptr ref");
3043 static void scan_for_call_type(int i, const struct parsed_opr *opr,
3044 int magic, const struct parsed_proto **pp_found, int *pp_i,
3047 const struct parsed_proto *pp = NULL;
3048 struct parsed_op *po;
3049 struct label_ref *lr;
3051 ops[i].cc_scratch = magic;
3054 if (g_labels[i] != NULL) {
3055 lr = &g_label_refs[i];
3056 for (; lr != NULL; lr = lr->next) {
3057 check_i(&ops[i], lr->i);
3058 scan_for_call_type(lr->i, opr, magic, pp_found, pp_i, multi);
3060 if (i > 0 && LAST_OP(i - 1))
3068 if (ops[i].cc_scratch == magic)
3070 ops[i].cc_scratch = magic;
3072 if (!(ops[i].flags & OPF_DATA))
3074 if (!is_opr_modified(opr, &ops[i]))
3076 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
3077 // most probably trashed by some processing
3082 opr = &ops[i].operand[1];
3083 if (opr->type != OPT_REG)
3087 po = (i >= 0) ? &ops[i] : ops;
3090 // reached the top - can only be an arg-reg
3091 if (opr->type != OPT_REG || g_func_pp == NULL)
3094 for (i = 0; i < g_func_pp->argc; i++) {
3095 if (g_func_pp->arg[i].reg == NULL)
3097 if (IS(opr->name, g_func_pp->arg[i].reg))
3100 if (i == g_func_pp->argc)
3102 pp = g_func_pp->arg[i].fptr;
3104 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
3105 i + 1, g_func_pp->arg[i].reg);
3106 check_func_pp(po, pp, "icall reg-arg");
3109 pp = try_recover_pp(po, opr, NULL);
3111 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
3112 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
3113 || (*pp_found)->is_stdcall != pp->is_stdcall
3114 || (*pp_found)->is_fptr != pp->is_fptr
3115 || (*pp_found)->argc != pp->argc
3116 || (*pp_found)->argc_reg != pp->argc_reg
3117 || (*pp_found)->argc_stack != pp->argc_stack)
3119 ferr(po, "icall: parsed_proto mismatch\n");
3129 static void add_label_ref(struct label_ref *lr, int op_i)
3131 struct label_ref *lr_new;
3138 lr_new = calloc(1, sizeof(*lr_new));
3140 lr_new->next = lr->next;
3144 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
3146 struct parsed_op *po = &ops[i];
3147 struct parsed_data *pd;
3148 char label[NAMELEN], *p;
3151 p = strchr(po->operand[0].name, '[');
3155 len = p - po->operand[0].name;
3156 strncpy(label, po->operand[0].name, len);
3159 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3160 if (IS(g_func_pd[j].label, label)) {
3166 //ferr(po, "label '%s' not parsed?\n", label);
3169 if (pd->type != OPT_OFFSET)
3170 ferr(po, "label '%s' with non-offset data?\n", label);
3172 // find all labels, link
3173 for (j = 0; j < pd->count; j++) {
3174 for (l = 0; l < opcnt; l++) {
3175 if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
3176 add_label_ref(&g_label_refs[l], i);
3186 static void clear_labels(int count)
3190 for (i = 0; i < count; i++) {
3191 if (g_labels[i] != NULL) {
3198 static int get_pp_arg_regmask_src(const struct parsed_proto *pp)
3203 for (i = 0; i < pp->argc; i++) {
3204 if (pp->arg[i].reg != NULL) {
3205 reg = char_array_i(regs_r32,
3206 ARRAY_SIZE(regs_r32), pp->arg[i].reg);
3208 ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
3209 pp->arg[i].reg, pp->name);
3210 regmask |= 1 << reg;
3217 static int get_pp_arg_regmask_dst(const struct parsed_proto *pp)
3219 if (strstr(pp->ret_type.name, "int64"))
3220 return (1 << xAX) | (1 << xDX);
3221 if (strcasecmp(pp->ret_type.name, "void") == 0)
3227 static void resolve_branches_parse_calls(int opcnt)
3229 const struct parsed_proto *pp_c;
3230 struct parsed_proto *pp;
3231 struct parsed_data *pd;
3232 struct parsed_op *po;
3233 const char *tmpname;
3237 for (i = 0; i < opcnt; i++)
3243 if (po->op == OP_CALL) {
3246 if (po->operand[0].type == OPT_LABEL) {
3247 tmpname = opr_name(po, 0);
3248 if (IS_START(tmpname, "loc_"))
3249 ferr(po, "call to loc_*\n");
3250 pp_c = proto_parse(g_fhdr, tmpname, g_header_mode);
3251 if (!g_header_mode && pp_c == NULL)
3252 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3255 pp = proto_clone(pp_c);
3256 my_assert_not(pp, NULL);
3259 else if (po->datap != NULL) {
3260 pp = calloc(1, sizeof(*pp));
3261 my_assert_not(pp, NULL);
3263 ret = parse_protostr(po->datap, pp);
3265 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3272 check_func_pp(po, pp, "fptr var call");
3273 if (pp->is_noreturn)
3274 po->flags |= OPF_TAIL;
3280 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3283 if (po->operand[0].type == OPT_REGMEM) {
3284 pd = try_resolve_jumptab(i, opcnt);
3292 for (l = 0; l < opcnt; l++) {
3293 if (g_labels[l] != NULL
3294 && IS(po->operand[0].name, g_labels[l]))
3296 if (l == i + 1 && po->op == OP_JMP) {
3297 // yet another alignment type..
3298 po->flags |= OPF_RMD|OPF_DONE;
3301 add_label_ref(&g_label_refs[l], i);
3307 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3310 if (po->operand[0].type == OPT_LABEL)
3314 ferr(po, "unhandled branch\n");
3318 po->flags |= OPF_TAIL;
3319 if (i > 0 && ops[i - 1].op == OP_POP)
3320 po->flags |= OPF_ATAIL;
3325 static void scan_prologue_epilogue(int opcnt)
3327 int ecx_push = 0, esp_sub = 0;
3331 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
3332 && ops[1].op == OP_MOV
3333 && IS(opr_name(&ops[1], 0), "ebp")
3334 && IS(opr_name(&ops[1], 1), "esp"))
3337 ops[0].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3338 ops[1].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3341 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
3342 g_stack_fsz = opr_const(&ops[2], 1);
3343 ops[2].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3347 // another way msvc builds stack frame..
3349 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3351 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3355 // and another way..
3356 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3357 && ops[i].operand[1].type == OPT_CONST
3358 && ops[i + 1].op == OP_CALL
3359 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3361 g_stack_fsz += ops[i].operand[1].val;
3362 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3364 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3371 for (; i < opcnt; i++)
3372 if (ops[i].flags & OPF_TAIL)
3375 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3376 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3382 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3383 || ops[j].op == OP_LEAVE)
3385 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3387 else if (ops[i].op == OP_CALL && ops[i].pp != NULL
3388 && ops[i].pp->is_noreturn)
3390 // on noreturn, msvc sometimes cleans stack, sometimes not
3395 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3396 ferr(&ops[j], "'pop ebp' expected\n");
3398 if (g_stack_fsz != 0) {
3399 if (ops[j].op == OP_LEAVE)
3401 else if (ops[j].op == OP_POP
3402 && ops[j - 1].op == OP_MOV
3403 && IS(opr_name(&ops[j - 1], 0), "esp")
3404 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3406 ops[j - 1].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3409 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3411 ferr(&ops[j], "esp restore expected\n");
3414 if (ecx_push && j >= 0 && ops[j].op == OP_POP
3415 && IS(opr_name(&ops[j], 0), "ecx"))
3417 ferr(&ops[j], "unexpected ecx pop\n");
3423 } while (i < opcnt);
3426 ferr(ops, "missing ebp epilogue\n");
3432 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3433 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3439 for (; i < opcnt; i++) {
3440 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3442 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3443 && ops[i].operand[1].type == OPT_CONST)
3445 g_stack_fsz = ops[i].operand[1].val;
3446 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3452 if (ecx_push && !esp_sub) {
3453 // could actually be args for a call..
3454 for (; i < opcnt; i++)
3455 if (ops[i].op != OP_PUSH)
3458 if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
3459 const struct parsed_proto *pp;
3460 pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
3461 j = pp ? pp->argc_stack : 0;
3462 while (i > 0 && j > 0) {
3464 if (ops[i].op == OP_PUSH) {
3465 ops[i].flags &= ~(OPF_RMD | OPF_DONE | OPF_NOREGS);
3470 ferr(&ops[i], "unhandled prologue\n");
3473 i = g_stack_fsz = ecx_push = 0;
3474 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3475 if (!(ops[i].flags & OPF_RMD))
3485 if (ecx_push || esp_sub)
3491 for (; i < opcnt; i++)
3492 if (ops[i].flags & OPF_TAIL)
3495 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3496 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3503 for (l = 0; l < ecx_push; l++) {
3504 if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
3506 else if (ops[j].op == OP_ADD
3507 && IS(opr_name(&ops[j], 0), "esp")
3508 && ops[j].operand[1].type == OPT_CONST)
3511 l += ops[j].operand[1].val / 4 - 1;
3514 ferr(&ops[j], "'pop ecx' expected\n");
3516 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3520 ferr(&ops[j], "epilogue scan failed\n");
3526 if (ops[j].op != OP_ADD
3527 || !IS(opr_name(&ops[j], 0), "esp")
3528 || ops[j].operand[1].type != OPT_CONST
3529 || ops[j].operand[1].val != g_stack_fsz)
3530 ferr(&ops[j], "'add esp' expected\n");
3532 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3533 ops[j].operand[1].val = 0; // hack for stack arg scanner
3538 } while (i < opcnt);
3541 ferr(ops, "missing esp epilogue\n");
3545 static const struct parsed_proto *resolve_icall(int i, int opcnt,
3546 int *pp_i, int *multi_src)
3548 const struct parsed_proto *pp = NULL;
3549 int search_advice = 0;
3554 switch (ops[i].operand[0].type) {
3558 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3563 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3571 // find an instruction that changed opr before i op
3572 // *op_i must be set to -1 by the caller
3573 // *entry is set to 1 if one source is determined to be the caller
3574 // returns 1 if found, *op_i is then set to origin
3575 static int resolve_origin(int i, const struct parsed_opr *opr,
3576 int magic, int *op_i, int *is_caller)
3578 struct label_ref *lr;
3581 if (ops[i].cc_scratch == magic)
3583 ops[i].cc_scratch = magic;
3586 if (g_labels[i] != NULL) {
3587 lr = &g_label_refs[i];
3588 for (; lr != NULL; lr = lr->next) {
3589 check_i(&ops[i], lr->i);
3590 ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3592 if (i > 0 && LAST_OP(i - 1))
3598 if (is_caller != NULL)
3603 if (ops[i].cc_scratch == magic)
3605 ops[i].cc_scratch = magic;
3607 if (!(ops[i].flags & OPF_DATA))
3609 if (!is_opr_modified(opr, &ops[i]))
3616 // XXX: could check if the other op does the same
3625 // find an instruction that previously referenced opr
3626 // if multiple results are found - fail
3627 // *op_i must be set to -1 by the caller
3628 // returns 1 if found, *op_i is then set to referencer insn
3629 static int resolve_last_ref(int i, const struct parsed_opr *opr,
3630 int magic, int *op_i)
3632 struct label_ref *lr;
3635 if (ops[i].cc_scratch == magic)
3637 ops[i].cc_scratch = magic;
3640 if (g_labels[i] != NULL) {
3641 lr = &g_label_refs[i];
3642 for (; lr != NULL; lr = lr->next) {
3643 check_i(&ops[i], lr->i);
3644 ret |= resolve_last_ref(lr->i, opr, magic, op_i);
3646 if (i > 0 && LAST_OP(i - 1))
3654 if (ops[i].cc_scratch == magic)
3656 ops[i].cc_scratch = magic;
3658 if (!is_opr_referenced(opr, &ops[i]))
3669 // find next instruction that reads opr
3670 // *op_i must be set to -1 by the caller
3671 // on return, *op_i is set to first referencer insn
3672 // returns 1 if exactly 1 referencer is found
3673 static int find_next_read(int i, int opcnt,
3674 const struct parsed_opr *opr, int magic, int *op_i)
3676 struct parsed_op *po;
3679 for (; i < opcnt; i++)
3681 if (ops[i].cc_scratch == magic)
3683 ops[i].cc_scratch = magic;
3686 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
3687 if (po->btj != NULL) {
3689 for (j = 0; j < po->btj->count; j++) {
3690 check_i(po, po->btj->d[j].bt_i);
3691 ret |= find_next_read(po->btj->d[j].bt_i, opcnt, opr,
3697 if (po->flags & OPF_RMD)
3699 check_i(po, po->bt_i);
3700 if (po->flags & OPF_CJMP) {
3701 ret |= find_next_read(po->bt_i, opcnt, opr, magic, op_i);
3710 if (!is_opr_read(opr, po)) {
3711 if (is_opr_modified(opr, po))
3714 if (po->flags & OPF_TAIL)
3729 static int try_resolve_const(int i, const struct parsed_opr *opr,
3730 int magic, unsigned int *val)
3735 ret = resolve_origin(i, opr, magic, &s_i, NULL);
3738 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3741 *val = ops[i].operand[1].val;
3748 static struct parsed_proto *process_call_early(int i, int opcnt,
3751 struct parsed_op *po = &ops[i];
3752 struct parsed_proto *pp;
3758 if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3762 // look for and make use of esp adjust
3764 if (!pp->is_stdcall && pp->argc_stack > 0)
3765 ret = scan_for_esp_adjust(i + 1, opcnt,
3766 pp->argc_stack * 4, &adj, &multipath, 0);
3768 if (pp->argc_stack > adj / 4)
3772 if (ops[ret].op == OP_POP) {
3773 for (j = 1; j < adj / 4; j++) {
3774 if (ops[ret + j].op != OP_POP
3775 || ops[ret + j].operand[0].reg != xCX)
3787 static struct parsed_proto *process_call(int i, int opcnt)
3789 struct parsed_op *po = &ops[i];
3790 const struct parsed_proto *pp_c;
3791 struct parsed_proto *pp;
3792 const char *tmpname;
3793 int call_i = -1, ref_i = -1;
3794 int adj = 0, multipath = 0;
3797 tmpname = opr_name(po, 0);
3802 pp_c = resolve_icall(i, opcnt, &call_i, &multipath);
3804 if (!pp_c->is_func && !pp_c->is_fptr)
3805 ferr(po, "call to non-func: %s\n", pp_c->name);
3806 pp = proto_clone(pp_c);
3807 my_assert_not(pp, NULL);
3809 // not resolved just to single func
3812 switch (po->operand[0].type) {
3814 // we resolved this call and no longer need the register
3815 po->regmask_src &= ~(1 << po->operand[0].reg);
3817 if (!multipath && i != call_i && ops[call_i].op == OP_MOV
3818 && ops[call_i].operand[1].type == OPT_LABEL)
3820 // no other source users?
3821 ret = resolve_last_ref(i, &po->operand[0], i + opcnt * 10,
3823 if (ret == 1 && call_i == ref_i) {
3824 // and nothing uses it after us?
3826 find_next_read(i + 1, opcnt, &po->operand[0],
3827 i + opcnt * 11, &ref_i);
3829 // then also don't need the source mov
3830 ops[call_i].flags |= OPF_RMD | OPF_NOREGS;
3842 pp = calloc(1, sizeof(*pp));
3843 my_assert_not(pp, NULL);
3846 ret = scan_for_esp_adjust(i + 1, opcnt,
3847 -1, &adj, &multipath, 0);
3848 if (ret < 0 || adj < 0) {
3849 if (!g_allow_regfunc)
3850 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3851 pp->is_unresolved = 1;
3855 if (adj > ARRAY_SIZE(pp->arg))
3856 ferr(po, "esp adjust too large: %d\n", adj);
3857 pp->ret_type.name = strdup("int");
3858 pp->argc = pp->argc_stack = adj;
3859 for (arg = 0; arg < pp->argc; arg++)
3860 pp->arg[arg].type.name = strdup("int");
3865 // look for and make use of esp adjust
3868 if (!pp->is_stdcall && pp->argc_stack > 0) {
3869 int adj_expect = pp->is_vararg ? -1 : pp->argc_stack * 4;
3870 ret = scan_for_esp_adjust(i + 1, opcnt,
3871 adj_expect, &adj, &multipath, 0);
3874 if (pp->is_vararg) {
3875 if (adj / 4 < pp->argc_stack) {
3876 fnote(po, "(this call)\n");
3877 ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3878 adj, pp->argc_stack * 4);
3880 // modify pp to make it have varargs as normal args
3882 pp->argc += adj / 4 - pp->argc_stack;
3883 for (; arg < pp->argc; arg++) {
3884 pp->arg[arg].type.name = strdup("int");
3887 if (pp->argc > ARRAY_SIZE(pp->arg))
3888 ferr(po, "too many args for '%s'\n", tmpname);
3890 if (pp->argc_stack > adj / 4) {
3891 fnote(po, "(this call)\n");
3892 ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3893 tmpname, pp->argc_stack * 4, adj);
3896 scan_for_esp_adjust(i + 1, opcnt,
3897 pp->argc_stack * 4, &adj, &multipath, 1);
3899 else if (pp->is_vararg)
3900 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3906 static int collect_call_args_early(struct parsed_op *po, int i,
3907 struct parsed_proto *pp, int *regmask)
3912 for (arg = 0; arg < pp->argc; arg++)
3913 if (pp->arg[arg].reg == NULL)
3916 // first see if it can be easily done
3917 for (j = i; j > 0 && arg < pp->argc; )
3919 if (g_labels[j] != NULL)
3923 if (ops[j].op == OP_CALL)
3925 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3927 else if (ops[j].op == OP_POP)
3929 else if (ops[j].flags & OPF_CJMP)
3931 else if (ops[j].op == OP_PUSH) {
3932 if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3934 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3938 if (pp->arg[arg].type.is_va_list)
3942 for (arg++; arg < pp->argc; arg++)
3943 if (pp->arg[arg].reg == NULL)
3952 for (arg = 0; arg < pp->argc; arg++)
3953 if (pp->arg[arg].reg == NULL)
3956 for (j = i; j > 0 && arg < pp->argc; )
3960 if (ops[j].op == OP_PUSH)
3962 ops[j].p_argnext = -1;
3963 ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3964 pp->arg[arg].datap = &ops[j];
3966 if (ops[j].operand[0].type == OPT_REG)
3967 *regmask |= 1 << ops[j].operand[0].reg;
3969 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
3970 ops[j].flags &= ~OPF_RSAVE;
3973 for (arg++; arg < pp->argc; arg++)
3974 if (pp->arg[arg].reg == NULL)
3982 static int collect_call_args_r(struct parsed_op *po, int i,
3983 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3984 int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
3986 struct parsed_proto *pp_tmp;
3987 struct parsed_op *po_tmp;
3988 struct label_ref *lr;
3989 int need_to_save_current;
3990 int arg_grp_current = 0;
3991 int save_args_seen = 0;
3999 ferr(po, "dead label encountered\n");
4003 for (; arg < pp->argc; arg++)
4004 if (pp->arg[arg].reg == NULL)
4006 magic = (magic & 0xffffff) | (arg << 24);
4008 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
4010 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
4011 if (ops[j].cc_scratch != magic) {
4012 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
4016 // ok: have already been here
4019 ops[j].cc_scratch = magic;
4021 if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
4022 lr = &g_label_refs[j];
4023 if (lr->next != NULL)
4025 for (; lr->next; lr = lr->next) {
4026 check_i(&ops[j], lr->i);
4027 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
4029 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
4030 arg_grp, arg, magic, need_op_saving, may_reuse);
4035 check_i(&ops[j], lr->i);
4036 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
4038 if (j > 0 && LAST_OP(j - 1)) {
4039 // follow last branch in reverse
4044 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
4045 arg_grp, arg, magic, need_op_saving, may_reuse);
4051 if (ops[j].op == OP_CALL)
4053 if (pp->is_unresolved)
4058 ferr(po, "arg collect hit unparsed call '%s'\n",
4059 ops[j].operand[0].name);
4060 if (may_reuse && pp_tmp->argc_stack > 0)
4061 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
4062 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
4064 // esp adjust of 0 means we collected it before
4065 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
4066 && (ops[j].operand[1].type != OPT_CONST
4067 || ops[j].operand[1].val != 0))
4069 if (pp->is_unresolved)
4072 fnote(po, "(this call)\n");
4073 ferr(&ops[j], "arg collect %d/%d hit esp adjust of %d\n",
4074 arg, pp->argc, ops[j].operand[1].val);
4076 else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
4078 if (pp->is_unresolved)
4081 fnote(po, "(this call)\n");
4082 ferr(&ops[j], "arg collect %d/%d hit pop\n", arg, pp->argc);
4084 else if (ops[j].flags & OPF_CJMP)
4086 if (pp->is_unresolved)
4091 else if (ops[j].op == OP_PUSH
4092 && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
4094 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
4097 ops[j].p_argnext = -1;
4098 po_tmp = pp->arg[arg].datap;
4100 ops[j].p_argnext = po_tmp - ops;
4101 pp->arg[arg].datap = &ops[j];
4103 need_to_save_current = 0;
4106 if (ops[j].operand[0].type == OPT_REG)
4107 reg = ops[j].operand[0].reg;
4109 if (!need_op_saving) {
4110 ret = scan_for_mod(&ops[j], j + 1, i, 1);
4111 need_to_save_current = (ret >= 0);
4113 if (need_op_saving || need_to_save_current) {
4114 // mark this push as one that needs operand saving
4115 ops[j].flags &= ~OPF_RMD;
4116 if (ops[j].p_argnum == 0) {
4117 ops[j].p_argnum = arg + 1;
4118 save_args |= 1 << arg;
4120 else if (ops[j].p_argnum < arg + 1) {
4121 // XXX: might kill valid var..
4122 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
4123 ops[j].p_argnum = arg + 1;
4124 save_args |= 1 << arg;
4127 if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
4130 if (arg_grp_current >= MAX_ARG_GRP)
4131 ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
4132 ops[j].p_argnum, pp->name);
4135 else if (ops[j].p_argnum == 0)
4136 ops[j].flags |= OPF_RMD;
4138 // some PUSHes are reused by different calls on other branches,
4139 // but that can't happen if we didn't branch, so they
4140 // can be removed from future searches (handles nested calls)
4142 ops[j].flags |= OPF_FARGNR;
4144 ops[j].flags |= OPF_FARG;
4145 ops[j].flags &= ~OPF_RSAVE;
4147 // check for __VALIST
4148 if (!pp->is_unresolved && g_func_pp != NULL
4149 && pp->arg[arg].type.is_va_list)
4152 ret = resolve_origin(j, &ops[j].operand[0],
4153 magic + 1, &k, NULL);
4154 if (ret == 1 && k >= 0)
4156 if (ops[k].op == OP_LEA) {
4157 snprintf(buf, sizeof(buf), "arg_%X",
4158 g_func_pp->argc_stack * 4);
4159 if (!g_func_pp->is_vararg
4160 || strstr(ops[k].operand[1].name, buf))
4162 ops[k].flags |= OPF_RMD | OPF_NOREGS | OPF_DONE;
4163 ops[j].flags |= OPF_RMD | OPF_NOREGS | OPF_VAPUSH;
4164 save_args &= ~(1 << arg);
4168 ferr(&ops[j], "lea va_list used, but no vararg?\n");
4170 // check for va_list from g_func_pp arg too
4171 else if (ops[k].op == OP_MOV
4172 && is_stack_access(&ops[k], &ops[k].operand[1]))
4174 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
4175 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
4177 ops[k].flags |= OPF_RMD | OPF_DONE;
4178 ops[j].flags |= OPF_RMD;
4179 ops[j].p_argpass = ret + 1;
4180 save_args &= ~(1 << arg);
4187 *save_arg_vars |= save_args;
4189 // tracking reg usage
4191 *regmask |= 1 << reg;
4194 if (!pp->is_unresolved) {
4196 for (; arg < pp->argc; arg++)
4197 if (pp->arg[arg].reg == NULL)
4200 magic = (magic & 0xffffff) | (arg << 24);
4203 if (ops[j].p_arggrp > arg_grp_current) {
4205 arg_grp_current = ops[j].p_arggrp;
4207 if (ops[j].p_argnum > 0)
4208 save_args_seen |= 1 << (ops[j].p_argnum - 1);
4211 if (arg < pp->argc) {
4212 ferr(po, "arg collect failed for '%s': %d/%d\n",
4213 pp->name, arg, pp->argc);
4217 if (arg_grp_current > *arg_grp)
4218 *arg_grp = arg_grp_current;
4223 static int collect_call_args(struct parsed_op *po, int i,
4224 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
4227 // arg group is for cases when pushes for
4228 // multiple funcs are going on
4229 struct parsed_op *po_tmp;
4230 int save_arg_vars_current = 0;
4235 ret = collect_call_args_r(po, i, pp, regmask,
4236 &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
4241 // propagate arg_grp
4242 for (a = 0; a < pp->argc; a++) {
4243 if (pp->arg[a].reg != NULL)
4246 po_tmp = pp->arg[a].datap;
4247 while (po_tmp != NULL) {
4248 po_tmp->p_arggrp = arg_grp;
4249 if (po_tmp->p_argnext > 0)
4250 po_tmp = &ops[po_tmp->p_argnext];
4256 save_arg_vars[arg_grp] |= save_arg_vars_current;
4258 if (pp->is_unresolved) {
4260 pp->argc_stack += ret;
4261 for (a = 0; a < pp->argc; a++)
4262 if (pp->arg[a].type.name == NULL)
4263 pp->arg[a].type.name = strdup("int");
4269 static void reg_use_pass(int i, int opcnt, unsigned char *cbits,
4270 int regmask_now, int *regmask,
4271 int regmask_save_now, int *regmask_save,
4272 int *regmask_init, int regmask_arg)
4274 struct parsed_op *po;
4282 for (; i < opcnt; i++)
4285 if (cbits[i >> 3] & (1 << (i & 7)))
4287 cbits[i >> 3] |= (1 << (i & 7));
4289 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
4290 if (po->flags & (OPF_RMD|OPF_DONE))
4292 if (po->btj != NULL) {
4293 for (j = 0; j < po->btj->count; j++) {
4294 check_i(po, po->btj->d[j].bt_i);
4295 reg_use_pass(po->btj->d[j].bt_i, opcnt, cbits,
4296 regmask_now, regmask, regmask_save_now, regmask_save,
4297 regmask_init, regmask_arg);
4302 check_i(po, po->bt_i);
4303 if (po->flags & OPF_CJMP)
4304 reg_use_pass(po->bt_i, opcnt, cbits,
4305 regmask_now, regmask, regmask_save_now, regmask_save,
4306 regmask_init, regmask_arg);
4312 if (po->op == OP_PUSH && !(po->flags & (OPF_FARG|OPF_DONE))
4313 && !g_func_pp->is_userstack
4314 && po->operand[0].type == OPT_REG)
4316 reg = po->operand[0].reg;
4317 ferr_assert(po, reg >= 0);
4320 flags_set = OPF_RSAVE | OPF_RMD | OPF_DONE;
4321 if (regmask_now & (1 << reg)) {
4322 already_saved = regmask_save_now & (1 << reg);
4323 flags_set = OPF_RSAVE | OPF_DONE;
4326 ret = scan_for_pop(i + 1, opcnt, i + opcnt * 3, reg, 0, 0);
4328 scan_for_pop(i + 1, opcnt, i + opcnt * 4, reg, 0, flags_set);
4331 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, 0);
4333 scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg,
4338 ferr_assert(po, !already_saved);
4339 po->flags |= flags_set;
4341 if (regmask_now & (1 << reg)) {
4342 regmask_save_now |= (1 << reg);
4343 *regmask_save |= regmask_save_now;
4348 else if (po->op == OP_POP && (po->flags & OPF_RSAVE)) {
4349 reg = po->operand[0].reg;
4350 ferr_assert(po, reg >= 0);
4352 if (regmask_save_now & (1 << reg))
4353 regmask_save_now &= ~(1 << reg);
4355 regmask_now &= ~(1 << reg);
4358 else if (po->op == OP_CALL) {
4359 if ((po->regmask_dst & (1 << xAX))
4360 && !(po->regmask_dst & (1 << xDX)))
4362 if (po->flags & OPF_TAIL)
4363 // don't need eax, will do "return f();" or "f(); return;"
4364 po->regmask_dst &= ~(1 << xAX);
4366 struct parsed_opr opr = OPR_INIT(OPT_REG, OPLM_DWORD, xAX);
4368 find_next_read(i + 1, opcnt, &opr, i + opcnt * 17, &j);
4371 po->regmask_dst &= ~(1 << xAX);
4376 if (po->flags & OPF_NOREGS)
4379 regmask_op = po->regmask_src | po->regmask_dst;
4381 regmask_new = po->regmask_src & ~regmask_now & ~regmask_arg;
4382 regmask_new &= ~(1 << xSP);
4383 if (g_bp_frame && !(po->flags & OPF_EBP_S))
4384 regmask_new &= ~(1 << xBP);
4386 if (po->op == OP_CALL) {
4387 // allow fastcall calls from anywhere, calee may be also sitting
4388 // in some fastcall table even when it's not using reg args
4389 if (regmask_new & po->regmask_src & (1 << xCX)) {
4390 *regmask_init |= (1 << xCX);
4391 regmask_now |= (1 << xCX);
4392 regmask_new &= ~(1 << xCX);
4394 if (regmask_new & po->regmask_src & (1 << xDX)) {
4395 *regmask_init |= (1 << xDX);
4396 regmask_now |= (1 << xDX);
4397 regmask_new &= ~(1 << xDX);
4401 if (regmask_new != 0)
4402 fnote(po, "uninitialized reg mask: %x\n", regmask_new);
4404 if (regmask_op & (1 << xBP)) {
4405 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4406 if (po->regmask_dst & (1 << xBP))
4407 // compiler decided to drop bp frame and use ebp as scratch
4408 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
4410 regmask_op &= ~(1 << xBP);
4414 regmask_now |= regmask_op;
4415 *regmask |= regmask_now;
4417 if (po->flags & OPF_TAIL)
4422 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
4426 for (i = 0; i < pp->argc; i++)
4427 if (pp->arg[i].reg == NULL)
4431 memmove(&pp->arg[i + 1], &pp->arg[i],
4432 sizeof(pp->arg[0]) * pp->argc_stack);
4433 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
4434 pp->arg[i].reg = strdup(reg);
4435 pp->arg[i].type.name = strdup("int");
4440 static void output_std_flags(FILE *fout, struct parsed_op *po,
4441 int *pfomask, const char *dst_opr_text)
4443 if (*pfomask & (1 << PFO_Z)) {
4444 fprintf(fout, "\n cond_z = (%s%s == 0);",
4445 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
4446 *pfomask &= ~(1 << PFO_Z);
4448 if (*pfomask & (1 << PFO_S)) {
4449 fprintf(fout, "\n cond_s = (%s%s < 0);",
4450 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
4451 *pfomask &= ~(1 << PFO_S);
4456 OPP_FORCE_NORETURN = (1 << 0),
4457 OPP_SIMPLE_ARGS = (1 << 1),
4458 OPP_ALIGN = (1 << 2),
4461 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
4464 const char *cconv = "";
4466 if (pp->is_fastcall)
4467 cconv = "__fastcall ";
4468 else if (pp->is_stdcall && pp->argc_reg == 0)
4469 cconv = "__stdcall ";
4471 fprintf(fout, (flags & OPP_ALIGN) ? "%-16s" : "%s", cconv);
4473 if (pp->is_noreturn || (flags & OPP_FORCE_NORETURN))
4474 fprintf(fout, "noreturn ");
4477 static void output_pp(FILE *fout, const struct parsed_proto *pp,
4482 fprintf(fout, (flags & OPP_ALIGN) ? "%-5s" : "%s ",
4486 output_pp_attrs(fout, pp, flags);
4489 fprintf(fout, "%s", pp->name);
4494 for (i = 0; i < pp->argc; i++) {
4496 fprintf(fout, ", ");
4497 if (pp->arg[i].fptr != NULL && !(flags & OPP_SIMPLE_ARGS)) {
4499 output_pp(fout, pp->arg[i].fptr, 0);
4501 else if (pp->arg[i].type.is_retreg) {
4502 fprintf(fout, "u32 *r_%s", pp->arg[i].reg);
4505 fprintf(fout, "%s", pp->arg[i].type.name);
4507 fprintf(fout, " a%d", i + 1);
4510 if (pp->is_vararg) {
4512 fprintf(fout, ", ");
4513 fprintf(fout, "...");
4518 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
4524 snprintf(buf1, sizeof(buf1), "%d", grp);
4525 snprintf(buf, buf_size, "s%s_a%d", buf1, num);
4530 static void gen_x_cleanup(int opcnt);
4532 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
4534 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
4535 struct parsed_opr *last_arith_dst = NULL;
4536 char buf1[256], buf2[256], buf3[256], cast[64];
4537 struct parsed_proto *pp, *pp_tmp;
4538 struct parsed_data *pd;
4540 int save_arg_vars[MAX_ARG_GRP] = { 0, };
4541 unsigned char cbits[MAX_OPS / 8];
4543 int need_tmp_var = 0;
4546 int label_pending = 0;
4547 int regmask_save = 0; // regs saved/restored in this func
4548 int regmask_arg; // regs from this function args (fastcall, etc)
4549 int regmask_ret; // regs needed on ret
4550 int regmask_now; // temp
4551 int regmask_init = 0; // regs that need zero initialization
4552 int regmask_pp = 0; // regs used in complex push-pop graph
4553 int regmask = 0; // used regs
4562 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
4563 g_stack_frame_used = 0;
4565 g_func_pp = proto_parse(fhdr, funcn, 0);
4566 if (g_func_pp == NULL)
4567 ferr(ops, "proto_parse failed for '%s'\n", funcn);
4569 regmask_arg = get_pp_arg_regmask_src(g_func_pp);
4570 regmask_ret = get_pp_arg_regmask_dst(g_func_pp);
4572 if (g_func_pp->has_retreg) {
4573 for (arg = 0; arg < g_func_pp->argc; arg++) {
4574 if (g_func_pp->arg[arg].type.is_retreg) {
4575 reg = char_array_i(regs_r32,
4576 ARRAY_SIZE(regs_r32), g_func_pp->arg[arg].reg);
4577 ferr_assert(ops, reg >= 0);
4578 regmask_ret |= 1 << reg;
4584 // - resolve all branches
4585 // - parse calls with labels
4586 resolve_branches_parse_calls(opcnt);
4589 // - handle ebp/esp frame, remove ops related to it
4590 scan_prologue_epilogue(opcnt);
4593 // - remove dead labels
4594 // - set regs needed at ret
4595 for (i = 0; i < opcnt; i++)
4597 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
4602 if (ops[i].op == OP_RET)
4603 ops[i].regmask_src |= regmask_ret;
4607 // - process trivial calls
4608 for (i = 0; i < opcnt; i++)
4611 if (po->flags & (OPF_RMD|OPF_DONE))
4614 if (po->op == OP_CALL)
4616 pp = process_call_early(i, opcnt, &j);
4618 if (!(po->flags & OPF_ATAIL))
4619 // since we know the args, try to collect them
4620 if (collect_call_args_early(po, i, pp, ®mask) != 0)
4626 // commit esp adjust
4627 if (ops[j].op != OP_POP)
4628 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
4630 for (l = 0; l < pp->argc_stack; l++)
4631 ops[j + l].flags |= OPF_DONE | OPF_RMD | OPF_NOREGS;
4635 if (strstr(pp->ret_type.name, "int64"))
4638 po->flags |= OPF_DONE;
4644 // - process calls, stage 2
4645 // - handle some push/pop pairs
4646 // - scan for STD/CLD, propagate DF
4647 for (i = 0; i < opcnt; i++)
4650 if (po->flags & OPF_RMD)
4653 if (po->op == OP_CALL)
4655 if (!(po->flags & OPF_DONE)) {
4656 pp = process_call(i, opcnt);
4658 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
4659 // since we know the args, collect them
4660 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4663 // for unresolved, collect after other passes
4667 ferr_assert(po, pp != NULL);
4669 po->regmask_src |= get_pp_arg_regmask_src(pp);
4670 po->regmask_dst |= get_pp_arg_regmask_dst(pp);
4672 if (strstr(pp->ret_type.name, "int64"))
4678 if (po->flags & OPF_DONE)
4681 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4682 && !(po->flags & OPF_RSAVE) && po->operand[0].type == OPT_CONST)
4684 scan_for_pop_const(i, opcnt, i + opcnt * 12);
4686 else if (po->op == OP_POP)
4687 scan_pushes_for_pop(i, opcnt, ®mask_pp);
4688 else if (po->op == OP_STD) {
4689 po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
4690 scan_propagate_df(i + 1, opcnt);
4695 // - find POPs for PUSHes, rm both
4696 // - scan for all used registers
4697 memset(cbits, 0, sizeof(cbits));
4698 reg_use_pass(0, opcnt, cbits, 0, ®mask,
4699 0, ®mask_save, ®mask_init, regmask_arg);
4702 // - find flag set ops for their users
4703 // - do unresolved calls
4704 // - declare indirect functions
4705 for (i = 0; i < opcnt; i++)
4708 if (po->flags & (OPF_RMD|OPF_DONE))
4711 if (po->flags & OPF_CC)
4713 int setters[16], cnt = 0, branched = 0;
4715 ret = scan_for_flag_set(i, i + opcnt * 6,
4716 &branched, setters, &cnt);
4717 if (ret < 0 || cnt <= 0)
4718 ferr(po, "unable to trace flag setter(s)\n");
4719 if (cnt > ARRAY_SIZE(setters))
4720 ferr(po, "too many flag setters\n");
4722 for (j = 0; j < cnt; j++)
4724 tmp_op = &ops[setters[j]]; // flag setter
4727 // to get nicer code, we try to delay test and cmp;
4728 // if we can't because of operand modification, or if we
4729 // have arith op, or branch, make it calculate flags explicitly
4730 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4732 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4733 pfomask = 1 << po->pfo;
4735 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4736 pfomask = 1 << po->pfo;
4739 // see if we'll be able to handle based on op result
4740 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4741 && po->pfo != PFO_Z && po->pfo != PFO_S
4742 && po->pfo != PFO_P)
4744 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4746 pfomask = 1 << po->pfo;
4749 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4750 propagate_lmod(tmp_op, &tmp_op->operand[0],
4751 &tmp_op->operand[1]);
4752 if (tmp_op->operand[0].lmod == OPLM_DWORD)
4757 tmp_op->pfomask |= pfomask;
4758 cond_vars |= pfomask;
4760 // note: may overwrite, currently not a problem
4764 if (po->op == OP_RCL || po->op == OP_RCR
4765 || po->op == OP_ADC || po->op == OP_SBB)
4766 cond_vars |= 1 << PFO_C;
4769 if (po->op == OP_CMPS || po->op == OP_SCAS) {
4770 cond_vars |= 1 << PFO_Z;
4772 else if (po->op == OP_MUL
4773 || (po->op == OP_IMUL && po->operand_cnt == 1))
4775 if (po->operand[0].lmod == OPLM_DWORD)
4778 else if (po->op == OP_CALL) {
4779 // note: resolved non-reg calls are OPF_DONE already
4781 ferr_assert(po, pp != NULL);
4783 if (pp->is_unresolved) {
4784 int regmask_stack = 0;
4785 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4788 // this is pretty rough guess:
4789 // see ecx and edx were pushed (and not their saved versions)
4790 for (arg = 0; arg < pp->argc; arg++) {
4791 if (pp->arg[arg].reg != NULL)
4794 tmp_op = pp->arg[arg].datap;
4796 ferr(po, "parsed_op missing for arg%d\n", arg);
4797 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4798 regmask_stack |= 1 << tmp_op->operand[0].reg;
4801 if (!((regmask_stack & (1 << xCX))
4802 && (regmask_stack & (1 << xDX))))
4804 if (pp->argc_stack != 0
4805 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4807 pp_insert_reg_arg(pp, "ecx");
4808 pp->is_fastcall = 1;
4809 regmask_init |= 1 << xCX;
4810 regmask |= 1 << xCX;
4812 if (pp->argc_stack != 0
4813 || ((regmask | regmask_arg) & (1 << xDX)))
4815 pp_insert_reg_arg(pp, "edx");
4816 regmask_init |= 1 << xDX;
4817 regmask |= 1 << xDX;
4821 // note: __cdecl doesn't fall into is_unresolved category
4822 if (pp->argc_stack > 0)
4826 else if (po->op == OP_MOV && po->operand[0].pp != NULL
4827 && po->operand[1].pp != NULL)
4829 // <var> = offset <something>
4830 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4831 && !IS_START(po->operand[1].name, "off_"))
4833 if (!po->operand[0].pp->is_fptr)
4834 ferr(po, "%s not declared as fptr when it should be\n",
4835 po->operand[0].name);
4836 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4837 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4838 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4839 fnote(po, "var: %s\n", buf1);
4840 fnote(po, "func: %s\n", buf2);
4841 ferr(po, "^ mismatch\n");
4845 else if (po->op == OP_DIV || po->op == OP_IDIV) {
4846 // 32bit division is common, look for it
4847 if (po->op == OP_DIV)
4848 ret = scan_for_reg_clear(i, xDX);
4850 ret = scan_for_cdq_edx(i);
4852 po->flags |= OPF_32BIT;
4856 else if (po->op == OP_CLD)
4857 po->flags |= OPF_RMD | OPF_DONE;
4859 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4864 // output starts here
4866 // define userstack size
4867 if (g_func_pp->is_userstack) {
4868 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4869 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4870 fprintf(fout, "#endif\n");
4873 // the function itself
4874 ferr_assert(ops, !g_func_pp->is_fptr);
4875 output_pp(fout, g_func_pp,
4876 (g_ida_func_attr & IDAFA_NORETURN) ? OPP_FORCE_NORETURN : 0);
4877 fprintf(fout, "\n{\n");
4879 // declare indirect functions
4880 for (i = 0; i < opcnt; i++) {
4882 if (po->flags & OPF_RMD)
4885 if (po->op == OP_CALL) {
4888 ferr(po, "NULL pp\n");
4890 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4891 if (pp->name[0] != 0) {
4892 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4893 memcpy(pp->name, "i_", 2);
4895 // might be declared already
4897 for (j = 0; j < i; j++) {
4898 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4899 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4909 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4912 output_pp(fout, pp, OPP_SIMPLE_ARGS);
4913 fprintf(fout, ";\n");
4918 // output LUTs/jumptables
4919 for (i = 0; i < g_func_pd_cnt; i++) {
4921 fprintf(fout, " static const ");
4922 if (pd->type == OPT_OFFSET) {
4923 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
4925 for (j = 0; j < pd->count; j++) {
4927 fprintf(fout, ", ");
4928 fprintf(fout, "&&%s", pd->d[j].u.label);
4932 fprintf(fout, "%s %s[] =\n { ",
4933 lmod_type_u(ops, pd->lmod), pd->label);
4935 for (j = 0; j < pd->count; j++) {
4937 fprintf(fout, ", ");
4938 fprintf(fout, "%u", pd->d[j].u.val);
4941 fprintf(fout, " };\n");
4945 // declare stack frame, va_arg
4947 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
4948 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
4952 if (g_func_pp->is_userstack) {
4953 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4954 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
4958 if (g_func_pp->is_vararg) {
4959 fprintf(fout, " va_list ap;\n");
4963 // declare arg-registers
4964 for (i = 0; i < g_func_pp->argc; i++) {
4965 if (g_func_pp->arg[i].reg != NULL) {
4966 reg = char_array_i(regs_r32,
4967 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
4968 if (regmask & (1 << reg)) {
4969 if (g_func_pp->arg[i].type.is_retreg)
4970 fprintf(fout, " u32 %s = *r_%s;\n",
4971 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4973 fprintf(fout, " u32 %s = (u32)a%d;\n",
4974 g_func_pp->arg[i].reg, i + 1);
4977 if (g_func_pp->arg[i].type.is_retreg)
4978 ferr(ops, "retreg '%s' is unused?\n",
4979 g_func_pp->arg[i].reg);
4980 fprintf(fout, " // %s = a%d; // unused\n",
4981 g_func_pp->arg[i].reg, i + 1);
4987 // declare normal registers
4988 regmask_now = regmask & ~regmask_arg;
4989 regmask_now &= ~(1 << xSP);
4990 if (regmask_now & 0x00ff) {
4991 for (reg = 0; reg < 8; reg++) {
4992 if (regmask_now & (1 << reg)) {
4993 fprintf(fout, " u32 %s", regs_r32[reg]);
4994 if (regmask_init & (1 << reg))
4995 fprintf(fout, " = 0");
4996 fprintf(fout, ";\n");
5001 if (regmask_now & 0xff00) {
5002 for (reg = 8; reg < 16; reg++) {
5003 if (regmask_now & (1 << reg)) {
5004 fprintf(fout, " mmxr %s", regs_r32[reg]);
5005 if (regmask_init & (1 << reg))
5006 fprintf(fout, " = { 0, }");
5007 fprintf(fout, ";\n");
5014 for (reg = 0; reg < 8; reg++) {
5015 if (regmask_save & (1 << reg)) {
5016 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
5022 for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
5023 if (save_arg_vars[i] == 0)
5025 for (reg = 0; reg < 32; reg++) {
5026 if (save_arg_vars[i] & (1 << reg)) {
5027 fprintf(fout, " u32 %s;\n",
5028 saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
5034 // declare push-pop temporaries
5036 for (reg = 0; reg < 8; reg++) {
5037 if (regmask_pp & (1 << reg)) {
5038 fprintf(fout, " u32 pp_%s;\n", regs_r32[reg]);
5045 for (i = 0; i < 8; i++) {
5046 if (cond_vars & (1 << i)) {
5047 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
5054 fprintf(fout, " u32 tmp;\n");
5059 fprintf(fout, " u64 tmp64;\n");
5064 fprintf(fout, "\n");
5066 if (g_func_pp->is_vararg) {
5067 if (g_func_pp->argc_stack == 0)
5068 ferr(ops, "vararg func without stack args?\n");
5069 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
5073 for (i = 0; i < opcnt; i++)
5075 if (g_labels[i] != NULL) {
5076 fprintf(fout, "\n%s:\n", g_labels[i]);
5079 delayed_flag_op = NULL;
5080 last_arith_dst = NULL;
5084 if (po->flags & OPF_RMD)
5089 #define assert_operand_cnt(n_) \
5090 if (po->operand_cnt != n_) \
5091 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
5093 // conditional/flag using op?
5094 if (po->flags & OPF_CC)
5100 // we go through all this trouble to avoid using parsed_flag_op,
5101 // which makes generated code much nicer
5102 if (delayed_flag_op != NULL)
5104 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
5105 po->pfo, po->pfo_inv);
5108 else if (last_arith_dst != NULL
5109 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
5110 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
5113 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
5114 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
5115 last_arith_dst->lmod, buf3);
5118 else if (tmp_op != NULL) {
5119 // use preprocessed flag calc results
5120 if (!(tmp_op->pfomask & (1 << po->pfo)))
5121 ferr(po, "not prepared for pfo %d\n", po->pfo);
5123 // note: pfo_inv was not yet applied
5124 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
5125 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
5128 ferr(po, "all methods of finding comparison failed\n");
5131 if (po->flags & OPF_JMP) {
5132 fprintf(fout, " if %s", buf1);
5134 else if (po->op == OP_RCL || po->op == OP_RCR
5135 || po->op == OP_ADC || po->op == OP_SBB)
5138 fprintf(fout, " cond_%s = %s;\n",
5139 parsed_flag_op_names[po->pfo], buf1);
5141 else if (po->flags & OPF_DATA) { // SETcc
5142 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
5143 fprintf(fout, " %s = %s;", buf2, buf1);
5146 ferr(po, "unhandled conditional op\n");
5150 pfomask = po->pfomask;
5152 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
5153 struct parsed_opr opr = OPR_INIT(OPT_REG, OPLM_DWORD, xCX);
5154 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
5156 if (ret != 1 || uval == 0) {
5157 // we need initial flags for ecx=0 case..
5158 if (i > 0 && ops[i - 1].op == OP_XOR
5159 && IS(ops[i - 1].operand[0].name,
5160 ops[i - 1].operand[1].name))
5162 fprintf(fout, " cond_z = ");
5163 if (pfomask & (1 << PFO_C))
5164 fprintf(fout, "cond_c = ");
5165 fprintf(fout, "0;\n");
5167 else if (last_arith_dst != NULL) {
5168 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
5169 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
5170 last_arith_dst->lmod, buf3);
5171 fprintf(fout, " cond_z = %s;\n", buf1);
5174 ferr(po, "missing initial ZF\n");
5181 assert_operand_cnt(2);
5182 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5183 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5184 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
5185 fprintf(fout, " %s = %s;", buf1,
5186 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5191 assert_operand_cnt(2);
5192 po->operand[1].lmod = OPLM_DWORD; // always
5193 fprintf(fout, " %s = %s;",
5194 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5195 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5200 assert_operand_cnt(2);
5201 fprintf(fout, " %s = %s;",
5202 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5203 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5207 assert_operand_cnt(2);
5208 switch (po->operand[1].lmod) {
5210 strcpy(buf3, "(s8)");
5213 strcpy(buf3, "(s16)");
5216 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
5218 fprintf(fout, " %s = %s;",
5219 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5220 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5225 assert_operand_cnt(2);
5226 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5227 fprintf(fout, " tmp = %s;",
5228 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
5229 fprintf(fout, " %s = %s;",
5230 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5231 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5232 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5233 fprintf(fout, " %s = %stmp;",
5234 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
5235 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
5236 snprintf(g_comment, sizeof(g_comment), "xchg");
5240 assert_operand_cnt(1);
5241 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5242 fprintf(fout, " %s = ~%s;", buf1, buf1);
5246 assert_operand_cnt(2);
5247 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5248 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5249 fprintf(fout, " %s = *(u8 *)(%s + %s);", buf1, buf2, buf1);
5250 strcpy(g_comment, "xlat");
5254 assert_operand_cnt(2);
5255 fprintf(fout, " %s = (s32)%s >> 31;",
5256 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5257 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5258 strcpy(g_comment, "cdq");
5262 assert_operand_cnt(3);
5263 if (po->flags & OPF_REP) {
5268 fprintf(fout, " eax = %sesi; esi %c= %d;",
5269 lmod_cast_u_ptr(po, po->operand[0].lmod),
5270 (po->flags & OPF_DF) ? '-' : '+',
5271 lmod_bytes(po, po->operand[0].lmod));
5272 strcpy(g_comment, "lods");
5277 assert_operand_cnt(3);
5278 if (po->flags & OPF_REP) {
5279 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
5280 (po->flags & OPF_DF) ? '-' : '+',
5281 lmod_bytes(po, po->operand[0].lmod));
5282 fprintf(fout, " %sedi = eax;",
5283 lmod_cast_u_ptr(po, po->operand[0].lmod));
5284 strcpy(g_comment, "rep stos");
5287 fprintf(fout, " %sedi = eax; edi %c= %d;",
5288 lmod_cast_u_ptr(po, po->operand[0].lmod),
5289 (po->flags & OPF_DF) ? '-' : '+',
5290 lmod_bytes(po, po->operand[0].lmod));
5291 strcpy(g_comment, "stos");
5296 assert_operand_cnt(3);
5297 j = lmod_bytes(po, po->operand[0].lmod);
5298 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
5299 l = (po->flags & OPF_DF) ? '-' : '+';
5300 if (po->flags & OPF_REP) {
5302 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
5305 " %sedi = %sesi;", buf1, buf1);
5306 strcpy(g_comment, "rep movs");
5309 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
5310 buf1, buf1, l, j, l, j);
5311 strcpy(g_comment, "movs");
5316 // repe ~ repeat while ZF=1
5317 assert_operand_cnt(3);
5318 j = lmod_bytes(po, po->operand[0].lmod);
5319 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
5320 l = (po->flags & OPF_DF) ? '-' : '+';
5321 if (po->flags & OPF_REP) {
5323 " for (; ecx != 0; ecx--) {\n");
5324 if (pfomask & (1 << PFO_C)) {
5327 " cond_c = %sesi < %sedi;\n", buf1, buf1);
5328 pfomask &= ~(1 << PFO_C);
5331 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
5332 buf1, buf1, l, j, l, j);
5334 " if (cond_z %s 0) break;\n",
5335 (po->flags & OPF_REPZ) ? "==" : "!=");
5338 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
5339 (po->flags & OPF_REPZ) ? "e" : "ne");
5343 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
5344 buf1, buf1, l, j, l, j);
5345 strcpy(g_comment, "cmps");
5347 pfomask &= ~(1 << PFO_Z);
5348 last_arith_dst = NULL;
5349 delayed_flag_op = NULL;
5353 // only does ZF (for now)
5354 // repe ~ repeat while ZF=1
5355 assert_operand_cnt(3);
5356 j = lmod_bytes(po, po->operand[0].lmod);
5357 l = (po->flags & OPF_DF) ? '-' : '+';
5358 if (po->flags & OPF_REP) {
5360 " for (; ecx != 0; ecx--) {\n");
5362 " cond_z = (%seax == %sedi); edi %c= %d;\n",
5363 lmod_cast_u(po, po->operand[0].lmod),
5364 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5366 " if (cond_z %s 0) break;\n",
5367 (po->flags & OPF_REPZ) ? "==" : "!=");
5370 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
5371 (po->flags & OPF_REPZ) ? "e" : "ne");
5374 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
5375 lmod_cast_u(po, po->operand[0].lmod),
5376 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5377 strcpy(g_comment, "scas");
5379 pfomask &= ~(1 << PFO_Z);
5380 last_arith_dst = NULL;
5381 delayed_flag_op = NULL;
5384 // arithmetic w/flags
5386 if (po->operand[1].type == OPT_CONST && !po->operand[1].val)
5387 goto dualop_arith_const;
5388 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5392 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5393 if (po->operand[1].type == OPT_CONST) {
5394 j = lmod_bytes(po, po->operand[0].lmod);
5395 if (((1ull << j * 8) - 1) == po->operand[1].val)
5396 goto dualop_arith_const;
5401 assert_operand_cnt(2);
5402 fprintf(fout, " %s %s= %s;",
5403 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5405 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5406 output_std_flags(fout, po, &pfomask, buf1);
5407 last_arith_dst = &po->operand[0];
5408 delayed_flag_op = NULL;
5412 // and 0, or ~0 used instead mov
5413 assert_operand_cnt(2);
5414 fprintf(fout, " %s = %s;",
5415 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5416 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5417 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5418 output_std_flags(fout, po, &pfomask, buf1);
5419 last_arith_dst = &po->operand[0];
5420 delayed_flag_op = NULL;
5425 assert_operand_cnt(2);
5426 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5427 if (pfomask & (1 << PFO_C)) {
5428 if (po->operand[1].type == OPT_CONST) {
5429 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5430 j = po->operand[1].val;
5433 if (po->op == OP_SHL)
5437 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
5441 ferr(po, "zero shift?\n");
5445 pfomask &= ~(1 << PFO_C);
5447 fprintf(fout, " %s %s= %s", buf1, op_to_c(po),
5448 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5449 if (po->operand[1].type != OPT_CONST)
5450 fprintf(fout, " & 0x1f");
5452 output_std_flags(fout, po, &pfomask, buf1);
5453 last_arith_dst = &po->operand[0];
5454 delayed_flag_op = NULL;
5458 assert_operand_cnt(2);
5459 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5460 fprintf(fout, " %s = %s%s >> %s;", buf1,
5461 lmod_cast_s(po, po->operand[0].lmod), buf1,
5462 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5463 output_std_flags(fout, po, &pfomask, buf1);
5464 last_arith_dst = &po->operand[0];
5465 delayed_flag_op = NULL;
5470 assert_operand_cnt(3);
5471 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5472 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5473 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5474 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5475 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
5476 if (po->operand[2].type != OPT_CONST)
5477 ferr(po, "TODO: masking\n");
5478 if (po->op == OP_SHLD) {
5479 fprintf(fout, " %s <<= %s; %s |= %s >> (%d - %s);",
5480 buf1, buf3, buf1, buf2, l, buf3);
5481 strcpy(g_comment, "shld");
5484 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
5485 buf1, buf3, buf1, buf2, l, buf3);
5486 strcpy(g_comment, "shrd");
5488 output_std_flags(fout, po, &pfomask, buf1);
5489 last_arith_dst = &po->operand[0];
5490 delayed_flag_op = NULL;
5495 assert_operand_cnt(2);
5496 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5497 if (po->operand[1].type == OPT_CONST) {
5498 j = po->operand[1].val;
5499 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
5500 fprintf(fout, po->op == OP_ROL ?
5501 " %s = (%s << %d) | (%s >> %d);" :
5502 " %s = (%s >> %d) | (%s << %d);",
5503 buf1, buf1, j, buf1,
5504 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
5508 output_std_flags(fout, po, &pfomask, buf1);
5509 last_arith_dst = &po->operand[0];
5510 delayed_flag_op = NULL;
5515 assert_operand_cnt(2);
5516 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5517 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5518 if (po->operand[1].type == OPT_CONST) {
5519 j = po->operand[1].val % l;
5521 ferr(po, "zero rotate\n");
5522 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
5523 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
5524 if (po->op == OP_RCL) {
5526 " %s = (%s << %d) | (cond_c << %d)",
5527 buf1, buf1, j, j - 1);
5529 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
5533 " %s = (%s >> %d) | (cond_c << %d)",
5534 buf1, buf1, j, l - j);
5536 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
5538 fprintf(fout, ";\n");
5539 fprintf(fout, " cond_c = tmp;");
5543 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
5544 output_std_flags(fout, po, &pfomask, buf1);
5545 last_arith_dst = &po->operand[0];
5546 delayed_flag_op = NULL;
5550 assert_operand_cnt(2);
5551 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5552 if (IS(opr_name(po, 0), opr_name(po, 1))) {
5553 // special case for XOR
5554 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
5555 fprintf(fout, " cond_be = 1;\n");
5556 pfomask &= ~(1 << PFO_BE);
5558 fprintf(fout, " %s = 0;",
5559 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5560 last_arith_dst = &po->operand[0];
5561 delayed_flag_op = NULL;
5567 assert_operand_cnt(2);
5568 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5569 if (pfomask & (1 << PFO_C)) {
5570 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5571 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5572 if (po->operand[0].lmod == OPLM_DWORD) {
5573 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
5574 fprintf(fout, " cond_c = tmp64 >> 32;\n");
5575 fprintf(fout, " %s = (u32)tmp64;",
5576 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5577 strcat(g_comment, "add64");
5580 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
5581 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
5582 fprintf(fout, " %s += %s;",
5583 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5586 pfomask &= ~(1 << PFO_C);
5587 output_std_flags(fout, po, &pfomask, buf1);
5588 last_arith_dst = &po->operand[0];
5589 delayed_flag_op = NULL;
5595 assert_operand_cnt(2);
5596 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5597 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
5598 for (j = 0; j <= PFO_LE; j++) {
5599 if (!(pfomask & (1 << j)))
5601 if (j == PFO_Z || j == PFO_S)
5604 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5605 fprintf(fout, " cond_%s = %s;\n",
5606 parsed_flag_op_names[j], buf1);
5607 pfomask &= ~(1 << j);
5614 assert_operand_cnt(2);
5615 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5616 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5617 if (po->op == OP_SBB
5618 && IS(po->operand[0].name, po->operand[1].name))
5620 // avoid use of unitialized var
5621 fprintf(fout, " %s = -cond_c;", buf1);
5622 // carry remains what it was
5623 pfomask &= ~(1 << PFO_C);
5626 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
5627 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5629 output_std_flags(fout, po, &pfomask, buf1);
5630 last_arith_dst = &po->operand[0];
5631 delayed_flag_op = NULL;
5635 assert_operand_cnt(2);
5636 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5637 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
5638 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5640 output_std_flags(fout, po, &pfomask, buf1);
5641 last_arith_dst = &po->operand[0];
5642 delayed_flag_op = NULL;
5643 strcat(g_comment, "bsf");
5647 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
5648 for (j = 0; j <= PFO_LE; j++) {
5649 if (!(pfomask & (1 << j)))
5651 if (j == PFO_Z || j == PFO_S || j == PFO_C)
5654 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5655 fprintf(fout, " cond_%s = %s;\n",
5656 parsed_flag_op_names[j], buf1);
5657 pfomask &= ~(1 << j);
5663 if (pfomask & (1 << PFO_C))
5664 // carry is unaffected by inc/dec.. wtf?
5665 ferr(po, "carry propagation needed\n");
5667 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5668 if (po->operand[0].type == OPT_REG) {
5669 strcpy(buf2, po->op == OP_INC ? "++" : "--");
5670 fprintf(fout, " %s%s;", buf1, buf2);
5673 strcpy(buf2, po->op == OP_INC ? "+" : "-");
5674 fprintf(fout, " %s %s= 1;", buf1, buf2);
5676 output_std_flags(fout, po, &pfomask, buf1);
5677 last_arith_dst = &po->operand[0];
5678 delayed_flag_op = NULL;
5682 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5683 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5684 fprintf(fout, " %s = -%s%s;", buf1,
5685 lmod_cast_s(po, po->operand[0].lmod), buf2);
5686 last_arith_dst = &po->operand[0];
5687 delayed_flag_op = NULL;
5688 if (pfomask & (1 << PFO_C)) {
5689 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
5690 pfomask &= ~(1 << PFO_C);
5695 if (po->operand_cnt == 2) {
5696 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5699 if (po->operand_cnt == 3)
5700 ferr(po, "TODO imul3\n");
5703 assert_operand_cnt(1);
5704 switch (po->operand[0].lmod) {
5706 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5707 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
5708 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5709 fprintf(fout, " edx = tmp64 >> 32;\n");
5710 fprintf(fout, " eax = tmp64;");
5713 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5714 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
5715 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5719 ferr(po, "TODO: unhandled mul type\n");
5722 last_arith_dst = NULL;
5723 delayed_flag_op = NULL;
5728 assert_operand_cnt(1);
5729 if (po->operand[0].lmod != OPLM_DWORD)
5730 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5732 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5733 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5734 po->op == OP_IDIV));
5735 switch (po->operand[0].lmod) {
5737 if (po->flags & OPF_32BIT)
5738 snprintf(buf3, sizeof(buf3), "%seax", buf2);
5740 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
5741 snprintf(buf3, sizeof(buf3), "%stmp64",
5742 (po->op == OP_IDIV) ? "(s64)" : "");
5744 if (po->operand[0].type == OPT_REG
5745 && po->operand[0].reg == xDX)
5747 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5748 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5751 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5752 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5756 ferr(po, "unhandled division type\n");
5758 last_arith_dst = NULL;
5759 delayed_flag_op = NULL;
5764 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5766 for (j = 0; j < 8; j++) {
5767 if (pfomask & (1 << j)) {
5768 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5769 fprintf(fout, " cond_%s = %s;",
5770 parsed_flag_op_names[j], buf1);
5777 last_arith_dst = NULL;
5778 delayed_flag_op = po;
5782 // SETcc - should already be handled
5785 // note: we reuse OP_Jcc for SETcc, only flags differ
5787 fprintf(fout, "\n goto %s;", po->operand[0].name);
5791 fprintf(fout, " if (ecx == 0)\n");
5792 fprintf(fout, " goto %s;", po->operand[0].name);
5793 strcat(g_comment, "jecxz");
5797 fprintf(fout, " if (--ecx == 0)\n");
5798 fprintf(fout, " goto %s;", po->operand[0].name);
5799 strcat(g_comment, "loop");
5803 assert_operand_cnt(1);
5804 last_arith_dst = NULL;
5805 delayed_flag_op = NULL;
5807 if (po->operand[0].type == OPT_REGMEM) {
5808 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5811 ferr(po, "parse failure for jmp '%s'\n",
5812 po->operand[0].name);
5813 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
5816 else if (po->operand[0].type != OPT_LABEL)
5817 ferr(po, "unhandled jmp type\n");
5819 fprintf(fout, " goto %s;", po->operand[0].name);
5823 assert_operand_cnt(1);
5825 my_assert_not(pp, NULL);
5828 if (po->flags & OPF_CC) {
5829 // we treat conditional branch to another func
5830 // (yes such code exists..) as conditional tailcall
5832 fprintf(fout, " {\n");
5835 if (pp->is_fptr && !pp->is_arg) {
5836 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5837 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5839 if (pp->is_unresolved)
5840 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5841 buf3, asmfn, po->asmln, pp->name);
5844 fprintf(fout, "%s", buf3);
5845 if (strstr(pp->ret_type.name, "int64")) {
5846 if (po->flags & OPF_TAIL)
5847 ferr(po, "int64 and tail?\n");
5848 fprintf(fout, "tmp64 = ");
5850 else if (!IS(pp->ret_type.name, "void")) {
5851 if (po->flags & OPF_TAIL) {
5852 if (regmask_ret & (1 << xAX)) {
5853 fprintf(fout, "return ");
5854 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5855 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5858 else if (po->regmask_dst & (1 << xAX)) {
5859 fprintf(fout, "eax = ");
5860 if (pp->ret_type.is_ptr)
5861 fprintf(fout, "(u32)");
5865 if (pp->name[0] == 0)
5866 ferr(po, "missing pp->name\n");
5867 fprintf(fout, "%s%s(", pp->name,
5868 pp->has_structarg ? "_sa" : "");
5870 if (po->flags & OPF_ATAIL) {
5871 if (pp->argc_stack != g_func_pp->argc_stack
5872 || (pp->argc_stack > 0
5873 && pp->is_stdcall != g_func_pp->is_stdcall))
5874 ferr(po, "incompatible tailcall\n");
5875 if (g_func_pp->has_retreg)
5876 ferr(po, "TODO: retreg+tailcall\n");
5878 for (arg = j = 0; arg < pp->argc; arg++) {
5880 fprintf(fout, ", ");
5883 if (pp->arg[arg].type.is_ptr)
5884 snprintf(cast, sizeof(cast), "(%s)",
5885 pp->arg[arg].type.name);
5887 if (pp->arg[arg].reg != NULL) {
5888 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5892 for (; j < g_func_pp->argc; j++)
5893 if (g_func_pp->arg[j].reg == NULL)
5895 fprintf(fout, "%sa%d", cast, j + 1);
5900 for (arg = 0; arg < pp->argc; arg++) {
5902 fprintf(fout, ", ");
5905 if (pp->arg[arg].type.is_ptr)
5906 snprintf(cast, sizeof(cast), "(%s)",
5907 pp->arg[arg].type.name);
5909 if (pp->arg[arg].reg != NULL) {
5910 if (pp->arg[arg].type.is_retreg)
5911 fprintf(fout, "&%s", pp->arg[arg].reg);
5913 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5918 tmp_op = pp->arg[arg].datap;
5920 ferr(po, "parsed_op missing for arg%d\n", arg);
5922 if (tmp_op->flags & OPF_VAPUSH) {
5923 fprintf(fout, "ap");
5925 else if (tmp_op->p_argpass != 0) {
5926 fprintf(fout, "a%d", tmp_op->p_argpass);
5928 else if (tmp_op->p_argnum != 0) {
5929 fprintf(fout, "%s%s", cast,
5930 saved_arg_name(buf1, sizeof(buf1),
5931 tmp_op->p_arggrp, tmp_op->p_argnum));
5935 out_src_opr(buf1, sizeof(buf1),
5936 tmp_op, &tmp_op->operand[0], cast, 0));
5940 fprintf(fout, ");");
5942 if (strstr(pp->ret_type.name, "int64")) {
5943 fprintf(fout, "\n");
5944 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5945 fprintf(fout, "%seax = tmp64;", buf3);
5948 if (pp->is_unresolved) {
5949 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
5951 strcat(g_comment, buf2);
5954 if (po->flags & OPF_TAIL) {
5956 if (i == opcnt - 1 || pp->is_noreturn)
5958 else if (IS(pp->ret_type.name, "void"))
5960 else if (!(regmask_ret & (1 << xAX)))
5962 // else already handled as 'return f()'
5965 if (regmask_ret & (1 << xAX)) {
5966 ferr(po, "int func -> void func tailcall?\n");
5969 fprintf(fout, "\n%sreturn;", buf3);
5970 strcat(g_comment, " ^ tailcall");
5974 strcat(g_comment, " tailcall");
5976 if (pp->is_noreturn)
5977 strcat(g_comment, " noreturn");
5978 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5979 strcat(g_comment, " argframe");
5980 if (po->flags & OPF_CC)
5981 strcat(g_comment, " cond");
5983 if (po->flags & OPF_CC)
5984 fprintf(fout, "\n }");
5986 delayed_flag_op = NULL;
5987 last_arith_dst = NULL;
5991 if (g_func_pp->is_vararg)
5992 fprintf(fout, " va_end(ap);\n");
5993 if (g_func_pp->has_retreg) {
5994 for (arg = 0; arg < g_func_pp->argc; arg++)
5995 if (g_func_pp->arg[arg].type.is_retreg)
5996 fprintf(fout, " *r_%s = %s;\n",
5997 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
6000 if (!(regmask_ret & (1 << xAX))) {
6001 if (i != opcnt - 1 || label_pending)
6002 fprintf(fout, " return;");
6004 else if (g_func_pp->ret_type.is_ptr) {
6005 fprintf(fout, " return (%s)eax;",
6006 g_func_pp->ret_type.name);
6008 else if (IS(g_func_pp->ret_type.name, "__int64"))
6009 fprintf(fout, " return ((u64)edx << 32) | eax;");
6011 fprintf(fout, " return eax;");
6013 last_arith_dst = NULL;
6014 delayed_flag_op = NULL;
6018 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
6019 if (po->p_argnum != 0) {
6020 // special case - saved func arg
6021 fprintf(fout, " %s = %s;",
6022 saved_arg_name(buf2, sizeof(buf2),
6023 po->p_arggrp, po->p_argnum), buf1);
6026 else if (po->flags & OPF_RSAVE) {
6027 fprintf(fout, " s_%s = %s;", buf1, buf1);
6030 else if (po->flags & OPF_PPUSH) {
6032 ferr_assert(po, tmp_op != NULL);
6033 out_dst_opr(buf2, sizeof(buf2), po, &tmp_op->operand[0]);
6034 fprintf(fout, " pp_%s = %s;", buf2, buf1);
6037 else if (g_func_pp->is_userstack) {
6038 fprintf(fout, " *(--esp) = %s;", buf1);
6041 if (!(g_ida_func_attr & IDAFA_NORETURN))
6042 ferr(po, "stray push encountered\n");
6047 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
6048 if (po->flags & OPF_RSAVE) {
6049 fprintf(fout, " %s = s_%s;", buf1, buf1);
6052 else if (po->flags & OPF_PPUSH) {
6053 // push/pop graph / non-const
6054 ferr_assert(po, po->datap == NULL);
6055 fprintf(fout, " %s = pp_%s;", buf1, buf1);
6058 else if (po->datap != NULL) {
6061 fprintf(fout, " %s = %s;", buf1,
6062 out_src_opr(buf2, sizeof(buf2),
6063 tmp_op, &tmp_op->operand[0],
6064 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
6067 else if (g_func_pp->is_userstack) {
6068 fprintf(fout, " %s = *esp++;", buf1);
6072 ferr(po, "stray pop encountered\n");
6081 strcpy(g_comment, "(emms)");
6086 ferr(po, "unhandled op type %d, flags %x\n",
6091 if (g_comment[0] != 0) {
6092 char *p = g_comment;
6093 while (my_isblank(*p))
6095 fprintf(fout, " // %s", p);
6100 fprintf(fout, "\n");
6102 // some sanity checking
6103 if (po->flags & OPF_REP) {
6104 if (po->op != OP_STOS && po->op != OP_MOVS
6105 && po->op != OP_CMPS && po->op != OP_SCAS)
6106 ferr(po, "unexpected rep\n");
6107 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
6108 && (po->op == OP_CMPS || po->op == OP_SCAS))
6109 ferr(po, "cmps/scas with plain rep\n");
6111 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
6112 && po->op != OP_CMPS && po->op != OP_SCAS)
6113 ferr(po, "unexpected repz/repnz\n");
6116 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
6118 // see is delayed flag stuff is still valid
6119 if (delayed_flag_op != NULL && delayed_flag_op != po) {
6120 if (is_any_opr_modified(delayed_flag_op, po, 0))
6121 delayed_flag_op = NULL;
6124 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
6125 if (is_opr_modified(last_arith_dst, po))
6126 last_arith_dst = NULL;
6132 if (g_stack_fsz && !g_stack_frame_used)
6133 fprintf(fout, " (void)sf;\n");
6135 fprintf(fout, "}\n\n");
6137 gen_x_cleanup(opcnt);
6140 static void gen_x_cleanup(int opcnt)
6144 for (i = 0; i < opcnt; i++) {
6145 struct label_ref *lr, *lr_del;
6147 lr = g_label_refs[i].next;
6148 while (lr != NULL) {
6153 g_label_refs[i].i = -1;
6154 g_label_refs[i].next = NULL;
6156 if (ops[i].op == OP_CALL) {
6158 proto_release(ops[i].pp);
6164 struct func_proto_dep;
6166 struct func_prototype {
6171 int has_ret:3; // -1, 0, 1: unresolved, no, yes
6172 unsigned int dep_resolved:1;
6173 unsigned int is_stdcall:1;
6174 struct func_proto_dep *dep_func;
6176 const struct parsed_proto *pp; // seed pp, if any
6179 struct func_proto_dep {
6181 struct func_prototype *proto;
6182 int regmask_live; // .. at the time of call
6183 unsigned int ret_dep:1; // return from this is caller's return
6186 static struct func_prototype *hg_fp;
6187 static int hg_fp_cnt;
6189 static struct scanned_var {
6191 enum opr_lenmod lmod;
6192 unsigned int is_seeded:1;
6193 unsigned int is_c_str:1;
6194 const struct parsed_proto *pp; // seed pp, if any
6196 static int hg_var_cnt;
6198 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6201 struct func_prototype *hg_fp_add(const char *funcn)
6203 struct func_prototype *fp;
6205 if ((hg_fp_cnt & 0xff) == 0) {
6206 hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
6207 my_assert_not(hg_fp, NULL);
6208 memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
6211 fp = &hg_fp[hg_fp_cnt];
6212 snprintf(fp->name, sizeof(fp->name), "%s", funcn);
6214 fp->argc_stack = -1;
6220 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
6225 for (i = 0; i < fp->dep_func_cnt; i++)
6226 if (IS(fp->dep_func[i].name, name))
6227 return &fp->dep_func[i];
6232 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
6235 if (hg_fp_find_dep(fp, name))
6238 if ((fp->dep_func_cnt & 0xff) == 0) {
6239 fp->dep_func = realloc(fp->dep_func,
6240 sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
6241 my_assert_not(fp->dep_func, NULL);
6242 memset(&fp->dep_func[fp->dep_func_cnt], 0,
6243 sizeof(fp->dep_func[0]) * 0x100);
6245 fp->dep_func[fp->dep_func_cnt].name = strdup(name);
6249 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
6251 const struct func_prototype *p1 = p1_, *p2 = p2_;
6252 return strcmp(p1->name, p2->name);
6256 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
6258 const struct func_prototype *p1 = p1_, *p2 = p2_;
6259 return p1->id - p2->id;
6263 // recursive register dep pass
6264 // - track saved regs (part 2)
6265 // - try to figure out arg-regs
6266 // - calculate reg deps
6267 static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
6268 struct func_prototype *fp, int regmask_save, int regmask_dst,
6269 int *regmask_dep, int *has_ret)
6271 struct func_proto_dep *dep;
6272 struct parsed_op *po;
6273 int from_caller = 0;
6278 for (; i < opcnt; i++)
6280 if (cbits[i >> 3] & (1 << (i & 7)))
6282 cbits[i >> 3] |= (1 << (i & 7));
6286 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
6287 if (po->flags & OPF_RMD)
6290 if (po->btj != NULL) {
6292 for (j = 0; j < po->btj->count; j++) {
6293 check_i(po, po->btj->d[j].bt_i);
6294 gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
6295 regmask_save, regmask_dst, regmask_dep, has_ret);
6300 check_i(po, po->bt_i);
6301 if (po->flags & OPF_CJMP) {
6302 gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
6303 regmask_save, regmask_dst, regmask_dep, has_ret);
6311 if (po->flags & OPF_FARG)
6312 /* (just calculate register deps) */;
6313 else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
6315 reg = po->operand[0].reg;
6316 ferr_assert(po, reg >= 0);
6318 if (po->flags & OPF_RSAVE) {
6319 regmask_save |= 1 << reg;
6322 if (po->flags & OPF_DONE)
6325 ret = scan_for_pop(i + 1, opcnt, i + opcnt * 2, reg, 0, 0);
6327 regmask_save |= 1 << reg;
6328 po->flags |= OPF_RMD;
6329 scan_for_pop(i + 1, opcnt, i + opcnt * 3, reg, 0, OPF_RMD);
6333 else if (po->flags & OPF_RMD)
6335 else if (po->op == OP_CALL) {
6336 po->regmask_dst |= 1 << xAX;
6338 dep = hg_fp_find_dep(fp, po->operand[0].name);
6340 dep->regmask_live = regmask_save | regmask_dst;
6342 else if (po->op == OP_RET) {
6343 if (po->operand_cnt > 0) {
6345 if (fp->argc_stack >= 0
6346 && fp->argc_stack != po->operand[0].val / 4)
6347 ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
6348 fp->argc_stack = po->operand[0].val / 4;
6352 // if has_ret is 0, there is uninitialized eax path,
6353 // which means it's most likely void func
6354 if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
6355 if (po->op == OP_CALL) {
6360 struct parsed_opr opr = OPR_INIT(OPT_REG, OPLM_DWORD, xAX);
6363 ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
6366 if (ret != 1 && from_caller) {
6367 // unresolved eax - probably void func
6371 if (j >= 0 && ops[j].op == OP_CALL) {
6372 dep = hg_fp_find_dep(fp, ops[j].operand[0].name);
6383 l = regmask_save | regmask_dst;
6384 if (g_bp_frame && !(po->flags & OPF_EBP_S))
6387 l = po->regmask_src & ~l;
6390 fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
6391 l, regmask_dst, regmask_save, po->flags);
6394 regmask_dst |= po->regmask_dst;
6396 if (po->flags & OPF_TAIL)
6401 static void gen_hdr(const char *funcn, int opcnt)
6403 int save_arg_vars[MAX_ARG_GRP] = { 0, };
6404 unsigned char cbits[MAX_OPS / 8];
6405 const struct parsed_proto *pp_c;
6406 struct parsed_proto *pp;
6407 struct func_prototype *fp;
6408 struct parsed_op *po;
6409 int regmask_dummy = 0;
6411 int max_bp_offset = 0;
6416 pp_c = proto_parse(g_fhdr, funcn, 1);
6418 // already in seed, will add to hg_fp later
6421 fp = hg_fp_add(funcn);
6423 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
6424 g_stack_frame_used = 0;
6427 // - resolve all branches
6428 // - parse calls with labels
6429 resolve_branches_parse_calls(opcnt);
6432 // - handle ebp/esp frame, remove ops related to it
6433 scan_prologue_epilogue(opcnt);
6436 // - remove dead labels
6438 for (i = 0; i < opcnt; i++)
6440 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6446 if (po->flags & (OPF_RMD|OPF_DONE))
6449 if (po->op == OP_CALL) {
6450 if (po->operand[0].type == OPT_LABEL)
6451 hg_fp_add_dep(fp, opr_name(po, 0));
6452 else if (po->pp != NULL)
6453 hg_fp_add_dep(fp, po->pp->name);
6458 // - remove dead labels
6459 // - handle push <const>/pop pairs
6460 for (i = 0; i < opcnt; i++)
6462 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6468 if (po->flags & (OPF_RMD|OPF_DONE))
6471 if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
6472 scan_for_pop_const(i, opcnt, i + opcnt * 13);
6476 // - process trivial calls
6477 for (i = 0; i < opcnt; i++)
6480 if (po->flags & (OPF_RMD|OPF_DONE))
6483 if (po->op == OP_CALL)
6485 pp = process_call_early(i, opcnt, &j);
6487 if (!(po->flags & OPF_ATAIL))
6488 // since we know the args, try to collect them
6489 if (collect_call_args_early(po, i, pp, ®mask_dummy) != 0)
6495 // commit esp adjust
6496 if (ops[j].op != OP_POP)
6497 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
6499 for (l = 0; l < pp->argc_stack; l++)
6500 ops[j + l].flags |= OPF_DONE | OPF_RMD | OPF_NOREGS;
6504 po->flags |= OPF_DONE;
6510 // - track saved regs (simple)
6512 for (i = 0; i < opcnt; i++)
6515 if (po->flags & (OPF_RMD|OPF_DONE))
6518 if (po->op == OP_PUSH && po->operand[0].type == OPT_REG
6519 && po->operand[0].reg != xCX)
6521 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, 0);
6523 // regmask_save |= 1 << po->operand[0].reg; // do it later
6524 po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
6525 scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, OPF_RMD);
6528 else if (po->op == OP_CALL)
6530 pp = process_call(i, opcnt);
6532 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
6533 // since we know the args, collect them
6534 ret = collect_call_args(po, i, pp, ®mask_dummy, save_arg_vars,
6541 memset(cbits, 0, sizeof(cbits));
6545 gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, ®mask_dep, &has_ret);
6547 // find unreachable code - must be fixed in IDA
6548 for (i = 0; i < opcnt; i++)
6550 if (cbits[i >> 3] & (1 << (i & 7)))
6553 if (g_labels[i] == NULL && i > 0 && ops[i - 1].op == OP_CALL
6554 && ops[i - 1].pp != NULL && ops[i - 1].pp->is_osinc)
6556 // the compiler sometimes still generates code after
6557 // noreturn OS functions
6560 if (ops[i].op != OP_NOP)
6561 ferr(&ops[i], "unreachable code\n");
6564 for (i = 0; i < g_eqcnt; i++) {
6565 if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
6566 max_bp_offset = g_eqs[i].offset;
6569 if (fp->argc_stack < 0) {
6570 max_bp_offset = (max_bp_offset + 3) & ~3;
6571 fp->argc_stack = max_bp_offset / 4;
6572 if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
6576 fp->regmask_dep = regmask_dep & ~(1 << xSP);
6577 fp->has_ret = has_ret;
6579 printf("// has_ret %d, regmask_dep %x\n",
6580 fp->has_ret, fp->regmask_dep);
6581 output_hdr_fp(stdout, fp, 1);
6582 if (IS(funcn, "sub_10007F72")) exit(1);
6585 gen_x_cleanup(opcnt);
6588 static void hg_fp_resolve_deps(struct func_prototype *fp)
6590 struct func_prototype fp_s;
6594 // this thing is recursive, so mark first..
6595 fp->dep_resolved = 1;
6597 for (i = 0; i < fp->dep_func_cnt; i++) {
6598 strcpy(fp_s.name, fp->dep_func[i].name);
6599 fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
6600 sizeof(hg_fp[0]), hg_fp_cmp_name);
6601 if (fp->dep_func[i].proto != NULL) {
6602 if (!fp->dep_func[i].proto->dep_resolved)
6603 hg_fp_resolve_deps(fp->dep_func[i].proto);
6605 dep = ~fp->dep_func[i].regmask_live
6606 & fp->dep_func[i].proto->regmask_dep;
6607 fp->regmask_dep |= dep;
6608 // printf("dep %s %s |= %x\n", fp->name,
6609 // fp->dep_func[i].name, dep);
6611 if (fp->has_ret == -1 && fp->dep_func[i].ret_dep)
6612 fp->has_ret = fp->dep_func[i].proto->has_ret;
6617 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6620 const struct parsed_proto *pp;
6621 char *p, namebuf[NAMELEN];
6627 for (; count > 0; count--, fp++) {
6628 if (fp->has_ret == -1)
6629 fprintf(fout, "// ret unresolved\n");
6631 fprintf(fout, "// dep:");
6632 for (j = 0; j < fp->dep_func_cnt; j++) {
6633 fprintf(fout, " %s/", fp->dep_func[j].name);
6634 if (fp->dep_func[j].proto != NULL)
6635 fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6636 fp->dep_func[j].proto->has_ret);
6638 fprintf(fout, "\n");
6641 p = strchr(fp->name, '@');
6643 memcpy(namebuf, fp->name, p - fp->name);
6644 namebuf[p - fp->name] = 0;
6652 pp = proto_parse(g_fhdr, name, 1);
6653 if (pp != NULL && pp->is_include)
6656 if (fp->pp != NULL) {
6657 // part of seed, output later
6661 regmask_dep = fp->regmask_dep;
6662 argc_stack = fp->argc_stack;
6664 fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6665 (fp->has_ret ? "int" : "void"));
6666 if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6667 && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6669 fprintf(fout, " __fastcall ");
6670 if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6676 else if (regmask_dep && !fp->is_stdcall) {
6677 fprintf(fout, "/*__usercall*/ ");
6679 else if (regmask_dep) {
6680 fprintf(fout, "/*__userpurge*/ ");
6682 else if (fp->is_stdcall)
6683 fprintf(fout, " __stdcall ");
6685 fprintf(fout, " __cdecl ");
6687 fprintf(fout, "%s(", name);
6690 for (j = 0; j < xSP; j++) {
6691 if (regmask_dep & (1 << j)) {
6694 fprintf(fout, ", ");
6696 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6698 fprintf(fout, "int");
6699 fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
6703 for (j = 0; j < argc_stack; j++) {
6706 fprintf(fout, ", ");
6707 if (fp->pp != NULL) {
6708 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6709 if (!fp->pp->arg[arg - 1].type.is_ptr)
6713 fprintf(fout, "int ");
6714 fprintf(fout, "a%d", arg);
6717 fprintf(fout, ");\n");
6721 static void output_hdr(FILE *fout)
6723 static const char *lmod_c_names[] = {
6724 [OPLM_UNSPEC] = "???",
6725 [OPLM_BYTE] = "uint8_t",
6726 [OPLM_WORD] = "uint16_t",
6727 [OPLM_DWORD] = "uint32_t",
6728 [OPLM_QWORD] = "uint64_t",
6730 const struct scanned_var *var;
6731 struct func_prototype *fp;
6732 char line[256] = { 0, };
6736 // add stuff from headers
6737 for (i = 0; i < pp_cache_size; i++) {
6738 if (pp_cache[i].is_cinc && !pp_cache[i].is_stdcall)
6739 snprintf(name, sizeof(name), "_%s", pp_cache[i].name);
6741 snprintf(name, sizeof(name), "%s", pp_cache[i].name);
6742 fp = hg_fp_add(name);
6743 fp->pp = &pp_cache[i];
6744 fp->argc_stack = fp->pp->argc_stack;
6745 fp->is_stdcall = fp->pp->is_stdcall;
6746 fp->regmask_dep = get_pp_arg_regmask_src(fp->pp);
6747 fp->has_ret = !IS(fp->pp->ret_type.name, "void");
6751 qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6752 for (i = 0; i < hg_fp_cnt; i++)
6753 hg_fp_resolve_deps(&hg_fp[i]);
6755 // note: messes up .proto ptr, don't use
6756 //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6759 for (i = 0; i < hg_var_cnt; i++) {
6762 if (var->pp != NULL)
6765 else if (var->is_c_str)
6766 fprintf(fout, "extern %-8s %s[];", "char", var->name);
6768 fprintf(fout, "extern %-8s %s;",
6769 lmod_c_names[var->lmod], var->name);
6772 fprintf(fout, " // seeded");
6773 fprintf(fout, "\n");
6776 fprintf(fout, "\n");
6778 // output function prototypes
6779 output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6782 fprintf(fout, "\n// - seed -\n");
6785 while (fgets(line, sizeof(line), g_fhdr))
6786 fwrite(line, 1, strlen(line), fout);
6789 // '=' needs special treatment
6791 static char *next_word_s(char *w, size_t wsize, char *s)
6800 for (i = 1; i < wsize - 1; i++) {
6802 printf("warning: missing closing quote: \"%s\"\n", s);
6811 for (; i < wsize - 1; i++) {
6812 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6818 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6819 printf("warning: '%s' truncated\n", w);
6824 static void scan_variables(FILE *fasm)
6826 struct scanned_var *var;
6827 char line[256] = { 0, };
6835 // skip to next data section
6836 while (my_fgets(line, sizeof(line), fasm))
6841 if (*p == 0 || *p == ';')
6844 p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6845 if (*p == 0 || *p == ';')
6848 if (*p != 's' || !IS_START(p, "segment para public"))
6854 if (p == NULL || !IS_START(p, "segment para public"))
6858 if (!IS_START(p, "'DATA'"))
6862 while (my_fgets(line, sizeof(line), fasm))
6871 if (*p == 0 || *p == ';')
6874 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6875 words[wordc][0] = 0;
6876 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6877 if (*p == 0 || *p == ';') {
6883 if (wordc == 2 && IS(words[1], "ends"))
6888 if (IS_START(words[0], "__IMPORT_DESCRIPTOR_")) {
6889 // when this starts, we don't need anything from this section
6893 if ((hg_var_cnt & 0xff) == 0) {
6894 hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6895 * (hg_var_cnt + 0x100));
6896 my_assert_not(hg_vars, NULL);
6897 memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6900 var = &hg_vars[hg_var_cnt++];
6901 snprintf(var->name, sizeof(var->name), "%s", words[0]);
6903 // maybe already in seed header?
6904 var->pp = proto_parse(g_fhdr, var->name, 1);
6905 if (var->pp != NULL) {
6906 if (var->pp->is_fptr) {
6907 var->lmod = OPLM_DWORD;
6910 else if (var->pp->is_func)
6912 else if (!guess_lmod_from_c_type(&var->lmod, &var->pp->type))
6913 aerr("unhandled C type '%s' for '%s'\n",
6914 var->pp->type.name, var->name);
6920 if (IS(words[1], "dd"))
6921 var->lmod = OPLM_DWORD;
6922 else if (IS(words[1], "dw"))
6923 var->lmod = OPLM_WORD;
6924 else if (IS(words[1], "db")) {
6925 var->lmod = OPLM_BYTE;
6926 if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6927 if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6931 else if (IS(words[1], "dq"))
6932 var->lmod = OPLM_QWORD;
6933 //else if (IS(words[1], "dt"))
6935 aerr("type '%s' not known\n", words[1]);
6943 static void set_label(int i, const char *name)
6949 p = strchr(name, ':');
6953 if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6954 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6955 g_labels[i] = realloc(g_labels[i], len + 1);
6956 my_assert_not(g_labels[i], NULL);
6957 memcpy(g_labels[i], name, len);
6958 g_labels[i][len] = 0;
6967 static struct chunk_item *func_chunks;
6968 static int func_chunk_cnt;
6969 static int func_chunk_alloc;
6971 static void add_func_chunk(FILE *fasm, const char *name, int line)
6973 if (func_chunk_cnt >= func_chunk_alloc) {
6974 func_chunk_alloc *= 2;
6975 func_chunks = realloc(func_chunks,
6976 func_chunk_alloc * sizeof(func_chunks[0]));
6977 my_assert_not(func_chunks, NULL);
6979 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6980 func_chunks[func_chunk_cnt].name = strdup(name);
6981 func_chunks[func_chunk_cnt].asmln = line;
6985 static int cmp_chunks(const void *p1, const void *p2)
6987 const struct chunk_item *c1 = p1, *c2 = p2;
6988 return strcmp(c1->name, c2->name);
6991 static int cmpstringp(const void *p1, const void *p2)
6993 return strcmp(*(char * const *)p1, *(char * const *)p2);
6996 static void scan_ahead(FILE *fasm)
7006 oldpos = ftell(fasm);
7009 while (my_fgets(line, sizeof(line), fasm))
7020 // get rid of random tabs
7021 for (i = 0; line[i] != 0; i++)
7022 if (line[i] == '\t')
7025 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
7028 next_word(words[0], sizeof(words[0]), p);
7029 if (words[0][0] == 0)
7030 aerr("missing name for func chunk?\n");
7032 add_func_chunk(fasm, words[0], asmln);
7034 else if (IS_START(p, "; sctend"))
7040 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
7041 words[wordc][0] = 0;
7042 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
7043 if (*p == 0 || *p == ';') {
7049 if (wordc == 2 && IS(words[1], "ends"))
7053 fseek(fasm, oldpos, SEEK_SET);
7057 int main(int argc, char *argv[])
7059 FILE *fout, *fasm, *frlist;
7060 struct parsed_data *pd = NULL;
7062 char **rlist = NULL;
7064 int rlist_alloc = 0;
7065 int func_chunks_used = 0;
7066 int func_chunks_sorted = 0;
7067 int func_chunk_i = -1;
7068 long func_chunk_ret = 0;
7069 int func_chunk_ret_ln = 0;
7070 int scanned_ahead = 0;
7072 char words[20][256];
7073 enum opr_lenmod lmod;
7074 char *sctproto = NULL;
7076 int pending_endp = 0;
7078 int skip_warned = 0;
7091 for (arg = 1; arg < argc; arg++) {
7092 if (IS(argv[arg], "-v"))
7094 else if (IS(argv[arg], "-rf"))
7095 g_allow_regfunc = 1;
7096 else if (IS(argv[arg], "-m"))
7098 else if (IS(argv[arg], "-hdr"))
7099 g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
7104 if (argc < arg + 3) {
7105 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdr.h> [rlist]*\n"
7106 "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n"
7108 " -hdr - header generation mode\n"
7109 " -rf - allow unannotated indirect calls\n"
7110 " -m - allow multiple .text sections\n"
7111 "[rlist] is a file with function names to skip,"
7119 asmfn = argv[arg++];
7120 fasm = fopen(asmfn, "r");
7121 my_assert_not(fasm, NULL);
7123 hdrfn = argv[arg++];
7124 g_fhdr = fopen(hdrfn, "r");
7125 my_assert_not(g_fhdr, NULL);
7128 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
7129 my_assert_not(rlist, NULL);
7130 // needs special handling..
7131 rlist[rlist_len++] = "__alloca_probe";
7133 func_chunk_alloc = 32;
7134 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
7135 my_assert_not(func_chunks, NULL);
7137 memset(words, 0, sizeof(words));
7139 for (; arg < argc; arg++) {
7140 frlist = fopen(argv[arg], "r");
7141 my_assert_not(frlist, NULL);
7143 while (my_fgets(line, sizeof(line), frlist)) {
7145 if (*p == 0 || *p == ';')
7148 if (IS_START(p, "#if 0")
7149 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
7153 else if (IS_START(p, "#endif"))
7160 p = next_word(words[0], sizeof(words[0]), p);
7161 if (words[0][0] == 0)
7164 if (rlist_len >= rlist_alloc) {
7165 rlist_alloc = rlist_alloc * 2 + 64;
7166 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
7167 my_assert_not(rlist, NULL);
7169 rlist[rlist_len++] = strdup(words[0]);
7178 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
7180 fout = fopen(argv[arg_out], "w");
7181 my_assert_not(fout, NULL);
7184 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
7185 my_assert_not(g_eqs, NULL);
7187 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
7188 g_label_refs[i].i = -1;
7189 g_label_refs[i].next = NULL;
7193 scan_variables(fasm);
7195 while (my_fgets(line, sizeof(line), fasm))
7204 // get rid of random tabs
7205 for (i = 0; line[i] != 0; i++)
7206 if (line[i] == '\t')
7211 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
7212 goto do_pending_endp; // eww..
7214 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
7216 static const char *attrs[] = {
7225 // parse IDA's attribute-list comment
7226 g_ida_func_attr = 0;
7229 for (; *p != 0; p = sskip(p)) {
7230 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
7231 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
7232 g_ida_func_attr |= 1 << i;
7233 p += strlen(attrs[i]);
7237 if (i == ARRAY_SIZE(attrs)) {
7238 anote("unparsed IDA attr: %s\n", p);
7241 if (IS(attrs[i], "fpd=")) {
7242 p = next_word(words[0], sizeof(words[0]), p);
7247 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
7250 next_word(words[0], sizeof(words[0]), p);
7251 if (words[0][0] == 0)
7252 aerr("missing name for func chunk?\n");
7254 if (!scanned_ahead) {
7255 add_func_chunk(fasm, words[0], asmln);
7256 func_chunks_sorted = 0;
7259 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
7261 if (func_chunk_i >= 0) {
7262 if (func_chunk_i < func_chunk_cnt
7263 && IS(func_chunks[func_chunk_i].name, g_func))
7265 // move on to next chunk
7266 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7268 aerr("seek failed for '%s' chunk #%d\n",
7269 g_func, func_chunk_i);
7270 asmln = func_chunks[func_chunk_i].asmln;
7274 if (func_chunk_ret == 0)
7275 aerr("no return from chunk?\n");
7276 fseek(fasm, func_chunk_ret, SEEK_SET);
7277 asmln = func_chunk_ret_ln;
7283 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
7284 func_chunks_used = 1;
7286 if (IS_START(g_func, "sub_")) {
7287 unsigned long addr = strtoul(p, NULL, 16);
7288 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
7289 if (addr > f_addr && !scanned_ahead) {
7290 //anote("scan_ahead caused by '%s', addr %lx\n",
7294 func_chunks_sorted = 0;
7302 for (i = wordc; i < ARRAY_SIZE(words); i++)
7304 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
7305 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
7306 if (*p == 0 || *p == ';') {
7311 if (*p != 0 && *p != ';')
7312 aerr("too many words\n");
7314 // alow asm patches in comments
7316 if (IS_START(p, "; sctpatch:")) {
7318 if (*p == 0 || *p == ';')
7320 goto parse_words; // lame
7322 if (IS_START(p, "; sctproto:")) {
7323 sctproto = strdup(p + 11);
7325 else if (IS_START(p, "; sctend")) {
7334 awarn("wordc == 0?\n");
7338 // don't care about this:
7339 if (words[0][0] == '.'
7340 || IS(words[0], "include")
7341 || IS(words[0], "assume") || IS(words[1], "segment")
7342 || IS(words[0], "align"))
7348 // do delayed endp processing to collect switch jumptables
7350 if (in_func && !g_skip_func && !end && wordc >= 2
7351 && ((words[0][0] == 'd' && words[0][2] == 0)
7352 || (words[1][0] == 'd' && words[1][2] == 0)))
7355 if (words[1][0] == 'd' && words[1][2] == 0) {
7357 if (g_func_pd_cnt >= pd_alloc) {
7358 pd_alloc = pd_alloc * 2 + 16;
7359 g_func_pd = realloc(g_func_pd,
7360 sizeof(g_func_pd[0]) * pd_alloc);
7361 my_assert_not(g_func_pd, NULL);
7363 pd = &g_func_pd[g_func_pd_cnt];
7365 memset(pd, 0, sizeof(*pd));
7366 strcpy(pd->label, words[0]);
7367 pd->type = OPT_CONST;
7368 pd->lmod = lmod_from_directive(words[1]);
7374 anote("skipping alignment byte?\n");
7377 lmod = lmod_from_directive(words[0]);
7378 if (lmod != pd->lmod)
7379 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
7382 if (pd->count_alloc < pd->count + wordc) {
7383 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
7384 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
7385 my_assert_not(pd->d, NULL);
7387 for (; i < wordc; i++) {
7388 if (IS(words[i], "offset")) {
7389 pd->type = OPT_OFFSET;
7392 p = strchr(words[i], ',');
7395 if (pd->type == OPT_OFFSET)
7396 pd->d[pd->count].u.label = strdup(words[i]);
7398 pd->d[pd->count].u.val = parse_number(words[i]);
7399 pd->d[pd->count].bt_i = -1;
7405 if (in_func && !g_skip_func) {
7407 gen_hdr(g_func, pi);
7409 gen_func(fout, g_fhdr, g_func, pi);
7414 g_ida_func_attr = 0;
7418 func_chunks_used = 0;
7421 memset(&ops, 0, pi * sizeof(ops[0]));
7426 for (i = 0; i < g_func_pd_cnt; i++) {
7428 if (pd->type == OPT_OFFSET) {
7429 for (j = 0; j < pd->count; j++)
7430 free(pd->d[j].u.label);
7444 if (IS(words[1], "proc")) {
7446 aerr("proc '%s' while in_func '%s'?\n",
7449 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
7451 strcpy(g_func, words[0]);
7452 set_label(0, words[0]);
7457 if (IS(words[1], "endp"))
7460 aerr("endp '%s' while not in_func?\n", words[0]);
7461 if (!IS(g_func, words[0]))
7462 aerr("endp '%s' while in_func '%s'?\n",
7465 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
7466 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
7472 if (!g_skip_func && func_chunks_used) {
7473 // start processing chunks
7474 struct chunk_item *ci, key = { g_func, 0 };
7476 func_chunk_ret = ftell(fasm);
7477 func_chunk_ret_ln = asmln;
7478 if (!func_chunks_sorted) {
7479 qsort(func_chunks, func_chunk_cnt,
7480 sizeof(func_chunks[0]), cmp_chunks);
7481 func_chunks_sorted = 1;
7483 ci = bsearch(&key, func_chunks, func_chunk_cnt,
7484 sizeof(func_chunks[0]), cmp_chunks);
7486 aerr("'%s' needs chunks, but none found\n", g_func);
7487 func_chunk_i = ci - func_chunks;
7488 for (; func_chunk_i > 0; func_chunk_i--)
7489 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
7492 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7494 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
7495 asmln = func_chunks[func_chunk_i].asmln;
7503 if (wordc == 2 && IS(words[1], "ends")) {
7507 goto do_pending_endp;
7511 // scan for next text segment
7512 while (my_fgets(line, sizeof(line), fasm)) {
7515 if (*p == 0 || *p == ';')
7518 if (strstr(p, "segment para public 'CODE' use32"))
7525 p = strchr(words[0], ':');
7527 set_label(pi, words[0]);
7531 if (!in_func || g_skip_func) {
7532 if (!skip_warned && !g_skip_func && g_labels[pi] != NULL) {
7534 anote("skipping from '%s'\n", g_labels[pi]);
7538 g_labels[pi] = NULL;
7542 if (wordc > 1 && IS(words[1], "="))
7545 aerr("unhandled equ, wc=%d\n", wordc);
7546 if (g_eqcnt >= eq_alloc) {
7548 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
7549 my_assert_not(g_eqs, NULL);
7552 len = strlen(words[0]);
7553 if (len > sizeof(g_eqs[0].name) - 1)
7554 aerr("equ name too long: %d\n", len);
7555 strcpy(g_eqs[g_eqcnt].name, words[0]);
7557 if (!IS(words[3], "ptr"))
7558 aerr("unhandled equ\n");
7559 if (IS(words[2], "dword"))
7560 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
7561 else if (IS(words[2], "word"))
7562 g_eqs[g_eqcnt].lmod = OPLM_WORD;
7563 else if (IS(words[2], "byte"))
7564 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
7565 else if (IS(words[2], "qword"))
7566 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
7568 aerr("bad lmod: '%s'\n", words[2]);
7570 g_eqs[g_eqcnt].offset = parse_number(words[4]);
7575 if (pi >= ARRAY_SIZE(ops))
7576 aerr("too many ops\n");
7578 parse_op(&ops[pi], words, wordc);
7580 if (sctproto != NULL) {
7581 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
7582 ops[pi].datap = sctproto;
7598 // vim:ts=2:shiftwidth=2:expandtab